File size: 83,606 Bytes
868a5eb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
"""Render a fully-aligned robot (FR3 / Panda arm + Robotiq 2F-85) over DROID raw videos,
using the per-episode robot model, calibrations and per-step joint states.

Outputs per camera, under <out_root>/<uuid>/<serial>/ (out_root defaults to out/):
  overlay.mp4      render alpha-blended on the real video
  sidebyside.mp4   [real | render | overlay]
  render.mp4 / mask.mp4 [/ normal.mp4]
  render/ mask/ [normal/]   per-frame PNGs (--save-frames)
plus <out_root>/<uuid>/render_meta.json (URDFs + md5, calibration source, time offset, sizes).

Geometry / calibration model (see README "calibration" and out/diag/DIAGNOSIS.md):
  * arm URDF per episode from data/robot_model_map.json (FR3 or Panda shell, identical kinematics),
    gripper assets/robotiq_2f85_fixed.urdf (MuJoCo-exact 4-bar pivots), mount link8 -> gripper
    from calib/mount_params.json if present else the MOUNT_* constants below.
  * camera->base extrinsics: data/<uuid>/calib_refined_v2.json when present
    (ext_base_pose6 + camera-frame ext_delta, wrist_delta, time_offset_ms), otherwise the
    official superset pose with identity delta and time_offset_ms = TIME_OFFSET_DEFAULT_MS
    (episodes absent from the superset: h5 camera_extrinsics, source 'h5', degraded).
    The old calib_refined.json (v1) embeds the pre-fix geometry and is IGNORED unless
    EpisodeSession(..., legacy_calib=True).
  * wrist camera: T_base2cam = pose6_to_mat(wrist_delta) @ inv(T_l8 @ X_handeye).  wrist_delta is
    the TOTAL camera-frame correction: when a session's wrist video is rotated 180 deg relative to
    the h5 hand-eye, the writer sets wrist_flipped=true AND folds the roll into wrist_delta
    (fold_wrist_flip); the renderer never applies wrist_flipped itself (a flag with an un-folded
    delta is detected and logged as a WARNING).
  * robot state for frame i is interpolated (cubic Hermite with joint_velocities, gripper linear)
    to estimated_capture[i] + time_offset_ms.
  * TinyRenderer row bias: RobotRenderer passes tiny_renderer=True to dutils.gl_projection_matrix
    explicitly (the dutils default is the plain matrix; see dutils.TINY_RENDERER_DEFAULT).
  * wrist-camera body (default ON, 2026-10-17): the real gripper carries the ZED Mini on its +y side and the
    SAM3 GT masks include it; RobotRenderer adds a rigid collision-free box (ZED Mini body, half extents
    calib/mount_params.json["wrist_cam_body"]) posed per episode from the h5 hand-eye (EpisodeSession.X_handeye:
    centre = left lens + R_cam @ lens_to_centre), fallback = mean pose in the gripper root frame.  mask.mp4 /
    normals / seg include it; the body is hidden for renders whose camera origin lies inside it (the wrist
    camera's own view).  RobotRenderer(wrist_cam_body=False) / --no-wrist-cam-body disable it;
    RobotRenderer.render(..., return_seg=True) + seg_body_masks() give arm / gripper / wrist_cam masks.
  * EpisodeSession(legacy_geometry=True) / --legacy-geometry reproduces the pre-2026-10 renders
    (legacy gripper URDF, MOUNT_*_LEGACY, mimic 1/1/-1/0, gmax 0.8, FR3 shell, plain projection,
    linear interpolation, v1 calibration + WRIST_DELTA_LEGACY) for before/after comparisons.

Usage:
  python render_episode.py <episode_dir> [--wrist] [--normals] [--save-frames] [--single STEP]
                           [--serials S1 S2] [--mount-pos x y z] [--mount-euler rx ry rz]
                           [--arm-urdf PATH] [--gripper-urdf PATH] [--mount-params PATH]
                           [--legacy-calib] [--legacy-geometry] [--linear-interp] [--no-wrist-cam-body]
                           [--out-root DIR] [--max-frames N]
"""
import argparse
import json
import sys
from pathlib import Path

import cv2
import h5py
import imageio.v2 as imageio
import numpy as np
import pybullet as p
from scipy.spatial.transform import Rotation as R

from dutils import (ROOT, gl_projection_matrix, gl_view_matrix, load_calib, load_calib_full,  # noqa: F401
                    mat_to_pose6, md5_file, md5_json, pose6_to_mat, scale_K)

W, H = 1280, 720

# ----------------------------------------------------------------------------- robot models
ARM_URDFS = {"fr3": ROOT / "assets/fr3_arm.urdf", "panda": ROOT / "assets/panda_arm.urdf"}
ARM_URDF = ARM_URDFS["fr3"]                      # default shell when nothing resolves (logged)
_ARM_URDF_DEFAULT = ARM_URDFS["fr3"]             # a module-level override of ARM_URDF counts as explicit
GRIPPER_URDF = ROOT / "assets/robotiq_2f85_fixed.urdf"   # canonical 2F-85 (MuJoCo-exact pivots)
GRIPPER_URDF_LEGACY = ROOT / "assets/robotiq_2f85_legacy_pivotbug.urdf"  # pre-fix file, diagnostics only
ROBOT_MODEL_MAP = ROOT / "data/robot_model_map.json"
MOUNT_PARAMS_PATH = ROOT / "calib/mount_params.json"

# flange (panda_link8) -> gripper URDF root.  A PRIOR until P0.6 writes calib/mount_params.json:
# rotz 91.3 deg from the 622-frame multi-lab SAM3-GT fit (every independent refit 90.5-91.6 deg;
# the wrist cameras' shared -4.9 deg roll is the same error).  pos (-1.9, 0.9, -2.1) mm comes
# from the same EXTERIOR-ONLY fit and is weakly determined there (1 px ~ 2 mm): with rotz 91.3 the
# exterior gripper-ROI IoU is 0.636 (this pos) / 0.628 (old pos -4.6, 2.0, -2.4 mm) / 0.635 (zero),
# while the wrist whole-gripper IoU is 0.712 / 0.726 / 0.700 but confounded by the per-session
# hand-eye error (wrist centroid dx +20..+28 px for every pos; out/diag/review_p0/mount_summary.txt).
# P0.6 must fit pos jointly on exterior gripper-ROI + wrist GT (DIAGNOSIS P0.6).
MOUNT_POS = np.array([-0.0019, 0.0009, -0.0021])
MOUNT_EULER = np.array([0.0, 0.0, np.deg2rad(91.3)])  # scipy 'xyz'
MOUNT_FITTED_ON = "prior: 622-frame multi-lab SAM3-GT exterior fit (out/diag/residual/h3.json); P0.6 refit pending"

# the pre-2026-10 pipeline's mount / gripper constants (one TRI episode, pivot-buggy gripper URDF,
# dark-pixel objective).  Only for EpisodeSession(legacy_geometry=True) / --legacy-geometry.
MOUNT_POS_LEGACY = np.array([-0.0046, 0.0020, -0.0024])
MOUNT_EULER_LEGACY = np.array([0.0, 0.0, np.deg2rad(96.36)])
GRIPPER_MAX_ANGLE_LEGACY = 0.8
GRIPPER_MIMIC_LEGACY = {
    "right_driver_joint": 1.0, "left_driver_joint": 1.0,
    "right_spring_link_joint": 1.0, "left_spring_link_joint": 1.0,
    "right_follower_joint": -1.0, "left_follower_joint": -1.0,
    "right_coupler_joint": 0.0, "left_coupler_joint": 0.0,
}

# Constant hand-eye correction for the wrist camera.  ZERO by design: the wrist correction is a
# per-episode quantity (calib_refined_v2.json["wrist_delta"]).  Kept for API compatibility.
WRIST_DELTA = np.zeros(6)
# the TRI-fitted constant of the old pipeline (absorbed the mount / pivot errors); legacy_calib only
WRIST_DELTA_LEGACY = np.array([0.00251, 0.00080, 0.00059, -0.00124, 0.00055, -0.00087])
# 180-deg roll about the wrist camera's optical axis (camera frame), the start pose of the flip test
# in the wrist stage (DIAGNOSIS P1.5).  wrist_delta in calib_refined_v2.json is TOTAL, i.e. a
# flipped session stores fold_wrist_flip(fitted_delta, True), and wrist_flipped is only a flag.
WRIST_FLIP_POSE6 = np.array([0.0, 0.0, 0.0, 0.0, 0.0, np.pi])

# gripper mimic map: joint name -> multiplier on the driver angle.  URDF cannot express the MJCF
# coupler<->follower closed loop; these linear coefficients reproduce the exact 4-bar solution
# to <= 0.06 mm pad error over 0..0.8 rad (out/diag/urdf_check/gripper/analytic.json).
GRIPPER_MIMIC = {
    "right_driver_joint": 1.0, "left_driver_joint": 1.0,
    "right_spring_link_joint": 0.9992, "left_spring_link_joint": 0.9992,
    "right_follower_joint": -0.9593, "left_follower_joint": -0.9593,
    "right_coupler_joint": 0.0, "left_coupler_joint": 0.0,
}
GRIPPER_MAX_ANGLE = 0.78  # rad at gripper_position == 1.0 (pads touch; GT optimum 0.775-0.80)

# ----------------------------------------------------------------------------- wrist-camera body
# The real DROID gripper carries the ZED Mini wrist camera (body 124.5 x 30.5 x 26.5 mm) on the +y side of the
# gripper root; the SAM3 GT masks (and the third-party dataset masks) include it, the URDFs do not.  Of the
# missing gripper-ROI coverage 66 % sits at the base on the camera side and a plain box for the body lifts the
# exterior gripper-ROI IoU 0.750 -> 0.775 and the GT->render coverage error 6.3 -> 3.8 px
# (out/compare_dn/gripper/summary.md sec 6).  Modelled as a rigid, collision-free box whose axes are the
# camera's own (x toward the right lens, y down, z optical): centre = left-lens position + R_cam @ lens_to_centre,
# posed per episode from the h5 hand-eye (EpisodeSession.X_handeye); episodes without wrist extrinsics in the
# h5 use the mean pose in the gripper ROOT frame (36 benchmark episodes, per-episode std 6-12 mm; optical axis
# 19.2 deg from +z toward the gripper axis).  Deliberately NOT a bracket plate (over-covers).
# calib/mount_params.json["wrist_cam_body"] carries these values so the mount md5 tracks the model;
# RobotRenderer(wrist_cam_body=False) / render_episode.py --no-wrist-cam-body disable it.
WRIST_CAM_BODY_KEY = "wrist_cam_body"
WRIST_CAM_BODY_KEYS = ("enabled", "half_extents", "lens_to_centre", "fallback_root_centre", "fallback_root_rotvec")
WRIST_CAM_BODY = {
    "enabled": True,
    "model": "ZED Mini body box 124.5 x 30.5 x 26.5 mm",
    "half_extents": [0.0623, 0.0153, 0.0133],          # m, camera axes
    "lens_to_centre": [0.0315, 0.0, -0.011],            # m, camera axes: left lens -> body centre
    "fallback_root_centre": [0.004, 0.077, 0.004],      # m, gripper ROOT frame (mean over 36 episodes)
    "fallback_root_rotvec": [0.00244, -0.51998, 3.08234],  # R_cam->root as a rotation vector
}
WRIST_CAM_BODY_RGBA = (0.22, 0.22, 0.24, 1.0)   # dark grey housing
WRIST_CAM_BODY_HALF_RANGE_M = (0.001, 0.2)
# camera origin inside the box inflated by this -> body hidden (the wrist camera's own view).  6 cm: the fitted
# wrist_delta moves the virtual camera up to ~4 cm (|t| p90 30 mm, max 72 mm on flipped sessions) while exterior
# cameras are metres away; the near plane (NEAR = 1 cm) also clips the body, which starts 2 mm in front of the lens.
WRIST_CAM_SELF_VIEW_MARGIN_M = 0.06
WRIST_CAM_PARK = (0.0, 0.0, -100.0)   # where a disabled / hidden body sits

# robot state time for frame i = estimated_capture[i] + TIME_OFFSET_DEFAULT_MS
# (= frame_received - 4 ms; constant 41 ms verified on 18396 streams; GT-IoU argmax +40, CI 30-50)
TIME_OFFSET_DEFAULT_MS = 37.0
HERMITE_MAX_GAP_MS = 300.0  # fall back to linear interpolation across larger state gaps

NEAR, FAR = 0.01, 10.0
TINY_RENDERER = True  # RobotRenderer uses ER_TINY_RENDERER -> passes cy+1 compensation explicitly

# sanity bounds for calib/mount_params.json (interface P0.6).  A units slip (degrees, millimetres)
# or a mimic map that silently leaves joints at 0 must fail loudly, not rotate the gripper by 91 rad.
MOUNT_PARAM_KEYS = ("mount_pos", "mount_euler", "gripper_max_angle", "gripper_mimic")
MOUNT_POS_MAX_M = 0.02            # |mount_pos| (flange centre -> gripper root offset is a few mm)
MOUNT_TILT_MAX_RAD = 0.2          # |rx|, |ry|
MOUNT_ROTZ_CENTER_RAD = np.pi / 2  # rotz ~ 90 deg (fits: 88-94 deg)
MOUNT_ROTZ_TOL_RAD = 0.2
GRIPPER_MAX_ANGLE_RANGE = (0.6, 0.9)
GRIPPER_MIMIC_RANGES = {"driver": (0.9, 1.1), "spring_link": (0.9, 1.1), "follower": (-1.1, -0.9),
                        "coupler": (-0.1, 0.1)}

# robot_serial numeric suffix -> arm type (DIAGNOSIS P0.3; from 6133 local metadata files)
SERIAL_SUFFIX_MAP = {
    1326595: "fr3", 1324143: "fr3", 1326783: "fr3", 1326895: "fr3", 1326898: "fr3", 1326691: "fr3",
    1326372: "panda", 1325882: "panda", 1325494: "panda", 1325686: "panda", 1325132: "panda",
    1325480: "panda", 1324688: "panda", 1325237: "panda",
}
PANDA_SERIAL_RANGE = (1324688, 1326372)
FR3_SERIAL_RANGE = (1326595, 1326898)

VERBOSE = True


def _log(msg):
    if VERBOSE:
        print(f"[render_episode] {msg}", file=sys.stderr, flush=True)


# ----------------------------------------------------------------------------- mount params

def mount_params_md5(mp):
    """Content id of a mount parameter set: md5 of the canonical JSON of the four interface keys
    (mount_pos, mount_euler, gripper_max_angle, gripper_mimic) plus, when present, the wrist-camera body
    (WRIST_CAM_BODY_KEYS).  Lets a calib_refined_v2.json written while the constants were in effect still
    be checked against a later file."""
    d = {k: mp.get(k) for k in MOUNT_PARAM_KEYS}
    wcb = mp.get(WRIST_CAM_BODY_KEY)
    if isinstance(wcb, dict):
        d[WRIST_CAM_BODY_KEY] = {k: wcb.get(k) for k in WRIST_CAM_BODY_KEYS}
    return md5_json(d)


def validate_wrist_cam_body(wcb):
    """-> list of problems for a wrist_cam_body dict (metres / radians; 3-vectors; sane magnitudes)."""
    if not isinstance(wcb, dict):
        return [f"{WRIST_CAM_BODY_KEY} must be a dict, got {type(wcb).__name__}"]
    probs = []
    if not isinstance(wcb.get("enabled", True), (bool, int, np.bool_)):
        probs.append(f"{WRIST_CAM_BODY_KEY}.enabled must be a bool, got {wcb.get('enabled')!r}")
    for k, lo, hi in (("half_extents", WRIST_CAM_BODY_HALF_RANGE_M[0], WRIST_CAM_BODY_HALF_RANGE_M[1]),
                      ("lens_to_centre", None, 0.1), ("fallback_root_centre", None, 0.2),
                      ("fallback_root_rotvec", None, np.pi + 1e-6)):
        v = wcb.get(k)
        if v is None:
            probs.append(f"{WRIST_CAM_BODY_KEY} missing key {k!r}")
            continue
        try:
            a = np.asarray(v, dtype=float).ravel()
        except (TypeError, ValueError):
            probs.append(f"{WRIST_CAM_BODY_KEY}.{k} = {v!r} not numeric")
            continue
        if a.shape != (3,) or not np.isfinite(a).all():
            probs.append(f"{WRIST_CAM_BODY_KEY}.{k} must be 3 finite numbers, got {v!r}")
        elif lo is not None and not ((a > lo) & (a < hi)).all():
            probs.append(f"{WRIST_CAM_BODY_KEY}.{k} = {a.tolist()} outside ({lo}, {hi}) m")
        elif lo is None and np.linalg.norm(a) >= hi:
            probs.append(f"{WRIST_CAM_BODY_KEY}.{k} = {a.tolist()}: norm >= {hi} (metres / radians expected)")
    return probs


def validate_mount_params(mp, require_all=True):
    """-> list of problems (empty == sane).  Bounds: |pos| < MOUNT_POS_MAX_M, |rx|,|ry| <
    MOUNT_TILT_MAX_RAD, |rz - pi/2| < MOUNT_ROTZ_TOL_RAD (radians!), gripper_max_angle in
    GRIPPER_MAX_ANGLE_RANGE, gripper_mimic has every GRIPPER_MIMIC joint with a coefficient in
    GRIPPER_MIMIC_RANGES for its joint family."""
    probs = []
    for k in MOUNT_PARAM_KEYS:
        if k not in mp or mp[k] is None:
            if require_all:
                probs.append(f"missing key {k!r}")
    pos = mp.get("mount_pos")
    if pos is not None:
        a = np.asarray(pos, dtype=float).ravel()
        if a.shape != (3,) or not np.isfinite(a).all():
            probs.append(f"mount_pos must be 3 finite numbers, got {pos!r}")
        elif np.linalg.norm(a) >= MOUNT_POS_MAX_M:
            probs.append(f"|mount_pos| = {np.linalg.norm(a) * 1e3:.1f} mm >= {MOUNT_POS_MAX_M * 1e3:.0f} mm (metres expected)")
    eul = mp.get("mount_euler")
    if eul is not None:
        a = np.asarray(eul, dtype=float).ravel()
        if a.shape != (3,) or not np.isfinite(a).all():
            probs.append(f"mount_euler must be 3 finite numbers, got {eul!r}")
        else:
            if abs(a[0]) >= MOUNT_TILT_MAX_RAD or abs(a[1]) >= MOUNT_TILT_MAX_RAD:
                probs.append(f"mount tilt rx/ry = {a[0]:.3f}/{a[1]:.3f} rad >= {MOUNT_TILT_MAX_RAD}")
            if abs(a[2] - MOUNT_ROTZ_CENTER_RAD) >= MOUNT_ROTZ_TOL_RAD:
                hint = " (looks like degrees)" if abs(a[2]) > 2 * np.pi else ""
                probs.append(f"mount rotz = {a[2]:.4f} rad, expected {MOUNT_ROTZ_CENTER_RAD:.4f} +- {MOUNT_ROTZ_TOL_RAD}{hint}")
    g = mp.get("gripper_max_angle")
    if g is not None:
        try:
            gf = float(g)
        except (TypeError, ValueError):
            gf = float("nan")
        if not (GRIPPER_MAX_ANGLE_RANGE[0] < gf < GRIPPER_MAX_ANGLE_RANGE[1]):
            probs.append(f"gripper_max_angle = {g!r} outside {GRIPPER_MAX_ANGLE_RANGE} rad")
    mm = mp.get("gripper_mimic")
    if mm is not None:
        if not isinstance(mm, dict):
            probs.append("gripper_mimic must be a dict {joint: coef}")
        else:
            missing = [j for j in GRIPPER_MIMIC if j not in mm]
            if missing:
                probs.append(f"gripper_mimic missing joints {missing}")
            for j, c in mm.items():
                fam = next((f for f in GRIPPER_MIMIC_RANGES if f"_{f}_joint" in j), None)
                try:
                    cf = float(c)
                except (TypeError, ValueError):
                    probs.append(f"gripper_mimic[{j!r}] = {c!r} not a number")
                    continue
                if not np.isfinite(cf):
                    probs.append(f"gripper_mimic[{j!r}] = {c!r} not finite")
                elif fam is not None and not (GRIPPER_MIMIC_RANGES[fam][0] <= cf <= GRIPPER_MIMIC_RANGES[fam][1]):
                    probs.append(f"gripper_mimic[{j!r}] = {cf} outside {GRIPPER_MIMIC_RANGES[fam]}")
    if mp.get(WRIST_CAM_BODY_KEY) is not None:
        probs += validate_wrist_cam_body(mp[WRIST_CAM_BODY_KEY])
    return probs


def _finish_mount_params(d):
    d["mount_pos"] = [float(v) for v in np.asarray(d["mount_pos"], dtype=float).ravel()]
    d["mount_euler"] = [float(v) for v in np.asarray(d["mount_euler"], dtype=float).ravel()]
    d["gripper_max_angle"] = float(d["gripper_max_angle"])
    d["gripper_mimic"] = {str(k): float(v) for k, v in d["gripper_mimic"].items()}
    # wrist-camera body: missing -> module default (enabled); normalised to plain floats / bool
    wcb = d.get(WRIST_CAM_BODY_KEY)
    if wcb is None:
        wcb = dict(WRIST_CAM_BODY, source="constants")
    else:
        wcb = dict(wcb)
    for k in WRIST_CAM_BODY_KEYS[1:]:
        wcb[k] = [float(v) for v in np.asarray(wcb.get(k, WRIST_CAM_BODY[k]), dtype=float).ravel()]
    wcb["enabled"] = bool(wcb.get("enabled", True))
    d[WRIST_CAM_BODY_KEY] = wcb
    d["md5_canonical"] = mount_params_md5(d)
    if not d.get("md5"):
        d["md5"] = d["md5_canonical"]
    return d


def constants_mount_params():
    """The module constants as a mount-params dict (source 'constants', md5 = canonical id)."""
    return _finish_mount_params({"mount_pos": list(MOUNT_POS), "mount_euler": list(MOUNT_EULER),
                                 "gripper_max_angle": GRIPPER_MAX_ANGLE, "gripper_mimic": dict(GRIPPER_MIMIC),
                                 WRIST_CAM_BODY_KEY: dict(WRIST_CAM_BODY, source="constants"),
                                 "fitted_on": MOUNT_FITTED_ON, "source": "constants", "md5": None, "md5_file": None})


def legacy_mount_params():
    """Pre-2026-10 pipeline constants (legacy_geometry)."""
    return _finish_mount_params({"mount_pos": list(MOUNT_POS_LEGACY), "mount_euler": list(MOUNT_EULER_LEGACY),
                                 "gripper_max_angle": GRIPPER_MAX_ANGLE_LEGACY,
                                 "gripper_mimic": dict(GRIPPER_MIMIC_LEGACY),
                                 WRIST_CAM_BODY_KEY: dict(WRIST_CAM_BODY, enabled=False, source="legacy(no body)"),
                                 "fitted_on": "legacy one-episode TRI fit (pivot-buggy URDF)",
                                 "source": "legacy-constants", "md5": None, "md5_file": None})


def load_mount_params(path=None, strict=True):
    """calib/mount_params.json (interface: mount_pos[3] m, mount_euler[3] rad scipy 'xyz',
    gripper_max_angle rad, gripper_mimic{joint: coef}, fitted_on, md5_inputs, optional wrist_cam_body
    {enabled, half_extents, lens_to_centre, fallback_root_centre, fallback_root_rotvec}) if present, else the
    module constants.  A present file must contain all four parameter keys and pass
    validate_mount_params; otherwise ValueError (strict=True) or WARNING + constants.
    Returns a dict with those keys plus 'source', 'md5' (file md5, or the canonical content md5 when
    the constants are in effect -- never None), 'md5_canonical' and 'md5_file'."""
    path = Path(path) if path is not None else MOUNT_PARAMS_PATH
    if not path.exists():
        return constants_mount_params()
    try:
        j = json.load(open(path))
    except (OSError, ValueError) as e:
        if strict:
            raise ValueError(f"cannot read mount params {path}: {e}")
        _log(f"WARNING: cannot read {path} ({e}); using constants")
        return constants_mount_params()
    d = {k: j[k] for k in MOUNT_PARAM_KEYS + ("fitted_on", "md5_inputs", WRIST_CAM_BODY_KEY) if k in j}
    probs = validate_mount_params(d, require_all=True)
    if probs:
        msg = f"invalid mount params in {path}: " + "; ".join(probs)
        if strict:
            raise ValueError(msg)
        _log(f"WARNING: {msg}; using constants")
        return constants_mount_params()
    d["source"] = str(path)
    d["md5_file"] = md5_file(path)
    d["md5"] = d["md5_file"]
    if WRIST_CAM_BODY_KEY not in j:
        _log(f"{path} has no {WRIST_CAM_BODY_KEY!r}; wrist-camera body from the module default (enabled)")
    else:
        d[WRIST_CAM_BODY_KEY] = dict(j[WRIST_CAM_BODY_KEY], source=str(path))
    return _finish_mount_params(d)


# ----------------------------------------------------------------------------- arm model lookup
_MODEL_MAP_CACHE = {}


def load_robot_model_map(path=None):
    """data/robot_model_map.json['episodes'] ({uuid: {arm, gripper, arm_urdf, gripper_urdf, ...}})."""
    path = Path(path) if path is not None else ROBOT_MODEL_MAP
    key = str(path)
    if key not in _MODEL_MAP_CACHE:
        if path.exists():
            _MODEL_MAP_CACHE[key] = json.load(open(path)).get("episodes", {})
        else:
            _log(f"WARNING: {path} not found; arm type falls back to metadata rules")
            _MODEL_MAP_CACHE[key] = {}
    return _MODEL_MAP_CACHE[key]


def _station_index(mm):
    """{frozenset(station camera serials): {'fr3': n, 'panda': n}} from the model map (cached by
    identity; the cache keeps a reference to the map so a freed dict cannot alias the id)."""
    if _MODEL_MAP_CACHE.get("_station_src") is not mm:
        idx = {}
        for e in mm.values():
            cams = e.get("station_cameras")
            if cams and e.get("arm") in ARM_URDFS:
                d = idx.setdefault(frozenset(str(c) for c in cams), {})
                d[e["arm"]] = d.get(e["arm"], 0) + 1
        _MODEL_MAP_CACHE["_station_src"] = mm
        _MODEL_MAP_CACHE["_station_idx"] = idx
    return _MODEL_MAP_CACHE["_station_idx"]


def arm_type_of_urdf(path):
    """'fr3' | 'panda' for the two shipped arm URDFs (by resolved path, then by file name), else
    'custom:<file name>'."""
    path = Path(path)
    for arm, cand in ARM_URDFS.items():
        try:
            if path.resolve() == Path(cand).resolve():
                return arm
        except OSError:
            pass
    low = path.name.lower()
    for arm in ("fr3", "panda"):
        if low.startswith(arm):
            return arm
    return f"custom:{path.name}"


def resolve_arm_type(uuid, meta=None, model_map=None):
    """-> (arm_type 'fr3'|'panda', source string, arm_urdf relative path or None).
    Order: robot_model_map -> case-insensitive 'fr3'/'panda' substring of metadata robot_serial ->
    numeric-suffix map -> serial number range -> station camera set (metadata ext1/ext2/wrist
    serials matched against the model map's station_cameras, unanimous) -> 'fr3' with a logged
    warning.  (NEVER a bare startswith('fr3'): it mislabels bare / upper-case serials.)
    meta=None: data/<uuid>/metadata.json is read when it exists."""
    mm = load_robot_model_map() if model_map is None else model_map
    e = mm.get(uuid)
    if e and e.get("arm") in ARM_URDFS:
        return e["arm"], f"robot_model_map({e.get('confidence', '?')})", e.get("arm_urdf")
    if meta is None:
        mp = ROOT / "data" / uuid / "metadata.json"
        if mp.exists():
            try:
                meta = json.load(open(mp))
            except (OSError, ValueError):
                meta = None
    serial = str((meta or {}).get("robot_serial") or "")
    sl = serial.lower()
    if "fr3" in sl:
        return "fr3", "metadata-substring", None
    if "panda" in sl:
        return "panda", "metadata-substring", None
    try:
        n = int(serial.split("-")[-1])
    except ValueError:
        n = None
    if n is not None:
        if n in SERIAL_SUFFIX_MAP:
            return SERIAL_SUFFIX_MAP[n], "serial-suffix-map", None
        if PANDA_SERIAL_RANGE[0] <= n <= PANDA_SERIAL_RANGE[1]:
            return "panda", "serial-range", None
        if FR3_SERIAL_RANGE[0] <= n <= FR3_SERIAL_RANGE[1]:
            return "fr3", "serial-range", None
    if meta:
        cams = frozenset(str(meta[k]) for k in ("ext1_cam_serial", "ext2_cam_serial", "wrist_cam_serial")
                         if meta.get(k) not in (None, "", "unknown"))
        votes = _station_index(mm).get(cams) if cams else None
        if votes and len(votes) == 1:
            arm = next(iter(votes))
            return arm, f"station-cameras(n={votes[arm]})", None
    _log(f"WARNING: cannot resolve arm type for {uuid} (robot_serial={serial!r}); defaulting to fr3")
    return "fr3", "default-fr3-WARNING", None


def resolve_arm_urdf(uuid, meta=None, model_map=None):
    """-> (Path to arm URDF, arm_type, source)."""
    arm, source, rel = resolve_arm_type(uuid, meta, model_map)
    path = ARM_URDFS[arm]
    if rel:
        cand = ROOT / rel
        if cand.exists():
            path = cand
    return Path(path), arm, source


def resolve_gripper_urdf(uuid, model_map=None):
    """-> (Path to gripper URDF, gripper type, source).  data/robot_model_map.json episodes[uuid]
    {gripper, gripper_urdf} when present and the file exists (interface: 'robotiq_2f85',
    'assets/robotiq_2f85_fixed.urdf' for all 999), else the canonical GRIPPER_URDF ('default')."""
    mm = load_robot_model_map() if model_map is None else model_map
    e = mm.get(uuid) or {}
    rel = e.get("gripper_urdf")
    gtype = str(e.get("gripper") or "robotiq_2f85")
    if rel:
        cand = ROOT / rel
        if cand.exists():
            return Path(cand), gtype, f"robot_model_map({e.get('confidence', '?')})"
        _log(f"WARNING: {uuid}: robot_model_map gripper_urdf {rel} not found; using {GRIPPER_URDF.name}")
    return Path(GRIPPER_URDF), gtype, "default"


# calib_refined_v2.json interface (README "interfaces"); EpisodeSession logs keys that are missing
V2_REQUIRED_KEYS = ("version", "time_offset_ms", "ext_base_pose6", "ext_base_source", "ext_delta",
                    "wrist_delta", "wrist_flipped", "quality", "time_quality", "gt_masks_used",
                    "mount_params_md5")
V2_QUALITY_KEYS = ("status", "metric_before", "metric_after", "metric_name", "n_steps", "notes")
V2_QUALITY_STATUS = ("ok", "degraded", "failed")
V2_EXT_SOURCE_PREFIXES = ("superset-GT", "superset-Pred", "gt_neighbor:", "h5", "session:")


def check_v2_record(r, wrist_serial=None):
    """-> list of interface deviations (strings; empty == conforming) of a loaded calib_refined_v2.json."""
    probs = [f"missing key {k!r}" for k in V2_REQUIRED_KEYS if k not in r]
    if r.get("version") not in (None, 2):
        probs.append(f"version {r.get('version')!r} != 2")
    for k in ("ext_base_pose6", "ext_delta", "wrist_delta"):
        for s, v in (r.get(k) or {}).items():
            a = np.asarray(v, dtype=float).ravel() if v is not None else np.zeros(0)
            if a.shape != (6,) or not np.isfinite(a).all():
                probs.append(f"{k}[{s}] is not 6 finite numbers")
    for s in (r.get("ext_base_pose6") or {}):
        if s not in (r.get("ext_delta") or {}):
            probs.append(f"ext_delta missing serial {s}")
        src = str((r.get("ext_base_source") or {}).get(s, ""))
        if not src.startswith(V2_EXT_SOURCE_PREFIXES):
            probs.append(f"ext_base_source[{s}] = {src!r} not in {V2_EXT_SOURCE_PREFIXES}")
    for s, q in (r.get("quality") or {}).items():
        if not isinstance(q, dict):
            probs.append(f"quality[{s}] is not a dict")
            continue
        miss = [k for k in V2_QUALITY_KEYS if k not in q]
        if miss:
            probs.append(f"quality[{s}] missing {miss}")
        if q.get("status") not in V2_QUALITY_STATUS:
            probs.append(f"quality[{s}].status = {q.get('status')!r}")
    tq = r.get("time_quality")
    if isinstance(tq, dict):
        miss = [k for k in ("sweep_class", "n_steps", "prior_used") if k not in tq]
        if miss:
            probs.append(f"time_quality missing {miss}")
    elif tq is not None:
        probs.append("time_quality is not a dict")
    if wrist_serial is not None and r.get("wrist_delta") and str(wrist_serial) not in r["wrist_delta"]:
        probs.append(f"wrist_delta has no entry for the wrist camera {wrist_serial} (keys {list(r['wrist_delta'])})")
    return probs


def fold_wrist_flip(delta6, flipped):
    """TOTAL wrist_delta for calib_refined_v2.json from a camera-frame delta fitted on top of the
    flip-test start pose: T = D' @ F @ inv(T_l8 @ X)  ->  wrist_delta = mat_to_pose6(D' @ F) with
    F = pose6_to_mat(WRIST_FLIP_POSE6) when flipped, else delta6 unchanged."""
    delta6 = np.asarray(delta6, dtype=float)
    if not flipped:
        return delta6.copy()
    return mat_to_pose6(pose6_to_mat(delta6) @ pose6_to_mat(WRIST_FLIP_POSE6))


def wrist_delta_has_flip(delta6):
    """True if a (total) wrist_delta contains a ~180-deg rotation (rotation angle > 90 deg)."""
    return float(R.from_euler("xyz", np.asarray(delta6, dtype=float)[3:6]).magnitude()) > np.pi / 2


# ----------------------------------------------------------------------------- renderer

class RobotRenderer:
    """pybullet DIRECT scene with one arm URDF + one 2F-85 URDF, rendered with ER_TINY_RENDERER.

    All pybullet calls are bound to this instance's physics client, so several renderers can
    coexist in one process (pybullet's implicit client is always 0, not the latest connect).
    The client is released by close() or when the instance is garbage collected, so pybullet
    re-uses id 0 for the next renderer created in a process that holds no other one (scripts
    with raw p.getCameraImage calls keep working as long as they hold one renderer at a time).

    tiny_renderer: cy+1 compensation passed to dutils.gl_projection_matrix for every render of this
    instance (default TINY_RENDERER = True; legacy_geometry sessions set False).

    wrist_cam_body: render the ZED Mini wrist-camera body (a third pybullet body: collision-free dark-grey
    box, see WRIST_CAM_BODY).  None -> mount_params["wrist_cam_body"]["enabled"] (file default True).
    Posed in set_state() from the current link8 pose x T_l8_to_wcam, where T_l8_to_wcam = X_handeye @
    [I | lens_to_centre] after set_wrist_cam_handeye(X) (EpisodeSession does this per episode) or
    T_mount @ fallback root pose.  Hidden automatically for a render whose camera origin lies inside the
    body (wrist_cam_self_view): the wrist camera cannot see its own housing.
    """

    def __init__(self, mount_pos=None, mount_euler=None, arm_urdf=None, gripper_urdf=None,
                 mount_params=None, tiny_renderer=None, wrist_cam_body=None):
        self.cid = p.connect(p.DIRECT)
        self.tiny_renderer = bool(TINY_RENDERER if tiny_renderer is None else tiny_renderer)
        mp = dict(mount_params) if mount_params is not None else load_mount_params()
        if mount_pos is not None:
            mp["mount_pos"] = [float(v) for v in np.asarray(mount_pos, dtype=float)]
            mp["mount_pos_source"] = "argument"
        if mount_euler is not None:
            mp["mount_euler"] = [float(v) for v in np.asarray(mount_euler, dtype=float)]
            mp["mount_euler_source"] = "argument"
        if mount_pos is not None or mount_euler is not None:
            # the effective parameters are no longer the file's: id them by content only
            mp["source"] = f"{mp.get('source', 'constants')}+argument"
            mp["md5"] = None
            mp["md5_file"] = None
        self.T_l8 = np.eye(4)
        self.arm = None
        self.gripper = None
        self.grip_joints = {}
        self.wrist_cam = None             # pybullet body id of the wrist-camera box (created below)
        self.wrist_cam_enabled = False
        self.wrist_cam_half = None
        self.X_handeye = None             # per-episode hand-eye (set_wrist_cam_handeye); None -> fallback pose
        self.T_l8_to_wcam = np.eye(4)
        self.T_wcam = None                # world pose of the box after the last set_state
        self.wrist_cam_source = None
        self.set_mount_params(mp)
        # explicit arm_urdf (argument, or a module-level override of ARM_URDF) => EpisodeSession must
        # not swap it (diagnostics); plain default => per-episode shell from the model map
        if arm_urdf is not None:
            self.arm_urdf_source = "argument"
        elif Path(ARM_URDF).resolve() != Path(_ARM_URDF_DEFAULT).resolve():
            self.arm_urdf_source = "module-override(ARM_URDF)"
        else:
            self.arm_urdf_source = "default"
        self.arm_urdf_explicit = self.arm_urdf_source != "default"
        self.load_arm(arm_urdf if arm_urdf is not None else ARM_URDF)
        self.load_gripper(gripper_urdf if gripper_urdf is not None else GRIPPER_URDF)
        self._create_wrist_cam_body()
        enabled = (bool(self.mount_params[WRIST_CAM_BODY_KEY].get("enabled", True)) if wrist_cam_body is None
                   else bool(wrist_cam_body))
        self.wrist_cam_body_source = "mount_params" if wrist_cam_body is None else "argument"
        self.set_wrist_cam_body(enabled)

    def set_mount_params(self, mp):
        """Install a mount-params dict (interface keys; missing ones -> constants).  Arguments /
        dicts outside the sanity bounds are allowed (diagnostic sweeps) but logged."""
        mp = dict(mp)
        for k, v in (("mount_pos", MOUNT_POS), ("mount_euler", MOUNT_EULER),
                     ("gripper_max_angle", GRIPPER_MAX_ANGLE), ("gripper_mimic", GRIPPER_MIMIC)):
            if mp.get(k) is None:
                mp[k] = list(v) if isinstance(v, np.ndarray) else (dict(v) if isinstance(v, dict) else v)
        probs = validate_mount_params(mp, require_all=True)
        if probs:
            _log(f"WARNING: mount params ({mp.get('source', 'argument')}) outside sanity bounds: " + "; ".join(probs))
        mp.setdefault("source", "argument")
        mp.setdefault("md5", None)
        mp.setdefault("md5_file", None)
        self.mount_params = _finish_mount_params(mp)
        self.mount_pos = np.asarray(self.mount_params["mount_pos"], dtype=float)
        self.mount_euler = np.asarray(self.mount_params["mount_euler"], dtype=float)
        self.gripper_max_angle = float(self.mount_params["gripper_max_angle"])
        self.gripper_mimic = dict(self.mount_params["gripper_mimic"])
        self.T_mount = np.eye(4)
        self.T_mount[:3, :3] = R.from_euler("xyz", self.mount_euler).as_matrix()
        self.T_mount[:3, 3] = self.mount_pos
        if self.gripper is not None:
            self._map_grip_joints()
        if self.wrist_cam is not None and not np.allclose(self.mount_params[WRIST_CAM_BODY_KEY]["half_extents"], self.wrist_cam_half):
            self._create_wrist_cam_body()      # extents changed -> new visual shape
        else:
            self._update_wcam_transform()

    # -- wrist-camera body -----------------------------------------------------------------
    def _create_wrist_cam_body(self):
        wcb = self.mount_params[WRIST_CAM_BODY_KEY]
        self.wrist_cam_half = np.asarray(wcb["half_extents"], dtype=float)
        if self.wrist_cam is not None:
            p.removeBody(self.wrist_cam, physicsClientId=self.cid)
        vs = p.createVisualShape(p.GEOM_BOX, halfExtents=[float(v) for v in self.wrist_cam_half],
                                 rgbaColor=list(WRIST_CAM_BODY_RGBA), physicsClientId=self.cid)
        self.wrist_cam = p.createMultiBody(baseMass=0, baseVisualShapeIndex=vs, basePosition=list(WRIST_CAM_PARK),
                                           physicsClientId=self.cid)
        self._update_wcam_transform()

    def _update_wcam_transform(self):
        """link8 -> box-centre transform: X_handeye @ [I | lens_to_centre] when a per-episode hand-eye is set,
        else T_mount @ (fallback mean pose in the gripper ROOT frame).  Re-places the body at the current T_l8."""
        wcb = self.mount_params[WRIST_CAM_BODY_KEY]
        T_lc = np.eye(4)
        T_lc[:3, 3] = np.asarray(wcb["lens_to_centre"], dtype=float)
        if self.X_handeye is not None:
            self.T_l8_to_wcam = np.asarray(self.X_handeye, dtype=float) @ T_lc
            self.wrist_cam_source = "h5_handeye"
        else:
            T_rb = np.eye(4)
            T_rb[:3, :3] = R.from_rotvec(np.asarray(wcb["fallback_root_rotvec"], dtype=float)).as_matrix()
            T_rb[:3, 3] = np.asarray(wcb["fallback_root_centre"], dtype=float)
            self.T_l8_to_wcam = self.T_mount @ T_rb
            self.wrist_cam_source = "fallback_root_mean"
        if self.wrist_cam is not None and self.wrist_cam_enabled:
            self.T_wcam = self.T_l8 @ self.T_l8_to_wcam
            self._place_wrist_cam(self.T_wcam)

    def set_wrist_cam_handeye(self, X_handeye):
        """Per-episode hand-eye (4x4 pose of the wrist camera's left lens in the panda_link8 frame) that places
        the wrist-camera body; None -> fallback mean pose in the gripper root frame."""
        self.X_handeye = None if X_handeye is None else np.array(X_handeye, dtype=float)
        self._update_wcam_transform()

    def set_wrist_cam_body(self, enabled):
        """Enable / disable the wrist-camera body (disabled -> parked at WRIST_CAM_PARK, never rendered)."""
        self.wrist_cam_enabled = bool(enabled) and self.wrist_cam is not None
        if self.wrist_cam is None:
            return
        if self.wrist_cam_enabled:
            self.T_wcam = self.T_l8 @ self.T_l8_to_wcam
            self._place_wrist_cam(self.T_wcam)
        else:
            self.T_wcam = None
            self._park_wrist_cam()

    def _park_wrist_cam(self):
        p.resetBasePositionAndOrientation(self.wrist_cam, list(WRIST_CAM_PARK), [0.0, 0.0, 0.0, 1.0],
                                          physicsClientId=self.cid)

    def _place_wrist_cam(self, T):
        p.resetBasePositionAndOrientation(self.wrist_cam, T[:3, 3].tolist(),
                                          R.from_matrix(T[:3, :3]).as_quat().tolist(), physicsClientId=self.cid)

    def wrist_cam_self_view(self, T_base2cam):
        """True if the camera origin lies inside the wrist-camera body inflated by WRIST_CAM_SELF_VIEW_MARGIN_M,
        i.e. the view is the wrist camera's own; render_raw then hides the body for that image (a camera cannot
        see its own housing; the box would otherwise straddle the near plane)."""
        if not self.wrist_cam_enabled or self.T_wcam is None:
            return False
        o = np.linalg.inv(np.asarray(T_base2cam, dtype=float))[:3, 3]
        local = self.T_wcam[:3, :3].T @ (o - self.T_wcam[:3, 3])
        return bool(np.all(np.abs(local) <= self.wrist_cam_half + WRIST_CAM_SELF_VIEW_MARGIN_M))

    def wrist_cam_info(self):
        """JSON-able description of the wrist-camera body as currently posed (render_meta / urdf_info):
        enabled, source (h5_handeye | fallback_root_mean), half_extents, lens_to_centre, centre_root /
        rotvec_root / R_cam_to_root (box in the gripper ROOT frame), lens_root, optical_axis_tilt_deg."""
        wcb = self.mount_params[WRIST_CAM_BODY_KEY]
        T_rb = np.linalg.inv(self.T_mount) @ self.T_l8_to_wcam
        lc = np.asarray(wcb["lens_to_centre"], dtype=float)
        z = T_rb[:3, 2]
        return dict(enabled=bool(self.wrist_cam_enabled), model=wcb.get("model"),
                    source=self.wrist_cam_source if self.wrist_cam_enabled else None,
                    params_source=wcb.get("source"), enabled_by=getattr(self, "wrist_cam_body_source", None),
                    half_extents=[float(v) for v in self.wrist_cam_half], lens_to_centre=[float(v) for v in lc],
                    centre_root=[float(v) for v in T_rb[:3, 3]],
                    rotvec_root=[float(v) for v in R.from_matrix(T_rb[:3, :3]).as_rotvec()],
                    R_cam_to_root=[[float(v) for v in row] for row in T_rb[:3, :3]],
                    lens_root=[float(v) for v in (T_rb[:3, 3] - T_rb[:3, :3] @ lc)],
                    optical_axis_tilt_deg=float(np.degrees(np.arccos(np.clip(z[2], -1.0, 1.0)))),
                    self_view_margin_m=WRIST_CAM_SELF_VIEW_MARGIN_M, rgba=list(WRIST_CAM_BODY_RGBA))

    def body_ids(self):
        """{'arm': id, 'gripper': id, 'wrist_cam': id | None (disabled)} pybullet body ids (seg low 24 bits)."""
        return dict(arm=self.arm, gripper=self.gripper, wrist_cam=self.wrist_cam if self.wrist_cam_enabled else None)

    def seg_body_masks(self, seg):
        """Per-body boolean masks from a render_raw / render(return_seg=True) segmentation image:
        {'arm', 'gripper', 'wrist_cam', 'robot' (arm | gripper), 'all' (== the render mask)}."""
        valid = seg >= 0
        obj = np.where(valid, seg & ((1 << 24) - 1), -1)
        arm, grip = obj == self.arm, obj == self.gripper
        wc = (obj == self.wrist_cam) if self.wrist_cam_enabled else np.zeros_like(valid)
        return dict(arm=arm, gripper=grip, wrist_cam=wc, robot=arm | grip, all=valid)

    # -- model loading -------------------------------------------------------------------
    def load_arm(self, arm_urdf):
        """(Re)load the arm URDF; returns True if the model changed. Link indices are identical
        for assets/fr3_arm.urdf and assets/panda_arm.urdf (panda_link8 == 7)."""
        arm_urdf = Path(arm_urdf)
        if self.arm is not None:
            if arm_urdf.resolve() == self.arm_urdf.resolve():
                return False
            p.removeBody(self.arm, physicsClientId=self.cid)
        self.arm = p.loadURDF(str(arm_urdf), useFixedBase=True, physicsClientId=self.cid)
        names = [p.getJointInfo(self.arm, j, physicsClientId=self.cid)[12].decode()
                 for j in range(p.getNumJoints(self.arm, physicsClientId=self.cid))]
        if "panda_link8" not in names:
            raise ValueError(f"{arm_urdf}: no panda_link8 link (links: {names})")
        self.link8 = names.index("panda_link8")
        self.arm_link_names = names
        self.arm_urdf = arm_urdf
        self.arm_md5 = md5_file(arm_urdf)
        return True

    def load_gripper(self, gripper_urdf):
        """(Re)load the gripper URDF (same link/joint names as the canonical file expected)."""
        gripper_urdf = Path(gripper_urdf)
        if self.gripper is not None:
            if gripper_urdf.resolve() == self.gripper_urdf.resolve():
                return False
            p.removeBody(self.gripper, physicsClientId=self.cid)
        self.gripper = p.loadURDF(str(gripper_urdf), useFixedBase=True, physicsClientId=self.cid)
        self.gripper_urdf = gripper_urdf
        self.gripper_md5 = md5_file(gripper_urdf)
        self._map_grip_joints()
        return True

    def _map_grip_joints(self):
        """joint index -> mimic coefficient for the loaded gripper; every mimic joint must exist."""
        self.grip_joints = {}
        self.grip_link_index = {}
        present = set()
        for j in range(p.getNumJoints(self.gripper, physicsClientId=self.cid)):
            info = p.getJointInfo(self.gripper, j, physicsClientId=self.cid)
            name = info[1].decode()
            present.add(name)
            self.grip_link_index[info[12].decode()] = j
            if name in self.gripper_mimic:
                self.grip_joints[j] = float(self.gripper_mimic[name])
        missing = [n for n in self.gripper_mimic if n not in present]
        if missing:
            _log(f"WARNING: gripper joints {missing} not found in {self.gripper_urdf}")

    def close(self):
        cid = getattr(self, "cid", None)
        if cid is None:
            return
        self.cid = None
        try:
            if p.isConnected(cid):
                p.disconnect(physicsClientId=cid)
        except Exception:  # pybullet.error or interpreter shutdown
            pass

    def __del__(self):
        try:
            self.close()
        except Exception:
            pass

    # -- state / rendering ---------------------------------------------------------------
    def set_state(self, q7, grip01):
        for j in range(7):
            p.resetJointState(self.arm, j, float(q7[j]), physicsClientId=self.cid)
        st = p.getLinkState(self.arm, self.link8, computeForwardKinematics=True,
                            physicsClientId=self.cid)
        T_l8 = np.eye(4)
        T_l8[:3, :3] = R.from_quat(st[5]).as_matrix()
        T_l8[:3, 3] = st[4]
        self.T_l8 = T_l8
        T_g = T_l8 @ self.T_mount
        quat = R.from_matrix(T_g[:3, :3]).as_quat()
        p.resetBasePositionAndOrientation(self.gripper, T_g[:3, 3], quat, physicsClientId=self.cid)
        theta = float(np.clip(grip01, 0.0, 1.0)) * self.gripper_max_angle
        for j, mult in self.grip_joints.items():
            p.resetJointState(self.gripper, j, mult * theta, physicsClientId=self.cid)
        if self.wrist_cam_enabled:
            self.T_wcam = T_l8 @ self.T_l8_to_wcam
            self._place_wrist_cam(self.T_wcam)

    def render_raw(self, T_base2cam, K, wh=(W, H), tiny_renderer=None):
        """-> (rgb HxWx3 uint8, depth buffer HxW float, seg HxW int) at the given size.
        tiny_renderer=None -> self.tiny_renderer (True: cy+1 compensation, passed explicitly).
        The wrist-camera body is hidden when the camera origin lies inside it (wrist_cam_self_view)."""
        w, h = int(wh[0]), int(wh[1])
        tr = self.tiny_renderer if tiny_renderer is None else bool(tiny_renderer)
        V = gl_view_matrix(T_base2cam)
        P = gl_projection_matrix(K, w, h, NEAR, FAR, tiny_renderer=tr)
        hide = self.wrist_cam_self_view(T_base2cam)
        if hide:
            self._park_wrist_cam()
        _, _, rgb, depth, seg = p.getCameraImage(
            w, h, viewMatrix=V, projectionMatrix=P,
            renderer=p.ER_TINY_RENDERER,
            flags=p.ER_SEGMENTATION_MASK_OBJECT_AND_LINKINDEX,
            physicsClientId=self.cid)
        if hide:
            self._place_wrist_cam(self.T_wcam)
        rgb = np.asarray(rgb, dtype=np.uint8).reshape(h, w, 4)[:, :, :3]
        depth = np.asarray(depth, dtype=np.float64).reshape(h, w)
        seg = np.asarray(seg).reshape(h, w)
        return rgb, depth, seg

    def render(self, T_base2cam, K, wh=(W, H), with_normals=False, tiny_renderer=None, return_seg=False):
        """-> rgb, mask[, normal][, seg].  K at the resolution wh (use dutils.scale_K to change it).
        mask covers every rendered body (arm, gripper, wrist-camera body when enabled and not the camera's
        own view); return_seg=True appends the raw segmentation image (object id in the low 24 bits, link
        index + 1 above) -> seg_body_masks(seg) / seg_link_mask(seg, body) for per-body masks."""
        rgb, depth, seg = self.render_raw(T_base2cam, K, wh, tiny_renderer)
        mask = seg >= 0
        out = [rgb, mask]
        if with_normals:
            z = FAR * NEAR / (FAR - (FAR - NEAR) * depth)
            out.append(camera_space_normals(z, K, mask))
        if return_seg:
            out.append(seg)
        return tuple(out)

    def seg_link_mask(self, seg, body, link_names=None):
        """Boolean mask of one body (self.arm / self.gripper / self.wrist_cam), optionally restricted to links
        (arm / gripper only)."""
        valid = seg >= 0
        obj = np.where(valid, seg & ((1 << 24) - 1), -1)
        m = obj == body
        if link_names:
            idx = {self.grip_link_index[n] if body == self.gripper else self.arm_link_names.index(n)
                   for n in link_names}
            link = np.where(valid, (seg >> 24) - 1, -2)
            m &= np.isin(link, list(idx))
        return m


def camera_space_normals(z_eye, K, mask):
    """Per-pixel camera-space normals from a clean synthetic depth map.

    Returns HxWx3 uint8, OpenGL camera convention (x right, y up, z toward
    viewer), encoded n*0.5+0.5; background pixels are 0.
    """
    h, w = z_eye.shape
    fx, fy = K[0, 0], K[1, 1]
    cx, cy = K[0, 2], K[1, 2]
    us, vs = np.meshgrid(np.arange(w), np.arange(h))
    # OpenCV camera frame (y down, z forward)
    X = (us - cx) / fx * z_eye
    Y = (vs - cy) / fy * z_eye
    P3 = np.stack([X, Y, z_eye], axis=-1)

    def one_sided(axis):
        # forward/backward differences; per pixel keep the side with the
        # smaller depth jump so occlusion boundaries don't smear normals
        sl_f = [slice(None)] * 3
        sl_b = [slice(None)] * 3
        sl_f[axis] = slice(0, -1)
        sl_b[axis] = slice(1, None)
        diff = P3[tuple(sl_b)] - P3[tuple(sl_f)]
        fwd = np.zeros_like(P3)
        bwd = np.zeros_like(P3)
        fwd[tuple(sl_f)] = diff  # last row/col missing
        bwd[tuple(sl_b)] = diff  # first row/col missing
        first = [slice(None)] * 3
        last = [slice(None)] * 3
        first[axis] = slice(0, 1)
        last[axis] = slice(-1, None)
        fwd[tuple(last)] = bwd[tuple(last)]
        bwd[tuple(first)] = fwd[tuple(first)]
        pick_bwd = np.abs(bwd[..., 2]) < np.abs(fwd[..., 2])
        out = fwd.copy()
        out[pick_bwd] = bwd[pick_bwd]
        return out

    dx = one_sided(1)
    dy = one_sided(0)
    n = np.cross(dy, dx)  # oriented toward the camera (-z in OpenCV frame)
    n /= np.linalg.norm(n, axis=-1, keepdims=True) + 1e-9
    n[..., 1] *= -1.0  # OpenCV -> OpenGL camera frame
    n[..., 2] *= -1.0
    out = np.zeros((h, w, 3), dtype=np.uint8)
    out[mask] = ((n[mask] * 0.5 + 0.5) * 255).astype(np.uint8)
    return out


# ----------------------------------------------------------------------------- episode session

class EpisodeSession:
    """Loads one raw episode and provides, per camera and frame index, the robot state
    interpolated to that camera's capture time (+ time offset) plus the base->cam transform.

    Attributes (all public, read by scripts/diag/*):
      uuid, meta, n, serials (exterior; + wrist_serial when wrist=True), wrist_serial,
      qs, gs, qvs (joint velocities or None), t_state, cap_ts{serial}, K{serial} (native intrinsics
      resolution), wh{serial} (that resolution), mp4_wh{serial} (real MP4 size), K_mp4{serial} (K at
      the MP4 size; == K unless the sizes differ), K_source{serial}, K_quality{serial} ('ok' |
      'degraded:<why>'), T_ext{serial} (base->cam incl. ext_delta), dt_ms, D (wrist camera-frame
      delta 4x4 = pose6_to_mat(wrist_delta), TOTAL, see fold_wrist_flip), X_handeye (left-lens pose of the
      wrist camera in the panda_link8 frame from h5 observation/camera_extrinsics/<wrist>_left vs FK; set
      whenever the h5 has it, independent of `wrist`; absent otherwise -> hasattr), X_handeye_source ('h5' |
      None), rr (RobotRenderer; rr.wrist_cam_info() / urdf_info['wrist_cam_body'] = the ZED Mini body pose), arm_type (shell actually rendered), arm_type_resolved (model map /
      metadata), urdf_info, calib_version (0 none / 1 legacy / 2), calib_path, ext_base_pose6{serial},
      ext_base_source{serial}, ext_delta{serial}, wrist_delta{serial}, wrist_flipped (flag only),
      quality (the v2 quality record {serial: {status, metric_before, metric_after, metric_name, n_steps,
      notes}}), time_quality, gt_masks_used, calib_mount_md5_ok (True/False/None), calib_problems (v2
      interface deviations, check_v2_record), gripper_type, interp_mode, legacy_calib, legacy_geometry.
    """

    def __init__(self, ep_dir, wrist=False, renderer=None, legacy_calib=False, calib_v2=None,
                 auto_urdf=True, interp_mode="hermite", calib_dir=None, legacy_geometry=False):
        self.ep_dir = Path(ep_dir)
        self.meta = json.load(open(self.ep_dir / "metadata.json"))
        self.uuid = self.meta["uuid"]
        self.wrist_serial = str(self.meta["wrist_cam_serial"])
        self.legacy_geometry = bool(legacy_geometry)
        if legacy_geometry:
            legacy_calib, interp_mode, auto_urdf = True, "linear", False

        # ---- h5 ----
        with h5py.File(self.ep_dir / "trajectory.h5", "r") as f:
            rs = f["observation/robot_state"]
            self.qs = rs["joint_positions"][:].astype(np.float64)
            self.gs = rs["gripper_position"][:].astype(np.float64)
            self.qvs = rs["joint_velocities"][:].astype(np.float64) if "joint_velocities" in rs else None
            self.t_state = f["observation/timestamp/robot_state/read_start"][:].astype(np.float64)
            cams = f["observation/timestamp/cameras"]
            cxg = f["observation/camera_extrinsics"]
            h5_serials = sorted({k[:-5] for k in cxg if k.endswith("_left") and k[:-5].isdigit()})
            wext = cxg[f"{self.wrist_serial}_left"][:] if f"{self.wrist_serial}_left" in cxg else None
            # h5 carries extrinsics for every camera the station ever had (ep1: 5 exterior serials,
            # 2 recorded); the recorded exterior cams are metadata ext1/ext2_cam_serial
            self.h5_ext = {s: cxg[f"{s}_left"][:] for s in h5_serials if s != self.wrist_serial}
            meta_ext = [str(self.meta.get(k)) for k in ("ext1_cam_serial", "ext2_cam_serial")
                        if str(self.meta.get(k) or "").isdigit()]
            all_serials = sorted(set(h5_serials) | set(meta_ext) | {self.wrist_serial})
            self.cap_ts = {s: cams[f"{s}_estimated_capture"][:].astype(np.float64)
                           for s in all_serials if f"{s}_estimated_capture" in cams}
            self.frame_received = {s: cams[f"{s}_frame_received"][:].astype(np.float64)
                                   for s in all_serials if f"{s}_frame_received" in cams}
        self.n = len(self.qs)
        if self.qvs is not None and (self.qvs.shape != self.qs.shape or not np.isfinite(self.qvs).all()):
            _log(f"{self.uuid}: joint_velocities unusable (shape {self.qvs.shape}); linear interpolation")
            self.qvs = None
        self.interp_mode = interp_mode if (interp_mode == "hermite" and self.qvs is not None) else "linear"

        # ---- calibration files: superset extrinsics + intrinsics (size-aware fallback) ----
        self.mp4_wh = {}
        for s in all_serials:
            mp4 = self.ep_dir / f"recordings/MP4/{s}.mp4"
            if mp4.exists():
                w_, h_, _ = video_size(mp4)
                if w_ > 0 and h_ > 0:
                    self.mp4_wh[s] = (w_, h_)
        cal = load_calib_full(self.uuid, calib_dir, wh_hint=self.mp4_wh)
        self.in_superset = bool(cal.get("in_superset", True))
        self.ext_sup = cal["ext"]
        self.ext_sup_source = cal["ext_source"]
        self.K = cal["K"]
        self.wh = cal["wh"]
        self.K_source = cal["K_source"]
        self.K_quality, self.K_mp4 = {}, {}
        for s, K in self.K.items():
            native, real = tuple(self.wh[s]), self.mp4_wh.get(s)
            if real is None or real == native:
                self.K_quality[s] = "ok"
                self.K_mp4[s] = K.copy()
            else:
                # ZED VGA (672x376) is a different crop/FOV mode: an anisotropic rescale of HD720
                # intrinsics is only a stop-gap -> degraded (P1 quality gate: K_source != own + wh mismatch)
                self.K_quality[s] = f"degraded:intrinsics {native[0]}x{native[1]} ({self.K_source[s]}) rescaled to MP4 {real[0]}x{real[1]}"
                self.K_mp4[s] = scale_K(K, real[0] / native[0], real[1] / native[1])
                _log(f"WARNING: {self.uuid}/{s}: {self.K_quality[s]}")
        if not self.in_superset:
            _log(f"WARNING: {self.uuid} not in calib/cam2base_extrinsic_superset.json; exterior base pose from h5 "
                 f"camera_extrinsics (source 'h5', degraded) unless a calib_refined_v2.json provides ext_base_pose6")
        # exterior cameras: superset order; without the superset the recorded (metadata) cams whose
        # h5 extrinsics exist, else every h5 exterior cam that has an MP4
        self._h5_fallback_serials = ([s for s in meta_ext if s in self.h5_ext]
                                     or [s for s in self.h5_ext if s in self.mp4_wh])
        self.serials = list(self.ext_sup) if self.ext_sup else list(self._h5_fallback_serials)

        # ---- robot model (per episode) ----
        arm_urdf, self.arm_type_resolved, arm_source = resolve_arm_urdf(self.uuid, self.meta)
        if legacy_geometry:
            # the pre-2026-10 pipeline rendered the FR3 shell + pivot-buggy gripper for every episode
            if renderer is None:
                renderer = RobotRenderer(arm_urdf=ARM_URDFS["fr3"], gripper_urdf=GRIPPER_URDF_LEGACY,
                                         mount_params=legacy_mount_params(), tiny_renderer=False, wrist_cam_body=False)
            else:
                renderer.load_arm(ARM_URDFS["fr3"])
                renderer.load_gripper(GRIPPER_URDF_LEGACY)
                renderer.set_mount_params(legacy_mount_params())
                renderer.tiny_renderer = False
                renderer.set_wrist_cam_body(False)     # pre-2026-10 renders had no wrist-camera body
            renderer.arm_urdf_explicit = True
            arm_source = "legacy_geometry(fr3 for all)"
        elif renderer is None:
            renderer = RobotRenderer(arm_urdf=arm_urdf)
            renderer.arm_urdf_explicit = False  # created here => stays per-episode
        elif auto_urdf and not renderer.arm_urdf_explicit:
            renderer.load_arm(arm_urdf)
        # gripper URDF per episode (interface: robot_model_map episodes[uuid].gripper_urdf; identical to the
        # canonical file for all 999).  Only a renderer still carrying the canonical default is switched: an
        # explicit gripper_urdf argument / legacy geometry is never overridden.
        gripper_urdf, self.gripper_type, gripper_source = resolve_gripper_urdf(self.uuid)
        if (not legacy_geometry and auto_urdf
                and Path(renderer.gripper_urdf).resolve() == Path(GRIPPER_URDF).resolve()
                and gripper_urdf.resolve() != Path(GRIPPER_URDF).resolve()):
            renderer.load_gripper(gripper_urdf)
            _log(f"{self.uuid}: gripper URDF from the model map: {gripper_urdf}")
        elif Path(renderer.gripper_urdf).resolve() != gripper_urdf.resolve():
            gripper_source = f"renderer({'legacy_geometry' if legacy_geometry else 'explicit'})"
        self.rr = renderer
        self.arm_type = arm_type_of_urdf(self.rr.arm_urdf)
        arm_override = self.arm_type != self.arm_type_resolved
        self.urdf_info = dict(
            arm_type=self.arm_type, arm_type_resolved=self.arm_type_resolved, arm_source=arm_source,
            arm_override=arm_override, arm_urdf_source=getattr(self.rr, "arm_urdf_source", None),
            arm_urdf=str(self.rr.arm_urdf), arm_md5=self.rr.arm_md5,
            gripper_type=self.gripper_type, gripper_source=gripper_source,
            gripper_urdf=str(self.rr.gripper_urdf), gripper_md5=self.rr.gripper_md5,
            mount_source=self.rr.mount_params.get("source"),
            mount_params_md5=self.rr.mount_params.get("md5"),
            mount_params_md5_canonical=self.rr.mount_params.get("md5_canonical"),
            mount_pos=[float(v) for v in self.rr.mount_pos],
            mount_euler=[float(v) for v in self.rr.mount_euler],
            gripper_max_angle=self.rr.gripper_max_angle, gripper_mimic=dict(self.rr.gripper_mimic),
            tiny_renderer=self.rr.tiny_renderer, legacy_geometry=self.legacy_geometry)
        _log(f"{self.uuid}: arm={self.arm_type} ({arm_source}"
             f"{'; OVERRIDES map ' + self.arm_type_resolved if arm_override else ''}) {self.rr.arm_urdf.name} "
             f"md5={self.rr.arm_md5} | gripper {self.rr.gripper_urdf.name} md5={self.rr.gripper_md5} | "
             f"mount {self.urdf_info['mount_source']} md5={self.urdf_info['mount_params_md5']} | "
             f"tiny_renderer={self.rr.tiny_renderer}")
        if any(v != "own" for v in self.K_source.values()):
            _log(f"{self.uuid}: intrinsics fallback used: "
                 + ", ".join(f"{s}:{v}" for s, v in self.K_source.items() if v != "own"))

        # ---- calibration (v2 / default / legacy) ----
        self._load_calibration(legacy_calib, calib_v2)

        # ---- wrist-camera hand-eye (always, when the h5 has it): constant X = left-lens pose in the link8
        # frame, averaged over ~32 steps.  Needed for the wrist render (wrist=True) AND to place the
        # wrist-camera body on the gripper for every camera.  Attribute absent when the h5 lacks it.
        self.X_handeye_source = None
        if wrist and wext is None:
            raise KeyError(f"{self.uuid}: no observation/camera_extrinsics/{self.wrist_serial}_left")
        if wext is not None:
            Xs = []
            for i in range(0, self.n, max(1, self.n // 32)):
                self.rr.set_state(self.qs[i], self.gs[i])
                Xs.append(np.linalg.inv(self.rr.T_l8) @ pose6_to_mat(wext[i]))
            Xs = np.stack(Xs)
            X = np.eye(4)
            X[:3, 3] = Xs[:, :3, 3].mean(axis=0)
            X[:3, :3] = R.from_matrix(Xs[:, :3, :3]).mean().as_matrix()
            self.X_handeye = X
            self.X_handeye_source = "h5"
        if wrist and self.wrist_serial not in self.serials:
            self.serials.append(self.wrist_serial)
        # wrist-camera body pose for this episode (per-episode hand-eye; fallback = mean root-frame pose).
        # A shared renderer is re-posed for every session; an explicitly disabled body stays disabled.
        self.rr.set_wrist_cam_handeye(getattr(self, "X_handeye", None))
        self.urdf_info["wrist_cam_body"] = self.rr.wrist_cam_info()
        if self.rr.wrist_cam_enabled:
            wi = self.urdf_info["wrist_cam_body"]
            _log(f"{self.uuid}: wrist-camera body ON ({wi['source']}): centre_root "
                 f"{np.round(wi['centre_root'], 4).tolist()} m, optical axis {wi['optical_axis_tilt_deg']:.1f} deg from +z")
        elif wext is None:
            _log(f"{self.uuid}: no h5 wrist extrinsics (no X_handeye)")

    # -- calibration -----------------------------------------------------------------------
    def _h5_base_pose6(self, serial):
        """Per-step h5 cam->base pose of an exterior camera reduced to one pose6 (median; the
        official DROID calibration is constant within an episode)."""
        arr = np.asarray(self.h5_ext[serial], dtype=float)
        return np.median(arr, axis=0) if arr.ndim == 2 else arr

    def _load_calibration(self, legacy_calib, calib_v2):
        self.legacy_calib = bool(legacy_calib)
        self.dt_ms = float(TIME_OFFSET_DEFAULT_MS)
        self.ext_base_pose6 = {s: np.array(v, dtype=float) for s, v in self.ext_sup.items()}
        self.ext_base_source = {s: f"superset-{self.ext_sup_source.get(s) or 'unknown'}" for s in self.ext_sup}
        if not self.ext_sup:
            for s in self._h5_fallback_serials:
                self.ext_base_pose6[s] = self._h5_base_pose6(s)
                self.ext_base_source[s] = "h5"
        self.ext_delta = {s: np.zeros(6) for s in self.ext_base_pose6}
        self.wrist_delta = {self.wrist_serial: np.zeros(6)}
        self.wrist_flipped = False
        self.quality = {}
        self.time_quality = {}
        self.gt_masks_used = False
        self.calib_mount_md5_ok = None      # True/False when a v2 file carries mount_params_md5, else None
        self.calib_problems = []            # interface deviations of the v2 file (check_v2_record)
        self.calib = None
        self.calib_version = 0
        self.calib_path = None
        v2_path = Path(calib_v2) if calib_v2 is not None else self.ep_dir / "calib_refined_v2.json"
        v1_path = self.ep_dir / "calib_refined.json"
        if legacy_calib:
            # OLD pipeline semantics: dt default 0, v1 deltas on top of the superset, TRI WRIST_DELTA
            self.dt_ms = 0.0
            self.wrist_delta[self.wrist_serial] = WRIST_DELTA_LEGACY.copy()
            if v1_path.exists():
                try:
                    r = json.load(open(v1_path))
                except (OSError, ValueError) as e:
                    _log(f"WARNING: corrupt {v1_path} ({e}); legacy deltas ignored")
                    r = {}
                self.dt_ms = float(r.get("time_offset_ms", 0.0))
                for s, d in r.get("ext_delta", {}).items():
                    if s in self.ext_delta:
                        self.ext_delta[s] = np.array(d, dtype=float)
                self.calib, self.calib_version, self.calib_path = r, 1, v1_path
            _log(f"{self.uuid}: LEGACY calibration (dt {self.dt_ms:+.0f} ms, WRIST_DELTA_LEGACY)")
        elif v2_path.exists():
            try:
                r = json.load(open(v2_path))
            except (OSError, ValueError) as e:
                _log(f"WARNING: corrupt {v2_path} ({e}); falling back to superset + default time offset")
                r = None
            if r is not None:
                self.calib, self.calib_path = r, v2_path
                self.calib_version = int(r.get("version", 2))
                self.dt_ms = float(r.get("time_offset_ms", TIME_OFFSET_DEFAULT_MS))
                srcs = r.get("ext_base_source", {}) or {}
                for s, pose in (r.get("ext_base_pose6", {}) or {}).items():
                    self.ext_base_pose6[str(s)] = np.array(pose, dtype=float)
                    self.ext_base_source[str(s)] = str(srcs.get(s, "v2"))
                    self.ext_delta.setdefault(str(s), np.zeros(6))
                for s, d in (r.get("ext_delta", {}) or {}).items():
                    self.ext_delta[str(s)] = np.array(d, dtype=float)
                for s, d in (r.get("wrist_delta", {}) or {}).items():
                    self.wrist_delta[str(s)] = np.array(d, dtype=float)
                self.wrist_flipped = bool(r.get("wrist_flipped", False))
                self.quality = r.get("quality", {}) or {}
                self.time_quality = r.get("time_quality", {}) or {}
                self.gt_masks_used = bool(r.get("gt_masks_used", False))
                self.calib_problems = check_v2_record(r, self.wrist_serial)
                if self.calib_problems:
                    _log(f"WARNING: {self.uuid}: {v2_path.name} deviates from the v2 interface: "
                         + "; ".join(self.calib_problems))
                mp_md5 = r.get("mount_params_md5")
                known = {self.rr.mount_params.get("md5"), self.rr.mount_params.get("md5_canonical"),
                         self.rr.mount_params.get("md5_file")} - {None}
                if mp_md5 and mp_md5 not in known:
                    self.calib_mount_md5_ok = False
                    _log(f"WARNING: {self.uuid}: {v2_path.name} fitted with mount_params md5 {mp_md5}, "
                         f"current {sorted(known)} ({self.rr.mount_params.get('source')}); deltas embed another mount "
                         f"-> STALE: re-run refine_v2 --force before rendering")
                elif not mp_md5:
                    _log(f"WARNING: {self.uuid}: {v2_path.name} has no mount_params_md5")
                else:
                    self.calib_mount_md5_ok = True
                wd = self.wrist_delta.get(self.wrist_serial, np.zeros(6))
                if self.wrist_flipped and not wrist_delta_has_flip(wd):
                    _log(f"WARNING: {self.uuid}: wrist_flipped=true but wrist_delta {np.round(wd, 4).tolist()} contains no "
                         f"180-deg roll; the v2 interface defines wrist_delta as TOTAL (fold_wrist_flip) and the flag is "
                         f"NOT applied by the renderer -> the wrist render is probably upside down")
                _log(f"{self.uuid}: calib v{self.calib_version} {v2_path.name}: dt {self.dt_ms:+.1f} ms, "
                     f"ext {', '.join(f'{s}<-{self.ext_base_source[s]}' for s in self.ext_base_pose6)}, "
                     f"wrist_delta {'yes' if any(np.any(d) for d in self.wrist_delta.values()) else 'identity'}"
                     f"{' FLIPPED(flag; roll folded into wrist_delta)' if self.wrist_flipped else ''}")
        else:
            if v1_path.exists():
                _log(f"{self.uuid}: legacy calib_refined.json IGNORED (embeds the old geometry); "
                     f"using {'superset' if self.ext_sup else 'h5'} extrinsics + dt {self.dt_ms:+.0f} ms")
        for s in self.ext_base_pose6:
            if s not in self.serials and s != self.wrist_serial:
                self.serials.append(s)
        self.T_ext = {s: pose6_to_mat(self.ext_delta.get(s, np.zeros(6)))
                      @ np.linalg.inv(pose6_to_mat(self.ext_base_pose6[s]))
                      for s in self.ext_base_pose6}
        self.D = pose6_to_mat(self.wrist_delta.get(self.wrist_serial, np.zeros(6)))

    # -- state interpolation ---------------------------------------------------------------
    def _hermite_q(self, t):
        ts = self.t_state
        n = len(ts)
        if n < 2 or t <= ts[0]:
            return self.qs[0].copy()
        if t >= ts[-1]:
            return self.qs[-1].copy()
        i = int(np.clip(np.searchsorted(ts, t, side="right") - 1, 0, n - 2))
        t0, t1 = ts[i], ts[i + 1]
        h = t1 - t0
        if h <= 0:
            return self.qs[i].copy()
        s = (t - t0) / h
        q0, q1 = self.qs[i], self.qs[i + 1]
        if h > HERMITE_MAX_GAP_MS:
            return q0 + s * (q1 - q0)
        m0 = self.qvs[i] * h / 1000.0  # rad/s -> rad per interval
        m1 = self.qvs[i + 1] * h / 1000.0
        s2, s3 = s * s, s * s * s
        return ((2 * s3 - 3 * s2 + 1) * q0 + (s3 - 2 * s2 + s) * m0
                + (-2 * s3 + 3 * s2) * q1 + (s3 - s2) * m1)

    def state_at(self, t_ms, mode=None):
        """(q[7], gripper01) at robot-state time t_ms.  mode: None (session default) |
        'hermite' (cubic Hermite with h5 joint_velocities) | 'linear'.  Gripper always linear."""
        mode = self.interp_mode if mode is None else mode
        g = float(np.interp(t_ms, self.t_state, self.gs))
        if mode == "hermite" and self.qvs is not None:
            q = self._hermite_q(float(t_ms))
        else:
            q = np.array([np.interp(t_ms, self.t_state, self.qs[:, j]) for j in range(7)])
        return q, g

    def set_step(self, serial, step, interp=True):
        """Set robot state for this camera frame; returns base->cam transform.
        Wrist: D @ inv(T_l8 @ X_handeye) with D = pose6_to_mat(wrist_delta) (TOTAL; wrist_flipped is
        a flag and is not applied here)."""
        serial = str(serial)
        if interp:
            q, g = self.state_at(self.cap_ts[serial][step] + self.dt_ms)
        else:
            q, g = self.qs[step], self.gs[step]
        self.rr.set_state(q, g)
        if serial == self.wrist_serial:
            return self.D @ np.linalg.inv(self.rr.T_l8 @ self.X_handeye)
        return self.T_ext[serial]

    def calib_summary(self):
        """JSON-serialisable record of the calibration actually used (for render_meta.json)."""
        return dict(calib_version=self.calib_version,
                    calib_path=str(self.calib_path) if self.calib_path else None,
                    legacy_calib=self.legacy_calib, legacy_geometry=self.legacy_geometry,
                    time_offset_ms=self.dt_ms, interp_mode=self.interp_mode,
                    in_superset=self.in_superset,
                    ext_base_source=dict(self.ext_base_source),
                    ext_base_pose6={s: [float(v) for v in d] for s, d in self.ext_base_pose6.items()},
                    ext_delta={s: [float(v) for v in d] for s, d in self.ext_delta.items()},
                    wrist_delta={s: [float(v) for v in d] for s, d in self.wrist_delta.items()},
                    wrist_delta_semantics="total (flip folded in; wrist_flipped is a flag)",
                    wrist_flipped=self.wrist_flipped, K_source=dict(self.K_source),
                    K_quality=dict(self.K_quality),
                    wh={s: list(v) for s, v in self.wh.items()},
                    mp4_wh={s: list(v) for s, v in self.mp4_wh.items()},
                    quality=self.quality, time_quality=self.time_quality,
                    gt_masks_used=self.gt_masks_used,
                    calib_mount_params_md5=(self.calib or {}).get("mount_params_md5") if self.calib_version == 2 else None,
                    calib_mount_md5_ok=self.calib_mount_md5_ok,
                    calib_problems=list(self.calib_problems),
                    mount_params_md5=self.rr.mount_params.get("md5"),
                    mount_params_md5_canonical=self.rr.mount_params.get("md5_canonical"),
                    tiny_renderer=self.rr.tiny_renderer)


# ----------------------------------------------------------------------------- video I/O

class VideoWriter:
    """H.264 writer (VS Code/browser playable), BGR input like cv2.VideoWriter.

    macro_block_size=1 stops imageio/ffmpeg from rescaling non-multiple-of-16 frames (672x376
    wrist videos used to come out 672x384).  yuv420p still needs even dimensions: odd sizes are
    padded by one pixel (edge replicate) and the pad is recorded in <path>.pad.json.
    """

    def __init__(self, path, fps=15, macro_block_size=1, quality=7):
        self.path = Path(path)
        self.size = None
        self.pad = (0, 0)
        self.n = 0
        self.w = imageio.get_writer(str(path), fps=fps, codec="libx264",
                                    quality=quality, pixelformat="yuv420p",
                                    macro_block_size=macro_block_size,
                                    ffmpeg_params=["-movflags", "+faststart"])

    def write(self, bgr):
        h, w = bgr.shape[:2]
        if self.size is None:
            self.size = (w, h)
            self.pad = (w % 2, h % 2)
            if any(self.pad):
                json.dump({"source_size": [w, h], "pad_right": self.pad[0], "pad_bottom": self.pad[1],
                           "note": "crop decoded frames to source_size"},
                          open(str(self.path) + ".pad.json", "w"))
        if any(self.pad):
            bgr = np.pad(bgr, ((0, self.pad[1]), (0, self.pad[0]), (0, 0)), mode="edge")
        self.w.append_data(np.ascontiguousarray(bgr[:, :, ::-1]))
        self.n += 1

    def release(self):
        self.w.close()


def video_size(path):
    """(width, height, n_frames) of a video as decoded by OpenCV."""
    cap = cv2.VideoCapture(str(path))
    try:
        return (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)), int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)),
                int(cap.get(cv2.CAP_PROP_FRAME_COUNT)))
    finally:
        cap.release()


def overlay_frame(real_bgr, render_rgb, mask, alpha=0.6):
    out = real_bgr.copy()
    render_bgr = render_rgb[:, :, ::-1]
    out[mask] = (alpha * render_bgr[mask] + (1 - alpha) * real_bgr[mask]).astype(np.uint8)
    return out


# ----------------------------------------------------------------------------- CLI

def main(argv=None):
    ap = argparse.ArgumentParser()
    ap.add_argument("ep_dir")
    ap.add_argument("--single", type=int, default=None, help="render only this step, save jpg")
    ap.add_argument("--serials", nargs="*", default=None)
    ap.add_argument("--mount-pos", nargs=3, type=float, default=None)
    ap.add_argument("--mount-euler", nargs=3, type=float, default=None)
    ap.add_argument("--mount-params", default=None, help="mount params json (default calib/mount_params.json)")
    ap.add_argument("--arm-urdf", default=None, help="override the per-episode arm URDF")
    ap.add_argument("--gripper-urdf", default=None, help="override the gripper URDF")
    ap.add_argument("--frame-offset", type=int, default=0)
    ap.add_argument("--save-frames", action="store_true")
    ap.add_argument("--normals", action="store_true", help="also write camera-space normal maps")
    ap.add_argument("--wrist", action="store_true", help="also render the wrist camera (per-step extrinsics from h5)")
    ap.add_argument("--no-interp", action="store_true", help="disable state interpolation to camera capture time")
    ap.add_argument("--linear-interp", action="store_true", help="linear instead of cubic Hermite joint interpolation")
    ap.add_argument("--legacy-calib", action="store_true", help="old calib_refined.json + WRIST_DELTA_LEGACY (diagnostics)")
    ap.add_argument("--legacy-geometry", action="store_true",
                    help="reproduce the pre-2026-10 renders: legacy gripper URDF + mount, FR3 shell, plain projection, "
                         "linear interpolation, legacy calibration (diagnostics / before-after comparison)")
    ap.add_argument("--no-wrist-cam-body", action="store_true",
                    help="do not render the ZED Mini wrist-camera body (calib/mount_params.json wrist_cam_body; default ON)")
    ap.add_argument("--out-root", default=None, help="output root (default <repo>/out)")
    ap.add_argument("--max-frames", type=int, default=None, help="render at most N frames per camera (smoke tests)")
    ap.add_argument("--alpha", type=float, default=0.6)
    args = ap.parse_args(argv)

    mount_params = load_mount_params(args.mount_params) if args.mount_params else None
    if args.legacy_geometry:
        if any(v is not None for v in (args.mount_pos, args.mount_euler, args.arm_urdf, args.gripper_urdf, mount_params)):
            _log("WARNING: --legacy-geometry overrides --mount-pos/--mount-euler/--arm-urdf/--gripper-urdf/--mount-params")
        rr = None
    else:
        rr = RobotRenderer(args.mount_pos, args.mount_euler, arm_urdf=args.arm_urdf,
                           gripper_urdf=args.gripper_urdf, mount_params=mount_params,
                           wrist_cam_body=False if args.no_wrist_cam_body else None)
    sess = EpisodeSession(args.ep_dir, wrist=args.wrist, renderer=rr, legacy_calib=args.legacy_calib,
                          interp_mode="linear" if args.linear_interp else "hermite",
                          legacy_geometry=args.legacy_geometry)
    rr = sess.rr
    ep_dir, uuid = sess.ep_dir, sess.uuid
    serials = args.serials or sess.serials
    interp = not args.no_interp
    out_root = Path(args.out_root) if args.out_root else ROOT / "out"
    meta = dict(uuid=uuid, urdf_info=sess.urdf_info, calib=sess.calib_summary(),
                mount_params={k: v for k, v in rr.mount_params.items()},
                mount_params_md5=rr.mount_params.get("md5"),
                wrist_cam_body=sess.urdf_info.get("wrist_cam_body"), videos={})

    for serial in serials:
        serial = str(serial)
        cap = cv2.VideoCapture(str(ep_dir / f"recordings/MP4/{serial}.mp4"))
        n_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        wh = (int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)),
              int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)))
        if serial not in sess.K:
            _log(f"WARNING: {serial}: no intrinsics (own or fallback); camera skipped")
            cap.release()
            continue
        Kc = sess.K_mp4.get(serial, sess.K[serial])
        k_quality = sess.K_quality.get(serial, "ok")
        if serial in sess.wh and tuple(sess.wh[serial]) != wh and tuple(sess.mp4_wh.get(serial, wh)) != wh:
            # should not happen (mp4_wh was probed from the same file); keep the stop-gap rescale, flagged
            k_quality = f"degraded:intrinsics {sess.wh[serial]} rescaled to decoded {wh}"
            _log(f"WARNING: {serial}: {k_quality}")
            Kc = scale_K(sess.K[serial], wh[0] / sess.wh[serial][0], wh[1] / sess.wh[serial][1])
        n = min(sess.n, n_frames)
        if args.max_frames is not None:
            n = min(n, args.max_frames)
        out_dir = out_root / uuid / serial
        out_dir.mkdir(parents=True, exist_ok=True)

        if args.single is not None:
            step = args.single
            cap.set(cv2.CAP_PROP_POS_FRAMES, step + args.frame_offset)
            ok, frame = cap.read()
            T = sess.set_step(serial, step, interp)
            rgb, mask = rr.render(T, Kc, wh)
            ov = overlay_frame(frame, rgb, mask, args.alpha)
            cv2.imwrite(str(out_dir / f"single_step{step:04d}.jpg"), ov)
            print(f"cam {serial}: wrote {out_dir}/single_step{step:04d}.jpg")
            cap.release()
            continue

        vw_ov = VideoWriter(out_dir / "overlay.mp4")
        vw_sbs = VideoWriter(out_dir / "sidebyside.mp4")
        vw_rgb = VideoWriter(out_dir / "render.mp4")
        vw_msk = VideoWriter(out_dir / "mask.mp4")
        vw_nrm = None
        if args.normals:
            vw_nrm = VideoWriter(out_dir / "normal.mp4")
        if args.save_frames:
            (out_dir / "render").mkdir(exist_ok=True)
            (out_dir / "mask").mkdir(exist_ok=True)
            if args.normals:
                (out_dir / "normal").mkdir(exist_ok=True)

        written = 0
        for step in range(n):
            ok, frame = cap.read()
            if not ok:
                break
            T = sess.set_step(serial, step, interp)
            res = rr.render(T, Kc, wh, with_normals=args.normals)
            rgb, mask = res[0], res[1]
            ov = overlay_frame(frame, rgb, mask, args.alpha)
            render_bgr = rgb[:, :, ::-1].copy()
            render_bgr[~mask] = 255
            vw_ov.write(ov)
            vw_sbs.write(np.hstack([frame, render_bgr, ov]))
            vw_rgb.write(render_bgr)
            vw_msk.write(np.repeat(mask[:, :, None].astype(np.uint8) * 255, 3, axis=2))
            if args.normals:
                normal_bgr = res[2][:, :, ::-1]
                vw_nrm.write(normal_bgr)
            if args.save_frames:
                cv2.imwrite(str(out_dir / "render" / f"{step:04d}.png"), render_bgr)
                cv2.imwrite(str(out_dir / "mask" / f"{step:04d}.png"),
                            mask.astype(np.uint8) * 255)
                if args.normals:
                    cv2.imwrite(str(out_dir / "normal" / f"{step:04d}.png"), normal_bgr)
            written += 1
        for vw in (vw_ov, vw_sbs, vw_rgb, vw_msk, vw_nrm):
            if vw is not None:
                vw.release()
        cap.release()
        # decoded size must equal the source size (macro-block rescale guard)
        sizes = {}
        for name in ("overlay", "render", "mask") + (("normal",) if args.normals else ()):
            w2, h2, n2 = video_size(out_dir / f"{name}.mp4")
            sizes[name] = [w2, h2, n2]
            if (w2, h2) != wh:
                _log(f"WARNING: {out_dir / name}.mp4 decoded {w2}x{h2} != source {wh[0]}x{wh[1]}")
        meta["videos"][serial] = dict(source_size=list(wh), n_frames=written, sizes=sizes,
                                      K_source=sess.K_source.get(serial), K_quality=k_quality,
                                      K_used=[[float(v) for v in row] for row in Kc])
        print(f"cam {serial}: wrote {written} frames ({wh[0]}x{wh[1]}) -> {out_dir}")

    if args.single is None:
        (out_root / uuid).mkdir(parents=True, exist_ok=True)
        json.dump(meta, open(out_root / uuid / "render_meta.json", "w"), indent=1, default=str)


if __name__ == "__main__":
    main()