#!/usr/bin/env python3
"""依頼246（pan245.py の写し：下の凡例の「ロボット」の印（映像の印の 0.75 倍）も、映像の印と同じ白いふちなしにする。大きさ・置き場所・ほかの凡例・映像の中の絵は同じ。静止画は still246_…）。もとの説明：依頼245（pan244.py の写し：(1) 緑の札「積んでいる」の黒い縁を消す（枠と三角を札と同じ緑にする。大きさは同じ）。
  (2) ▼と札「ロボット」の白いふちを消す（形の大きさ・置き方・動きは同じ。下の凡例の印は依頼244 のまま＝白いふちあり）。
  (3) 札の上に置くと上の帯に隠れるとき（依頼243・244 では札の横にずらしたコマ）だけ、札「ロボット」をロボットの下に出し、上向きの▲でロボットを指す（案A）。
      ▲の先はロボットの床の円のいちばん下の画素の GAP 下。上下の動きは同じ幅・同じ速さで、ロボットから離れる向き（下）へ。札を横にずらす置き方はやめる。
  ほかは依頼244 のまま。読むファイルは camspath244_…（依頼244 の写し）、静止画は still245_…）。もとの説明：依頼244（pan243.py の写し：本の映像の「窓に映る範囲」の枠を、画面の上でゆがまない四角（窓と同じ 1:1・真ん中はロボット・広さは窓に映る横 12 m）にする。
  ロボットのまわりの白い輪を出さない（30倍・5倍・窓）。パネルの下の注から「白い輪＝ロボット」を消し、下の凡例の「ロボット」の印を ○ から▼と札「ロボット」の形にする。
  ほか（▼と札・窓・帯・パネル・問題の輪・札・ほかの凡例）は依頼243 のまま。読むファイルは camspath244_…、静止画は still244_…）。もとの説明：依頼243（pan241.py の写し：ロボットの真上の▼と札「ロボット」（30倍・5倍の両方）と、30倍の引きのときだけ右下の拡大の窓（2つめのカメラ win の絵）を足す。
  ▼と札は1つの形（札の下の辺から▼が出る）で、画面の上で大きさは変えない。動画の時間で 1 秒に 1 往復・幅 BOB_PX 上下に動く。
  今の札（tag() で描いた札）と重なるときは、その札の上へずらす。
  窓は 380×380（黒の枠 4px）。本の映像には窓に映っている床の範囲を黒の細い枠で示し、窓と細い線でつなぐ。
  ロボット（と▼）が窓に隠れる位置に来たら、窓を左下へ移す（戻すのは右下の窓から WIN_BACK_PX 離れたとき）。
  ほか（帯・パネル・輪・札・凡例）は依頼241 のまま。読むファイルは camspath243_…、静止画は still243_…）。もとの説明：依頼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, ImageFilter
import numpy as np
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 = {}

# ---------------- 依頼243：▼と札「ロボット」・拡大の窓 ----------------
ROBOT_H = 1.081                 # ロボットの高さ（params の W3 の h。HospitalLook の見た目の円柱の上の面）
TRI_W, TRI_H = 36, 20           # ▼の横・高さ（px）
TAG_FS, TAG_H, TAG_PAD, TAG_R = 22, 34, 12, 8     # 札「ロボット」の字・高さ・左右の余白・角の丸み
EDGE = 2                        # 白いふち（px）。依頼245：映像の印では描かない。依頼246：凡例の印でも描かない（絵の大きさを決める余白にだけ使う）
ROBOT_R = 0.2745                # 依頼245：ロボットの円の半径（直径 0.549。HospitalLook の見た目の円柱）
GAP = 6                         # ▼の先とロボットの上の面（または下の札）との間（px）
BOB_PX, BOB_HZ = 10, 1.0        # 上下の動き：幅 10px・動画の時間で 1 秒に 1 往復
WIN, WIN_EDGE = 380, 4          # 窓（外の大きさ）・黒の枠
WIN_PAD = 16                    # 窓と映像の右／左の端・凡例の帯との間
LEG_TOP = H - 104               # 下の凡例の帯の上の端（legend_bottom）
WIN_HIDE_PX = 12                # ロボット（と▼）がこの余白を含めて窓に入ったら隠れたとみる
WIN_BACK_PX = 60                # 左下へ移したあと、右下の窓からこれだけ離れたら右下へ戻す
TAGS = []
WINBOX = [None]                 # 依頼245：このコマの拡大の窓の箱（▲と札が窓と重なったかを数えるだけ）
BANNER_DAY, BANNER_CLIP = 140, 112      # 上の帯の高さ（1日の早回し：3行＝P_banner の text3 あり・1便の通し：compose_clip）


def _sprite(edge_on=True, up=False):
    """▼と札をつないだ1つの形（黒・白いふち）。返す：RGBA の絵、▼の先の点（絵の中の x, y）。
    依頼245：edge_on=False で白いふちなし（絵の大きさは同じ）。up=True で上下を返した形（上に▲・下に札。字は正しい向き）"""
    f = P.font(True, TAG_FS)
    tw = int(math.ceil(ImageDraw.Draw(Image.new("L", (4, 4))).textlength("ロボット", font=f)))
    bw = tw + 2 * TAG_PAD
    m = EDGE + 2
    w, h = bw + 2 * m, TAG_H + TRI_H + 2 * m
    cx = w / 2.0
    mask = Image.new("L", (w, h), 0)
    d = ImageDraw.Draw(mask)
    d.rounded_rectangle([m, m, m + bw - 1, m + TAG_H - 1], radius=TAG_R, fill=255)
    yb = m + TAG_H - 2                                   # 札の下の辺に重ねて、すき間を作らない
    d.polygon([(cx - TRI_W / 2.0, yb), (cx + TRI_W / 2.0, yb), (cx, m + TAG_H + TRI_H - 1)], fill=255)
    if up: mask = mask.transpose(Image.FLIP_TOP_BOTTOM)
    edge = mask.filter(ImageFilter.MaxFilter(2 * EDGE + 1)) if edge_on else mask
    im = Image.new("RGBA", (w, h), (255, 255, 255, 0))
    im.putalpha(edge)
    blk = Image.new("RGBA", (w, h), (12, 12, 12, 255))
    im.paste(blk, (0, 0), mask)
    if up:
        ImageDraw.Draw(im).text((cx, h - 1 - m - TAG_H / 2.0 + 1), "ロボット", font=f, fill=(255, 255, 255, 255), anchor="mm")
        return im, (cx, h - 1 - (m + TAG_H + TRI_H - 1))
    ImageDraw.Draw(im).text((cx, m + TAG_H / 2.0), "ロボット", font=f, fill=(255, 255, 255, 255), anchor="mm")
    return im, (cx, m + TAG_H + TRI_H - 1)


SPRITE, TIP = None, None
LEG_SCALE = 0.75                # 依頼244：凡例の▼と札「ロボット」（映像の印の 0.75 倍。凡例の帯の高さ 56 に入れる）
_LEG = []


def legend_sprite():
    if not _LEG:
        LS, _ = _sprite(edge_on=False)                      # 依頼246：凡例も映像の印と同じ白いふちなし（絵の大きさは同じ）
        w, h = LS.size
        _LEG.append(LS.resize((int(round(w * LEG_SCALE)), int(round(h * LEG_SCALE))), Image.LANCZOS))
    return _LEG[0]


def bob(i):
    """動画のコマ i（25 コマ/秒）の上下の動き（0〜BOB_PX、上へ）"""
    return BOB_PX * 0.5 * (1.0 - math.cos(2.0 * math.pi * BOB_HZ * i / 25.0))


SIDE = [0, 0]                   # 札の上に置くと上の帯に隠れるので、札の横に置いたコマの数（依頼245 では使わない）
SPRITE_UP, TIP_UP = None, None  # 依頼245：▲と札（ロボットの下）
LOW = {"n": 0, "legend": 0, "tags": 0, "win": 0, "frames": []}     # 依頼245：下に出したコマの数・凡例の帯／ほかの札／窓と重なったコマの数（数えるだけ）


def marker(im, top, i, avoid, ymin=0, low=None):
    """▼の先を top（ロボットの上の面の真上の画素）の GAP 上に置く。avoid の箱（今の札）と重なるときは、その札の上へずらす。
    ずらすと形の上の端（上下に動く分を含む）が ymin（上の帯の下の端）より上に出て隠れるときだけ、ずらさずに、重なる札の左（入らなければ右）に、帯にかからない高さで置く。返す：置いた形の箱"""
    global SPRITE, TIP, SPRITE_UP, TIP_UP
    if top is None: return None
    if SPRITE is None: SPRITE, TIP = _sprite(edge_on=False)          # 依頼245：白いふちなし
    if SPRITE_UP is None: SPRITE_UP, TIP_UP = _sprite(edge_on=False, up=True)
    sw, sh = SPRITE.size
    x = top[0]
    ytip = top[1] - GAP
    box = lambda x, ytip: [x - TIP[0], ytip - TIP[1], x - TIP[0] + sw, ytip - TIP[1] + sh]
    hits = lambda bx: [b for b in avoid if b[0] - 4 < bx[2] and bx[0] < b[2] + 4 and b[1] - 4 < bx[3] and bx[1] < b[3] + 4]
    for _ in range(20):
        hit = hits(box(x, ytip))
        if not hit: break
        ytip = min(b[1] for b in hit) - GAP
    if ytip - TIP[1] - BOB_PX < ymin and ytip != top[1] - GAP and low is not None:     # 依頼245：上の帯に隠れる → ロボットの下に▲と札（案A）。重なりはよけずに数える
        uw, uh = SPRITE_UP.size
        ytip = low[1] + GAP + bob(i)                                   # 上下の動きはロボットから離れる向き（下）
        ox, oy = int(round(low[0] - TIP_UP[0])), int(round(ytip - TIP_UP[1]))
        im.paste(SPRITE_UP, (ox, oy), SPRITE_UP)
        bx = [ox, oy, ox + uw, oy + uh]
        LOW["n"] += 1; LOW["frames"].append(i)
        if bx[3] > LEG_TOP: LOW["legend"] += 1
        if hits(bx): LOW["tags"] += 1
        if WINBOX[0] is not None and _over(bx, WINBOX[0], 0): LOW["win"] += 1
        return bx
    ytip -= bob(i)
    ox, oy = int(round(x - TIP[0])), int(round(ytip - TIP[1]))
    im.paste(SPRITE, (ox, oy), SPRITE)
    return [ox, oy, ox + sw, oy + sh]


def WinCam(proj, row, w, h, inner):
    """窓のカメラ（744×744 を窓の中 372×372 に縮める）"""
    c = PathCam(proj, row, w, h, "win")
    c.sx = c.sy = inner / float(w)
    return c


def floor_quad(proj, row):
    """窓のカメラに映る床（y=0）の四隅（左上・右上・右下・左下の順。絵の隅から床へ下ろした点）"""
    V = np.array([[float(row["v%d%d" % (r, k)]) for k in range(4)] for r in range(4)])
    Pm = np.array(proj, dtype=float)
    inv = np.linalg.inv(Pm @ V)
    out = []
    for nx, ny in ((-1, 1), (1, 1), (1, -1), (-1, -1)):
        a = inv @ np.array([nx, ny, -1.0, 1.0]); a = a[:3] / a[3]
        b = inv @ np.array([nx, ny, 1.0, 1.0]); b = b[:3] / b[3]
        k = a[1] / (a[1] - b[1])
        q = a + k * (b - a)
        out.append((q[0], q[2]))
    return out


def win_square(cam, wp):
    """依頼244：本の映像に描く窓の範囲の枠。画面の上で縦横がまっすぐな正方形（窓と同じ 1:1）。
    真ん中＝窓のカメラの注視点（＝そのコマのロボットの位置・床）を本のカメラで画素にした点。
    一辺＝窓に映る横 WIN_W_M（注視点の所で 12 m）：注視点から窓のカメラの右向き（水平）に ±6 m の2点を本のカメラで画素にした間の長さ。
    返す：四隅（左上・右上・右下・左下）。画面に出ないときは None を含む"""
    tx, tz = float(wp["tx"]), float(wp["tz"])
    rx, rz = float(wp["v00"]), float(wp["v02"])                  # 窓のカメラの右向き（view の1行目。水平なので y の成分は 0）
    n = math.hypot(rx, rz)
    rx, rz = rx / n, rz / n
    c, a, b = cam.px(tx, tz), cam.px(tx - rx * WIN_W_M / 2.0, tz - rz * WIN_W_M / 2.0), cam.px(tx + rx * WIN_W_M / 2.0, tz + rz * WIN_W_M / 2.0)
    if c is None or a is None or b is None: return [None]
    h = math.hypot(b[0] - a[0], b[1] - a[1]) / 2.0
    SQ.append(2 * h)
    return [(c[0] - h, c[1] - h), (c[0] + h, c[1] - h), (c[0] + h, c[1] + h), (c[0] - h, c[1] + h)]


WIN_W_M = 12.0                  # 依頼244：窓に映る横（win243.py の WIN_W_M）
SQ = []                         # 依頼244：描いた枠の一辺（数えるだけ）


def win_rect(side):
    x0 = SW - WIN_PAD - WIN if side == "R" else WIN_PAD
    y1 = LEG_TOP - WIN_PAD
    return [x0, y1 - WIN, x0 + WIN, y1]


def robot_box(cam, x, z):
    """ロボット（輪の大きさ）と、その上の▼・札の出る所の箱（窓に隠れるかを見るため。札の分はずらす前の位置）"""
    p0, p1 = cam.px(x, z), cam.px(x, z, ROBOT_H)
    if p0 is None or p1 is None: return None
    global SPRITE, TIP
    if SPRITE is None: SPRITE, TIP = _sprite(edge_on=False)     # 依頼245：白いふちなし（大きさは同じ）
    sh = SPRITE.size[1]
    return [p0[0] - 30, p1[1] - GAP - BOB_PX - sh, p0[0] + 30, p0[1] + 20]


def _over(a, b, pad):
    return a[0] < b[2] + pad and b[0] - pad < a[2] and a[1] < b[3] + pad and b[1] - pad < a[3]


def win_sides(D):
    """1日の早回しのコマごとの窓の位置（R＝右下・L＝左下・None＝出さない）。前のコマから順に決める"""
    sides, side, moves, back = [], "R", 0, 0
    for i, (r, pr, m) in enumerate(zip(D["rows"], D["paths"], D["meta"])):
        if m["speed"] != "30倍":
            sides.append(None); side = "R"; continue
        cam = PathCam(D["proj"], pr, D["w"], D["h"], "w_")
        rb = robot_box(cam, float(r["robot_x"]), float(r["robot_z"]))
        if rb is not None:
            if _over(rb, win_rect(side), WIN_HIDE_PX):
                side = "L" if side == "R" else "R"
                if side == "L": moves += 1
                else: back += 1
            elif side == "L" and not _over(rb, win_rect("R"), WIN_BACK_PX):
                side = "R"; back += 1
        sides.append(side)
    return sides, moves, back


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 + legend_sprite().size[0] - 30     # 依頼244：ロボットの印が ○（36）より横に長い分
    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:                                   # 依頼244：ロボットの印は ○ でなく、▼と札「ロボット」の形（映像の印を LEG_SCALE に縮めた物）
            lg = legend_sprite()
            im.paste(lg, (x - 4, int(round(y - lg.size[1] / 2.0))), lg)
            d.text((x + lg.size[0] + 6, y), s, font=f, fill=P.INK, anchor="lm")
            x += wdt + 52
            continue
        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秒）・札＝依頼と受け渡し"     # 依頼244：「白い輪＝ロボット」を消す
    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]
    TAGS.append([box[0], box[1], box[2], box[3] + (11 if bar is not None else 0)])     # 依頼243：▼と札「ロボット」をよけるため（三角を含む）
    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, MINT if lab == "積んでいる" else P.INK, fn)     # 依頼161：札の枠は黒。依頼245：「積んでいる」だけ黒い縁を消す（枠と三角を札と同じ緑に）
    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, "camspath244_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))}
    D = 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))
    if cam == "flowday":                                  # 依頼243：拡大の窓（win）。30倍のコマと同じ時刻に1枚ずつ
        wr = [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"] == "win"]
        wp = [r for r in csv.DictReader(open(os.path.join(run, "look139", "look_path.csv"), encoding="utf-8")) if r["cam"] == "win"]
        assert len(wr) == len(wp) == sum(1 for m in meta if m["speed"] == "30倍"), (len(wr), len(wp))
        wj = json.load(open(os.path.join(run, "look139", "cam_win.json"), encoding="utf-8"))
        D["win"] = {r["t_s"]: (r, p) for r, p in zip(wr, wp)}
        D["win_proj"], D["win_w"], D["win_h"] = wj["projectionMatrix"], wj["width"], wj["height"]
        D["sides"], D["moves"], D["backs"] = win_sides(D)
    return D


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, i)
    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.overlay(im, cam, D["ev"], t, P.font(True, 22), None)     # 依頼244：ロボットの白い輪を出さない（robot_xz を渡さない）
    del TAGS[:]
    marks158(im, cam, r, t, D)
    WINBOX[0] = win_rect(D["sides"][i]) if D["sides"][i] is not None else None
    marker(im, cam.px(float(r["robot_x"]), float(r["robot_z"]), ROBOT_H), i, TAGS, BANNER_DAY + 4, robot_low(cam, r))     # 依頼243・245
    if D["sides"][i] is not None: window(im, cam, r, i, D["sides"][i])               # 依頼243：30倍の引きのときだけ
    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 robot_low(cam, r):
    """依頼245：ロボットの床の円（半径 ROBOT_R・高さ 0）のいちばん下の画素（x はその点）"""
    x, z = float(r["robot_x"]), float(r["robot_z"])
    ps = [cam.px(x + ROBOT_R * math.cos(a), z + ROBOT_R * math.sin(a), 0.0) for a in (2 * math.pi * k / 32 for k in range(32))]
    ps = [p for p in ps if p is not None]
    if not ps: return None
    c = cam.px(x, z, 0.0)
    return (c[0] if c else max(ps, key=lambda p: p[1])[0], max(p[1] for p in ps))


def window(im, cam, r, i, side):
    """依頼243：拡大の窓（右下 R・左下 L）。本の映像に窓の範囲の枠と、窓へつなぐ線を描いてから窓を置く"""
    D = DATA
    wr, wp = D["win"][r["t_s"]]
    inner = WIN - 2 * WIN_EDGE
    q = win_square(cam, wp)                                                            # 依頼244：台形（床へ下ろした4点）でなく画面の上の四角
    x0, y0, x1, y1 = win_rect(side)
    d = ImageDraw.Draw(im)
    if all(p is not None for p in q):
        corners = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
        qc = (sum(p[0] for p in q) / 4.0, sum(p[1] for p in q) / 4.0)
        wc = ((x0 + x1) / 2.0, (y0 + y1) / 2.0)
        a = min(q, key=lambda p: (p[0] - wc[0]) ** 2 + (p[1] - wc[1]) ** 2)              # 見本 C のとおり1本：枠の窓にいちばん近い隅 → 窓の枠にいちばん近い隅
        b = min(corners, key=lambda p: (p[0] - qc[0]) ** 2 + (p[1] - qc[1]) ** 2)
        d.line([a, b], fill=P.INK, width=2)
        d.line(q + [q[0]], fill=P.INK, width=2, joint="curve")
    src = Image.open(os.path.join(RUN, "look139", wr["file"])).convert("RGB").resize((inner, inner), Image.LANCZOS)
    wc = WinCam(D["win_proj"], wp, D["win_w"], D["win_h"], inner)
    marker(src, wc.px(float(wr["robot_x"]), float(wr["robot_z"]), ROBOT_H), i, [])
    d.rectangle([x0, y0, x1 - 1, y1 - 1], fill=P.INK)
    im.paste(src, (x0 + WIN_EDGE, y0 + WIN_EDGE))


def compose_clip(im, r, pr, t, i):
    """動画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)
    del TAGS[:]
    marks158(im, cam, r, t, D)
    WINBOX[0] = None
    marker(im, cam.px(float(r["robot_x"]), float(r["robot_z"]), ROBOT_H), i, TAGS, BANNER_CLIP + 4, robot_low(cam, r))     # 依頼243・245
    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.overlay(im, pc, D["ev"], t, P.font(True, 22), None)     # 依頼244：ロボットの白い輪を出さない
    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, "still246_%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)
    LOW.update(n=0, legend=0, tags=0, win=0, frames=[])     # 依頼245：同じ作業の係が次の区切りを受けても数えを足し込まない
    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, {k: LOW[k] for k in ("n", "legend", "tags", "win")}, list(LOW["frames"])     # 依頼245：▲と札を下に出した数


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, "camspath244_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"])
    if cam == "flowday":
        D0 = load(run, cam)
        print("窓：30倍のコマ %d・左下へ移した回数 %d・右下へ戻した回数 %d・左下のコマ %d" % (sum(1 for x in D0["sides"] if x), D0["moves"], D0["backs"], sum(1 for x in D0["sides"] if x == "L")))
    tmp = tempfile.mkdtemp(prefix="pan246_", 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:
        res = pool.map(seg, jobs, chunksize=1)
    parts = [q[0] for q in res]
    tot = {k: sum(q[1][k] for q in res) for k in ("n", "legend", "tags", "win")}
    fr = [i for q in res for i in q[2]]
    print("依頼245：▲と札をロボットの下に出したコマ %(n)d・凡例の帯と重なった %(legend)d・ほかの札と重なった %(tags)d・拡大の窓と重なった %(win)d" % tot)
    with open(dst + ".low246.txt", "w", encoding="utf-8") as fo:
        fo.write("n %(n)d legend %(legend)d tags %(tags)d win %(win)d\n" % tot)
        fo.write(" ".join(map(str, fr)) + "\n")
    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()
