File size: 22,723 Bytes
2b2cfc6
 
 
 
5711283
 
 
2b2cfc6
5711283
 
 
2b2cfc6
 
 
 
 
 
 
 
 
 
 
 
5711283
 
 
2b2cfc6
 
 
 
 
 
 
 
5711283
 
 
2b2cfc6
5711283
 
 
 
 
 
 
 
2b2cfc6
5711283
 
 
 
 
 
 
 
 
 
 
2b2cfc6
 
 
5711283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2cfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5711283
 
 
 
 
 
 
 
 
 
 
2b2cfc6
 
5711283
2b2cfc6
5711283
2b2cfc6
5711283
2b2cfc6
5711283
2b2cfc6
5711283
 
 
 
2b2cfc6
5711283
2b2cfc6
 
5711283
 
 
 
 
 
 
 
 
 
2b2cfc6
5711283
 
 
 
 
 
2b2cfc6
 
 
 
 
 
5711283
2b2cfc6
5711283
 
 
 
2b2cfc6
5711283
 
 
 
 
2b2cfc6
 
 
 
 
 
5711283
 
 
2b2cfc6
 
 
 
5711283
 
 
2b2cfc6
5711283
2b2cfc6
 
 
5711283
 
 
 
2b2cfc6
 
 
 
 
 
 
5711283
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b2cfc6
 
 
5711283
2b2cfc6
 
 
 
5711283
 
 
2b2cfc6
5711283
 
2b2cfc6
 
 
 
 
 
 
 
5711283
2b2cfc6
 
 
 
 
 
5711283
 
 
2b2cfc6
 
 
 
5711283
2b2cfc6
 
5711283
2b2cfc6
 
 
 
 
5711283
 
2b2cfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5711283
 
2b2cfc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5711283
2b2cfc6
 
 
 
5711283
2b2cfc6
 
 
 
 
 
 
 
 
 
 
 
5711283
2b2cfc6
 
 
 
 
 
 
 
 
 
 
 
 
5711283
 
2b2cfc6
 
 
 
 
 
5711283
 
 
2b2cfc6
5711283
 
 
 
 
2b2cfc6
 
5711283
2b2cfc6
 
 
 
5711283
 
 
2b2cfc6
 
5711283
2b2cfc6
5711283
 
2b2cfc6
 
 
 
 
 
 
 
 
 
5711283
2b2cfc6
 
5711283
 
 
 
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
"""Interactive playback for React data — accepts a single `.pt` OR a
directory of segments / episodes, concatenates same-episode segments
into one continuous timeline, and lets you switch between source
episodes with N / P.

Usage
-----
Single file (mode1_v1 episode OR a single mode2_v1 segment):
    python examples/play_react_pt.py \\
        processed/mode2_v1/motherboard/2026-05-11/episode_012.segment_00.pt

Whole task — episode-by-episode browser:
    python examples/play_react_pt.py \\
        processed/mode2_v1/motherboard

  All segments of `episode_NNN` are concatenated into one playback
  timeline; N / P jumps to the next / previous source episode.

  Works with mode1_v1 too (each `.pt` is treated as a one-segment
  episode); N / P then jumps file-to-file.

Headless export (one MP4 per episode):
    python examples/play_react_pt.py <root> --save_video_dir /tmp/out

Controls
--------
    space         — pause / resume
    → / d         — next frame
    ← / a         — previous frame
    1..6          — playback speed 1× / 2× / 5× / 10× / 25× / 50×
    r             — reset GelSight diff reference to current frame
    n             — next episode
    p             — previous episode
    q             — quit
"""
import argparse
import collections
import re
import sys
import time
from pathlib import Path

import cv2
import numpy as np
import torch

# ──────────────────────────────────────────────────────────────────────────────
TRACKER_COLORS = {
    "sensor_left":  (  0, 255, 120),
    "sensor_right": (  0, 180, 255),
}
PANEL_W, PANEL_H = 1280, 480
VIEW_THUMB = (320, 240)
TAC_THUMB = (240, 240)
OT_PANEL = (320, 240)
TRAIL_PANEL = (640, 240)
CONTROLS_PANEL = (320, 240)

SEGMENT_FNAME_RE = re.compile(r"^(episode_\d+)\.segment_(\d+)\.pt$")
PLAIN_EPISODE_RE = re.compile(r"^(episode_\d+)\.pt$")


def _to_hwc(t):
    return t.permute(1, 2, 0).numpy() if t.ndim == 3 else t.numpy()

def _view_to_bgr(view_chw):
    return view_chw.permute(1, 2, 0).numpy()

def _tactile_to_bgr(tac_chw):
    rgb = tac_chw.permute(1, 2, 0).numpy()
    return rgb[..., ::-1]

def _diff_thumb(frame_bgr, ref_bgr, size):
    diff = np.clip(frame_bgr.astype(np.int16) - ref_bgr.astype(np.int16) + 128, 0, 255).astype(np.uint8)
    return cv2.resize(diff, size, interpolation=cv2.INTER_NEAREST)


# ──────────────────────────────────────────────────────────────────────────────
# Episode discovery
# ──────────────────────────────────────────────────────────────────────────────

def discover_episodes(root: Path) -> list[dict]:
    """Walk `root`, group .pt files by source episode key '<date>/episode_NNN',
    and return one entry per episode with its segment paths sorted.

    Handles both:
      - mode2_v1: `<root>/<date>/episode_NNN.segment_MM.pt`
      - mode1_v1: `<root>/<date>/episode_NNN.pt`
    """
    pts = sorted(root.rglob("*.pt"))
    if not pts:
        raise SystemExit(f"No .pt files under {root}")

    episodes: dict[str, dict] = {}    # key: "<date>/<ep>" → {date, ep_stem, segs: [(seg_idx, path)]}
    for p in pts:
        m_seg = SEGMENT_FNAME_RE.match(p.name)
        m_plain = PLAIN_EPISODE_RE.match(p.name)
        if m_seg:
            ep_stem, seg_idx = m_seg.group(1), int(m_seg.group(2))
        elif m_plain:
            ep_stem, seg_idx = m_plain.group(1), 0
        else:
            continue
        date = p.parent.name
        key = f"{date}/{ep_stem}"
        episodes.setdefault(key, {"date": date, "ep_stem": ep_stem, "segs": []})
        episodes[key]["segs"].append((seg_idx, p))

    out = []
    for key in sorted(episodes):
        ep = episodes[key]
        ep["segs"].sort(key=lambda x: x[0])
        out.append({"key": key, **ep})
    return out


# ──────────────────────────────────────────────────────────────────────────────
# Episode-load
# ──────────────────────────────────────────────────────────────────────────────

class LoadedEpisode:
    """One source episode, with all its segments concatenated for playback.

    Stores:
      - keys for the 5 image-shaped tensors (view, tactile_*) concatenated
      - keys for the 5 per-frame scalar/vector tensors
      - segment_bounds[i] = (start_in_concat, end_in_concat, seg_idx, source_h5_range)
        for the i-th segment
      - p01 reference frames pulled from the *first* segment's _contact_meta
    """
    PER_FRAME_KEYS = (
        "view", "tactile_left", "tactile_right",
        "sensor_left_pose", "sensor_right_pose", "timestamps",
        "tactile_left_intensity",  "tactile_right_intensity",
        "tactile_left_mixed",      "tactile_right_mixed",
    )

    def __init__(self, ep_meta: dict):
        self.key = ep_meta["key"]
        self.date = ep_meta["date"]
        self.ep_stem = ep_meta["ep_stem"]
        self.segment_paths = [p for _, p in ep_meta["segs"]]
        print(f"[player] loading episode {self.key}  "
              f"({len(self.segment_paths)} segment{'s' if len(self.segment_paths) > 1 else ''})...")

        per_seg = [torch.load(p, weights_only=False, map_location="cpu") for p in self.segment_paths]
        cat = {}
        for k in self.PER_FRAME_KEYS:
            if k in per_seg[0]:
                cat[k] = torch.cat([s[k] for s in per_seg], dim=0)
        # Boundaries
        bounds = []
        cursor = 0
        for i, s in enumerate(per_seg):
            n = s["view"].shape[0]
            meta = s.get("_contact_meta", {})
            bounds.append({
                "start_in_concat": cursor,
                "end_in_concat":   cursor + n - 1,
                "seg_idx":         int(meta.get("source_segment_idx", i)),
                "source_h5_range": meta.get("source_h5_frame_range"),
                "n_frames":        n,
            })
            cursor += n
        self.data = cat
        self.bounds = bounds
        self.n_frames = cursor
        meta0 = per_seg[0].get("_contact_meta", {})
        # p01 references from the first segment (same per-source-episode)
        self.ref_L = _tactile_to_bgr(meta0["ref_p01_left"]) if meta0.get("ref_p01_left") is not None else _tactile_to_bgr(per_seg[0]["tactile_left"][0])
        self.ref_R = _tactile_to_bgr(meta0["ref_p01_right"]) if meta0.get("ref_p01_right") is not None else _tactile_to_bgr(per_seg[0]["tactile_right"][0])
        print(f"[player]   total {self.n_frames} frames  ({self.n_frames / 30.0:.1f}s)")

    def segment_at(self, frame_idx: int) -> dict:
        for b in self.bounds:
            if b["start_in_concat"] <= frame_idx <= b["end_in_concat"]:
                return b
        return self.bounds[-1]

    def is_segment_start(self, frame_idx: int) -> bool:
        return any(frame_idx == b["start_in_concat"] for b in self.bounds[1:])


# ──────────────────────────────────────────────────────────────────────────────
# Panel renderer
# ──────────────────────────────────────────────────────────────────────────────

def _make_ot_panel(pose_L, pose_R, t_idx, t_sec, w, h):
    panel = np.zeros((h, w, 3), np.uint8)
    cv2.putText(panel, "OptiTrack (this frame)", (8, 22),
                cv2.FONT_HERSHEY_SIMPLEX, 0.55, (200, 200, 200), 1, cv2.LINE_AA)
    cv2.line(panel, (8, 30), (w - 8, 30), (60, 60, 60), 1)
    y = 56
    for name, p, color in [("sensor_left", pose_L, TRACKER_COLORS["sensor_left"]),
                            ("sensor_right", pose_R, TRACKER_COLORS["sensor_right"])]:
        cv2.putText(panel, name, (8, y), cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 1, cv2.LINE_AA)
        y += 18
        if p is None or all(v == 0 for v in p):
            cv2.putText(panel, "  no data", (8, y), cv2.FONT_HERSHEY_SIMPLEX, 0.4, (100, 100, 100), 1, cv2.LINE_AA)
            y += 36; continue
        x, yv, z, qx, qy, qz, qw = p
        cv2.putText(panel, f"  x={x:+.3f} y={yv:+.3f} z={z:+.3f}", (8, y), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (220, 220, 220), 1, cv2.LINE_AA)
        y += 16
        cv2.putText(panel, f"  qx={qx:+.2f} qy={qy:+.2f}", (8, y), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (160, 160, 160), 1, cv2.LINE_AA)
        y += 16
        cv2.putText(panel, f"  qz={qz:+.2f} qw={qw:+.2f}", (8, y), cv2.FONT_HERSHEY_SIMPLEX, 0.38, (160, 160, 160), 1, cv2.LINE_AA)
        y += 24
    cv2.putText(panel, f"t = {t_sec:.2f} s   (concat frame {t_idx})",
                (8, h - 14), cv2.FONT_HERSHEY_SIMPLEX, 0.45, (200, 200, 200), 1, cv2.LINE_AA)
    return panel


def _make_trail_panel(iL_trail, iR_trail, boundary_marks, w, h, threshold=0.4):
    panel = np.zeros((h, w, 3), np.uint8)
    cv2.putText(panel, "Contact intensity (mixed)  — orange = L  ·  blue = R  ·  red = segment cut",
                (8, 22), cv2.FONT_HERSHEY_SIMPLEX, 0.48, (200, 200, 200), 1, cv2.LINE_AA)
    cv2.line(panel, (8, 30), (w - 8, 30), (60, 60, 60), 1)
    mid_y = h - 26
    max_y = 50
    cv2.line(panel, (8, mid_y), (w - 8, mid_y), (80, 80, 80), 1)
    if not iL_trail:
        return panel
    N = len(iL_trail)
    smax = max(max(iL_trail), max(iR_trail), float(threshold) * 1.5, 1e-3)
    x_scale = (w - 16) / max(N - 1, 1)
    for i in range(N - 1):
        x0 = int(8 + i * x_scale); x1 = int(8 + (i + 1) * x_scale)
        y0L = mid_y - int(min(iL_trail[i],     smax) / smax * max_y)
        y1L = mid_y - int(min(iL_trail[i + 1], smax) / smax * max_y)
        cv2.line(panel, (x0, y0L), (x1, y1L), (0, 159, 230), 1, cv2.LINE_AA)
        y0R = mid_y + int(min(iR_trail[i],     smax) / smax * max_y)
        y1R = mid_y + int(min(iR_trail[i + 1], smax) / smax * max_y)
        cv2.line(panel, (x0, y0R), (x1, y1R), (178, 114, 0), 1, cv2.LINE_AA)
    # Segment-cut markers
    for off in boundary_marks:
        if 0 <= off < N:
            x = int(8 + off * x_scale)
            cv2.line(panel, (x, 35), (x, h - 30), (0, 0, 220), 1, cv2.LINE_AA)
    cv2.putText(panel, f"L = {iL_trail[-1]:.2f}", (10, 50),
                cv2.FONT_HERSHEY_SIMPLEX, 0.42, (0, 159, 230), 1, cv2.LINE_AA)
    cv2.putText(panel, f"R = {iR_trail[-1]:.2f}", (10, h - 8),
                cv2.FONT_HERSHEY_SIMPLEX, 0.42, (178, 114, 0), 1, cv2.LINE_AA)
    return panel


def _make_controls_panel(w, h, paused, speed, ep_idx, n_eps):
    panel = np.zeros((h, w, 3), np.uint8)
    cv2.putText(panel, "Controls", (10, 22),
                cv2.FONT_HERSHEY_SIMPLEX, 0.55, (200, 200, 200), 1, cv2.LINE_AA)
    cv2.line(panel, (10, 30), (w - 10, 30), (60, 60, 60), 1)
    keys = [
        ("SPACE",  "pause / resume"),
        ("←  →",   "prev / next frame"),
        ("1..6",   "speed 1x/2x/5x/10x/25x/50x"),
        ("n  p",   "next / prev episode"),
        ("r",      "reset gel-diff ref"),
        ("q",      "quit"),
    ]
    y = 52
    for k, v in keys:
        cv2.putText(panel, f"[{k}]", (10, y),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.42, (140, 200, 140), 1, cv2.LINE_AA)
        cv2.putText(panel, v, (110, y),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.42, (200, 200, 200), 1, cv2.LINE_AA)
        y += 22
    state = "|| PAUSED" if paused else "> PLAYING"
    state_col = (0, 140, 255) if paused else (0, 220, 80)
    cv2.putText(panel, state, (10, h - 50),
                cv2.FONT_HERSHEY_SIMPLEX, 0.55, state_col, 2, cv2.LINE_AA)
    cv2.putText(panel, f"speed: {speed}x", (10, h - 30),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (180, 180, 180), 1, cv2.LINE_AA)
    cv2.putText(panel, f"episode {ep_idx + 1} / {n_eps}", (10, h - 10),
                cv2.FONT_HERSHEY_SIMPLEX, 0.45, (180, 180, 180), 1, cv2.LINE_AA)
    return panel


def build_panel(ep: LoadedEpisode, frame_idx: int, ref_L_bgr, ref_R_bgr,
                iL_trail, iR_trail, boundary_marks_local,
                paused: bool, speed: int,
                ep_idx: int, n_eps: int):
    view_bgr  = _view_to_bgr(ep.data["view"][frame_idx])
    tac_L_bgr = _tactile_to_bgr(ep.data["tactile_left"][frame_idx])
    tac_R_bgr = _tactile_to_bgr(ep.data["tactile_right"][frame_idx])

    view_thumb  = cv2.resize(view_bgr,  VIEW_THUMB, interpolation=cv2.INTER_NEAREST)
    tac_L_thumb = cv2.resize(tac_L_bgr, TAC_THUMB,  interpolation=cv2.INTER_NEAREST)
    tac_R_thumb = cv2.resize(tac_R_bgr, TAC_THUMB,  interpolation=cv2.INTER_NEAREST)
    tac_L_diff  = _diff_thumb(tac_L_bgr, ref_L_bgr, TAC_THUMB)
    tac_R_diff  = _diff_thumb(tac_R_bgr, ref_R_bgr, TAC_THUMB)
    for img, label in [(view_thumb, "cam0 / view"),
                       (tac_L_thumb, "tactile_left"),
                       (tac_L_diff,  "tac_L diff (vs p01)"),
                       (tac_R_thumb, "tactile_right"),
                       (tac_R_diff,  "tac_R diff (vs p01)")]:
        cv2.putText(img, label, (6, 14),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.4, (220, 220, 220), 1, cv2.LINE_AA)
    row1 = np.hstack([view_thumb, tac_L_thumb, tac_L_diff, tac_R_thumb, tac_R_diff])

    pose_L = ep.data["sensor_left_pose"][frame_idx].tolist()
    pose_R = ep.data["sensor_right_pose"][frame_idx].tolist()
    t_sec  = float(ep.data["timestamps"][frame_idx] - ep.data["timestamps"][0])
    ot_panel       = _make_ot_panel(pose_L, pose_R, frame_idx, t_sec, *OT_PANEL)
    trail_panel    = _make_trail_panel(list(iL_trail), list(iR_trail),
                                        boundary_marks_local, *TRAIL_PANEL)
    controls_panel = _make_controls_panel(*CONTROLS_PANEL, paused=paused, speed=speed,
                                           ep_idx=ep_idx, n_eps=n_eps)
    row2 = np.hstack([ot_panel, trail_panel, controls_panel])
    panel = np.vstack([row1, row2])

    # Top status bar
    cv2.rectangle(panel, (0, 0), (PANEL_W, 22), (30, 30, 30), -1)
    state = "PAUSED" if paused else "PLAYING"
    seg = ep.segment_at(frame_idx)
    h5r = seg["source_h5_range"]
    seg_label = f"seg {seg['seg_idx']:02d}"
    if h5r:
        seg_label += f"  H5[{h5r[0]}..{h5r[1]}]"
    status = (f"[{state}]  ep {ep_idx + 1}/{n_eps}  {ep.key}  ·  "
              f"frame {frame_idx + 1}/{ep.n_frames}  ·  t={t_sec:.2f}s  ·  "
              f"{seg_label}  ·  {speed}x")
    cv2.putText(panel, status, (10, 16),
                cv2.FONT_HERSHEY_SIMPLEX, 0.46, (0, 200, 255), 1, cv2.LINE_AA)

    # Segment-cut flash: red border for the first 2 frames of a non-first segment
    if ep.is_segment_start(frame_idx):
        cv2.rectangle(panel, (0, 22), (PANEL_W - 1, PANEL_H - 1), (0, 0, 220), 3)

    return panel


# ──────────────────────────────────────────────────────────────────────────────
# Main
# ──────────────────────────────────────────────────────────────────────────────

def main():
    ap = argparse.ArgumentParser(description="Interactive React .pt player.")
    ap.add_argument("path", help="A single .pt file OR a directory of episodes/segments.")
    ap.add_argument("--save_video", default=None,
                    help="When `path` is a single .pt: write that one episode as MP4 here.")
    ap.add_argument("--save_video_dir", default=None,
                    help="When `path` is a directory: write one MP4 per episode into this dir.")
    ap.add_argument("--fps", type=float, default=30.0)
    ap.add_argument("--trail_frames", type=int, default=120)
    args = ap.parse_args()

    in_path = Path(args.path)
    if not in_path.exists():
        print(f"Not found: {in_path}", file=sys.stderr); sys.exit(1)

    if in_path.is_file():
        # Single .pt → one-episode mode (use parent dir for discovery to enable n/p)
        parent_root = in_path.parent.parent  # <root>/<date>/file.pt → <root>
        episodes = discover_episodes(parent_root)
        # Find the episode that contains this exact file
        target_path = in_path.resolve()
        start_idx = 0
        for i, ep_meta in enumerate(episodes):
            if any(p.resolve() == target_path for _, p in ep_meta["segs"]):
                start_idx = i; break
    else:
        episodes = discover_episodes(in_path)
        start_idx = 0
    print(f"[player] discovered {len(episodes)} episode(s) under {in_path}")

    headless_dir = Path(args.save_video_dir) if args.save_video_dir else None
    headless_single = args.save_video

    if headless_single and len(episodes) > 1 and in_path.is_dir():
        print("--save_video accepts a single output path; for a directory pass --save_video_dir instead.", file=sys.stderr)
        sys.exit(1)

    headless = headless_single is not None or headless_dir is not None

    if headless:
        if headless_dir:
            headless_dir.mkdir(parents=True, exist_ok=True)
        for ep_idx in range(start_idx, len(episodes)):
            ep = LoadedEpisode(episodes[ep_idx])
            out_path = (Path(headless_single)
                        if headless_single else
                        (headless_dir / f"{ep.date}_{ep.ep_stem}.mp4"))
            fourcc = cv2.VideoWriter_fourcc(*"mp4v")
            writer = cv2.VideoWriter(str(out_path), fourcc, args.fps, (PANEL_W, PANEL_H))
            iL_trail = collections.deque(maxlen=args.trail_frames)
            iR_trail = collections.deque(maxlen=args.trail_frames)
            print(f"  → {out_path}")
            for f in range(ep.n_frames):
                iL_trail.append(float(ep.data["tactile_left_mixed"][f]))
                iR_trail.append(float(ep.data["tactile_right_mixed"][f]))
                local_boundary_marks = [
                    args.trail_frames - 1 - (f - b["start_in_concat"])
                    for b in ep.bounds[1:]
                    if b["start_in_concat"] <= f and (f - b["start_in_concat"]) < args.trail_frames
                ]
                panel = build_panel(ep, f, ep.ref_L, ep.ref_R,
                                    iL_trail, iR_trail, local_boundary_marks,
                                    paused=False, speed=1,
                                    ep_idx=ep_idx, n_eps=len(episodes))
                writer.write(panel)
            writer.release()
            if headless_single:
                break
        return

    # Interactive
    paused, speed = False, 1
    SPEEDS = {ord('1'): 1, ord('2'): 2, ord('3'): 5,
              ord('4'): 10, ord('5'): 25, ord('6'): 50}

    ep_idx = start_idx
    while 0 <= ep_idx < len(episodes):
        ep = LoadedEpisode(episodes[ep_idx])
        WIN = "React .pt player"
        cv2.namedWindow(WIN, cv2.WINDOW_AUTOSIZE)
        cv2.createTrackbar("Frame", WIN, 0, max(1, ep.n_frames - 1), lambda v: None)
        ref_L, ref_R = ep.ref_L, ep.ref_R
        iL_trail = collections.deque(maxlen=args.trail_frames)
        iR_trail = collections.deque(maxlen=args.trail_frames)
        frame_idx = 0
        last_drawn = -1
        action = "stay"     # 'next' | 'prev' | 'quit' | 'stay'

        while True:
            frame_idx = max(0, min(frame_idx, ep.n_frames - 1))
            pos = cv2.getTrackbarPos("Frame", WIN)
            if pos != frame_idx and pos != last_drawn:
                frame_idx = pos; paused = True

            iL_trail.append(float(ep.data["tactile_left_mixed"][frame_idx]))
            iR_trail.append(float(ep.data["tactile_right_mixed"][frame_idx]))
            boundary_marks = [
                args.trail_frames - 1 - (frame_idx - b["start_in_concat"])
                for b in ep.bounds[1:]
                if b["start_in_concat"] <= frame_idx and (frame_idx - b["start_in_concat"]) < args.trail_frames
            ]

            panel = build_panel(ep, frame_idx, ref_L, ref_R,
                                iL_trail, iR_trail, boundary_marks,
                                paused=paused, speed=speed,
                                ep_idx=ep_idx, n_eps=len(episodes))
            cv2.imshow(WIN, panel)
            if cv2.getTrackbarPos("Frame", WIN) != frame_idx:
                cv2.setTrackbarPos("Frame", WIN, frame_idx)
            last_drawn = frame_idx

            key = cv2.waitKey(1) & 0xFF
            if   key == ord('q'): action = "quit"; break
            elif key == ord(' '): paused = not paused
            elif key in (81, ord('a')): paused = True; frame_idx -= 1
            elif key in (83, ord('d')): paused = True; frame_idx += 1
            elif key in SPEEDS:   speed = SPEEDS[key]
            elif key == ord('r'):
                ref_L = _tactile_to_bgr(ep.data["tactile_left"][frame_idx])
                ref_R = _tactile_to_bgr(ep.data["tactile_right"][frame_idx])
                print(f"  diff ref reset to frame {frame_idx}")
            elif key == ord('n'):
                action = "next"; break
            elif key == ord('p'):
                action = "prev"; break

            if not paused:
                frame_idx += speed
                if frame_idx >= ep.n_frames:
                    print(f"End of episode {ep.key}.")
                    paused = True
                    frame_idx = ep.n_frames - 1
                time.sleep(max(0.0, 1.0 / (args.fps * speed) - 0.001))

        cv2.destroyAllWindows()
        if action == "quit": return
        if action == "next":
            ep_idx = min(ep_idx + 1, len(episodes) - 1)
            if ep_idx == len(episodes) - 1 and episodes[ep_idx]["key"] == ep.key:
                print("Already at last episode.")
        elif action == "prev":
            ep_idx = max(ep_idx - 1, 0)
            if ep_idx == 0 and episodes[ep_idx]["key"] == ep.key:
                print("Already at first episode.")
        else:
            # natural end of an episode — pause; wait for explicit action
            paused = True


if __name__ == "__main__":
    main()