#!/usr/bin/env python3
"""依頼241（pan180.py の写し：上の帯の「店の時刻」を「病院の時刻」にする（30倍・5倍）。ほかは同じ）。もとの説明：依頼180（pan179.py の写し：カメラは cams180（寄り n_cross を足す）、静止画は 22＋3、still180_…・camspath180_…）。もとの説明：依頼179（pan161.py の写し：カメラは cams179（寄り2つを足す）、静止画は 22＋2、still180_…・camspath180_…。もとの説明：依頼161（pan158.py の写し：場面の札の枠（と下の三角）を緑（MINT_D）から黒（P.INK）にする。「受け取る人を待つ」の札の下の帯は今のまま（帯の枠 MINT_D・中 MINT）。
  tag() に帯の枠の色を別に渡せるようにした（bar＝(割合, 色, 帯の枠の色)）。静止画は still161_…。もとの説明：依頼158（pan157.py の写し：カメラは cams158（寄り4つを足す）、静止画は 18＋4。呼ぶ場面と台の前の受け渡しを場面の印とパネルに出す（request_view。見た目だけ）：
  依頼の印＝積む所の台の上の札（白地＝ふつう・黒地＝至急。数と、いちばん古い依頼の待っている秒）、積む・受け取る人の上の緑の札、
  届け先で受け取る人を待っているロボットの上の札（待っている秒と、この便の pickup_wait_s の目安の帯）、人が運んでいる補助者の上の札。
  パネルに「呼ぶ・荷物」（道ごとの待っている荷物の数・いちばん古い依頼の待っている秒、いま積んでいる・受け取りを待つ・受け取っている、運んでいる荷物の数）。
  動画2（1便の通し：trip_b・trip_r）は5倍・寄りで付いて行く。もとの説明：依頼157（pan155.py の写し：カメラは cams157（寄り 外来の大廊下の清掃を足す）、静止画は 17＋1、凡例に清掃のカート）。もとの説明：依頼155（pan154.py の写し：カメラは cams155（寄り 化学療法のトイレの前を足す）、静止画は 16＋1）。もとの説明：依頼154（pan149.py の写し：カメラは cams154（寄り 救急の待合・正面玄関から救急へ行く道を足す）、静止画は8つ×2つの時刻）。もとの説明：依頼149（pan147.py の写しを直した：カメラは cams149、静止画は6つ×2つの時刻、エレベーター・トイレ）。もとの説明：依頼147（pan143.py の写しを直した：カメラは cams147、静止画7枚、題に人の動き）。もとの説明：依頼143：h1 の静止画（8枚）と1日の早回しの動画に、輪・パネル・凡例・上の帯を付ける（1920×1080）。依頼141 の pan141.py と同じ作り
（輪・凡例・パネルの形は依頼140 の pan140.py）。違うのは：病院 h1、ロボットの状態（台の前で待っている・積む所へ移る）、
行き先の名前を短く、道（緑・青（表）・青（裏口）・赤）、引きは西半分と東半分、問題を 廊下／部屋の中 に分けて帯に出す。

  python3 pan143.py stills <回のフォルダ> <出力フォルダ>
  python3 pan143.py video <回のフォルダ> flowday <出力.mp4> [並べる数]
  python3 pan143.py frame <回のフォルダ> flowday <コマ番号> <出力.png>
"""
import csv, json, math, os, subprocess, sys, tempfile
from multiprocessing import Pool
from PIL import Image, ImageDraw
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import pan140 as P
from cams180 import cams as cams143, still_cams
import trips158 as TP

W, H, SW = P.W, P.H, P.SW
SHORT = {"救急室の処置室": "救急室", "内科外来の処置室": "内科（表）", "内科外来の処置室（裏口）": "内科（裏口）", "薬剤部の払い出し口": "薬剤部",
         "検査部の検体受付": "検体受付", "外来化学療法室の受付": "化学療法室"}
ROUTE_JA = {"green": "緑", "blue": "青（表）", "blue_back": "青（裏口）", "red": "赤"}
STATE = [("待ち", "台の前で待っている"), ("行き", "行き"), ("帰り", "帰り"), ("移る", "積む所へ移る")]
ROUTE_COL = {"green": "緑", "blue": "青", "red": "赤"}
TABLE = {"green": (101.6, 14.75), "blue": (12.0, 39.4), "red": (15.35, 11.0)}      # 積む所の台の前（hospital_h1.json の stops の端）
MINT, MINT_D = (79, 174, 142), (38, 120, 92)                                       # 依頼153 の色A（#4FAE8E）と、その濃い色
STAGES = ["依頼が出る", "待つ", "積む", "走る", "届け先で待つ", "受け取る"]
CAMJA = {c[0]: c[6] + ("" if c[0] == "top_all" else "・75°見下ろし・左30°") for c in cams143()}
CAMJA.update({n: CAMJA[c[0]] for n, c, tk in still_cams()})
RUN = None
DATA = {}


def legend157(im):
    """依頼157：pan140 の凡例に「清掃のカート」（灰色の箱＋押す青の職員）を足す"""
    d = ImageDraw.Draw(im)
    f = P.font(False, 24)
    items = ["患者・付き添い", "杖の人", "車いす", "スタッフ", "ストレッチャー", "清掃のカート", "ロボット"]
    x0, y0, x = 24, 24, 44
    widths = [int(d.textlength(s, font=f)) for s in items]
    total = sum(widths) + len(items) * 52 + 20
    d.rectangle([x0, y0, x0 + total, y0 + 56], fill=(242, 241, 238))
    y = y0 + 28
    for s, wdt in zip(items, widths):
        if s == "患者・付き添い":
            d.ellipse([x, y - 11, x + 22, y + 11], fill=P.YELLOW)
        elif s == "杖の人":
            d.ellipse([x, y - 11, x + 22, y + 11], fill=P.YELLOW)
            d.line([x + 25, y - 9, x + 25, y + 12], fill=P.DARK, width=4)
        elif s == "車いす":
            d.rectangle([x - 1, y - 13, x + 23, y + 13], fill=P.DARK)
            d.ellipse([x + 4, y - 7, x + 18, y + 7], fill=P.YELLOW)
        elif s == "スタッフ":
            d.ellipse([x, y - 11, x + 22, y + 11], fill=P.BLUE)
        elif s == "ストレッチャー":
            d.rectangle([x - 2, y - 8, x + 18, y + 8], fill=(222, 223, 225), outline=(150, 150, 150))
            d.ellipse([x + 19, y - 6, x + 31, y + 6], fill=P.BLUE)
        elif s == "清掃のカート":
            d.rectangle([x, y - 7, x + 12, y + 7], fill=(222, 223, 225), outline=(110, 110, 110))
            d.ellipse([x + 13, y - 6, x + 25, y + 6], fill=P.BLUE)
        else:
            d.ellipse([x, y - 11, x + 22, y + 11], fill=P.WHITE, outline=(60, 60, 60), width=2)
        d.text((x + 36, y), s, font=f, fill=P.INK, anchor="lm")
        x += wdt + 52


class PathCam:
    def __init__(self, proj, row, w, h, name):
        self.name = name
        self.w, self.h = w, h
        self.p = proj
        self.v = [[float(row["v%d%d" % (r, k)]) for k in range(4)] for r in range(4)]
        self.sx, self.sy = SW / w, H / h

    px = P.Cam.px
    ppm = P.Cam.ppm


def counts(ev, t0, t):
    c = {k: 0 for k in range(1, 7)}
    c["fast"] = c["wait2"] = c["room"] = 0
    for e in ev:
        te = float(e["t_s"])
        if te < t0 - 1e-6 or te > t + 1e-6: continue
        k = int(e["type"])
        if e["dir"] == "待ち":
            if k == 2: c["wait2"] += 1
            continue
        c[k] += 1
        if e.get("area") == "部屋の中" and k <= 5: c["room"] += 1
        if k == 2 and e.get("note") == "速いまま": c["fast"] += 1
    return c


def hand_lines(row, D, t):
    """パネルの「呼ぶ・荷物」の下の行（いま何をしているか）"""
    out = []
    h = row.get("hand", "")
    tn = row.get("hand_trip", "0")
    it = row.get("hand_items", "0")
    if h == "積んでいる": out.append(("積んでいる（便 %s・荷物 %s 個）" % (tn, it), True))
    elif h == "積む人が台で待つ": out.append(("積む人がロボットを待つ（便 %s）" % tn, True))
    elif h == "受け取りを待つ":
        out.append(("受け取る人を待つ %d 秒（目安 %d 秒）" % (int(float(row["hand_wait_s"])), int(round(float(row["hand_pw_s"])))), True))
    elif h == "受け取っている": out.append(("受け取っている（便 %s・荷物 %s 個）" % (tn, it), True))
    if row["leg_dir"] in ("行き",) and row["trip_no"] not in ("", "0"):
        out.append(("運んでいる荷物 %s 個（便 %s）" % (D["items"].get(row["trip_no"], "?"), row["trip_no"]), True))
    cw = row.get("carry_walk", "")
    if cw:
        out.append(("人が運ぶ回 %s%s" % (cw.rstrip("r"), "（受け取りに行く）" if cw.endswith("r") else "（人が運んでいる）"), True))
    if not out: out.append(("積む・受け取る人はいない", False))
    return out


def panel(im, row, ev, t, t0, title0, camja, summ, wide, D):
    d = ImageDraw.Draw(im)
    d.rectangle([SW, 0, W, H], fill=P.PANEL_BG)
    x0, xr = SW + 40, W - 40
    f_s, f_m, f_mb, f_big, f_num = P.font(False, 22), P.font(False, 25), P.font(True, 27), P.font(True, 50), P.font(True, 40)
    d.text((x0, 18), "病院 h1・人の動き・%s・%.1fm/秒・種%d" % (summ["plan"], summ["speed_mps"], summ["seed"]), font=f_s, fill=P.GRAY)
    d.text((x0, 46), "色 %s・車いすの場所 %s" % (P.SCHEME_JA["A"], "あり" if summ.get("wheelchair_marks") == "on" else "なし"), font=f_s, fill=P.GRAY)
    cfs = 22
    while cfs > 14 and d.textlength("カメラ %s" % camja, font=P.font(False, cfs)) > xr - x0: cfs -= 1     # 枠の幅に収まるまで字を小さくする
    d.text((x0, 74), "カメラ %s" % camja, font=P.font(False, cfs), fill=P.GRAY)
    d.text((x0, 102), P.clock(t), font=f_big, fill=P.INK)
    y = 176
    rs = int(row["rescue_staff"])
    d.text((x0, y), "ロボット 1台" + ("（助けのスタッフ %d 人）" % rs if rs else ""), font=f_mb, fill=P.INK)
    y += 40
    cur = row["leg_dir"]
    for key, ja in STATE:
        on = key == cur
        lab = ja
        if on and key == "待ち" and row.get("trip_no") not in ("", "0", None): lab = "届け先で待っている"
        d.text((x0 + 8, y), lab, font=f_m, fill=P.INK if on else (150, 150, 148))
        if on:
            d.ellipse([xr - 34, y + 2, xr - 4, y + 32], fill=P.WHITE, outline=(80, 80, 80), width=3)
            if key in ("行き", "帰り", "移る") and row["leg_from"]:
                d.text((xr - 44, y + 17), "%s→%s" % (SHORT.get(row["leg_from"], row["leg_from"]), SHORT.get(row["leg_to"], row["leg_to"])), font=f_s, fill=P.GRAY, anchor="rm")
            elif key == "待ち" and row["leg_from"]:
                d.text((xr - 44, y + 17), SHORT.get(row["leg_from"], row["leg_from"]), font=f_s, fill=P.GRAY, anchor="rm")
        y += 34
    y += 8
    d.line([x0, y, xr, y], fill=P.LINE, width=2)
    y += 10
    d.text((x0, y), "呼ぶ・荷物", font=f_mb, fill=P.INK)
    d.text((xr, y + 18), "待っている荷物・いちばん古い依頼の待ち", font=P.font(False, 16), fill=P.GRAY, anchor="rm")
    y += 38
    wt = D["req"].waiting(t)
    frs = D["req"].fresh(t)
    for rk in ("green", "blue", "red"):
        n, nu, old = wt.get(rk, [0, 0, 0.0])
        on = n > 0
        fm, fmu = frs.get(rk, [0, 0])
        d.text((x0 + 8, y), "%s（%s）" % (ROUTE_COL[rk], SHORT.get({"green": "救急室の処置室", "blue": "内科外来の処置室", "red": "薬剤部の払い出し口"}[rk])), font=f_m, fill=P.INK if on else (150, 150, 148))
        txt = ("%d 個%s・%d分%02d秒" % (n, "（至急 %d）" % nu if nu else "", int(old) // 60, int(old) % 60)) if on else ("依頼が出た" if fm else "0 個")
        if not on and fm: on, nu = True, fmu
        if nu:
            tw = d.textlength(txt, font=P.font(True, 25))
            d.rectangle([xr - tw - 10, y - 1, xr + 4, y + 31], fill=P.INK)
            d.text((xr - 2, y + 15), txt, font=P.font(True, 25), fill=P.WHITE, anchor="rm")
        else:
            d.text((xr, y + 15), txt, font=P.font(True, 25) if on else f_m, fill=P.INK if on else (150, 150, 148), anchor="rm")
        y += 34
    for txt, on in hand_lines(row, D, t):
        if on: d.rectangle([x0, y + 2, x0 + 8, y + 28], fill=MINT_D)
        d.text((x0 + 16, y + 15), txt, font=f_m, fill=P.INK if on else (150, 150, 148), anchor="lm")
        y += 34
    y += 6
    d.line([x0, y, xr, y], fill=P.LINE, width=2)
    y += 8
    d.text((x0, y + 6), "大廊下の人（x0〜70）", font=f_m, fill=P.INK)
    d.text((xr, y + 20), row["hall_people"], font=f_num, fill=P.INK, anchor="rm")
    y += 52
    d.line([x0, y, xr, y], fill=P.LINE, width=2)
    y += 10
    d.text((x0, y), title0, font=f_mb, fill=P.INK)
    y += 40
    c = counts(ev, t0, t)
    for k in range(1, 6):
        d.ellipse([x0 + 6, y + 5, x0 + 28, y + 27], outline=P.COLORS[k], width=4)
        d.text((x0 + 40, y + 16), "%d %s" % (k, P.TYPES[k]), font=f_m, fill=P.INK, anchor="lm")
        d.text((xr, y + 16), str(c[k]), font=P.font(True, 30), fill=P.INK, anchor="rm")
        y += 36
    d.ellipse([x0 + 6, y + 5, x0 + 28, y + 27], outline=P.COLORS[2], width=4)
    d.text((x0 + 40, y + 16), "台の前で待っている間のひやり", font=f_s, fill=P.INK, anchor="lm")
    d.text((xr, y + 16), str(c["wait2"]), font=P.font(True, 30), fill=P.INK, anchor="rm")
    y += 38
    d.rectangle([x0 + 9, y + 5, x0 + 27, y + 23], outline=P.FAST_COL, width=3)
    d.rectangle([x0 + 4, y, x0 + 32, y + 28], outline=P.FAST_COL, width=2)
    d.text((x0 + 44, y + 14), "うち速いままのひやり（走っている間） %d" % c["fast"], font=f_s, fill=P.INK, anchor="lm")
    y += 32
    d.rectangle([x0 + 5, y + 1, x0 + 31, y + 27], outline=(255, 210, 0), width=4)
    d.line([x0 + 9, y + 5, x0 + 27, y + 23], fill=P.OVER_COL, width=5)
    d.line([x0 + 9, y + 23, x0 + 27, y + 5], fill=P.OVER_COL, width=5)
    d.text((x0 + 44, y + 14), "止まりきれなかった %d" % c[6], font=f_s, fill=P.INK, anchor="lm")
    y += 32
    note = "輪＝問題の起きた所（10秒）" + ("・白い輪＝ロボット" if wide else "") + "・札＝依頼と受け渡し"
    d.text((x0, min(y + 2, H - 30)), note, font=P.font(False, 19), fill=P.GRAY)
    return c


def tag(d, at, text, fill, ink, edge, fnt, bar=None):
    """場面の札（at＝画素の点の上に、下向きの三角を付けて置く）。bar＝(割合, 色, 帯の枠の色)：札の下の帯（依頼161：帯の枠は札の枠と別の色）"""
    if at is None: return
    tw = d.textlength(text, font=fnt)
    x, y = at
    w2, hgt = tw / 2 + 10, 34
    box = [x - w2, y - 14 - hgt, x + w2, y - 14]
    d.polygon([(x - 8, y - 15), (x + 8, y - 15), (x, y - 3)], fill=edge)
    d.rounded_rectangle(box, radius=7, fill=fill, outline=edge, width=3)
    d.text((x, (box[1] + box[3]) / 2), text, font=fnt, fill=ink, anchor="mm")
    if bar is not None:
        fr, col, bedge = bar
        bx = [box[0], box[3] + 3, box[2], box[3] + 11]
        d.rectangle(bx, fill=(230, 228, 224), outline=bedge, width=1)
        d.rectangle([bx[0], bx[1], bx[0] + (bx[2] - bx[0]) * max(0.0, min(1.0, fr)), bx[3]], fill=col)


def marks158(im, cam, row, t, D):
    """依頼の印・積む／受け取る人・届け先で待つロボット・人が運んでいる補助者の札（見た目だけ）"""
    d = ImageDraw.Draw(im)
    fn = P.font(True, 22)
    wt = D["req"].waiting(t)
    fr = D["req"].fresh(t)
    for rk, (x, z) in TABLE.items():
        n, nu, old = wt.get(rk, [0, 0, 0.0])
        m, mu = fr.get(rk, [0, 0])
        if n > 0:
            txt = ("至急 依頼 %d" if nu or mu else "依頼 %d") % n + "・%d分%02d秒" % (int(old) // 60, int(old) % 60)
            u = nu or mu
        elif m > 0:
            txt = ("至急 " if mu else "") + "依頼が出た（いま積んでいる便へ）"     # 積み始めたあとに出た依頼は、出てから 10 秒だけ印を出す
            u = mu
        else:
            continue
        tag(d, cam.px(x, z, 2.8), txt, P.INK if u else P.WHITE, P.WHITE if u else P.INK, P.INK, fn)     # ロボットの札（高さ 1.3）より上に出す
    h = row.get("hand", "")
    if row.get("hand_x"):
        hp = cam.px(float(row["hand_x"]), float(row["hand_z"]), 1.9)
        lab = {"積んでいる": "積んでいる", "積む人が台で待つ": "積む人（ロボットを待つ）", "受け取りを待つ": "受け取りに向かう", "受け取っている": "受け取っている"}.get(h, h)
        if lab: tag(d, hp, lab, MINT, P.WHITE, P.INK, fn)     # 依頼161：札の枠は黒
    if h == "受け取りを待つ":
        rp = cam.px(float(row["robot_x"]), float(row["robot_z"]), 1.3)
        w_s, pw = float(row["hand_wait_s"]), float(row["hand_pw_s"])
        tag(d, rp, "受け取る人を待つ %d秒（目安 %d秒）" % (int(w_s), int(round(pw))), P.WHITE, P.INK, P.INK, fn, bar=(w_s / max(pw, 1.0), MINT, MINT_D))     # 依頼161：札の枠は黒・帯は緑のまま
    elif h in ("積んでいる", "受け取っている"):
        rp = cam.px(float(row["robot_x"]), float(row["robot_z"]), 1.3)
        tag(d, rp, "荷物 %s 個" % row.get("hand_items", "?"), P.WHITE, P.INK, P.INK, fn)
    elif row["leg_dir"] == "行き" and row["trip_no"] not in ("", "0"):
        rp = cam.px(float(row["robot_x"]), float(row["robot_z"]), 1.3)
        tag(d, rp, "荷物 %s 個" % D["items"].get(row["trip_no"], "?"), P.WHITE, P.INK, P.INK, fn)
    if row.get("carry_x"):
        cp = cam.px(float(row["carry_x"]), float(row["carry_z"]), 1.9)
        tag(d, cp, "人が運んでいる" if not row["carry_walk"].endswith("r") else "人が運ぶ（受け取りへ）", MINT, P.WHITE, P.INK, fn)


def stage(row, D, t, tn):
    """動画2：いまの段（STAGES の番号。-1＝依頼の前・6＝帰る・移る）"""
    rq = [q for q in D["req"].items if q["by"] == "robot" and q["trip"] is not None and q["trip"] + 1 == tn]
    h = row.get("hand", ""); ht = row.get("hand_trip", "0")
    if ht == str(tn):
        if h in ("積んでいる",): return 2
        if h == "受け取りを待つ": return 4
        if h == "受け取っている": return 5
    if row["trip_no"] == str(tn) and row["leg_dir"] == "行き": return 3
    if row["trip_no"] == str(tn) and row["leg_dir"] in ("帰り",): return 6
    tr = D["trips"].get(str(tn))
    if tr and tr["end_s"] and t >= float(tr["end_s"]) - 1e-6: return 6
    if tr and tr["arrive_b_s"] and t >= float(tr["arrive_b_s"]): return 6
    if not rq or t < min(q["t"] for q in rq): return 1 if h == "積む人が台で待つ" else -1
    if t < min(q["t"] for q in rq) + 3.0: return 0
    return 1


def legend_bottom(im):
    box = im.crop((0, H - 104, SW, H))
    legend157(box)
    im.paste(box, (0, H - 104))


def load(run, cam):
    rows = [r for r in csv.DictReader(open(os.path.join(run, "look139", "look_frames.csv"), encoding="utf-8")) if r["kind"] == "path" and r["cam"] == cam]
    paths = [r for r in csv.DictReader(open(os.path.join(run, "look139", "look_path.csv"), encoding="utf-8")) if r["cam"] == cam]
    base = os.path.dirname(os.path.dirname(run))
    meta = [r for r in csv.DictReader(open(os.path.join(base, "camspath241_meta.csv"), encoding="utf-8")) if r["cam"] == cam]
    assert len(rows) == len(paths), (len(rows), len(paths))
    if cam == "flowday":
        assert len(rows) == len(meta), (len(rows), len(meta))
        for a, b in zip(rows, meta):
            assert abs(float(a["t_s"]) - float(b["t_s"])) < 0.051, (a["t_s"], b["t_s"])
    j = json.load(open(os.path.join(run, "look139", "cam_%s.json" % cam), encoding="utf-8"))
    ev = list(csv.DictReader(open(os.path.join(run, "events.csv"), encoding="utf-8")))
    summ = json.load(open(os.path.join(run, "summary.json"), encoding="utf-8"))
    trips = {r["trip_no"]: r for r in csv.DictReader(open(os.path.join(run, "trips.csv"), encoding="utf-8"))}
    items = {str(i + 1): q["items"] for i, q in enumerate(TP.trips_param(run))}
    return dict(rows=rows, paths=paths, meta=meta, proj=j["projectionMatrix"], w=j["width"], h=j["height"], ev=ev, summ=summ, cam=cam, trips=trips,
                req=TP.Req(run), items=items, clips=TP.clip_trips(run))


def compose(i):
    D = DATA
    r, pr = D["rows"][i], D["paths"][i]
    t = float(r["t_s"])
    src = Image.open(os.path.join(RUN, "look139", r["file"])).convert("RGB").resize((SW, H), Image.LANCZOS)
    im = Image.new("RGB", (W, H), P.PANEL_BG)
    im.paste(src, (0, 0))
    if D["cam"].startswith("trip_"): return compose_clip(im, r, pr, t)
    m = D["meta"][i]
    a = float(m["near_a"])
    wide = a < 0.5
    cam = PathCam(D["proj"], pr, D["w"], D["h"], "w_" if wide else "n_")
    P.WIDE.add("w_")
    P.overlay(im, cam, D["ev"], t, P.font(True, 22), (float(r["robot_x"]), float(r["robot_z"])))
    marks158(im, cam, r, t, D)
    legend_bottom(im)
    sp = m["speed"]
    trip = r["trip_no"] if r["trip_no"] not in ("", "0") else ""
    sd = "西半分" if m["side"] == "west" else "東半分"
    camja = ("引き・%s・75°見下ろし・左30°" % sd) if a <= 0 else ("寄り・75°見下ろし・左30°・付いて行く" if a >= 1 else "引き⇄寄りに切り替え中")
    c = panel(im, r, D["ev"], t, 0.0, "7時30分からの1日の問題", camja, D["summ"], wide, D)
    route = ""
    if trip and trip in D["trips"]:
        route = "　%s便目・%s（%s→%s）" % (trip, ROUTE_JA.get(D["trips"][trip]["route"], ""), SHORT.get(D["trips"][trip]["from"], ""), SHORT.get(D["trips"][trip]["to"], ""))
    elif r["leg_dir"] == "移る":
        route = "　積む所へ移る（%s→%s）" % (SHORT.get(r["leg_from"], r["leg_from"]), SHORT.get(r["leg_to"], r["leg_to"]))
    t1 = "%s　病院の時刻の%s%s" % (P.clock(t), sp, route if sp == "5倍" else "")
    t2 = "1日の問題（走っている間）　1 急に止まった %d・2 ひやり %d・3 人がよけさせられた %d・4 立ち往生 %d・5 横切り %d（うち部屋の中 %d）" % (
        c[1], c[2], c[3], c[4], c[5], c["room"])
    P_banner(im, t1, t2, "台の前で待っている間のひやり %d" % c["wait2"])
    return im


def compose_clip(im, r, pr, t):
    """動画2：1便の通し（5倍・寄りで付いて行く）。上の帯に、いまの段（依頼が出る→待つ→積む→走る→届け先で待つ→受け取る）"""
    D = DATA
    key = "blue" if D["cam"] == "trip_b" else "red"
    tn, why = D["clips"][key]
    cam = PathCam(D["proj"], pr, D["w"], D["h"], "n_")
    P.overlay(im, cam, D["ev"], t, P.font(True, 22), None)
    marks158(im, cam, r, t, D)
    legend_bottom(im)
    tr = D["trips"][str(tn)]
    panel(im, r, D["ev"], t, 0.0, "7時30分からの1日の問題", "寄り・75°見下ろし・左30°・付いて行く", D["summ"], False, D)
    k = stage(r, D, t, tn)
    lay = Image.new("RGBA", (SW, 112), (249, 247, 244, 232))
    d = ImageDraw.Draw(lay)
    d.text((24, 28), "%s　病院の時刻の5倍　%s便目・%s（%s→%s）・荷物 %s 個" % (P.clock(t), tn, ROUTE_JA.get(tr["route"], ""), SHORT.get(tr["from"], ""), SHORT.get(tr["to"], ""), D["items"].get(str(tn), "?")),
           font=P.font(True, 30), fill=P.INK, anchor="lm")
    x = 24
    fb, fr = P.font(True, 26), P.font(False, 24)
    for j, st in enumerate(STAGES):
        on = j == k
        f = fb if on else fr
        tw = d.textlength(st, font=f)
        if on:
            d.rounded_rectangle([x - 8, 62, x + tw + 8, 100], radius=8, fill=MINT_D)
            d.text((x, 81), st, font=f, fill=P.WHITE, anchor="lm")
        else:
            d.text((x, 81), st, font=f, fill=P.INK if (k > j or k == 6) else (150, 150, 148), anchor="lm")
        x += tw + 16
        if j < len(STAGES) - 1:
            d.text((x, 81), "→", font=fr, fill=P.GRAY, anchor="lm")
            x += 34
    if k == 6: d.text((x + 10, 81), "（帰る・次の積む所へ移る）", font=fr, fill=P.GRAY, anchor="lm")
    elif k == -1: d.text((x + 10, 81), "（依頼の前）", font=fr, fill=P.GRAY, anchor="lm")
    im.paste(lay, (0, 0), lay)
    return im


def P_banner(im, text1, text2, text3=""):
    lay = Image.new("RGBA", (SW, 140 if text3 else 104), (249, 247, 244, 225))
    d = ImageDraw.Draw(lay)
    d.text((24, 31), text1, font=P.font(True, 34 if len(text1) < 40 else 30), fill=P.INK, anchor="lm")
    fs = 22
    while fs > 14 and d.textlength(text2, font=P.font(False, fs)) > SW - 40: fs -= 1          # 依頼158：枠の幅に収まるまで字を小さくする
    d.text((24, 80), text2, font=P.font(False, fs), fill=P.INK, anchor="lm")
    if text3:
        d.text((24, 116), text3, font=P.font(False, 22), fill=P.INK, anchor="lm")
    im.paste(lay, (0, 0), lay)


def still(run, cam, out, what):
    D = load(run, cam)
    assert len(D["rows"]) == 1, (cam, len(D["rows"]))
    r, pr = D["rows"][0], D["paths"][0]
    t = float(r["t_s"])
    src = Image.open(os.path.join(run, "look139", r["file"])).convert("RGB").resize((SW, H), Image.LANCZOS)
    im = Image.new("RGB", (W, H), P.PANEL_BG)
    im.paste(src, (0, 0))
    wide = not cam.startswith("n_")
    pc = PathCam(D["proj"], pr, D["w"], D["h"], "w_" if wide else "n_")
    P.WIDE.add("w_")
    P.overlay(im, pc, D["ev"], t, P.font(True, 22), (float(r["robot_x"]), float(r["robot_z"])))
    marks158(im, pc, r, t, D)
    legend_bottom(im)
    panel(im, r, D["ev"], t, 0.0, "7時30分からの1日の問題", CAMJA[cam], D["summ"], wide, D)
    P_banner(im, "%s　%s" % (P.clock(t), CAMJA[cam].split("・")[0] + "・" + CAMJA[cam].split("・")[1] if "・" in CAMJA[cam] else CAMJA[cam]), what)
    f = os.path.join(out, "still241_%s.png" % cam)
    im.save(f)
    return f, t


def init(run, cam):
    global RUN, DATA
    RUN = run
    DATA = load(run, cam)


def seg(args):
    run, cam, lo, hi, dst = args
    init(run, cam)
    p = subprocess.Popen([P.FFMPEG, "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "%dx%d" % (W, H), "-framerate", "25",
                          "-i", "-", "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "18", "-g", "50", dst], stdin=subprocess.PIPE)
    for i in range(lo, hi):
        p.stdin.write(compose(i).tobytes())
    p.stdin.close()
    p.wait()
    return dst


def main():
    mode, run = sys.argv[1], sys.argv[2]
    if mode == "stills":
        out = sys.argv[3]
        os.makedirs(out, exist_ok=True)
        base = os.path.dirname(os.path.dirname(run))
        whats = {r["cam"]: r["what"] for r in csv.DictReader(open(os.path.join(base, "camspath241_stills.csv"), encoding="utf-8"))}
        for c, _, _ in still_cams():
            if c in whats: print(*still(run, c, out, whats[c]))
        return
    cam = sys.argv[3]
    if mode == "frame":
        init(run, cam)
        compose(int(sys.argv[4])).save(sys.argv[5])
        print(sys.argv[5], DATA["rows"][int(sys.argv[4])]["t_s"])
        return
    dst = sys.argv[4]
    nproc = int(sys.argv[5]) if len(sys.argv) > 5 else 8
    n = len(load(run, cam)["rows"])
    tmp = tempfile.mkdtemp(prefix="pan179_", dir=os.path.dirname(os.path.abspath(dst)))
    k = max(1, math.ceil(n / (nproc * 4)))
    jobs = [(run, cam, lo, min(n, lo + k), os.path.join(tmp, "s%04d.mp4" % (lo // k))) for lo in range(0, n, k)]
    with Pool(nproc) as pool:
        parts = pool.map(seg, jobs, chunksize=1)
    lst = os.path.join(tmp, "list.txt")
    open(lst, "w").write("".join("file '%s'\n" % q for q in parts))
    subprocess.check_call([P.FFMPEG, "-y", "-loglevel", "error", "-f", "concat", "-safe", "0", "-i", lst, "-c", "copy", "-movflags", "+faststart", dst])
    for q in parts: os.remove(q)
    os.remove(lst); os.rmdir(tmp)
    print(dst, n, "コマ", n / 25.0, "秒")


if __name__ == "__main__":
    main()
