File size: 22,169 Bytes
cb94592
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
#!/usr/bin/env python3
"""Render a force review video from one MCAP, replicating the official
FusionX Tactile Foxglove panel (touchtronixrobotics.fusionx-tactile-panel
v0.2.4 .foxe) and the fusionx_foxglove_annotated.json layout.

Layout (1920x1080):
  top 71.5%:    [ FusionX Tactile panel | head camera / wrist lh + rh ]
  bottom 28.5%: semantic state timeline (contact / target / subtask)
The layout's 3D hand-pose panels are not reproduced.

Tactile rendering matches the extension exactly: per-finger 4x3 pixel grids
(LH little-ring-middle-index at columns 1/5/9/13, RH index..little at
5/9/13/17, thumb at row 6), colour hsl(240*(1-v/vmax), 90%, 50%) with a
fixed 0-20 N scale in force-pixels mode (0-255 in raw mode), sample-and-hold
of the latest message like the live panel (no interpolation).

All streams are aligned on MCAP log_time, so tactile, cameras, and
annotations share one clock (fixes the per-stream offset in visualize.py).

Usage: visualize_force.py <recording_dir> [--mode auto|force-pixels|raw]
       [--start S] [--duration S] [--fps N] [--out PATH]
"""

from __future__ import annotations

import argparse
import colorsys
import json
import subprocess
import sys
from pathlib import Path

import cv2
import numpy as np
from mcap.reader import make_reader

FINGERS = ("thumb", "index", "middle", "ring", "little")
HEAD_TOPIC = "/camera/head/rgb/h264"
WRIST_TOPICS = {"lh": "/camera/wrist/lh/h264", "rh": "/camera/wrist/rh/h264"}
MONO_TOPICS = {"lh": "/camera/head/mono_left/h264", "rh": "/camera/head/mono_right/h264"}
TACTILE_TOPICS = {"lh": "/glove/lh/tactile", "rh": "/glove/rh/tactile"}
STATE_TOPIC = "/annotations/semantic/state"

CANVAS_W, CANVAS_H = 1920, 1080
TOP_H = 772          # 71.45% column split from the annotated layout
HEAD_H = 574         # 74.36% split of the camera column
PANEL_W = CANVAS_W // 2


def hex_bgr(h: str) -> tuple[int, int, int]:
    h = h.lstrip("#")
    return (int(h[4:6], 16), int(h[2:4], 16), int(h[0:2], 16))


# Extension colours (dist/extension.js)
PANEL_BG = hex_bgr("#0b1118")
SVG_BG = hex_bgr("#111821")
CELL_STROKE = hex_bgr("#263241")
INK = hex_bgr("#edf2f7")
MUTED = hex_bgr("#78889b")
FAINT = hex_bgr("#aab4c3")
SCALE_INK = hex_bgr("#d9e2ec")
BEND_TRACK = hex_bgr("#202b38")
BEND_FILL = hex_bgr("#00c800")
BEND_INK = hex_bgr("#c8c8c8")
BTN_ACTIVE = hex_bgr("#2563eb")
BTN_IDLE = hex_bgr("#202b38")
BTN_BORDER = hex_bgr("#3b4858")
CAM_BG = hex_bgr("#0e0e0e")

# State-timeline categorical palette (dataviz reference palette, dark steps,
# fixed order; values beyond the list reuse it cyclically but every segment
# is also direct-labelled so colour is never the only identity)
TRACK_COLORS = [hex_bgr(c) for c in (
    "#3987e5", "#d95926", "#199e70", "#c98500",
    "#d55181", "#008300", "#9085e9", "#e66767",
)]

FONT = cv2.FONT_HERSHEY_SIMPLEX


def heat_color(value: float, vmax: float) -> tuple[int, int, int]:
    # extension: fill = hsl(240*(1-clamp(v/vmax)) 90% 50%)
    hue = 240.0 * (1.0 - min(max(value / vmax, 0.0), 1.0))
    r, g, b = colorsys.hls_to_rgb(hue / 360.0, 0.5, 0.9)
    return (int(b * 255), int(g * 255), int(r * 255))


def put_text(img, text, x, y, px, color, weight=1):
    scale = px / 22.0
    cv2.putText(img, text, (int(x), int(y)), FONT, scale, color, weight, cv2.LINE_AA)


def text_w(text, px, weight=1):
    return cv2.getTextSize(text, FONT, px / 22.0, weight)[0][0]


# ---------------------------------------------------------------------------
# MCAP extraction
# ---------------------------------------------------------------------------

def decode_varint(buf: bytes, i: int) -> tuple[int, int]:
    x = s = 0
    while True:
        b = buf[i]
        i += 1
        x |= (b & 0x7F) << s
        if not (b & 0x80):
            return x, i
        s += 7


def proto_bytes_field(buf: bytes, field_no: int) -> bytes:
    i, n = 0, len(buf)
    while i < n:
        key, i = decode_varint(buf, i)
        fn, wt = key >> 3, key & 7
        if wt == 2:
            ln, i = decode_varint(buf, i)
            if fn == field_no:
                return buf[i : i + ln]
            i += ln
        elif wt == 0:
            _, i = decode_varint(buf, i)
        elif wt == 1:
            i += 8
        elif wt == 5:
            i += 4
        else:
            raise ValueError(f"bad wire type {wt}")
    return b""


def parse_tactile(obj: dict) -> dict:
    adc = np.zeros((5, 12), np.float32)
    for i, name in enumerate(FINGERS):
        row = (obj.get("finger_pressure") or {}).get(name) or []
        adc[i, : min(12, len(row))] = row[:12]
    force = None
    pix = obj.get("finger_force_N_pixels")
    if pix:
        force = np.zeros((5, 12), np.float32)
        for i in range(min(5, len(pix))):
            force[i, : min(12, len(pix[i]))] = pix[i][:12]
    palm = np.zeros(60, np.float32)
    raw_palm = obj.get("palm_pressure") or []
    palm[: min(60, len(raw_palm))] = raw_palm[:60]
    bend = np.zeros(5, np.float32)
    raw_bend = obj.get("finger_bend") or []
    bend[: min(5, len(raw_bend))] = raw_bend[:5]
    return {"adc": adc, "force": force, "palm": palm, "bend": bend,
            "sample_idx": int(obj.get("sample_idx", -1))}


def parse_state(obj: dict) -> tuple[str | None, str | None, str | None]:
    aa = obj.get("atomic_actions") or []
    st = obj.get("subtasks") or []
    contact = aa[0].get("contact_state_start") if aa else None
    target = aa[0].get("target_object") if aa else None
    subtask = st[0].get("description") if st else None
    return contact, target, subtask


def extract(mcap: Path, tmp_dir: Path) -> dict:
    with open(mcap, "rb") as f:
        summary = make_reader(f).get_summary()
    available = {ch.topic for ch in (summary.channels or {}).values()} if summary else set()

    cams = {"head": (HEAD_TOPIC, "Head Camera")}
    for side in ("lh", "rh"):
        if WRIST_TOPICS[side] in available:
            cams[f"wrist_{side}"] = (WRIST_TOPICS[side], f"Wrist {side.upper()}")
        elif MONO_TOPICS[side] in available:
            cams[f"wrist_{side}"] = (MONO_TOPICS[side], f"Head mono {'L' if side == 'lh' else 'R'}")
    topic_to_cam = {t: k for k, (t, _) in cams.items()}

    writers = {k: (tmp_dir / f"_{k}.h264").open("wb") for k in cams}
    cam_times = {k: [] for k in cams}
    tactile = {h: {"t": [], "samples": []} for h in ("lh", "rh")}
    states = []

    topics = [t for t, _ in cams.values()] + list(TACTILE_TOPICS.values())
    if STATE_TOPIC in available:
        topics.append(STATE_TOPIC)

    print(f"reading {mcap.name} ...", flush=True)
    with open(mcap, "rb") as f:
        for _sch, ch, msg in make_reader(f).iter_messages(topics=topics):
            t = msg.log_time / 1e9
            if ch.topic in topic_to_cam:
                payload = proto_bytes_field(msg.data, 3)
                if payload:
                    key = topic_to_cam[ch.topic]
                    writers[key].write(payload)
                    cam_times[key].append(t)
            elif ch.topic == STATE_TOPIC:
                states.append((t, *parse_state(json.loads(msg.data))))
            else:
                hand = "lh" if ch.topic == TACTILE_TOPICS["lh"] else "rh"
                tactile[hand]["t"].append(t)
                tactile[hand]["samples"].append(parse_tactile(json.loads(msg.data)))
    for w in writers.values():
        w.close()

    out = {"cams": {}, "tactile": {}, "states": states}
    for k, (topic, label) in cams.items():
        raw = tmp_dir / f"_{k}.h264"
        mp4 = tmp_dir / f"_{k}.mp4"
        subprocess.run(
            ["ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
             "-fflags", "+genpts", "-r", "30", "-f", "h264", "-i", str(raw),
             "-c", "copy", str(mp4)],
            check=True,
        )
        raw.unlink()
        out["cams"][k] = {"mp4": mp4, "times": np.asarray(cam_times[k]), "label": label}
        print(f"  {label:12s} {len(cam_times[k])} frames", flush=True)
    for h in ("lh", "rh"):
        has_force = any(s["force"] is not None for s in tactile[h]["samples"])
        out["tactile"][h] = {
            "t": np.asarray(tactile[h]["t"]),
            "samples": tactile[h]["samples"],
            "has_force": has_force,
        }
        print(f"  {h} tactile   {len(tactile[h]['t'])} samples  force {'yes' if has_force else 'no'}", flush=True)
    print(f"  state       {len(states)} messages", flush=True)
    return out


# ---------------------------------------------------------------------------
# FusionX Tactile panel (faithful to dist/extension.js)
# ---------------------------------------------------------------------------

def sensor_cells(hand: str, sample: dict, mode: str):
    long_names = ["little", "ring", "middle", "index"] if hand == "lh" else ["index", "middle", "ring", "little"]
    anchors = {n: (1, (1 if hand == "lh" else 5) + 4 * k) for k, n in enumerate(long_names)}
    anchors["thumb"] = (6, 17 if hand == "lh" else 1)
    cells = []
    for fi, name in enumerate(FINGERS):
        row0, col0 = anchors[name]
        values = sample["force"][fi] if mode == "force-pixels" else sample["adc"][fi]
        for n, v in enumerate(values):
            cells.append((row0 + n // 3, col0 + n % 3, float(v)))
    if mode == "raw":
        base = 1 if hand == "lh" else 5
        for r, v in enumerate(sample["palm"]):
            cells.append((6 + r // 15, base + r % 15, float(v)))
    return cells


def draw_heatmap(img, x0, y0, bw, bh, hand: str, sample: dict | None, mode: str):
    sc = min(bw / 28.0, bh / 12.0)
    ox = x0 + (bw - 28 * sc) / 2
    oy = y0 + (bh - 12 * sc) / 2
    cv2.rectangle(img, (int(ox), int(oy)), (int(ox + 28 * sc), int(oy + 12 * sc)), SVG_BG, -1)
    if sample is None:
        msg = f"Waiting for {TACTILE_TOPICS[hand]}"
        put_text(img, msg, ox + 14 * sc - text_w(msg, 15) / 2, oy + 6 * sc, 15, FAINT)
        return
    if mode == "force-pixels" and sample["force"] is None:
        msg = "Pixel force unavailable in this recording"
        put_text(img, msg, ox + 14 * sc - text_w(msg, 15) / 2, oy + 6 * sc, 15, FAINT)
        return

    vmax = 255.0 if mode == "raw" else 20.0
    shift = 7 if hand == "lh" else 0
    for row, col, v in sensor_cells(hand, sample, mode):
        cx, cy = ox + (col + shift) * sc, oy + row * sc
        p0, p1 = (int(cx), int(cy)), (int(cx + 0.9 * sc), int(cy + 0.9 * sc))
        cv2.rectangle(img, p0, p1, heat_color(v, vmax), -1)
        cv2.rectangle(img, p0, p1, CELL_STROKE, 1)
    # colour scale: 11 blocks, red (vmax) on top -> blue (0) at bottom
    sx = ox + (4.5 if hand == "lh" else 22.5) * sc
    for n in range(11):
        sy = oy + (1 + 0.8 * n) * sc
        r, g, b = colorsys.hls_to_rgb(n / 10.0 * 240.0 / 360.0, 0.5, 0.9)
        cv2.rectangle(img, (int(sx), int(sy)), (int(sx + sc), int(sy + 0.82 * sc)),
                      (int(b * 255), int(g * 255), int(r * 255)), -1)
    tx = ox + (0.5 if hand == "lh" else 24.0) * sc
    put_text(img, "255 ADC" if mode == "raw" else "20 N", tx, oy + 1.6 * sc, 0.65 * sc, SCALE_INK)
    put_text(img, "0", tx, oy + 9.3 * sc, 0.65 * sc, SCALE_INK)
    if mode == "raw":
        px = ox + ((15.5 if hand == "lh" else 12.5) + shift) * sc
        put_text(img, "palm", px - text_w("palm", 0.65 * sc) / 2, oy + 11 * sc, 0.65 * sc, SCALE_INK)


def draw_bend(img, x0, y0, bw, bh, hand: str, sample: dict):
    sc = min(bw / 28.0, bh / 10.0)
    ox = x0 + (bw - 28 * sc) / 2
    oy = y0 + (bh - 10 * sc) / 2
    cv2.rectangle(img, (int(ox), int(oy)), (int(ox + 28 * sc), int(oy + 10 * sc)), SVG_BG, -1)
    for t, name in enumerate(FINGERS):
        c = (25.5 - 4 * t) if hand == "lh" else (2.5 + 4 * t)
        bx = ox + (c - 1) * sc
        h = min(max(float(sample["bend"][t]) / 255.0, 0.0), 1.0) * 7.5 * sc
        cv2.rectangle(img, (int(bx), int(oy + 2 * sc)), (int(bx + 2 * sc), int(oy + 9.5 * sc)), BEND_TRACK, -1)
        if h > 0:
            cv2.rectangle(img, (int(bx), int(oy + 9.5 * sc - h)), (int(bx + 2 * sc), int(oy + 9.5 * sc)), BEND_FILL, -1)
        letter = name[0].upper()
        put_text(img, letter, ox + c * sc - text_w(letter, 0.8 * sc) / 2, oy + 1.35 * sc, 0.8 * sc, BEND_INK)


def draw_tactile_panel(img, x0, y0, w, h, samples: dict, mode: str, t_sec: float):
    cv2.rectangle(img, (x0, y0), (x0 + w, y0 + h), PANEL_BG, -1)
    pad = 12
    put_text(img, "FusionX Tactile", x0 + pad, y0 + 26, 17, INK, 2)
    stamp = f"t = {t_sec:6.2f} s"
    put_text(img, stamp, x0 + w - pad - text_w(stamp, 14), y0 + 26, 14, MUTED)
    # mode buttons
    by = y0 + 38
    bw = (w - 2 * pad - 8) // 2
    for i, (m, label) in enumerate((("raw", "Raw ADC"), ("force-pixels", "Pixel Force"))):
        bx = x0 + pad + i * (bw + 8)
        cv2.rectangle(img, (bx, by), (bx + bw, by + 30), BTN_ACTIVE if m == mode else BTN_IDLE, -1)
        cv2.rectangle(img, (bx, by), (bx + bw, by + 30), BTN_BORDER, 1)
        put_text(img, label, bx + (bw - text_w(label, 14)) / 2, by + 20, 14, INK)

    sec_y = by + 42
    sec_h = h - (sec_y - y0) - 8
    half = w // 2
    cv2.line(img, (x0 + half, sec_y), (x0 + half, y0 + h - 8), BTN_BORDER, 1)
    for i, hand in enumerate(("lh", "rh")):
        hx = x0 + i * half + (8 if i else pad)
        hw = half - pad - 8
        title = f"{'Left' if hand == 'lh' else 'Right'} Hand"
        put_text(img, title, hx + (hw - text_w(title, 15, 2)) / 2, sec_y + 18, 15, INK, 2)
        heat_h = int(hw * 12 / 28)
        bend_h = int(hw * 10 / 28)
        avail = sec_h - 28 - 24 - 14
        if heat_h + bend_h > avail:
            k = avail / (heat_h + bend_h)
            heat_h, bend_h = int(heat_h * k), int(bend_h * k)
        draw_heatmap(img, hx, sec_y + 28, hw, heat_h, hand, samples[hand], mode)
        if samples[hand] is not None:
            draw_bend(img, hx, sec_y + 38 + heat_h, hw, bend_h, hand, samples[hand])
            foot = f"{TACTILE_TOPICS[hand]}  sample {samples[hand]['sample_idx']}"
        else:
            foot = TACTILE_TOPICS[hand]
        put_text(img, foot, hx + hw - text_w(foot, 12), y0 + h - 16, 12, MUTED)


# ---------------------------------------------------------------------------
# State timeline (StateTransitions panel paths)
# ---------------------------------------------------------------------------

TRACKS = (("contact", 1), ("target", 2), ("subtask", 3))


def build_segments(states, t0, t1):
    """Per track: list of (start, end, value) merged over consecutive equal values."""
    tracks = []
    for _, idx in TRACKS:
        segs = []
        for t, *vals in states:
            v = vals[idx - 1]
            if segs and segs[-1][2] == v:
                segs[-1][1] = t
            else:
                if segs:
                    segs[-1][1] = t
                segs.append([t, t1, v])
        tracks.append([(max(s, t0), min(e, t1), v) for s, e, v in segs
                       if v is not None and e > t0 and s < t1])
    return tracks


def render_timeline_bg(w, h, tracks, t0, t1):
    img = np.full((h, w, 3), PANEL_BG, np.uint8)
    label_w, right = 90, 16
    span = max(t1 - t0, 1e-9)

    def tx(t):
        return label_w + (t - t0) / span * (w - label_w - right)

    color_maps = []
    row_h = (h - 34) // len(TRACKS)
    for ti, (name, _) in enumerate(TRACKS):
        cmap = {}
        color_maps.append(cmap)
        y = 10 + ti * row_h
        put_text(img, name, 12, y + row_h // 2 + 5, 14, FAINT)
        bar_y, bar_h = y + 6, row_h - 18
        cv2.rectangle(img, (label_w, bar_y), (w - right, bar_y + bar_h), SVG_BG, -1)
        for s, e, v in tracks[ti]:
            if v not in cmap:
                cmap[v] = TRACK_COLORS[len(cmap) % len(TRACK_COLORS)]
            x0, x1 = int(tx(s)), int(tx(e))
            cv2.rectangle(img, (x0, bar_y), (max(x1 - 2, x0 + 1), bar_y + bar_h), cmap[v], -1)
            label = str(v)
            if text_w(label, 13) < x1 - x0 - 10:
                put_text(img, label, x0 + 6, bar_y + bar_h // 2 + 5, 13, INK, 1)
    axis_y = h - 18
    step = max(10, int(round(span / 8 / 10)) * 10)
    t = 0
    while t <= span:
        x = int(tx(t0 + t))
        cv2.line(img, (x, axis_y - 4), (x, axis_y), MUTED, 1)
        put_text(img, f"{t:d}s", x + 3, axis_y + 12, 12, MUTED)
        t += step
    return img, tx


# ---------------------------------------------------------------------------
# Cameras
# ---------------------------------------------------------------------------

class CamReader:
    def __init__(self, mp4: Path, times: np.ndarray, label: str):
        self.cap = cv2.VideoCapture(str(mp4))
        self.times = times
        self.label = label
        self.idx = -1
        self.frame = None

    def at(self, t: float):
        while self.idx + 1 < len(self.times) and self.times[self.idx + 1] <= t:
            ok, frame = self.cap.read()
            if not ok:
                break
            self.idx += 1
            self.frame = frame
        return self.frame

    def release(self):
        self.cap.release()


def blit_camera(canvas, x0, y0, bw, bh, frame, label):
    cv2.rectangle(canvas, (x0, y0), (x0 + bw, y0 + bh), CAM_BG, -1)
    if frame is not None:
        fh, fw = frame.shape[:2]
        s = min(bw / fw, bh / fh)
        nw, nh = int(fw * s), int(fh * s)
        ox, oy = x0 + (bw - nw) // 2, y0 + (bh - nh) // 2
        canvas[oy : oy + nh, ox : ox + nw] = cv2.resize(frame, (nw, nh), interpolation=cv2.INTER_AREA)
    else:
        put_text(canvas, "waiting", x0 + bw / 2 - text_w("waiting", 16) / 2, y0 + bh / 2, 16, MUTED)
    tw = text_w(label, 14)
    cv2.rectangle(canvas, (x0 + 8, y0 + 8), (x0 + 20 + tw, y0 + 32), (0, 0, 0), -1)
    put_text(canvas, label, x0 + 14, y0 + 25, 14, INK)


# ---------------------------------------------------------------------------
# Main
# ---------------------------------------------------------------------------

def ffmpeg_writer(dest: Path, w: int, h: int, fps: float) -> subprocess.Popen:
    return subprocess.Popen(
        ["ffmpeg", "-y", "-hide_banner", "-loglevel", "error",
         "-f", "rawvideo", "-pix_fmt", "bgr24", "-s", f"{w}x{h}", "-r", str(fps), "-i", "-",
         "-c:v", "libx264", "-preset", "veryfast", "-pix_fmt", "yuv420p", "-crf", "20",
         "-movflags", "+faststart", str(dest)],
        stdin=subprocess.PIPE,
    )


def main() -> None:
    ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("recording_dir", nargs="?", default=".")
    ap.add_argument("--mode", choices=("auto", "force-pixels", "raw"), default="auto")
    ap.add_argument("--start", type=float, default=0.0, help="offset into recording, seconds")
    ap.add_argument("--duration", type=float, default=None, help="seconds to render")
    ap.add_argument("--fps", type=float, default=30.0)
    ap.add_argument("--out", type=Path, default=None)
    args = ap.parse_args()

    root = Path(args.recording_dir).resolve()
    root = root.parent if root.is_file() else root
    mcaps = sorted(root.glob("*.mcap"))
    if not mcaps:
        sys.exit(f"no .mcap found in {root}")
    out_dir = root / "output"
    out_dir.mkdir(exist_ok=True)
    dest = args.out or out_dir / "force_video.mp4"

    streams = extract(mcaps[0], out_dir)

    firsts = [c["times"][0] for c in streams["cams"].values() if len(c["times"])]
    lasts = [c["times"][-1] for c in streams["cams"].values() if len(c["times"])]
    for h in ("lh", "rh"):
        t = streams["tactile"][h]["t"]
        if t.size:
            firsts.append(t[0])
            lasts.append(t[-1])
    t0, t1 = min(firsts), max(lasts)
    t0 += args.start
    if args.duration is not None:
        t1 = min(t1, t0 + args.duration)
    n_frames = max(1, int(round((t1 - t0) * args.fps)))

    if args.mode == "auto":
        mode = "force-pixels" if any(streams["tactile"][h]["has_force"] for h in ("lh", "rh")) else "raw"
    else:
        mode = args.mode
    print(f"rendering {n_frames} frames ({(t1 - t0):.1f}s) mode={mode} -> {dest.name}", flush=True)

    cams = {k: CamReader(c["mp4"], c["times"], c["label"]) for k, c in streams["cams"].items()}
    tl_h = CANVAS_H - TOP_H
    if streams["states"]:
        seg_tracks = build_segments(streams["states"], t0, t1)
        timeline_bg, tl_tx = render_timeline_bg(CANVAS_W, tl_h, seg_tracks, t0, t1)
    else:
        timeline_bg, tl_tx = np.full((tl_h, CANVAS_W, 3), PANEL_BG, np.uint8), None
        put_text(timeline_bg, "no semantic annotations in this recording",
                 CANVAS_W / 2 - text_w("no semantic annotations in this recording", 15) / 2,
                 tl_h / 2, 15, MUTED)

    proc = ffmpeg_writer(dest, CANVAS_W, CANVAS_H, args.fps)
    canvas = np.zeros((CANVAS_H, CANVAS_W, 3), np.uint8)
    wrist_w, wrist_h = PANEL_W // 2, TOP_H - HEAD_H
    tac = streams["tactile"]
    for i in range(n_frames):
        t = t0 + i / args.fps
        samples = {}
        for h in ("lh", "rh"):
            j = int(np.searchsorted(tac[h]["t"], t, "right")) - 1
            samples[h] = tac[h]["samples"][j] if j >= 0 else None
        draw_tactile_panel(canvas, 0, 0, PANEL_W, TOP_H, samples, mode, t - t0)
        blit_camera(canvas, PANEL_W, 0, PANEL_W, HEAD_H, cams["head"].at(t), cams["head"].label)
        for k, key in enumerate(("wrist_lh", "wrist_rh")):
            if key in cams:
                blit_camera(canvas, PANEL_W + k * wrist_w, HEAD_H, wrist_w, wrist_h,
                            cams[key].at(t), cams[key].label)
            else:
                blit_camera(canvas, PANEL_W + k * wrist_w, HEAD_H, wrist_w, wrist_h, None, key)
        canvas[TOP_H:] = timeline_bg
        if tl_tx is not None:
            x = int(tl_tx(t))
            cv2.line(canvas, (x, TOP_H + 4), (x, CANVAS_H - 20), INK, 2)
        proc.stdin.write(canvas.tobytes())
        if i % 900 == 0:
            print(f"  frame {i}/{n_frames}", flush=True)
    proc.stdin.close()
    if proc.wait() != 0:
        raise RuntimeError("ffmpeg encode failed")
    for c in cams.values():
        c.release()
    for k in streams["cams"]:
        streams["cams"][k]["mp4"].unlink(missing_ok=True)
    print(f"wrote {dest}  {dest.stat().st_size / 1e6:.1f} MB", flush=True)


if __name__ == "__main__":
    main()