File size: 25,796 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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
#!/usr/bin/env python3
"""Decode head/wrist RGB and render tactile review videos from one MCAP.

Usage: visualize.py <recording_dir> [--remap-only]
<recording_dir> is a folder containing the .mcap (defaults to the current
directory); outputs go to <recording_dir>/output.
"""

from __future__ import annotations

import json
import shutil
import subprocess
import sys
from pathlib import Path

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


def _resolve_root() -> Path:
    args = [a for a in sys.argv[1:] if not a.startswith("--")]
    root = Path(args[0]).resolve() if args else Path.cwd()
    return root.parent if root.is_file() else root


ROOT = _resolve_root()
_mcaps = sorted(ROOT.glob("*.mcap"))
MCAP = _mcaps[0] if _mcaps else ROOT / "recording_000.mcap"
OUT = ROOT / "output"
FPS = 30.0
FINGERS = ("thumb", "index", "middle", "ring", "little")


def detect_n_frames() -> int:
    for qa in (ROOT / "qa_result.json", ROOT / "labels" / "qa_result.json"):
        if qa.exists():
            obj = json.loads(qa.read_text())
            n = int(obj.get("summary", {}).get("frame_count") or 0)
            if n > 0:
                return n
    for sem in (
        ROOT / "semantic_annotation_result.json",
        ROOT / "labels" / "semantic_annotation_result.json",
    ):
        if sem.exists():
            obj = json.loads(sem.read_text())
            dur = float(obj.get("video_duration_sec") or 0.0)
            if dur > 0:
                return max(1, int(round(dur * FPS)))
    return 0


N_FRAMES = detect_n_frames()

HEAD_TOPIC = "/camera/head/rgb/h264"
WRIST_LH_TOPIC = "/camera/wrist/lh/h264"
WRIST_RH_TOPIC = "/camera/wrist/rh/h264"
MONO_L_TOPIC = "/camera/head/mono_left/h264"
MONO_R_TOPIC = "/camera/head/mono_right/h264"
LH_TACTILE = "/glove/lh/tactile"
RH_TACTILE = "/glove/rh/tactile"

# Review-dashboard tactile panel: official FusionX anatomical layout
# LH long fingers L->R = little, ring, middle, index; thumb lower-right
# RH long fingers L->R = index, middle, ring, little; thumb lower-left
# Palm shares the long-finger column grid (official cols: LH 1-15, RH 5-19),
# so each palm cell sits directly under its finger column at the same pitch.
# Bend bars are centered under their finger pads (thumb bar under thumb pad).
PANEL_W, PANEL_H = 800, 1080
FORCE_W, FORCE_H = 800, 720
BG = (12, 12, 12)
PAD_BG = (28, 24, 22)
CELL = 22
PAD_GAP = 8


def decode_varint(buf: bytes, i: int) -> tuple[int, int]:
    x = 0
    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 = 0
    n = 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)
            chunk = buf[i : i + ln]
            i += ln
            if fn == field_no:
                return chunk
        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 red_heat(normalized: float) -> tuple[int, int, int]:
    n = float(np.clip(normalized, 0.0, 1.0))
    n = n**0.75
    return (int(10 + 20 * (1 - n)), int(8 + 40 * n), int(18 + 237 * n))


def _rounded_rect(img: np.ndarray, x0: int, y0: int, x1: int, y1: int, color, radius: int = 10, filled: bool = True) -> None:
    thickness = -1 if filled else 1
    cv2.rectangle(img, (x0 + radius, y0), (x1 - radius, y1), color, thickness)
    cv2.rectangle(img, (x0, y0 + radius), (x1, y1 - radius), color, thickness)
    for cx, cy in ((x0 + radius, y0 + radius), (x1 - radius, y0 + radius), (x0 + radius, y1 - radius), (x1 - radius, y1 - radius)):
        cv2.circle(img, (cx, cy), radius, color, thickness, cv2.LINE_AA)


def finger_pad_size() -> tuple[int, int]:
    return 3 * CELL + 12, 4 * CELL + 12


def draw_finger_pad(img: np.ndarray, x: int, y: int, values: np.ndarray, vmax: float) -> None:
    pad_w, pad_h = finger_pad_size()
    _rounded_rect(img, x, y, x + pad_w, y + pad_h, PAD_BG, 6, True)
    for i, value in enumerate(values):
        r, c = divmod(int(i), 3)  # row0 = tip, col0 = left  (FusionX pixel1-3)
        cx = x + 6 + c * CELL
        cy = y + 6 + r * CELL
        cv2.rectangle(img, (cx + 1, cy + 1), (cx + CELL - 2, cy + CELL - 2), red_heat(value / max(vmax, 1e-6)), -1)
    _rounded_rect(img, x, y, x + pad_w, y + pad_h, (80, 74, 70), 6, False)


def draw_palm_pad(img: np.ndarray, x: int, y: int, palm: np.ndarray, vmax: float) -> tuple[int, int]:
    # x = left edge of the leftmost long-finger pad; palm column c reuses that
    # pad grid: virtual column c -> pad c//4, in-pad column c%4 (c%4 == 3 = gap)
    pad_w, _ = finger_pad_size()
    w, h = 4 * pad_w + 3 * PAD_GAP, 4 * CELL + 12
    _rounded_rect(img, x, y, x + w, y + h, PAD_BG, 6, True)
    for i, value in enumerate(palm):
        r, c = divmod(int(i), 15)  # row0 nearest fingers, col0 = leftmost long finger
        cx = x + 6 + (c // 4) * (pad_w + PAD_GAP) + (c % 4) * CELL
        cy = y + 6 + r * CELL
        cv2.rectangle(
            img,
            (cx + 1, cy + 1),
            (cx + CELL - 2, cy + CELL - 2),
            red_heat(value / max(vmax, 1e-6)),
            -1,
        )
    _rounded_rect(img, x, y, x + w, y + h, (80, 74, 70), 6, False)
    return w, h


def hand_spec(hand: str) -> dict:
    if hand == "lh":
        return {
            "long": (("little", "L"), ("ring", "R"), ("middle", "M"), ("index", "I")),
            "thumb": ("thumb", "T"),
            "thumb_side": "right",
            "bend": (("little", "L"), ("ring", "R"), ("middle", "M"), ("index", "I"), ("thumb", "T")),
        }
    return {
        "long": (("index", "I"), ("middle", "M"), ("ring", "R"), ("little", "L")),
        "thumb": ("thumb", "T"),
        "thumb_side": "left",
        "bend": (("thumb", "T"), ("index", "I"), ("middle", "M"), ("ring", "R"), ("little", "L")),
    }


def draw_hand_block(
    img: np.ndarray,
    y0: int,
    hand: str,
    title: str,
    finger: np.ndarray,
    palm: np.ndarray | None,
    bend: np.ndarray,
    vmax: float,
) -> int:
    spec = hand_spec(hand)
    pad_w, pad_h = finger_pad_size()
    cv2.putText(img, title, (20, y0 + 26), cv2.FONT_HERSHEY_SIMPLEX, 0.62, (230, 230, 230), 2, cv2.LINE_AA)

    long_w = 4 * pad_w + 3 * PAD_GAP
    block_w = long_w + PAD_GAP + pad_w
    x_block = (img.shape[1] - block_w) // 2
    y_long = y0 + 40

    long_xs = []
    for k, (name, letter) in enumerate(spec["long"]):
        x = x_block + (pad_w + PAD_GAP if spec["thumb_side"] == "left" else 0) + k * (pad_w + PAD_GAP)
        long_xs.append(x)
        draw_finger_pad(img, x, y_long, finger[FINGERS.index(name)], vmax)
        cv2.putText(img, letter, (x + pad_w // 2 - 7, y_long + pad_h + 22), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (200, 200, 200), 2, cv2.LINE_AA)

    y_palm = y_long + pad_h + 30
    if palm is not None:
        palm_x = long_xs[0]  # official layout: palm spans exactly the long-finger columns
        pw, ph = draw_palm_pad(img, palm_x, y_palm, palm, vmax)
        cv2.putText(img, "palm", (palm_x + pw // 2 - 22, y_palm + ph + 18), cv2.FONT_HERSHEY_SIMPLEX, 0.42, (160, 160, 160), 1, cv2.LINE_AA)
        y_thumb = y_palm
    else:
        y_thumb = y_palm

    thumb_name, thumb_letter = spec["thumb"]
    thumb_x = x_block if spec["thumb_side"] == "left" else x_block + long_w + PAD_GAP
    draw_finger_pad(img, thumb_x, y_thumb, finger[FINGERS.index(thumb_name)], vmax)
    cv2.putText(
        img,
        thumb_letter,
        (thumb_x + pad_w // 2 - 7, y_thumb + pad_h + 22),
        cv2.FONT_HERSHEY_SIMPLEX,
        0.55,
        (200, 200, 200),
        2,
        cv2.LINE_AA,
    )

    # Bend bars: official Foxglove order (LH L-R-M-I-T, RH T-I-M-R-L),
    # each bar centered under its finger pad like the official panel
    y_bar = max(y_long + pad_h, y_thumb + pad_h) + 50
    track_h = 70
    bar_cxs = [x + pad_w // 2 for x in long_xs]
    thumb_cx = thumb_x + pad_w // 2
    bar_cxs = [thumb_cx, *bar_cxs] if spec["thumb_side"] == "left" else [*bar_cxs, thumb_cx]
    for k, (name, letter) in enumerate(spec["bend"]):
        cx = bar_cxs[k]
        bx = cx - 8
        cv2.rectangle(img, (bx, y_bar), (bx + 16, y_bar + track_h), (40, 36, 34), -1)
        h = int(max(0.0, min(1.0, float(bend[FINGERS.index(name)]) / 255.0)) * track_h)
        cv2.rectangle(img, (bx, y_bar + track_h - h), (bx + 16, y_bar + track_h), (0, 200, 0), -1)
        cv2.putText(img, letter, (cx - 6, y_bar - 8), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (180, 180, 180), 1, cv2.LINE_AA)
    return y_bar + track_h + 16


def draw_review_hand(
    hand: str, finger: np.ndarray, palm: np.ndarray | None, bend: np.ndarray, vmax: float, t_sec: float
) -> np.ndarray:
    img = np.full((FORCE_H, FORCE_W, 3), BG, dtype=np.uint8)
    title = f"{'LH' if hand == 'lh' else 'RH'} glove (tactile + bend)   t={t_sec:5.2f}s"
    draw_hand_block(img, 8, hand, title, finger, palm, bend, vmax)
    return img


def draw_review_panel(
    lh_f: np.ndarray,
    lh_p: np.ndarray | None,
    lh_b: np.ndarray,
    rh_f: np.ndarray,
    rh_p: np.ndarray | None,
    rh_b: np.ndarray,
    vmax: float,
    t_sec: float,
) -> np.ndarray:
    img = np.full((PANEL_H, PANEL_W, 3), BG, dtype=np.uint8)
    cv2.putText(img, f"t = {t_sec:6.2f}s", (PANEL_W - 200, 26), cv2.FONT_HERSHEY_SIMPLEX, 0.50, (170, 170, 170), 1, cv2.LINE_AA)
    y = draw_hand_block(img, 10, "lh", "LH glove (tactile + bend)", lh_f, lh_p, lh_b, vmax)
    draw_hand_block(img, y + 8, "rh", "RH glove (tactile + bend)", rh_f, rh_p, rh_b, vmax)
    return img


def list_mcap_topics() -> set[str]:
    with open(MCAP, "rb") as f:
        summary = make_reader(f).get_summary()
    if not summary or not summary.channels:
        return set()
    return {ch.topic for ch in summary.channels.values()}


def extract_streams() -> dict:
    available = list_mcap_topics()
    side_l_topic = WRIST_LH_TOPIC if WRIST_LH_TOPIC in available else MONO_L_TOPIC
    side_r_topic = WRIST_RH_TOPIC if WRIST_RH_TOPIC in available else MONO_R_TOPIC
    side_l_key = "wrist_lh" if side_l_topic == WRIST_LH_TOPIC else "mono_left"
    side_r_key = "wrist_rh" if side_r_topic == WRIST_RH_TOPIC else "mono_right"
    raw_paths = {
        "head": OUT / "_head.h264",
        side_l_key: OUT / f"_{side_l_key}.h264",
        side_r_key: OUT / f"_{side_r_key}.h264",
    }
    writers = {k: p.open("wb") for k, p in raw_paths.items()}
    topic_to_key = {
        HEAD_TOPIC: "head",
        side_l_topic: side_l_key,
        side_r_topic: side_r_key,
    }
    tactile = {h: {"t": [], "finger": [], "palm": [], "bend": [], "force": [], "has_force": False} for h in ("lh", "rh")}
    t0 = None
    counts = {k: 0 for k in raw_paths}
    print("reading MCAP (video + tactile) ...", flush=True)
    print(f"  cameras: head + {side_l_key} + {side_r_key}", flush=True)
    with open(MCAP, "rb") as f:
        reader = make_reader(f)
        for _sch, ch, msg in reader.iter_messages(
            topics=[HEAD_TOPIC, side_l_topic, side_r_topic, LH_TACTILE, RH_TACTILE]
        ):
            if ch.topic in topic_to_key:
                payload = proto_bytes_field(msg.data, 3)
                if payload:
                    writers[topic_to_key[ch.topic]].write(payload)
                    counts[topic_to_key[ch.topic]] += 1
                continue
            obj = json.loads(msg.data)
            parsed = _parse_tactile(obj)
            if t0 is None:
                t0 = parsed["t"]
            _append_tactile(tactile, parsed, t0)
    for w in writers.values():
        w.close()
    print(f"  video frames {counts}", flush=True)
    out = {"raw": raw_paths, "t0": t0}
    out.update(_pack_tactile(tactile))
    return out


def _named_finger(named: dict) -> np.ndarray:
    finger = np.zeros((5, 12), dtype=np.float32)
    for i, name in enumerate(FINGERS):
        row = named.get(name) or []
        finger[i, : min(12, len(row))] = row[:12]
    return finger


def _parse_tactile(obj: dict) -> dict:
    named = obj.get("finger_pressure") or {}
    adc = _named_finger(named)
    force = None
    pix = obj.get("finger_force_N_pixels")
    if pix:
        force = np.zeros((5, 12), dtype=np.float32)
        for i in range(min(5, len(pix))):
            row = pix[i]
            force[i, : min(12, len(row))] = row[:12]
    palm = np.zeros(60, dtype=np.float32)
    raw_palm = obj.get("palm_pressure") or []
    palm[: min(60, len(raw_palm))] = raw_palm[:60]
    bend = np.zeros(5, dtype=np.float32)
    raw_bend = obj.get("finger_bend") or []
    bend[: min(5, len(raw_bend))] = raw_bend[:5]
    return {
        "hand": obj["hand"],
        "t": float(obj["timestamp"]),
        "adc": adc,
        "force": force,
        "palm": palm,
        "bend": bend,
    }


def _append_tactile(tactile: dict, parsed: dict, t0: float) -> None:
    hand = parsed["hand"]
    tactile[hand]["t"].append(parsed["t"] - t0)
    tactile[hand]["finger"].append(parsed["adc"])
    tactile[hand]["palm"].append(parsed["palm"])
    tactile[hand]["bend"].append(parsed["bend"])
    if parsed["force"] is not None:
        tactile[hand]["force"].append(parsed["force"])
        tactile[hand]["has_force"] = True
    else:
        tactile[hand]["force"].append(np.zeros((5, 12), dtype=np.float32))


def _pack_tactile(tactile: dict) -> dict:
    out = {}
    for h in ("lh", "rh"):
        out[h] = {
            "t": np.asarray(tactile[h]["t"], dtype=np.float64),
            "adc": np.asarray(tactile[h]["finger"], dtype=np.float32),
            "force": np.asarray(tactile[h]["force"], dtype=np.float32),
            "palm": np.asarray(tactile[h]["palm"], dtype=np.float32),
            "bend": np.asarray(tactile[h]["bend"], dtype=np.float32),
            "has_force": bool(tactile[h]["has_force"]),
        }
        adc_max = float(out[h]["adc"].max()) if out[h]["adc"].size else 0.0
        force_max = float(out[h]["force"].max()) if out[h]["has_force"] and out[h]["force"].size else 0.0
        print(
            f"  {h} tactile {out[h]['t'].shape[0]}  "
            f"ADC max {adc_max:.0f}  "
            f"force {'yes' if out[h]['has_force'] else 'no'} {force_max:.2f} N  "
            f"palm max {float(out[h]['palm'].max()) if out[h]['palm'].size else 0:.0f}  "
            f"bend max {float(out[h]['bend'].max()) if out[h]['bend'].size else 0:.0f}",
            flush=True,
        )
    return out


def extract_tactile() -> dict:
    tactile = {h: {"t": [], "finger": [], "palm": [], "bend": [], "force": [], "has_force": False} for h in ("lh", "rh")}
    t0 = None
    print("reading MCAP tactile ...", flush=True)
    with open(MCAP, "rb") as f:
        reader = make_reader(f)
        for _sch, _ch, msg in reader.iter_messages(topics=[LH_TACTILE, RH_TACTILE]):
            parsed = _parse_tactile(json.loads(msg.data))
            if t0 is None:
                t0 = parsed["t"]
            _append_tactile(tactile, parsed, t0)
    out = {"t0": t0}
    out.update(_pack_tactile(tactile))
    return out


def _interp_nd(t: np.ndarray, values: np.ndarray, grid: np.ndarray) -> np.ndarray:
    flat = values.reshape(len(t), -1)
    out = np.empty((len(grid), flat.shape[1]), dtype=np.float32)
    for c in range(flat.shape[1]):
        out[:, c] = np.interp(grid, t, flat[:, c])
    return out.reshape((len(grid),) + values.shape[1:])


def resample_hand(hand: dict, n: int = N_FRAMES, fps: float = FPS) -> dict:
    t = hand["t"]
    grid = np.arange(n, dtype=np.float64) / fps
    empty = {
        "adc": np.zeros((n, 5, 12), np.float32),
        "force": np.zeros((n, 5, 12), np.float32),
        "palm": np.zeros((n, 60), np.float32),
        "bend": np.zeros((n, 5), np.float32),
        "has_force": bool(hand.get("has_force")),
    }
    if t.size == 0:
        return empty
    return {
        "adc": _interp_nd(t, hand["adc"], grid),
        "force": _interp_nd(t, hand["force"], grid) if hand.get("has_force") else empty["force"],
        "palm": _interp_nd(t, hand["palm"], grid),
        "bend": _interp_nd(t, hand["bend"], grid),
        "has_force": bool(hand.get("has_force")),
    }


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


def render_force_video(hand: str, series: dict, dest: Path, mode: str, vmax: float) -> None:
    proc = _ffmpeg_raw(dest, FORCE_W, FORCE_H)
    finger = series["force"] if mode == "force-pixels" else series["adc"]
    palm = None if mode == "force-pixels" else series["palm"]
    bend = series["bend"]
    n = finger.shape[0]
    for i in range(n):
        frame = draw_review_hand(hand, finger[i], None if palm is None else palm[i], bend[i], vmax, i / FPS)
        proc.stdin.write(frame.tobytes())
        if i % 900 == 0:
            print(f"  {hand} {mode} {i}/{n}", flush=True)
    proc.stdin.close()
    if proc.wait() != 0:
        raise RuntimeError(f"ffmpeg failed for {dest}")


def render_review_panel(lh: dict, rh: dict, dest: Path, mode: str, vmax: float) -> None:
    proc = _ffmpeg_raw(dest, PANEL_W, PANEL_H)
    lf = lh["force"] if mode == "force-pixels" else lh["adc"]
    rf = rh["force"] if mode == "force-pixels" else rh["adc"]
    lp = None if mode == "force-pixels" else lh["palm"]
    rp = None if mode == "force-pixels" else rh["palm"]
    n = lf.shape[0]
    for i in range(n):
        frame = draw_review_panel(
            lf[i],
            None if lp is None else lp[i],
            lh["bend"][i],
            rf[i],
            None if rp is None else rp[i],
            rh["bend"][i],
            vmax,
            i / FPS,
        )
        proc.stdin.write(frame.tobytes())
        if i % 900 == 0:
            print(f"  review panel {i}/{n}", flush=True)
    proc.stdin.close()
    if proc.wait() != 0:
        raise RuntimeError(f"ffmpeg failed for {dest}")


def _label_filter(src: str, tag: str, label: str, w: int, h: int) -> str:
    font = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
    return (
        f"{src}fps=30,tpad=stop_mode=clone:stop=-1,setpts=PTS-STARTPTS,"
        f"scale={w}:{h}:force_original_aspect_ratio=decrease,"
        f"pad={w}:{h}:(ow-iw)/2:(oh-ih)/2,setsar=1,"
        f"drawtext=fontfile={font}:text='{label}':x=16:y=16:fontsize=26:fontcolor=white:box=1:boxcolor=black@0.45[{tag}]"
    )


def compose_summary(
    cameras: list[tuple[Path, str]],
    tactile: Path,
    dest: Path,
    n_frames: int,
) -> None:
    left_w, right_w, height = 1120, 800, 1080
    head_h, small_h, small_w = 360, 360, 560
    slots = list(cameras[1:5])
    while len(slots) < 4:
        slots.append((None, f"EXO {len(slots) - 1}" if len(slots) >= 2 else "unavailable"))
    # keep screenshot labels for the last two placeholders
    if slots[2][0] is None:
        slots[2] = (None, "EXO 1")
    if slots[3][0] is None:
        slots[3] = (None, "EXO 2")
    filt_parts = [_label_filter("[0:v]", "h", cameras[0][1], left_w, head_h)]
    inputs = ["-i", str(cameras[0][0])]
    next_i = 1
    for k, (path, label) in enumerate(slots, start=1):
        tag = f"c{k}"
        if path is None:
            filt_parts.append(
                f"color=c=0x0e0e0e:s={small_w}x{small_h}:r=30,"
                f"drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:"
                f"text='{label}':x=16:y=16:fontsize=26:fontcolor=white:box=1:boxcolor=black@0.45,"
                f"drawtext=fontfile=/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf:"
                f"text='unavailable':x=(w-text_w)/2:y=(h-text_h)/2:fontsize=28:fontcolor=0x666666[{tag}]"
            )
        else:
            filt_parts.append(_label_filter(f"[{next_i}:v]", tag, label, small_w, small_h))
            inputs += ["-i", str(path)]
            next_i += 1
    inputs += ["-i", str(tactile)]
    filt_parts.append(f"[{next_i}:v]fps=30,scale={right_w}:{height},setsar=1[t]")
    layout = f"0_0|0_{head_h}|{small_w}_{head_h}|0_{head_h + small_h}|{small_w}_{head_h + small_h}|{left_w}_0"
    filt = ";".join(filt_parts) + f";[h][c1][c2][c3][c4][t]xstack=inputs=6:layout={layout}[v]"
    cmd = [
        "ffmpeg",
        "-y",
        "-hide_banner",
        "-loglevel",
        "error",
        *inputs,
        "-filter_complex",
        filt,
        "-map",
        "[v]",
        "-c:v",
        "libx264",
        "-preset",
        "veryfast",
        "-pix_fmt",
        "yuv420p",
        "-crf",
        "20",
        "-t",
        f"{n_frames / FPS:.3f}",
        "-movflags",
        "+faststart",
        str(dest),
    ]
    subprocess.run(cmd, check=True)


def reset_output() -> None:
    if OUT.exists():
        shutil.rmtree(OUT)
    OUT.mkdir(parents=True)


def main() -> None:
    if not MCAP.exists():
        raise SystemExit(f"no .mcap found in {ROOT}\nusage: visualize.py <recording_dir> [--remap-only]")
    remap_only = "--remap-only" in sys.argv
    videos = {
        "head": OUT / "head_rgb.mp4",
        "force_lh": OUT / "force_lh.mp4",
        "force_rh": OUT / "force_rh.mp4",
        "tactile": OUT / "tactile_panel.mp4",
        "summary": OUT / "summary.mp4",
    }
    if remap_only:
        side_keys = [k for k in ("wrist_lh", "wrist_rh", "mono_left", "mono_right") if (OUT / f"{k}.mp4").exists()]
        if not videos["head"].exists() or len(side_keys) < 2:
            raise FileNotFoundError("camera videos missing; run without --remap-only")
        videos[side_keys[0]] = OUT / f"{side_keys[0]}.mp4"
        videos[side_keys[1]] = OUT / f"{side_keys[1]}.mp4"
        streams = extract_tactile()
        streams["side_keys"] = (side_keys[0], side_keys[1])
    else:
        reset_output()
        streams = extract_streams()
        side_keys = [k for k in streams["raw"] if k != "head"]
        for key in side_keys:
            videos[key] = OUT / f"{key}.mp4"
        print("encoding camera videos ...", flush=True)
        jobs = []
        for key in ["head", *side_keys]:
            raw = streams["raw"][key]
            if raw.stat().st_size == 0:
                raise RuntimeError(f"empty camera stream: {key}")
            jobs.append(
                subprocess.Popen(
                    [
                        "ffmpeg",
                        "-y",
                        "-hide_banner",
                        "-loglevel",
                        "error",
                        "-fflags",
                        "+genpts",
                        "-r",
                        str(int(FPS)),
                        "-i",
                        str(raw),
                        "-c:v",
                        "libx264",
                        "-preset",
                        "veryfast",
                        "-pix_fmt",
                        "yuv420p",
                        "-crf",
                        "23",
                        "-movflags",
                        "+faststart",
                        str(videos[key]),
                    ]
                )
            )
        for p in jobs:
            if p.wait() != 0:
                raise RuntimeError("ffmpeg camera encode failed")
        for raw in streams["raw"].values():
            raw.unlink(missing_ok=True)
        streams["side_keys"] = tuple(side_keys)

    n_frames = N_FRAMES
    if n_frames <= 0:
        dur = 0.0
        for h in ("lh", "rh"):
            t = streams[h]["t"]
            if t.size:
                dur = max(dur, float(t[-1]))
        n_frames = max(1, int(round(dur * FPS)))
    print(f"episode frames {n_frames} ({n_frames / FPS:.1f}s)", flush=True)

    print("resampling tactile to 30 Hz ...", flush=True)
    lh = resample_hand(streams["lh"], n=n_frames)
    rh = resample_hand(streams["rh"], n=n_frames)
    mode = "force-pixels" if (lh["has_force"] or rh["has_force"]) else "raw"
    if mode == "force-pixels":
        vmax = 20.0
    else:
        vmax = float(max(np.percentile(np.concatenate([lh["adc"].ravel(), rh["adc"].ravel()]), 99.5), 32.0))
    print(f"  review mode {mode}  vmax {vmax:.1f}", flush=True)

    print("rendering review tactile videos ...", flush=True)
    render_force_video("lh", lh, videos["force_lh"], mode, vmax)
    render_force_video("rh", rh, videos["force_rh"], mode, vmax)
    render_review_panel(lh, rh, videos["tactile"], mode, vmax)

    print("composing summary ...", flush=True)
    side_keys = list(streams.get("side_keys") or ("wrist_lh", "wrist_rh"))
    label_map = {
        "wrist_lh": "WRIST LH",
        "wrist_rh": "WRIST RH",
        "mono_left": "HEAD MONO L",
        "mono_right": "HEAD MONO R",
    }
    cameras = [("head", "HEAD RGB")] + [(k, label_map.get(k, k.upper())) for k in side_keys]
    camera_paths = [(videos["head"] if k == "head" else videos[k], lab) for k, lab in cameras]
    compose_summary(camera_paths, videos["tactile"], videos["summary"], n_frames)
    print("wrote", OUT)
    for p in sorted(OUT.iterdir()):
        print(f"  {p.name:16s} {p.stat().st_size / 1e6:8.1f} MB")


if __name__ == "__main__":
    main()