#!/usr/bin/env python3
"""依頼312（pan272.py の写し。パネルの題を「（依頼312）」にしただけ）／依頼272：清掃の立体の撮影（-c272Look on の回の look272/）に、病院の依頼245 と同じ形の印・窓・上の帯・下の凡例と、
依頼269 と同じ中身の右のパネルを付けて 1920×1080 にする。

見本（病院）：hospital/20261120_flow245/tools/pan245.py（▼と札・▲と札・拡大の窓・窓の範囲の四角・上の帯）と pan140.py（字・色・画素への移し方・パネルの形）。
  値と形は写した（W 1920・H 1080・左 1360・25 コマ/秒・▼ 36×20・札の字 22・高さ 34・上下の動き 10px／1秒・窓 380（枠 4）・帯 140 など）。
違うのは：
  ロボットは2台なので、札は「ロボット1」「ロボット2」（号機の番号を足した）。▼の先＝箱の上の面の真上（高さ 0.619）
  ▲の先＝箱の床の外形のいちばん下の画素（半径 ROBOT_R＝長い辺の半分で数える円）
  窓は 30倍の引き（全長を含む）のときだけ。窓の台＝カメラの道（paths272）の robot（問題に近い台、なければ1号機）
  パネルの中身は依頼269 の vid269.py と同じ（台ごとの状態と水・清掃員と警備員の状態・拭けた割合・引っかかった・人を呼んだ・立ち往生で人が動かした・拭けた割合の線）
  問題の輪・場面の札（病院だけのもの）は描かない

  python3 pan272.py video <回のフォルダ> <meta.csv> <題> <出力.mp4> [並べる数]
  python3 pan272.py frame <回のフォルダ> <meta.csv> <題> <コマ番号> <出力.png>
  python3 pan272.py still <回のフォルダ> <カメラ名> <題> <何を撮ったか> <出力.png>
"""
import bisect, csv, json, math, os, subprocess, sys, tempfile
from multiprocessing import Pool
from PIL import Image, ImageDraw, ImageFilter, ImageFont
import numpy as np

FFMPEG = "/opt/homebrew/Caskroom/miniforge/base/envs/ros_env/bin/ffmpeg"
FONT_B = os.path.expanduser("~/Library/Fonts/NotoSansJP-Bold.otf")
FONT_R = os.path.expanduser("~/Library/Fonts/NotoSansJP-Regular.otf")
W, H, SW = 1920, 1080, 1360
YELLOW, BLUE, WHITE, DARK = (250, 204, 33), (23, 97, 230), (255, 255, 255), (77, 79, 84)
INK, GRAY, PANEL_BG, LINE = (29, 29, 27), (110, 110, 108), (249, 247, 244), (200, 198, 194)
QUIET = (150, 150, 148)
BAD = (220, 30, 40)                       # 病院の問題1の色（止まっている・待っている）
PAINT_ROBOT = (169, 213, 238)             # 立体の床の上に出た塗りの色（試しの絵の画素）
PAINT_STAFF = (146, 169, 200)             # 青（試しの絵の画素）
FPS = 25

ROBOT_H = 0.619
ROBOT_R = 0.2925
TRI_W, TRI_H = 36, 20
TAG_FS, TAG_H, TAG_PAD, TAG_R = 22, 34, 12, 8
EDGE = 2
GAP = 6
BOB_PX, BOB_HZ = 10, 1.0
WIN, WIN_EDGE = 380, 4
WIN_PAD = 16
LEG_TOP = H - 104
WIN_HIDE_PX = 12
WIN_BACK_PX = 60
WIN_W_M = 12.0
BANNER = 140
LEG_SCALE = 0.75
BADSTATE = ("待ち", "引っかかり", "止まっている", "人を待つ")

_F = {}


def font(b, s):
    k = (b, s)
    if k not in _F: _F[k] = ImageFont.truetype(FONT_B if b else FONT_R, s)
    return _F[k]


def clock(t):
    s = int(math.floor(22 * 3600 + t + 1e-6)) % 86400
    return "%d時%02d分%02d秒" % (s // 3600, s % 3600 // 60, s % 60)


def hm(t):
    s = int(math.floor(22 * 3600 + t + 1e-6)) % 86400
    return "%d:%02d" % (s // 3600, s % 3600 // 60)


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

    def px(self, x, z, y=0.0):
        P = (x, y, z, 1.0)
        c = [sum(self.v[r][k] * P[k] for k in range(4)) for r in range(4)]
        q = [sum(self.p[r][k] * c[k] for k in range(4)) for r in range(4)]
        if q[3] <= 1e-6: return None
        return (q[0] / q[3] + 1) / 2 * self.w * self.sx, (1 - q[1] / q[3]) / 2 * self.h * self.sy


# ---------------- ▼と札（病院の依頼245 の形：白いふちなし。凡例だけ白いふちあり）----------------

_SPR = {}


def _sprite(text, edge_on=True, up=False):
    k = (text, edge_on, up)
    if k in _SPR: return _SPR[k]
    f = font(True, TAG_FS)
    tw = int(math.ceil(ImageDraw.Draw(Image.new("L", (4, 4))).textlength(text, 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), text, font=f, fill=(255, 255, 255, 255), anchor="mm")
        r = (im, (cx, h - 1 - (m + TAG_H + TRI_H - 1)))
    else:
        ImageDraw.Draw(im).text((cx, m + TAG_H / 2.0), text, font=f, fill=(255, 255, 255, 255), anchor="mm")
        r = (im, (cx, m + TAG_H + TRI_H - 1))
    _SPR[k] = r
    return r


def legend_sprite():
    LS, _ = _sprite("ロボット")
    w, h = LS.size
    return LS.resize((int(round(w * LEG_SCALE)), int(round(h * LEG_SCALE))), Image.LANCZOS)


def bob(i):
    return BOB_PX * 0.5 * (1.0 - math.cos(2.0 * math.pi * BOB_HZ * i / float(FPS)))


LOW = {"n": 0}


def _hits(bx, avoid):
    return [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]


def marker(im, text, top, i, avoid, ymin=0, low=None):
    """▼の先を top の GAP 上に置く（病院の依頼245 の marker と同じ決め方）。avoid の箱（ほかの台の印）と重なるときはその上へずらす。
    上の帯に隠れるときは、ロボットの下に▲と札を出す（上下の動きは下へ）"""
    if top is None: return None
    spr, tip = _sprite(text, edge_on=False)
    sw, sh = spr.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]
    for _ in range(20):
        hit = _hits(box(x, ytip), avoid)
        if not hit: break
        ytip = min(b[1] for b in hit) - GAP
    if ytip - tip[1] - BOB_PX < ymin and low is not None:
        su, tu = _sprite(text, edge_on=False, up=True)
        uw, uh = su.size
        yt = low[1] + GAP + bob(i)
        ox, oy = int(round(low[0] - tu[0])), int(round(yt - tu[1]))
        im.paste(su, (ox, oy), su)
        LOW["n"] += 1
        return [ox, oy, ox + uw, oy + uh]
    ytip -= bob(i)
    ox, oy = int(round(x - tip[0])), int(round(ytip - tip[1]))
    im.paste(spr, (ox, oy), spr)
    return [ox, oy, ox + sw, oy + sh]


def robot_low(cam, x, 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 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
    sh = _sprite("ロボット1", edge_on=False)[0].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_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 win_square(cam, wp):
    """窓の範囲の枠（病院の依頼244）：画面の上で縦横がまっすぐな正方形。真ん中＝窓のカメラの注視点、一辺＝注視点の所で横 12 m"""
    tx, tz = float(wp["tx"]), float(wp["tz"])
    rx, rz = float(wp["v00"]), float(wp["v02"])
    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
    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)]


# ---------------- 読む ----------------

def nearest_le(keys, t):
    i = bisect.bisect_right(keys, t + 1e-6) - 1
    return keys[max(i, 0)]


def load(run, meta=None):
    lk = os.path.join(run, "look272")
    fr = list(csv.DictReader(open(os.path.join(lk, "look_frames.csv"), encoding="utf-8")))
    pa = list(csv.DictReader(open(os.path.join(lk, "look_path.csv"), encoding="utf-8")))
    assert len(fr) == len(pa)
    D = dict(run=run, lk=lk, fr=fr, pa=pa)
    rt, pt = {}, {}
    for r in csv.DictReader(open(os.path.join(run, "robot_track.csv"), encoding="utf-8")): rt.setdefault(float(r["t_s"]), []).append(r)
    for r in csv.DictReader(open(os.path.join(run, "people_track.csv"), encoding="utf-8")): pt.setdefault(float(r["t_s"]), []).append(r)
    D["rt"], D["rts"], D["pt"], D["pts"] = rt, sorted(rt), pt, sorted(pt)
    D["calls"] = list(csv.DictReader(open(os.path.join(run, "calls.csv"), encoding="utf-8")))
    D["snags"] = list(csv.DictReader(open(os.path.join(run, "snags.csv"), encoding="utf-8")))
    D["info"] = json.load(open(os.path.join(run, "run_info.json"), encoding="utf-8"))
    D["nrob"] = int(D["info"]["robots"])
    night = [(f, p) for f, p in zip(fr, pa) if f["cam"] == "night"]
    D["night"] = night
    D["share"] = [(float(f["t_s"]), float(f["robot_cleaned_share"])) for f, p in night]
    win = {f["t_s"]: (f, p) for f, p in zip(fr, pa) if f["cam"] == "win"}
    D["win"] = win
    if meta:
        m = [r for r in csv.DictReader(open(meta, encoding="utf-8")) if r["cam"] == "night"]
        assert len(m) == len(night), (len(m), len(night))
        for a, (f, p) in zip(m, night):
            assert abs(float(a["t_s"]) - float(f["t_s"])) < 0.026, (a["t_s"], f["t_s"])
        D["meta"] = m
        D["sides"] = win_sides(D)
    return D


def robots_xz(f, n):
    out = []
    for k in range(1, n + 1):
        if f.get("r%d_x" % k, "") == "": continue
        out.append((k, float(f["r%d_x" % k]), float(f["r%d_z" % k])))
    return out


def win_sides(D):
    sides, side = [], "R"
    for (f, p), m in zip(D["night"], D["meta"]):
        if m["speed"] != "30倍" or f["t_s"] not in D["win"]:
            sides.append(None); side = "R"; continue
        cam = PathCam(p, 2720, 2160)
        k = int(m["robot"])
        rb = robot_box(cam, float(f["r%d_x" % k]), float(f["r%d_z" % k]))
        if rb is not None:
            if _over(rb, win_rect(side), WIN_HIDE_PX): side = "L" if side == "R" else "R"
            elif side == "L" and not _over(rb, win_rect("R"), WIN_BACK_PX): side = "R"
        sides.append(side)
    return sides


# ---------------- 描く ----------------

def legend_bottom(im, split):
    d = ImageDraw.Draw(im)
    f = font(False, 24)
    items = ["清掃員", "警備員", "ロボット", "ロボットが拭いた", "清掃員が拭いた"] + (["区画の境"] if split else [])
    lg = legend_sprite()
    widths = [int(d.textlength(s, font=f)) for s in items]
    total = sum(widths) + len(items) * 52 + 20 + lg.size[0] - 30
    x0, y0, x = 24, H - 104 + 24, 44
    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=BLUE)
        elif s == "警備員": d.ellipse([x, y - 11, x + 22, y + 11], fill=YELLOW)
        elif s == "ロボット":
            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=INK, anchor="lm")
            x += wdt + 52 + lg.size[0] - 30
            continue
        elif s == "ロボットが拭いた": d.rectangle([x - 2, y - 12, x + 24, y + 12], fill=PAINT_ROBOT, outline=(150, 150, 150))
        elif s == "清掃員が拭いた": d.rectangle([x - 2, y - 12, x + 24, y + 12], fill=PAINT_STAFF, outline=(150, 150, 150))
        elif s == "区画の境":
            for k in range(3): d.line([x - 2 + k * 10, y, x + 4 + k * 10, y], fill=INK, width=3)
        d.text((x + 36, y), s, font=f, fill=INK, anchor="lm")
        x += wdt + 52


def banner(im, t1, t2, t3=""):
    lay = Image.new("RGBA", (SW, BANNER if t3 else 104), (249, 247, 244, 225))
    d = ImageDraw.Draw(lay)
    fs1 = 34
    while fs1 > 22 and d.textlength(t1, font=font(True, fs1)) > SW - 40: fs1 -= 1
    d.text((24, 31), t1, font=font(True, fs1), fill=INK, anchor="lm")
    fs = 22
    while fs > 14 and d.textlength(t2, font=font(False, fs)) > SW - 40: fs -= 1
    d.text((24, 80), t2, font=font(False, fs), fill=INK, anchor="lm")
    if t3:
        fs = 22
        while fs > 14 and d.textlength(t3, font=font(False, fs)) > SW - 40: fs -= 1
        d.text((24, 116), t3, font=font(False, fs), fill=INK, anchor="lm")
    im.paste(lay, (0, 0), lay)


def panel(im, D, t, share_rs, share_ps, title, camja, upto):
    d = ImageDraw.Draw(im)
    d.rectangle([SW, 0, W, H], fill=PANEL_BG)
    x0, xr = SW + 40, W - 40
    f_s, f_m, f_mb, f_big = font(False, 22), font(False, 25), font(True, 27), font(True, 50)
    d.text((x0, 18), "商業施設の夜間の床清掃（依頼312）", font=f_s, fill=GRAY)
    d.text((x0, 46), title, font=f_s, fill=GRAY)
    cfs = 22
    while cfs > 14 and d.textlength("カメラ %s" % camja, font=font(False, cfs)) > xr - x0: cfs -= 1
    d.text((x0, 74), "カメラ %s" % camja, font=font(False, cfs), fill=GRAY)
    d.text((x0, 102), clock(t), font=f_big, fill=INK)
    y = 176
    rows = D["rt"][nearest_le(D["rts"], t)]
    prow = D["pt"][nearest_le(D["pts"], t)]
    d.text((x0, y), "ロボット %d台 がしていること" % len(rows), font=f_mb, fill=INK)
    y += 42
    for r in rows:
        bad = any(b in r["state"] for b in BADSTATE)
        d.text((x0 + 8, y + 15), "%s号機" % r["robot"], font=font(True, 25), fill=INK, anchor="lm")
        st = r["state"]
        fs = 25
        while fs > 16 and d.textlength(st, font=font(False, fs)) > 250: fs -= 1
        d.text((x0 + 100, y + 15), st, font=font(False, fs), fill=BAD if bad else INK, anchor="lm")
        d.text((xr, y + 15), "水 %.0f/1200㎡" % float(r["water_m2"]), font=font(False, 18), fill=GRAY, anchor="rm")
        y += 36
    y += 8
    d.line([x0, y, xr, y], fill=LINE, width=2)
    y += 10
    d.text((x0, y), "清掃員 3人・警備員 1人", font=f_mb, fill=INK)
    y += 42
    for p in prow:
        name = "清掃員%s" % p["person"] if p["role"] == "清掃員" else "警備員"
        busy = p["state"] != "控室"
        c = BLUE if p["role"] == "清掃員" else YELLOW
        d.ellipse([x0 + 6, y + 4, x0 + 28, y + 26], fill=c if busy else PANEL_BG, outline=c, width=3)
        d.text((x0 + 40, y + 15), name, font=f_m, fill=INK, anchor="lm")
        hot = "呼び出し" in p["state"] or "動かす" in p["state"]
        d.text((x0 + 170, y + 15), p["state"], font=f_m, fill=BAD if hot else (INK if busy else QUIET), anchor="lm")
        y += 34
    y += 8
    d.line([x0, y, xr, y], fill=LINE, width=2)
    y += 12
    nw = sum(1 for c in D["calls"] if c["kind"] == "水" and float(c["t_call_s"]) <= t)
    ns = sum(1 for c in D["calls"] if c["kind"] == "引っかかり" and float(c["t_call_s"]) <= t)
    nr = sum(1 for c in D["calls"] if c["kind"] == "立ち往生" and 0 <= float(c["t_take_s"]) <= t)
    nsn = sum(1 for s in D["snags"] if float(s["t_s"]) <= t)
    for name, v, hotc in [("ロボットの床 拭けた", "%d%%" % int(round(share_rs * 100)), None), ("人の床 拭けた", "%d%%" % int(round(share_ps * 100)), None),
                          ("引っかかった", "%d回" % nsn, nsn), ("人を呼んだ（水・引っかかり）", "%d・%d回" % (nw, ns), nw + ns),
                          ("立ち往生で人が動かした", "%d回" % nr, nr)]:
        col = INK if hotc is None else (BAD if hotc else QUIET)
        d.text((x0, y + 20), name, font=f_m, fill=INK, anchor="lm")
        d.text((xr, y + 20), v, font=font(True, 36), fill=col, anchor="rm")
        y += 48
    y += 8
    d.line([x0, y, xr, y], fill=LINE, width=2)
    y += 12
    d.text((x0, y), "ロボットの床の拭けた割合（22:00〜6:00）", font=font(False, 19), fill=GRAY)
    y += 34
    gh = min(130, H - 40 - y)
    X = lambda tt: x0 + (xr - x0) * tt / 28800.0
    Y = lambda v: y + gh - gh * v
    d.line([x0, y + gh, xr, y + gh], fill=LINE, width=2)
    pts = [(X(a), Y(b)) for a, b in upto] + [(X(t), Y(share_rs))]
    if len(pts) > 1: d.line(pts, fill=(23, 97, 230), width=3)
    d.line([X(t), y, X(t), y + gh], fill=INK, width=2)


def grid_share(run, t_end, step=60.0):
    """静止画の回（引きのコマがない）：grid.bin.gz の cleanT から、ロボットが拭いたロボットの床の割合を step 秒ごとに作る"""
    import gzip
    b = gzip.open(os.path.join(run, "grid.bin.gz")).read()
    k = b.index(b"\n")
    h = json.loads(b[:k]); n = h["w"] * h["h"]; o = k + 1
    robot = np.frombuffer(b, np.uint8, n, o); by = np.frombuffer(b, np.uint8, n, o + 4 * n); ct = np.frombuffer(b, np.float32, n, o + 5 * n)
    sel = (robot == 1)
    tt = np.sort(ct[sel & (by >= 1) & (by < 10)])
    tot = int(sel.sum())
    out, t = [], 0.0
    while t <= t_end + 1e-6:
        out.append((t, float(np.searchsorted(tt, t, side="right")) / tot)); t += step
    return out


def camja_of(m):
    if m is None: return ""
    a = float(m["near_a"])
    if m["view"] == "全長": return "引き・全長（フロア全体 200×90 m）・75°見下ろし・左30°"
    if a >= 1.0: return "寄り・75°見下ろし・左30°・問題の所"
    if a > 0.0: return "引き⇄寄りに切り替え中"
    return "引き・フロアの一部（72×36 m）・75°見下ろし・左30°"


RUN, DATA, TITLE = None, None, ""


def people_at(D, t):
    """人の位置（people_track の 1 秒ごとを線でつなぐ。出ている人だけ）"""
    a = nearest_le(D["pts"], t)
    j = bisect.bisect_right(D["pts"], a + 1e-6)
    b = D["pts"][j] if j < len(D["pts"]) else a
    ra, rb = D["pt"][a], {r["person"]: r for r in D["pt"][b]}
    u = 0.0 if b == a else (t - a) / (b - a)
    out = []
    for r in ra:
        if r["visible"] != "1": continue
        q = rb.get(r["person"], r)
        if q["visible"] != "1": q = r
        out.append((float(r["x"]) + u * (float(q["x"]) - float(r["x"])), float(r["z"]) + u * (float(q["z"]) - float(r["z"]))))
    return out


def person_boxes(cam, ppl):
    """人の体の箱（画面）。▼と札がかぶさって人を隠さないよう、印はこの箱の上へずらす（病院の「札と重なるときは上へ」と同じ決め方）"""
    out = []
    for x, z in ppl:
        a, b, c = cam.px(x, z, 0.0), cam.px(x, z, 1.8), cam.px(x + 0.3, z, 0.0)
        if a is None or b is None or c is None: continue
        r = max(4.0, abs(c[0] - a[0]))
        out.append([a[0] - r, b[1] - r, a[0] + r, a[1] + 2])
    return out


def draw_markers(im, cam, f, n, i, ymin, avoid=None):
    placed = []
    for k, x, z in robots_xz(f, n):
        av = placed + (avoid or [])
        b = marker(im, "ロボット%d" % k, cam.px(x, z, ROBOT_H), i, av, ymin, robot_low(cam, x, z))
        if b: placed.append(b)
    return placed


def window(im, cam, D, f, m, i, side):
    wf, wp = D["win"][f["t_s"]]
    inner = WIN - 2 * WIN_EDGE
    q = win_square(cam, wp)
    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)
        b = min(corners, key=lambda p: (p[0] - qc[0]) ** 2 + (p[1] - qc[1]) ** 2)
        d.line([a, b], fill=INK, width=2)
        d.line(q + [q[0]], fill=INK, width=2, joint="curve")
    src = Image.open(os.path.join(D["lk"], wf["file"])).convert("RGB").resize((inner, inner), Image.LANCZOS)
    wc = PathCam(wp, 744, 744, inner, inner)
    draw_markers(src, wc, wf, D["nrob"], i, -1000, person_boxes(wc, people_at(D, float(wf["t_s"]))))
    d.rectangle([x0, y0, x1 - 1, y1 - 1], fill=INK)
    im.paste(src, (x0 + WIN_EDGE, y0 + WIN_EDGE))


def compose(i):
    D = DATA
    f, p = D["night"][i]
    m = D["meta"][i]
    t = float(f["t_s"])
    src = Image.open(os.path.join(D["lk"], f["file"])).convert("RGB").resize((SW, H), Image.LANCZOS)
    im = Image.new("RGB", (W, H), PANEL_BG)
    im.paste(src, (0, 0))
    cam = PathCam(p, 2720, 2160)
    draw_markers(im, cam, f, D["nrob"], i, BANNER + 4, person_boxes(cam, people_at(D, t)))
    if D["sides"][i] is not None: window(im, cam, D, f, m, i, D["sides"][i])
    legend_bottom(im, bool(D["info"]["cut_x"]) and D["info"]["split"] == "split")
    k = bisect.bisect_right([a for a, b in D["share"]], t + 1e-6)
    upto = D["share"][:k:20]
    panel(im, D, t, float(f["robot_cleaned_share"]), float(f["people_cleaned_share"]), TITLE, camja_of(m), upto)
    sp = m["speed"]
    t1 = "%s　施設の時刻の%s" % (clock(t), sp) + ("　%s" % m["what"] if sp == "5倍" and m["what"] else "")
    t2 = "%s　拭いた所：水色＝ロボットが拭いた・青＝清掃員が拭いた%s" % (TITLE, "・点線＝区画の境" if D["info"]["split"] == "split" else "")
    banner(im, t1, t2)
    return im


def seg(args):
    global RUN, DATA, TITLE
    run, meta, title, lo, hi, dst = args
    if DATA is None or RUN != run:
        RUN, TITLE = run, title
        DATA = load(run, meta)
    LOW["n"] = 0
    p = subprocess.Popen([FFMPEG, "-y", "-loglevel", "error", "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", "%dx%d" % (W, H), "-framerate", str(FPS),
                          "-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()
    rc = p.wait()
    return dst, LOW["n"], rc, hi - lo


def nframes(mp4):
    r = subprocess.run([FFMPEG.replace("ffmpeg", "ffprobe"), "-v", "error", "-select_streams", "v:0", "-count_packets", "-show_entries", "stream=nb_read_packets", "-of", "csv=p=0", mp4], capture_output=True, text=True)
    try: return int(r.stdout.strip().split(",")[0])
    except ValueError: return -1


def still(run, camname, title, what, out):
    D = load(run)
    rows = [(f, p) for f, p in zip(D["fr"], D["pa"]) if f["cam"] == camname]
    assert len(rows) == 1, (camname, len(rows))
    f, p = rows[0]
    t = float(f["t_s"])
    src = Image.open(os.path.join(D["lk"], f["file"])).convert("RGB").resize((SW, H), Image.LANCZOS)
    im = Image.new("RGB", (W, H), PANEL_BG)
    im.paste(src, (0, 0))
    cam = PathCam(p, int(Image.open(os.path.join(D["lk"], f["file"])).size[0]), int(Image.open(os.path.join(D["lk"], f["file"])).size[1]))
    draw_markers(im, cam, f, D["nrob"], 0, BANNER + 4, person_boxes(cam, people_at(D, t)))
    legend_bottom(im, D["info"]["split"] == "split")
    if not D["share"]: D["share"] = grid_share(run, t)
    k = bisect.bisect_right([a for a, b in D["share"]], t + 1e-6)
    near = float(p["dist"]) < 40.0
    camja = "寄り・75°見下ろし・左30°・問題の所" if near else "引き・フロアの一部・75°見下ろし・左30°"
    panel(im, D, t, float(f["robot_cleaned_share"]), float(f["people_cleaned_share"]), title, camja, D["share"][:k:20])
    banner(im, "%s　%s" % (clock(t), "寄り" if near else "引き"), what, "%s　拭いた所：水色＝ロボットが拭いた・青＝清掃員が拭いた%s" % (title, "・点線＝区画の境" if D["info"]["split"] == "split" else ""))
    im.save(out)
    return out, t


def main():
    mode = sys.argv[1]
    global RUN, DATA, TITLE
    if mode == "still":
        run, camname, title, what, out = sys.argv[2:7]
        print(*still(run, camname, title, what, out))
        return
    run, meta, title = sys.argv[2], sys.argv[3], sys.argv[4]
    if mode == "frame":
        RUN, TITLE = run, title
        DATA = load(run, meta)
        compose(int(sys.argv[5])).save(sys.argv[6])
        print(sys.argv[6], DATA["night"][int(sys.argv[5])][0]["t_s"])
        return
    dst = sys.argv[5]
    nproc = int(sys.argv[6]) if len(sys.argv) > 6 else 8
    D0 = load(run, meta)
    n = len(D0["night"])
    sides = D0["sides"]
    print("窓：30倍のコマ %d・左下のコマ %d" % (sum(1 for x in sides if x), sum(1 for x in sides if x == "L")), flush=True)
    del D0
    tmp = tempfile.mkdtemp(prefix="pan312_", dir="/tmp")          # 区切りは Mac の内蔵ディスクに作る（KIOXIA に作った区切りが1つ壊れたため）
    k = max(1, math.ceil(n / (nproc * 4)))
    jobs = [(run, meta, title, 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]
    # 区切りごとにコマ数を確かめ、合わないものだけ作り直す（2回まで）
    for job, q in zip(jobs, res):
        for _ in range(2):
            if q[2] == 0 and nframes(job[5]) == q[3]: break
            print("区切りを作り直す:", job[5], q[2], nframes(job[5]), q[3], flush=True)
            q = seg(job)
        assert q[2] == 0 and nframes(job[5]) == q[3], ("区切りが作れない", job[5])
    print("▲と札をロボットの下に出したコマ（印の数）%d" % sum(q[1] for q in res))
    lst = os.path.join(tmp, "list.txt")
    open(lst, "w").write("".join("file '%s'\n" % q for q in parts))
    subprocess.check_call([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 / float(FPS), "秒")


if __name__ == "__main__":
    main()
