File size: 70,694 Bytes
3459b76
 
e481415
 
 
3b0720c
3459b76
4e729b9
3459b76
7f8fcb7
05c8c5b
5a72443
f0b6460
f297b77
 
 
99b9e51
 
 
 
 
5a72443
61b921a
a67c231
af004bd
ec42e2b
f297b77
 
28fa965
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cc5cd26
 
 
 
 
 
 
 
 
 
 
 
7f8fcb7
32a10f3
 
 
 
 
 
 
 
61b921a
 
 
 
 
 
 
 
6a3e49a
 
 
 
 
61b921a
6a3e49a
61b921a
6a3e49a
61b921a
 
 
6a3e49a
 
 
61b921a
6a3e49a
61b921a
 
6a3e49a
 
61b921a
 
32a10f3
 
 
 
 
 
61b921a
6a3e49a
32a10f3
f297b77
 
 
32a10f3
f297b77
32a10f3
 
 
 
 
 
 
 
 
 
61b921a
 
 
 
32a10f3
6a3e49a
 
32a10f3
672057c
80a6f5a
32a10f3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f297b77
 
 
80a6f5a
 
 
7677a27
80a6f5a
61b921a
6a3e49a
80a6f5a
f297b77
 
 
 
 
 
 
 
 
 
 
 
80a6f5a
 
 
61b921a
 
 
 
 
 
80a6f5a
f297b77
7677a27
 
 
 
 
6a3e49a
 
 
80a6f5a
 
 
 
672057c
80a6f5a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f297b77
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2ab4dc
d6c4e26
66c623b
 
ae40f9a
 
 
 
 
 
 
 
 
 
 
 
 
 
d6c4e26
ae40f9a
 
 
 
 
 
 
 
d6c4e26
ae40f9a
 
 
66c623b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b35a92e
66c623b
 
f0b6460
 
 
 
 
 
 
 
 
 
 
 
 
 
f297b77
 
 
 
99b9e51
7f8fcb7
99b9e51
 
 
 
 
f297b77
 
99b9e51
 
 
 
 
f0b6460
 
 
 
 
99b9e51
50d50b0
99b9e51
f297b77
 
 
32a10f3
 
 
99b9e51
 
 
32a10f3
f297b77
 
62cb625
50d50b0
 
62cb625
f297b77
 
 
 
99b9e51
7f8fcb7
99b9e51
 
 
 
 
 
 
 
 
 
 
f0b6460
 
80a6f5a
7677a27
c24b90e
 
80a6f5a
f297b77
 
 
 
 
 
 
 
cc5cd26
dd0d99e
de50589
18df056
7f8fcb7
18df056
 
 
 
 
 
 
7f8fcb7
f297b77
2ec5dcb
7f8fcb7
 
f297b77
 
7f8fcb7
 
 
 
18df056
7f8fcb7
 
 
18df056
 
7f8fcb7
f297b77
 
 
18df056
f297b77
02d40a4
18df056
3459b76
e198d7e
 
1fad3ed
7f8fcb7
 
f06dd83
 
 
 
7f8fcb7
 
 
 
 
1fad3ed
7f8fcb7
 
 
 
 
 
 
1fad3ed
7f8fcb7
 
1fad3ed
7f8fcb7
99b9e51
7f8fcb7
 
 
 
18df056
1fad3ed
17ea525
7f8fcb7
 
 
5ed99ac
5e0bb06
014fc47
62cb625
99b9e51
28fa965
17ea525
28fa965
 
 
 
7f8fcb7
73ff731
7f8fcb7
 
62cb625
 
 
 
 
73ff731
62cb625
 
 
 
17ea525
de50589
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17ea525
 
235e34b
1fad3ed
de50589
17ea525
de50589
 
 
 
 
 
 
 
ae40f9a
 
 
235e34b
de50589
17ea525
 
de50589
17ea525
62cb625
 
17ea525
62cb625
 
28fa965
 
 
62cb625
17ea525
235e34b
 
 
 
 
 
 
62cb625
73ff731
62cb625
7f8fcb7
73ff731
 
 
 
 
 
 
28fa965
 
73ff731
28fa965
 
 
 
73ff731
7f8fcb7
28fa965
73ff731
99b9e51
62cb625
 
 
73ff731
 
7455283
 
 
 
 
73ff731
7455283
 
 
28fa965
 
73ff731
 
7f8fcb7
 
 
 
 
 
 
 
 
18df056
 
7f8fcb7
 
 
 
 
 
28fa965
 
 
7f8fcb7
18df056
 
7f8fcb7
18df056
7f8fcb7
 
de50589
66c623b
e2ab4dc
66c623b
495a767
7f8fcb7
014fc47
7f8fcb7
 
 
 
014fc47
 
 
 
495a767
7f8fcb7
495a767
7f8fcb7
 
495a767
18df056
 
 
7f8fcb7
 
8954d50
 
235e34b
8954d50
235e34b
 
 
8954d50
 
66c623b
 
 
f8976b4
61b921a
 
6a3e49a
61b921a
 
6a3e49a
 
de50589
7f8fcb7
de50589
dd0d99e
395185d
 
 
 
 
18df056
 
 
dd0d99e
7f8fcb7
de50589
b35a92e
 
 
fb09dce
ed56ca1
 
 
b35a92e
7f8fcb7
de50589
7f8fcb7
 
de50589
e4ed98a
 
 
 
 
 
 
 
 
 
 
 
 
 
7f8fcb7
e4ed98a
 
 
 
 
7f8fcb7
 
 
 
a4f6ac4
7f8fcb7
 
 
 
 
18df056
 
7f8fcb7
 
 
28fa965
 
99b9e51
28fa965
99b9e51
28fa965
 
 
 
 
 
 
18df056
 
7f8fcb7
99b9e51
a4f6ac4
 
1b040dc
 
 
 
 
7f8fcb7
 
28fa965
 
 
 
 
7f8fcb7
 
 
 
 
28fa965
 
 
 
 
7f8fcb7
 
 
 
28fa965
7f8fcb7
 
f297b77
7f8fcb7
 
 
 
 
 
 
 
 
824c842
 
 
 
 
 
 
f013501
61b921a
824c842
672057c
f013501
 
 
 
 
824c842
 
 
 
 
 
 
672057c
61b921a
6a3e49a
824c842
61b921a
824c842
f6bc38e
824c842
 
 
 
 
 
 
 
 
 
 
 
672057c
61b921a
 
 
6a3e49a
 
 
61b921a
 
6a3e49a
824c842
 
672057c
6a3e49a
824c842
 
 
 
a637bd3
 
 
 
 
 
 
 
 
d9cce19
 
a47c9fa
d23c4ea
cffad78
a637bd3
 
 
824c842
 
a637bd3
824c842
a637bd3
824c842
 
a637bd3
 
f013501
97d32b8
a637bd3
d23c4ea
cffad78
 
 
 
 
 
 
a637bd3
 
 
 
 
f013501
 
 
 
a637bd3
f013501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a637bd3
 
 
f013501
d9cce19
f013501
d9cce19
f013501
 
 
d9cce19
f013501
 
 
a637bd3
824c842
a637bd3
824c842
 
108b51b
 
824c842
a637bd3
824c842
 
108b51b
824c842
 
 
 
 
 
 
 
 
 
97d32b8
 
 
 
d9cce19
 
 
61b921a
 
 
 
824c842
 
 
f013501
61b921a
824c842
d9cce19
 
 
 
 
 
 
 
f8976b4
824c842
 
43d3c55
824c842
 
 
 
 
 
 
a637bd3
43d3c55
824c842
a637bd3
 
824c842
 
 
 
 
 
 
43d3c55
 
 
a67c231
43d3c55
 
 
 
 
672057c
43d3c55
 
a67c231
 
 
 
 
 
 
 
 
 
 
43d3c55
4e729b9
395185d
4e729b9
 
 
824c842
 
cffad78
824c842
43d3c55
 
 
 
f8976b4
43d3c55
824c842
 
 
 
4e729b9
824c842
 
 
 
 
 
 
 
 
 
43d3c55
 
 
 
 
f8976b4
 
a67c231
43d3c55
 
 
 
 
 
 
 
 
f8976b4
43d3c55
 
 
 
fb09dce
a67c231
 
 
 
f8976b4
43d3c55
 
824c842
ed56ca1
 
 
 
d9cce19
 
 
108b51b
824c842
 
d9cce19
 
 
4e729b9
108b51b
4e729b9
 
cffad78
 
 
824c842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4e729b9
824c842
4e729b9
395185d
4e729b9
 
 
 
 
 
 
 
 
 
 
 
 
 
395185d
cffad78
 
4e729b9
 
 
 
 
 
 
 
395185d
4e729b9
 
 
824c842
 
 
4e729b9
 
 
 
 
cffad78
 
108b51b
 
 
 
 
 
 
 
 
d23c4ea
 
3e8ca01
 
 
 
108b51b
 
 
 
3e8ca01
108b51b
 
 
cffad78
 
108b51b
 
 
 
97d32b8
108b51b
 
 
97d32b8
 
 
 
 
 
 
 
 
cffad78
108b51b
 
 
97d32b8
cffad78
 
f013501
108b51b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ca01
 
 
108b51b
 
 
d23c4ea
 
108b51b
 
 
 
 
 
 
 
 
 
 
 
 
3e8ca01
108b51b
 
 
 
 
 
cffad78
 
108b51b
3e8ca01
 
 
f013501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
824c842
108b51b
 
 
 
 
3e8ca01
108b51b
 
cffad78
 
108b51b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f013501
 
 
 
 
 
 
 
108b51b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97d32b8
108b51b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ca01
108b51b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cffad78
 
108b51b
 
 
 
3e8ca01
 
 
108b51b
 
 
 
 
 
 
 
 
 
 
 
 
3e8ca01
 
108b51b
 
 
 
 
cffad78
 
108b51b
 
 
97d32b8
 
 
 
 
 
 
108b51b
 
 
 
 
 
 
 
 
 
 
 
 
97d32b8
 
 
 
 
 
 
 
 
 
 
 
108b51b
cffad78
 
108b51b
 
 
 
 
 
3e8ca01
108b51b
 
 
 
 
 
 
 
 
 
 
 
 
824c842
 
 
 
4e729b9
 
a637bd3
d9cce19
 
 
 
 
a637bd3
 
 
 
 
 
 
 
 
 
 
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
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
# CRITICAL: Clear CUDA_VISIBLE_DEVICES BEFORE any imports
# HF Spaces may set this to "0" dynamically, locking us to a single GPU
# import os
# if "CUDA_VISIBLE_DEVICES" in os.environ:
#     del os.environ["CUDA_VISIBLE_DEVICES"]
import os

import collections
import logging
import time
from threading import Event, RLock, Thread
from queue import Queue, Full, Empty
from typing import Any, Dict, List, Optional, Sequence, Tuple

import cv2
import numpy as np
import torch
from concurrent.futures import ThreadPoolExecutor
from models.detectors.base import ObjectDetector
from models.model_loader import load_detector, load_detector_on_device
from models.segmenters.model_loader import load_segmenter, load_segmenter_on_device
from utils.video import StreamingVideoWriter
from jobs.storage import set_track_data, store_latest_frame, get_job_storage
from inspection.masks import rle_encode
import tempfile
import json as json_module


class AsyncVideoReader:
    """
    Async video reader that decodes frames in a background thread.
    
    This prevents GPU starvation on multi-GPU systems by prefetching frames
    while the main thread is busy dispatching work to GPUs.
    """
    
    def __init__(self, video_path: str, prefetch_size: int = 32):
        """
        Initialize async video reader.
        
        Args:
            video_path: Path to video file
            prefetch_size: Number of frames to prefetch (default 32)
        """
        from queue import Queue
        from threading import Thread
        
        self.video_path = video_path
        self.prefetch_size = prefetch_size
        
        # Open video to get metadata
        self._cap = cv2.VideoCapture(video_path)
        if not self._cap.isOpened():
            raise ValueError(f"Unable to open video: {video_path}")
        
        self.fps = self._cap.get(cv2.CAP_PROP_FPS) or 30.0
        self.width = int(self._cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.height = int(self._cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        self.total_frames = int(self._cap.get(cv2.CAP_PROP_FRAME_COUNT))
        
        # Prefetch queue
        self._queue: Queue = Queue(maxsize=prefetch_size)
        self._error: Exception = None
        self._finished = False
        
        # Start decoder thread
        self._thread = Thread(target=self._decode_loop, daemon=True)
        self._thread.start()
    
    def _decode_loop(self):
        """Background thread that continuously decodes frames."""
        try:
            while True:
                success, frame = self._cap.read()
                if not success:
                    break
                self._queue.put(frame)  # Blocks when queue is full (backpressure)
        except Exception as e:
            self._error = e
            logging.error(f"AsyncVideoReader decode error: {e}")
        finally:
            self._cap.release()
            self._queue.put(None)  # Sentinel to signal end
            self._finished = True
    
    def __iter__(self):
        return self
    
    def __next__(self) -> np.ndarray:
        if self._error:
            raise self._error
        
        frame = self._queue.get()
        if frame is None:
            raise StopIteration
        return frame
    
    def close(self):
        """Stop the decoder thread and release resources."""
        # Signal thread to stop by releasing cap (if not already done)
        if self._cap.isOpened():
            self._cap.release()
        # Drain queue to unblock thread if it's waiting on put()
        while not self._queue.empty():
            try:
                self._queue.get_nowait()
            except:
                break
    
    def __enter__(self):
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        self.close()


def _check_cancellation(job_id: Optional[str]) -> None:
    """Check if job has been cancelled and raise exception if so."""
    if job_id is None:
        return
    from jobs.storage import get_job_storage
    from jobs.models import JobStatus

    job = get_job_storage().get(job_id)
    if job and job.status == JobStatus.CANCELLED:
        raise RuntimeError("Job cancelled by user")


def _color_for_label(label: str) -> Tuple[int, int, int]:
    # Deterministic BGR color from label text.
    value = abs(hash(label)) % 0xFFFFFF
    blue = value & 0xFF
    green = (value >> 8) & 0xFF
    red = (value >> 16) & 0xFF
    return (blue, green, red)


# Mission-relevance colors (BGR)
_COLOR_MISSION_RELEVANT = (0, 0, 255)      # red
_COLOR_NOT_RELEVANT = (128, 128, 128)      # gray


def _mission_colors_for_dets(
    dets: list,
    verdicts: Dict[str, bool],
) -> Tuple[Optional[List[Tuple[int, int, int]]], Optional[List[bool]]]:
    """Return per-detection BGR colors and hide_labels flags based on mission verdicts.

    Returns (None, None) if no verdicts available yet.
    """
    if not verdicts:
        return None, None
    colors = []
    hide = []
    for d in dets:
        tid = d.get("track_id")
        if tid and tid in verdicts:
            relevant = verdicts[tid]
            colors.append(_COLOR_MISSION_RELEVANT if relevant else _COLOR_NOT_RELEVANT)
            hide.append(not relevant)
        else:
            # Unassessed — use default hash color, show label
            label = d.get("label", "obj")
            colors.append(_color_for_label(label))
            hide.append(False)
    return colors, hide


def draw_boxes(
    frame: np.ndarray,
    boxes: np.ndarray,
    labels: Optional[Sequence[int]] = None,
    queries: Optional[Sequence[str]] = None,
    label_names: Optional[Sequence[str]] = None,
    colors: Optional[Sequence[Tuple[int, int, int]]] = None,
    hide_labels: Optional[Sequence[bool]] = None,
) -> np.ndarray:
    output = frame.copy()
    if boxes is None:
        return output
    for idx, box in enumerate(boxes):
        x1, y1, x2, y2 = [int(coord) for coord in box]
        if label_names is not None and idx < len(label_names):
            label = label_names[idx]
        elif labels is not None and idx < len(labels) and queries is not None:
            label_idx = int(labels[idx])
            if 0 <= label_idx < len(queries):
                label = queries[label_idx]
            else:
                label = f"label_{label_idx}"
        else:
            label = f"label_{idx}"
        if colors is not None and idx < len(colors):
            color = colors[idx]
        else:
            color = (128, 128, 128) if not label else _color_for_label(label)
        cv2.rectangle(output, (x1, y1), (x2, y2), color, thickness=2)
        should_hide = hide_labels is not None and idx < len(hide_labels) and hide_labels[idx]
        if label and not should_hide:
            font = cv2.FONT_HERSHEY_SIMPLEX
            font_scale = 0.6
            thickness = 2
            text_size, baseline = cv2.getTextSize(label, font, font_scale, thickness)
            text_w, text_h = text_size
            pad = 4
            text_x = x1
            text_y = max(y1 - 6, text_h + pad)
            box_top_left = (text_x, text_y - text_h - pad)
            box_bottom_right = (text_x + text_w + pad, text_y + baseline)
            cv2.rectangle(output, box_top_left, box_bottom_right, color, thickness=-1)
            cv2.putText(
                output,
                label,
                (text_x + pad // 2, text_y - 2),
                font,
                font_scale,
                (255, 255, 255),
                thickness,
                lineType=cv2.LINE_AA,
            )
    return output


def draw_masks(
    frame: np.ndarray,
    masks: np.ndarray,
    alpha: float = 0.65,
    labels: Optional[Sequence[str]] = None,
    colors: Optional[Sequence[Tuple[int, int, int]]] = None,
    hide_labels: Optional[Sequence[bool]] = None,
) -> np.ndarray:
    output = frame.copy()
    if masks is None or len(masks) == 0:
        return output
    for idx, mask in enumerate(masks):
        if mask is None:
            continue
        if mask.ndim == 3:
            mask = mask[0]
        if mask.shape[:2] != output.shape[:2]:
            mask = cv2.resize(mask, (output.shape[1], output.shape[0]), interpolation=cv2.INTER_NEAREST)
        mask_bool = mask.astype(bool)
        overlay = np.zeros_like(output, dtype=np.uint8)
        label = None
        if labels and idx < len(labels):
            label = labels[idx]
        if colors is not None and idx < len(colors):
            color = colors[idx]
        else:
            # Use a fallback key for consistent color even when no label text
            color_key = label if label else f"object_{idx}"
            color = _color_for_label(color_key)
        overlay[mask_bool] = color
        output = cv2.addWeighted(output, 1.0, overlay, alpha, 0)
        contours, _ = cv2.findContours(
            mask_bool.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
        )
        if contours:
            cv2.drawContours(output, contours, -1, color, thickness=2)
        # Only draw label text when explicit labels were provided and not hidden
        should_hide = hide_labels is not None and idx < len(hide_labels) and hide_labels[idx]
        if label and not should_hide:
            coords = np.column_stack(np.where(mask_bool))
            if coords.size:
                y, x = coords[0]
                font = cv2.FONT_HERSHEY_SIMPLEX
                font_scale = 0.6
                thickness = 2
                text_size, baseline = cv2.getTextSize(label, font, font_scale, thickness)
                text_w, text_h = text_size
                pad = 4
                text_x = int(x)
                text_y = max(int(y) - 6, text_h + pad)
                box_top_left = (text_x, text_y - text_h - pad)
                box_bottom_right = (text_x + text_w + pad, text_y + baseline)
                cv2.rectangle(output, box_top_left, box_bottom_right, color, thickness=-1)
                cv2.putText(
                    output,
                    label,
                    (text_x + pad // 2, text_y - 2),
                    font,
                    font_scale,
                    (255, 255, 255),
                    thickness,
                    lineType=cv2.LINE_AA,
                )
    return output


def _build_detection_records(
    boxes: np.ndarray,
    scores: Sequence[float],
    labels: Sequence[int],
    queries: Sequence[str],
    label_names: Optional[Sequence[str]] = None,
) -> List[Dict[str, Any]]:
    detections: List[Dict[str, Any]] = []
    for idx, box in enumerate(boxes):
        if label_names is not None and idx < len(label_names):
            label = label_names[idx]
        else:
            label_idx = int(labels[idx]) if idx < len(labels) else -1
            if 0 <= label_idx < len(queries):
                label = queries[label_idx]
            else:
                label = f"label_{label_idx}"
        detections.append(
            {
                "label": label,
                "score": float(scores[idx]) if idx < len(scores) else 0.0,
                "bbox": [int(coord) for coord in box.tolist()],
            }
        )
    return detections


from utils.tracker import ByteTracker
from utils.tiling import batched_nms as _batched_nms


def _apply_nms(detections: List[Dict[str, Any]], iou_threshold: float = 0.45) -> List[Dict[str, Any]]:
    """Apply per-class NMS to detection records before tracking.

    Works on the dict format produced by _build_detection_records():
        [{"label": str, "score": float, "bbox": [x1,y1,x2,y2]}, ...]

    This is a universal post-detection NMS that catches duplicates
    regardless of which detector produced them.
    """
    if len(detections) <= 1:
        return detections

    boxes = torch.tensor([d["bbox"] for d in detections], dtype=torch.float32)
    scores = torch.tensor([d["score"] for d in detections], dtype=torch.float32)
    label_to_id: Dict[str, int] = {}
    label_ids = []
    for d in detections:
        lbl = d["label"]
        if lbl not in label_to_id:
            label_to_id[lbl] = len(label_to_id)
        label_ids.append(label_to_id[lbl])
    labels = torch.tensor(label_ids, dtype=torch.int64)

    keep = _batched_nms(boxes, scores, labels, iou_threshold)
    return [detections[i] for i in keep.tolist()]


class SpeedEstimator:
    def __init__(self, fps: float = 30.0):
        self.fps = fps
        self.pixel_scale_map = {} # label -> pixels_per_meter (heuristic)

    def estimate(self, detections: List[Dict[str, Any]]):
        for det in detections:
            history = det.get('history', [])
            if len(history) < 5: continue
            
            # Simple heuristic: Speed based on pixel movement
            # We assume a base depth or size.
            # Delta over last 5 frames
            curr = history[-1]
            prev = history[-5]
            
            # Centroids
            cx1 = (curr[0] + curr[2]) / 2
            cy1 = (curr[1] + curr[3]) / 2
            cx2 = (prev[0] + prev[2]) / 2
            cy2 = (prev[1] + prev[3]) / 2
            
            dist_px = np.sqrt((cx1-cx2)**2 + (cy1-cy2)**2)
            
            # Heuristic scale: Assume car is ~4m long? Or just arbitrary pixel scale
            # If we had GPT distance, we could calibrate.
            # For now, let's use a dummy scale: 50px = 1m (very rough)
            # Speed = (dist_px / 50) meters / (5 frames / 30 fps) seconds
            #       = (dist_px / 50) / (0.166) m/s
            #       = (dist_px * 0.12) m/s
            #       = * 3.6 km/h
            
            scale = 50.0 
            dt = 5.0 / self.fps
            
            speed_mps = (dist_px / scale) / dt
            speed_kph = speed_mps * 3.6
            
            # Smoothing
            det['speed_kph'] = speed_kph
            
            # Direction
            dx = cx1 - cx2
            dy = cy1 - cy2
            angle = np.degrees(np.arctan2(dy, dx)) # 0 is right, 90 is down
            
            # Map to clock direction (12 is up = -90 deg)
            # -90 (up) -> 12
            # 0 (right) -> 3
            # 90 (down) -> 6
            # 180 (left) -> 9
            
            # Adjust so 12 is up (negative Y)
            # angle -90 is 12
            clock_hour = ((angle + 90) / 30 + 12) % 12
            if clock_hour == 0: clock_hour = 12.0
            det['direction_clock'] = f"{int(round(clock_hour))} o'clock"
            det['angle_deg'] = angle # 0 is right, 90 is down (screen space)


_MODEL_LOCKS: Dict[str, RLock] = {}
_MODEL_LOCKS_GUARD = RLock()


def _get_model_lock(kind: str, name: str) -> RLock:
    key = f"{kind}:{name}"
    with _MODEL_LOCKS_GUARD:
        lock = _MODEL_LOCKS.get(key)
        if lock is None:
            lock = RLock()
            _MODEL_LOCKS[key] = lock
        return lock


def infer_frame(
    frame: np.ndarray,
    queries: Sequence[str],
    detector_name: Optional[str] = None,
    detector_instance: Optional[ObjectDetector] = None,
) -> Tuple[np.ndarray, List[Dict[str, Any]]]:
    if detector_instance:
        detector = detector_instance
    else:
        detector = load_detector(detector_name)
    
    text_queries = list(queries) or ["object"]
    try:
        if hasattr(detector, "lock"):
            lock = detector.lock
        else:
            lock = _get_model_lock("detector", detector.name)
        
        with lock:
            result = detector.predict(frame, text_queries)
            detections = _build_detection_records(
                result.boxes, result.scores, result.labels, text_queries, result.label_names
            )

        display_labels = [det["label"] for det in detections]

    except Exception:
        logging.exception("Inference failed for queries %s", text_queries)
        raise
    return draw_boxes(
        frame,
        result.boxes,
        labels=None, # Use custom labels
        queries=None,
        label_names=display_labels,
    ), detections


def _build_display_label(det):
    """Build display label for a detection."""
    return det["label"]

def infer_segmentation_frame(
    frame: np.ndarray,
    text_queries: Optional[List[str]] = None,
    segmenter_name: Optional[str] = None,
    segmenter_instance: Optional[Any] = None,
) -> Tuple[np.ndarray, Any]:
    if segmenter_instance:
        segmenter = segmenter_instance
        # Use instance lock if available
        if hasattr(segmenter, "lock"):
            lock = segmenter.lock
        else:
            lock = _get_model_lock("segmenter", segmenter.name)
    else:
        segmenter = load_segmenter(segmenter_name)
        lock = _get_model_lock("segmenter", segmenter.name)
        
    with lock:
        result = segmenter.predict(frame, text_prompts=text_queries)
    labels = text_queries or []
    if len(labels) == 1:
        masks = result.masks if result.masks is not None else []
        labels = [labels[0] for _ in range(len(masks))]
    return draw_masks(frame, result.masks, labels=labels), result


def run_inference(
    input_video_path: str,
    output_video_path: str,
    queries: List[str],
    max_frames: Optional[int] = None,
    detector_name: Optional[str] = None,
    job_id: Optional[str] = None,
    stream_queue: Optional[Queue] = None,
    first_frame_detections: Optional[List[Dict[str, Any]]] = None,
    _ttfs_t0: Optional[float] = None,
) -> Tuple[str, List[List[Dict[str, Any]]]]:

    def _ttfs(msg):
        if _ttfs_t0 is not None:
            logging.info("[TTFS:%s] +%.1fs %s", job_id, time.perf_counter() - _ttfs_t0, msg)

    _ttfs("enter run_inference")

    # 1. Setup Video Reader
    try:
        reader = AsyncVideoReader(input_video_path)
    except ValueError:
        logging.exception("Failed to open video at %s", input_video_path)
        raise

    fps = reader.fps
    width = reader.width
    height = reader.height
    total_frames = reader.total_frames

    if max_frames is not None:
        total_frames = min(total_frames, max_frames)

    _ttfs(f"video_opened ({total_frames} frames, {width}x{height}, {fps:.1f}fps)")

    # 2. Defaults and Config
    if not queries:
        queries = ["person", "car", "truck", "motorcycle", "bicycle", "bus", "train", "airplane"]
        logging.info("No queries provided, using defaults: %s", queries)

    logging.info("Detection queries: %s", queries)
    active_detector = detector_name or "yolo11"

    # Parallel Model Loading
    num_gpus = torch.cuda.device_count()
    detectors = []

    if num_gpus > 0:
        logging.info("Detected %d GPUs. Loading models in parallel...", num_gpus)
        # Pre-download weights before parallel GPU init to avoid race conditions
        from models.model_loader import prefetch_weights
        prefetch_weights(active_detector)

        def load_models_on_gpu(gpu_id: int):
            device_str = f"cuda:{gpu_id}"
            try:
                det = load_detector_on_device(active_detector, device_str)
                det.lock = RLock()
                return (gpu_id, det)
            except Exception as e:
                logging.error(f"Failed to load models on GPU {gpu_id}: {e}")
                raise

        with ThreadPoolExecutor(max_workers=num_gpus) as loader_pool:
            futures = [loader_pool.submit(load_models_on_gpu, i) for i in range(num_gpus)]
            results = [f.result() for f in futures]

            # Sort by GPU ID to ensure consistent indexing
            results.sort(key=lambda x: x[0])
            for _, det in results:
                detectors.append(det)
    else:
        logging.info("No GPUs detected. Loading CPU models...")
        det = load_detector(active_detector)
        det.lock = RLock()
        detectors.append(det)

    _ttfs(f"models_loaded ({active_detector}, {num_gpus} GPUs)")

    # queue_in: (frame_idx, frame_data)
    # queue_out: (frame_idx, processed_frame, detections)
    queue_in = Queue(maxsize=16) 
    # Tuning for A10: buffer at least 32 frames per GPU (batch size)
    # GPT Latency Buffer: GPT takes ~3s. At 30fps, that's 90 frames. We need to absorb this burst.
    queue_out_max = max(128, (len(detectors) if detectors else 1) * 32)
    queue_out = Queue(maxsize=queue_out_max)
    
    
    # 6. Worker Function (Unified)
    
    # Robustness: Define flag early so workers can see it
    writer_finished = False 
    
    def worker_task(gpu_idx: int):
        logging.info(f"Worker {gpu_idx} started. PID: {os.getpid()}")
        detector_instance = detectors[gpu_idx]
        
        batch_size = detector_instance.max_batch_size if detector_instance.supports_batch else 1
        batch_accum = [] # List[Tuple[idx, frame]]
        
        def flush_batch():
            if not batch_accum: return
            logging.info(f"Worker {gpu_idx} flushing batch of {len(batch_accum)} frames")
            
            indices = [item[0] for item in batch_accum]
            frames = [item[1] for item in batch_accum]
            
            # --- UNIFIED INFERENCE ---
            # Separate frame 0 if we have cached detections (avoid re-detecting)
            cached_frame0 = None
            detect_indices = indices
            detect_frames = frames
            if first_frame_detections is not None and 0 in indices:
                f0_pos = indices.index(0)
                cached_frame0 = (indices[f0_pos], frames[f0_pos])
                detect_indices = indices[:f0_pos] + indices[f0_pos+1:]
                detect_frames = frames[:f0_pos] + frames[f0_pos+1:]
                logging.info("Worker %d: reusing cached detections for frame 0", gpu_idx)

            # Run detection batch (excluding frame 0 if cached)
            det_results_map = {}
            if detect_frames:
                try:
                    if detector_instance.supports_batch:
                        with detector_instance.lock:
                             raw_results = detector_instance.predict_batch(detect_frames, queries)
                    else:
                        with detector_instance.lock:
                             raw_results = [detector_instance.predict(f, queries) for f in detect_frames]
                    for di, dr in zip(detect_indices, raw_results):
                        det_results_map[di] = dr
                except BaseException as e:
                    logging.exception("Batch detection crashed with critical error")
                    for di in detect_indices:
                        det_results_map[di] = None

            # --- POST PROCESSING ---
            batch_det_summary = []
            for i, (idx, frame) in enumerate(zip(indices, frames)):
                # 1. Detections — use cached for frame 0 if available
                detections = []
                if cached_frame0 is not None and idx == 0:
                    detections = [d.copy() for d in first_frame_detections]
                else:
                    d_res = det_results_map.get(idx)
                    if d_res:
                        detections = _build_detection_records(
                            d_res.boxes, d_res.scores, d_res.labels, queries, d_res.label_names
                        )
                # Apply universal NMS to remove duplicate detections
                if detections:
                    detections = _apply_nms(detections, iou_threshold=0.45)
                batch_det_summary.append((idx, len(detections)))

                # 2. Frame Rendering
                processed = frame.copy()

                # 3. Output
                while True:
                    try:
                        queue_out.put((idx, processed, detections), timeout=1.0)
                        break
                    except Full:
                        # Robustness: Check if writer is dead
                        if writer_finished:
                            raise RuntimeError("Writer thread died unexpectedly")
                        if job_id: _check_cancellation(job_id)

            total_dets = sum(c for _, c in batch_det_summary)
            if total_dets == 0 or indices[0] % 90 == 0:
                logging.info("Worker %d batch [frames %s]: %d total detections %s",
                             gpu_idx,
                             f"{indices[0]}-{indices[-1]}",
                             total_dets,
                             [(idx, cnt) for idx, cnt in batch_det_summary if cnt > 0])
            batch_accum.clear()
            logging.info(f"Worker {gpu_idx} finished flushing batch")

        while True:
            try:
                item = queue_in.get(timeout=2.0)
            except Empty:
                # Periodic check for cancellation if main thread is slow
                if job_id: _check_cancellation(job_id)
                continue

            try:
                if item is None:
                    logging.info(f"Worker {gpu_idx} received sentinel. Flushing and exiting.")
                    flush_batch()
                    break
                    
                frame_idx, frame_data = item
                # logging.info(f"Worker {gpu_idx} got frame {frame_idx}") # Verbose
                
                if frame_idx % 30 == 0:
                    logging.info("Processing frame %d on device %s", frame_idx, "cpu" if num_gpus==0 else f"cuda:{gpu_idx}")

                batch_accum.append((frame_idx, frame_data))
                if len(batch_accum) >= batch_size:
                    flush_batch()
            except BaseException as e:
                logging.exception(f"Worker {gpu_idx} CRASHED processing frame. Recovering...")
                # Emit empty/failed frames for the batch to keep sequence alive
                for idx, frm in batch_accum:
                    try:
                        # Fallback: Return original frame with empty detections
                        queue_out.put((idx, frm, []), timeout=5.0)
                        logging.info(f"Emitted fallback frame {idx}")
                    except:
                        pass
                batch_accum.clear()
            finally:
                queue_in.task_done()
        
        logging.info(f"Worker {gpu_idx} thread exiting normally.")

    # 6. Start Workers
    workers = []
    num_workers = len(detectors)
    for i in range(num_workers):
        t = Thread(target=worker_task, args=(i,), daemon=True)
        t.start()
        workers.append(t)

    _ttfs(f"workers_started ({num_workers} GPU workers)")

    # 7. Start Writer / Output Collection (Main Thread or separate)
    # We will run writer logic in the main thread after feeding is done? 
    # No, we must write continuously.
    
    all_detections_map = {}
    
    # writer_finished initialized earlier
    # writer_finished = False 

    
    _first_frame_published = False

    def writer_loop():
        nonlocal writer_finished, _first_frame_published
        next_idx = 0
        buffer = {}

        # Initialize Tracker & Speed Estimator
        tracker = ByteTracker(frame_rate=fps)
        speed_est = SpeedEstimator(fps=fps)

        try:
            with StreamingVideoWriter(output_video_path, fps, width, height) as writer:
                while next_idx < total_frames:
                    # Fetch from queue
                    try:
                        while next_idx not in buffer:
                            # Backpressure: bound the reorder buffer to prevent memory blowup
                            if len(buffer) > 128:
                                logging.warning("Writer reorder buffer too large (%d items), applying backpressure (waiting for frame %d)...", len(buffer), next_idx)
                                time.sleep(0.05)

                            item = queue_out.get(timeout=1.0) # wait

                            idx, p_frame, dets = item
                            buffer[idx] = (p_frame, dets)

                        if next_idx == 0:
                            _ttfs("first_frame_dequeued_from_gpu")

                        # Write next_idx
                        p_frame, dets = buffer.pop(next_idx)

                        # --- SEQUENTIAL TRACKING ---
                        pre_track_count = len(dets)
                        dets = tracker.update(dets)
                        if (next_idx % 30 == 0) or (pre_track_count > 0 and len(dets) == 0):
                            logging.info("Writer frame %d: %d detections in -> %d tracked out",
                                         next_idx, pre_track_count, len(dets))
                        speed_est.estimate(dets)

                        # --- RENDER BOXES & OVERLAYS ---
                        if dets:
                            display_boxes = np.array([d['bbox'] for d in dets])
                            display_labels = [d.get('label', 'obj') for d in dets]
                            # Apply mission-relevance colors (red/gray) if verdicts available
                            det_colors = None
                            det_hide = None
                            if job_id:
                                verdicts = get_job_storage().get_mission_verdicts(job_id)
                                det_colors, det_hide = _mission_colors_for_dets(dets, verdicts)
                            p_frame = draw_boxes(p_frame, display_boxes, label_names=display_labels, colors=det_colors, hide_labels=det_hide)

                        writer.write(p_frame)

                        if stream_queue:
                            from jobs.streaming import publish_frame as _publish
                            if job_id:
                                _publish(job_id, p_frame)
                            else:
                                stream_queue.put(p_frame)
                            if not _first_frame_published:
                                _first_frame_published = True
                                _ttfs("first_frame_published_to_stream")

                        all_detections_map[next_idx] = dets

                        # Store tracks for frontend access
                        if job_id:
                            set_track_data(job_id, next_idx, dets)
                            store_latest_frame(job_id, p_frame)
                            # Report progress every 10 frames (and on the last frame)
                            if next_idx % 10 == 0 or next_idx == total_frames - 1:
                                get_job_storage().update(job_id, frames_processed=next_idx + 1, total_frames=total_frames)

                        next_idx += 1

                        if next_idx % 30 == 0:
                            logging.debug("Wrote frame %d/%d", next_idx, total_frames)

                    except Empty:
                        if job_id:
                            _check_cancellation(job_id)
                        if not any(w.is_alive() for w in workers) and queue_out.empty():
                            logging.error(
                                "Workers stopped unexpectedly while waiting for frame %d.",
                                next_idx,
                            )
                            break
                        continue
                    except Exception:
                        logging.exception("Writer loop processing error at index %d", next_idx)
                        if job_id:
                            _check_cancellation(job_id)
                        if not any(w.is_alive() for w in workers) and queue_out.empty():
                            logging.error(
                                "Workers stopped unexpectedly while writer handled frame %d.",
                                next_idx,
                            )
                            break
                        continue
        except Exception as e:
            logging.exception("Writer loop failed")
        finally:
            logging.info("Writer loop finished. Wrote %d frames (target %d)", next_idx, total_frames)
            writer_finished = True

    writer_thread = Thread(target=writer_loop, daemon=True)
    writer_thread.start()

    _ttfs("writer_thread_started")

    # 8. Feed Frames (Main Thread)
    try:
        frames_fed = 0
        reader_iter = iter(reader)
        while True:
            _check_cancellation(job_id)
            if max_frames is not None and frames_fed >= max_frames:
                break
                
            try:
                frame = next(reader_iter)
            except StopIteration:
                break
                
            queue_in.put((frames_fed, frame)) # Blocks if full
            if frames_fed == 0:
                _ttfs("first_frame_fed_to_gpu")
            frames_fed += 1
            
        logging.info("Feeder finished. Fed %d frames (expected %d)", frames_fed, total_frames)

        # Update total_frames to actual count so writer knows when to stop
        if frames_fed != total_frames:
            logging.info("Updating total_frames from %d to %d (actual fed)", total_frames, frames_fed)
            total_frames = frames_fed
            
        # Signal workers to stop
        for _ in range(num_workers):
            try:
                queue_in.put(None, timeout=5.0) # Using timeout to prevent infinite block
            except Full:
                logging.warning("Failed to send stop signal to a worker (queue full)")

        # Wait for queue to process
        queue_in.join()
        
    except Exception as e:
        logging.exception("Feeding frames failed")
        # Ensure we try to signal workers even on error
        for _ in range(num_workers):
            try:
                queue_in.put_nowait(None)
            except Full: pass
        raise
    finally:
        reader.close()


    # Wait for writer
    writer_thread.join()

    # Sort detections
    sorted_detections = []
    # If we crashed early, we return what we have
    max_key = max(all_detections_map.keys()) if all_detections_map else -1
    for i in range(max_key + 1):
        sorted_detections.append(all_detections_map.get(i, []))

    logging.info("Inference complete. Output: %s", output_video_path)
    return output_video_path, sorted_detections
def _gsam2_render_frame(
    frame_dir: str,
    frame_names: List[str],
    frame_idx: int,
    frame_objects: Dict,
    height: int,
    width: int,
    frame_store=None,
    mission_verdicts: Optional[Dict[str, bool]] = None,
) -> np.ndarray:
    """Render a single GSAM2 tracking frame (masks only, no bboxes). CPU-only."""
    if frame_store is not None:
        frame = frame_store.get_bgr(frame_idx).copy()  # .copy() — render mutates
    else:
        frame_path = os.path.join(frame_dir, frame_names[frame_idx])
        frame = cv2.imread(frame_path)
    if frame is None:
        return np.zeros((height, width, 3), dtype=np.uint8)

    if not frame_objects:
        return frame

    masks_list: List[np.ndarray] = []
    mask_labels: List[str] = []
    mask_colors: Optional[List[Tuple[int, int, int]]] = None if not mission_verdicts else []
    mask_hide: Optional[List[bool]] = None if not mission_verdicts else []

    for obj_id, obj_info in frame_objects.items():
        mask = obj_info.mask
        label = obj_info.class_name
        if mask is not None:
            if isinstance(mask, torch.Tensor):
                mask_np = mask.cpu().numpy().astype(bool)
            else:
                mask_np = np.asarray(mask).astype(bool)
            if mask_np.shape[:2] != (height, width):
                mask_np = cv2.resize(
                    mask_np.astype(np.uint8),
                    (width, height),
                    interpolation=cv2.INTER_NEAREST,
                ).astype(bool)
            masks_list.append(mask_np)
            mask_labels.append(label)
            if mask_colors is not None:
                tid = str(obj_id)
                if tid in mission_verdicts:
                    relevant = mission_verdicts[tid]
                    mask_colors.append(_COLOR_MISSION_RELEVANT if relevant else _COLOR_NOT_RELEVANT)
                    mask_hide.append(not relevant)
                else:
                    mask_colors.append(_color_for_label(label or f"object_{obj_id}"))
                    mask_hide.append(False)

    if masks_list:
        # Draw masks with labels — no bboxes for segmentation mode
        frame = draw_masks(frame, np.stack(masks_list), labels=mask_labels, colors=mask_colors, hide_labels=mask_hide)

    return frame


def run_grounded_sam2_tracking(
    input_video_path: str,
    output_video_path: str,
    queries: List[str],
    max_frames: Optional[int] = None,
    segmenter_name: Optional[str] = None,
    job_id: Optional[str] = None,
    stream_queue: Optional[Queue] = None,
    step: int = 20,
    _perf_metrics: Optional[Dict[str, float]] = None,
    _perf_lock=None,
    num_maskmem: Optional[int] = None,
    detector_name: Optional[str] = None,
    _ttfs_t0: Optional[float] = None,
) -> str:
    """Run Grounded-SAM-2 video tracking pipeline.

    Uses multi-GPU data parallelism when multiple GPUs are available.
    Falls back to single-GPU ``process_video`` otherwise.
    """
    import copy
    import shutil
    from contextlib import nullcontext
    from PIL import Image as PILImage

    from utils.video import extract_frames_to_jpeg_dir
    from utils.frame_store import SharedFrameStore, MemoryBudgetExceeded
    from models.segmenters.grounded_sam2 import MaskDictionary, ObjectInfo, LazyFrameObjects

    active_segmenter = segmenter_name or "GSAM2-L"

    def _ttfs(msg):
        if _ttfs_t0 is not None:
            logging.info("[TTFS:%s] +%.1fs %s", job_id, time.perf_counter() - _ttfs_t0, msg)

    _ttfs("enter run_grounded_sam2_tracking")

    logging.info(
        "Grounded-SAM-2 tracking: segmenter=%s, queries=%s, step=%d",
        active_segmenter, queries, step,
    )

    # 1. Load frames — prefer in-memory SharedFrameStore, fall back to JPEG dir
    _use_frame_store = True
    frame_store = None
    _t_ext = time.perf_counter()
    try:
        frame_store = SharedFrameStore(input_video_path, max_frames=max_frames)
        fps, width, height = frame_store.fps, frame_store.width, frame_store.height
        total_frames = len(frame_store)
        frame_names = [f"{i:06d}.jpg" for i in range(total_frames)]

        # Write single dummy JPEG for init_state bootstrapping
        dummy_frame_dir = tempfile.mkdtemp(prefix="gsam2_dummy_")
        cv2.imwrite(os.path.join(dummy_frame_dir, "000000.jpg"), frame_store.get_bgr(0))
        frame_dir = dummy_frame_dir
        logging.info("SharedFrameStore: %d frames in memory (dummy dir: %s)", total_frames, frame_dir)
    except MemoryBudgetExceeded:
        logging.info("Memory budget exceeded, falling back to JPEG extraction")
        _use_frame_store = False
        frame_store = None
        frame_dir = tempfile.mkdtemp(prefix="gsam2_frames_")
        frame_names, fps, width, height = extract_frames_to_jpeg_dir(
            input_video_path, frame_dir, max_frames=max_frames,
        )
        total_frames = len(frame_names)

    try:
        if _perf_metrics is not None:
            _t_e2e = time.perf_counter()
            if torch.cuda.is_available():
                torch.cuda.reset_peak_memory_stats()
            _perf_metrics["frame_extraction_ms"] = (time.perf_counter() - _t_ext) * 1000.0

        _ttfs(f"frame_extraction done ({total_frames} frames, in_memory={_use_frame_store})")
        logging.info("Loaded %d frames (in_memory=%s)", total_frames, _use_frame_store)

        num_gpus = torch.cuda.device_count()

        # ==================================================================
        # Phase 5: Parallel rendering + sequential video writing
        # (Hoisted above tracking so render pipeline starts before tracking
        #  completes — segments are fed incrementally via callback / queue.)
        # ==================================================================
        _check_cancellation(job_id)

        render_in: Queue = Queue(maxsize=32)
        render_out: Queue = Queue(maxsize=128)
        render_done = False
        num_render_workers = min(4, os.cpu_count() or 1)

        def _render_worker():
            while True:
                item = render_in.get()
                if item is None:
                    break
                fidx, fobjs = item
                try:
                    # Deferred GPU->CPU: materialize lazy objects in render thread
                    if isinstance(fobjs, LazyFrameObjects):
                        fobjs = fobjs.materialize()

                    if _perf_metrics is not None:
                        _t_r = time.perf_counter()

                    # Fetch mission verdicts for coloring
                    seg_verdicts = None
                    if job_id:
                        seg_verdicts = get_job_storage().get_mission_verdicts(job_id) or None
                    frm = _gsam2_render_frame(
                        frame_dir, frame_names, fidx, fobjs,
                        height, width,
                        frame_store=frame_store,
                        mission_verdicts=seg_verdicts,
                    )

                    if _perf_metrics is not None:
                        _r_ms = (time.perf_counter() - _t_r) * 1000.0
                        if _perf_lock:
                            with _perf_lock: _perf_metrics["render_total_ms"] += _r_ms
                        else:
                            _perf_metrics["render_total_ms"] += _r_ms

                    payload = (fidx, frm, fobjs)
                    while True:
                        try:
                            render_out.put(payload, timeout=1.0)
                            break
                        except Full:
                            if render_done:
                                return
                except Exception:
                    logging.exception("Render failed for frame %d", fidx)
                    blank = np.zeros((height, width, 3), dtype=np.uint8)
                    try:
                        render_out.put((fidx, blank, {}), timeout=5.0)
                    except Full:
                        pass

        r_workers = [
            Thread(target=_render_worker, daemon=True)
            for _ in range(num_render_workers)
        ]
        for t in r_workers:
            t.start()

        # --- ObjectInfo → detection dict adapter ---
        def _objectinfo_to_dets(frame_objects_dict):
            dets = []
            masks_rle = {}  # {instance_id: rle_dict}
            for obj_id, info in frame_objects_dict.items():
                dets.append({
                    "label": info.class_name,
                    "bbox": [info.x1, info.y1, info.x2, info.y2],
                    "score": 1.0,
                    "track_id": str(obj_id),
                    "instance_id": obj_id,
                })
                # RLE-encode the mask if present
                if info.mask is not None:
                    try:
                        if isinstance(info.mask, torch.Tensor):
                            mask_np = info.mask.cpu().numpy().astype(bool)
                        else:
                            mask_np = np.asarray(info.mask).astype(bool)
                        masks_rle[obj_id] = rle_encode(mask_np)
                    except Exception:
                        logging.debug("Failed to RLE-encode mask for obj %d", obj_id)
            return dets, masks_rle

        # Shared streaming state (publisher ↔ writer)
        _stream_deque: collections.deque = collections.deque()  # unbounded — publisher drains at its own pace
        _stream_lock = RLock()
        _stream_writer_done = Event()

        def _writer_loop():
            nonlocal render_done
            _first_deposit = False
            next_idx = 0
            buf: Dict[int, Tuple] = {}

            # Per-track bbox history (replaces ByteTracker for GSAM2)
            track_history: Dict[int, List] = {}
            speed_est = SpeedEstimator(fps=fps)

            try:
                with StreamingVideoWriter(
                    output_video_path, fps, width, height
                ) as writer:
                    # --- Write + stream (publisher handles pacing) ---
                    while next_idx < total_frames:
                        try:
                            while next_idx not in buf:
                                if len(buf) > 128:
                                    logging.warning(
                                        "Render reorder buffer large (%d), "
                                        "waiting for frame %d",
                                        len(buf), next_idx,
                                    )
                                    time.sleep(0.05)
                                idx, frm, fobjs = render_out.get(timeout=1.0)
                                buf[idx] = (frm, fobjs)

                            frm, fobjs = buf.pop(next_idx)

                            # Build detection records and track history
                            if fobjs:
                                dets, masks_rle = _objectinfo_to_dets(fobjs)

                                # Maintain per-track bbox history (30-frame window)
                                for det in dets:
                                    iid = det["instance_id"]
                                    track_history.setdefault(iid, []).append(det["bbox"])
                                    if len(track_history[iid]) > 30:
                                        track_history[iid].pop(0)
                                    det["history"] = list(track_history[iid])

                                speed_est.estimate(dets)

                                # Store tracks for frontend
                                if job_id:
                                    set_track_data(job_id, next_idx, copy.deepcopy(dets))
                                    store_latest_frame(job_id, frm)
                                    # Store masks
                                    from jobs.storage import set_mask_data as _set_mask
                                    for iid, rle in masks_rle.items():
                                        _set_mask(job_id, next_idx, iid, rle)
                            else:
                                if job_id:
                                    set_track_data(job_id, next_idx, [])

                            # Report progress every 10 frames (and on the last frame)
                            if job_id and (next_idx % 10 == 0 or next_idx == total_frames - 1):
                                get_job_storage().update(job_id, frames_processed=next_idx + 1, total_frames=total_frames)

                            if _perf_metrics is not None:
                                _t_w = time.perf_counter()

                            # Write to video file (always, single copy)
                            writer.write(frm)

                            if _perf_metrics is not None:
                                _perf_metrics["writer_total_ms"] += (time.perf_counter() - _t_w) * 1000.0

                            # --- Deposit frame for stream publisher ---
                            if stream_queue or job_id:
                                with _stream_lock:
                                    _stream_deque.append(frm)
                                if not _first_deposit:
                                    _first_deposit = True
                                    _ttfs("first_frame_deposited_to_deque")

                            next_idx += 1
                            if next_idx % 30 == 0:
                                logging.info(
                                    "Rendered frame %d / %d",
                                    next_idx, total_frames,
                                )
                        except Empty:
                            if job_id:
                                _check_cancellation(job_id)
                            if not any(t.is_alive() for t in r_workers) and render_out.empty():
                                logging.error(
                                    "Render workers stopped while waiting "
                                    "for frame %d", next_idx,
                                )
                                break
                            continue
            finally:
                render_done = True
                _stream_writer_done.set()

        def _stream_publisher_thread():
            """Forward every frame from deque to stream queue. Consumer handles pacing."""
            from jobs.streaming import publish_frame as _pub

            published = 0

            while True:
                frame = None
                with _stream_lock:
                    if _stream_deque:
                        frame = _stream_deque.popleft()

                if frame is not None:
                    if job_id:
                        _pub(job_id, frame)
                    elif stream_queue:
                        stream_queue.put(frame)
                    if published == 0:
                        _ttfs("first_publish_frame")
                    published += 1
                else:
                    # Deque empty — check termination
                    if _stream_writer_done.is_set():
                        with _stream_lock:
                            if not _stream_deque:
                                break
                        continue
                    time.sleep(0.01)  # brief wait for next frame

            logging.info("Stream publisher finished: published %d frames", published)

        writer_thread = Thread(target=_writer_loop, daemon=True)
        writer_thread.start()

        _publisher_thread = None
        if stream_queue or job_id:
            _publisher_thread = Thread(target=_stream_publisher_thread, daemon=True)
            _publisher_thread.start()

        _ttfs("writer+publisher threads started")

        # ==================================================================
        # Phase 1-4: Tracking  (single-GPU fallback vs multi-GPU pipeline)
        # Segments are fed incrementally to render_in as they complete.
        # ==================================================================
        try:
            if num_gpus <= 1:
                # ---------- Single-GPU fallback ----------
                device_str = "cuda:0" if torch.cuda.is_available() else "cpu"
                _seg_kw = {"num_maskmem": num_maskmem} if num_maskmem is not None else {}
                if detector_name is not None:
                    _seg_kw["detector_name"] = detector_name

                if _perf_metrics is not None:
                    _t_load = time.perf_counter()

                segmenter = load_segmenter_on_device(active_segmenter, device_str, **_seg_kw)
                _check_cancellation(job_id)

                if _perf_metrics is not None:
                    _perf_metrics["model_load_ms"] = (time.perf_counter() - _t_load) * 1000.0
                    segmenter._perf_metrics = _perf_metrics
                    segmenter._perf_lock = None

                _ttfs(f"model loaded ({active_segmenter})")

                if _perf_metrics is not None:
                    _t_track = time.perf_counter()

                def _feed_segment(seg_frames):
                    """Fallback for empty/carry-forward segments (already CPU)."""
                    for fidx in sorted(seg_frames.keys()):
                        render_in.put((fidx, seg_frames[fidx]))

                def _feed_segment_gpu(segment_output):
                    """Feed LazyFrameObjects into render_in (GPU->CPU deferred)."""
                    # Deduplicate: frame_indices has one entry per (frame, obj)
                    seen = set()
                    for fi in segment_output.frame_indices:
                        if fi not in seen:
                            seen.add(fi)
                            render_in.put((fi, LazyFrameObjects(segment_output, fi)))

                _ttfs("process_video started")
                tracking_results = segmenter.process_video(
                    frame_dir, frame_names, queries,
                    on_segment=_feed_segment,
                    on_segment_output=_feed_segment_gpu,
                    _ttfs_t0=_ttfs_t0,
                    _ttfs_job_id=job_id,
                    frame_store=frame_store,
                )

                if _perf_metrics is not None:
                    _perf_metrics["tracking_total_ms"] = (time.perf_counter() - _t_track) * 1000.0

                logging.info(
                    "Single-GPU tracking complete: %d frames",
                    len(tracking_results),
                )
            else:
                # ---------- Multi-GPU pipeline ----------
                logging.info(
                    "Multi-GPU GSAM2 tracking: %d GPUs, %d frames, step=%d",
                    num_gpus, total_frames, step,
                )

                # Phase 1: Load one segmenter per GPU (parallel)
                if _perf_metrics is not None:
                    _t_load = time.perf_counter()

                segmenters = []
                with ThreadPoolExecutor(max_workers=num_gpus) as pool:
                    _seg_kw_multi = {"num_maskmem": num_maskmem} if num_maskmem is not None else {}
                    if detector_name is not None:
                        _seg_kw_multi["detector_name"] = detector_name
                    futs = [
                        pool.submit(
                            load_segmenter_on_device,
                            active_segmenter,
                            f"cuda:{i}",
                            **_seg_kw_multi,
                        )
                        for i in range(num_gpus)
                    ]
                    segmenters = [f.result() for f in futs]
                logging.info("Loaded %d segmenters", len(segmenters))

                if _perf_metrics is not None:
                    _perf_metrics["model_load_ms"] = (time.perf_counter() - _t_load) * 1000.0
                    import threading as _th
                    _actual_lock = _perf_lock or _th.Lock()
                    for seg in segmenters:
                        seg._perf_metrics = _perf_metrics
                        seg._perf_lock = _actual_lock

                _ttfs(f"model loaded ({active_segmenter}, {num_gpus} GPUs)")

                # Phase 2: Init SAM2 models/state per GPU (parallel)
                if _perf_metrics is not None:
                    _t_init = time.perf_counter()

                if frame_store is not None:
                    # Models are lazy-loaded; ensure at least one is ready so we
                    # can read image_size.  Phase 1 (load_segmenter_on_device)
                    # only constructs the object — _video_predictor is still None.
                    segmenters[0]._ensure_models_loaded()
                    sam2_img_size = segmenters[0]._video_predictor.image_size

                    # Pre-create the shared adapter (validates memory budget)
                    shared_adapter = frame_store.sam2_adapter(image_size=sam2_img_size)

                    _REQUIRED_KEYS = {"images", "num_frames", "video_height", "video_width", "cached_features"}

                    def _init_seg_state(seg):
                        seg._ensure_models_loaded()
                        state = seg._video_predictor.init_state(
                            video_path=frame_dir,  # dummy dir with 1 JPEG
                            offload_video_to_cpu=True,
                            async_loading_frames=False,  # 1 dummy frame, instant
                        )
                        # Validate expected keys exist before patching
                        missing = _REQUIRED_KEYS - set(state.keys())
                        if missing:
                            raise RuntimeError(f"SAM2 init_state missing expected keys: {missing}")
                        # CRITICAL: Clear cached_features BEFORE patching images
                        # init_state caches dummy frame 0's backbone features — must evict
                        state["cached_features"] = {}
                        # Patch in real frame data
                        state["images"] = shared_adapter
                        state["num_frames"] = total_frames
                        state["video_height"] = height
                        state["video_width"] = width
                        return state
                else:
                    def _init_seg_state(seg):
                        seg._ensure_models_loaded()
                        return seg._video_predictor.init_state(
                            video_path=frame_dir,
                            offload_video_to_cpu=True,
                            async_loading_frames=True,
                        )

                with ThreadPoolExecutor(max_workers=len(segmenters)) as pool:
                    futs = [pool.submit(_init_seg_state, seg) for seg in segmenters]
                    inference_states = [f.result() for f in futs]

                if _perf_metrics is not None:
                    _perf_metrics["init_state_ms"] = (time.perf_counter() - _t_init) * 1000.0
                    _t_track = time.perf_counter()

                _ttfs("multi-GPU tracking started")

                # Phase 3: Parallel segment processing (queue-based workers)
                segments = list(range(0, total_frames, step))
                num_total_segments = len(segments)
                seg_queue_in: Queue = Queue()
                seg_queue_out: Queue = Queue()

                for i, start_idx in enumerate(segments):
                    seg_queue_in.put((i, start_idx))
                for _ in segmenters:
                    seg_queue_in.put(None)  # sentinel

                iou_thresh = segmenters[0].iou_threshold

                def _segment_worker(gpu_idx: int):
                    seg = segmenters[gpu_idx]
                    state = inference_states[gpu_idx]
                    device_type = seg.device.split(":")[0]
                    ac = (
                        torch.autocast(device_type=device_type, dtype=torch.bfloat16)
                        if device_type == "cuda"
                        else nullcontext()
                    )
                    with ac:
                        while True:
                            if job_id:
                                try:
                                    _check_cancellation(job_id)
                                except RuntimeError as e:
                                    if "cancelled" in str(e).lower():
                                        logging.info(
                                            "Segment worker %d cancelled.",
                                            gpu_idx,
                                        )
                                        break
                                    raise
                            item = seg_queue_in.get()
                            if item is None:
                                break
                            seg_idx, start_idx = item
                            try:
                                logging.info(
                                    "GPU %d processing segment %d (frame %d)",
                                    gpu_idx, seg_idx, start_idx,
                                )
                                if frame_store is not None:
                                    image = frame_store.get_pil_rgb(start_idx)
                                else:
                                    img_path = os.path.join(
                                        frame_dir, frame_names[start_idx]
                                    )
                                    with PILImage.open(img_path) as pil_img:
                                        image = pil_img.convert("RGB")

                                if job_id:
                                    _check_cancellation(job_id)
                                masks, boxes, labels = seg.detect_keyframe(
                                    image, queries,
                                )

                                if masks is None:
                                    seg_queue_out.put(
                                        (seg_idx, start_idx, None, {})
                                    )
                                    continue

                                mask_dict = MaskDictionary()
                                mask_dict.add_new_frame_annotation(
                                    mask_list=masks,
                                    box_list=(
                                        boxes.clone()
                                        if torch.is_tensor(boxes)
                                        else torch.tensor(boxes)
                                    ),
                                    label_list=labels,
                                )

                                segment_output = seg.propagate_segment(
                                    state, start_idx, mask_dict, step,
                                )
                                seg_queue_out.put(
                                    (seg_idx, start_idx, mask_dict, segment_output)
                                )
                            except RuntimeError as e:
                                if "cancelled" in str(e).lower():
                                    logging.info(
                                        "Segment worker %d cancelled.",
                                        gpu_idx,
                                    )
                                    break
                                raise
                            except Exception:
                                logging.exception(
                                    "Segment %d failed on GPU %d",
                                    seg_idx, gpu_idx,
                                )
                                seg_queue_out.put(
                                    (seg_idx, start_idx, None, {})
                                )

                seg_workers = []
                for i in range(num_gpus):
                    t = Thread(
                        target=_segment_worker, args=(i,), daemon=True,
                    )
                    t.start()
                    seg_workers.append(t)

                # Phase 4: Streaming reconciliation — process segments in order
                # as they arrive, feeding render_in incrementally.
                _recon_accum_ms = 0.0

                global_id_counter = 0
                sam2_masks = MaskDictionary()
                tracking_results: Dict[int, Dict[int, ObjectInfo]] = {}

                def _mask_to_cpu(mask):
                    """Normalize mask to CPU tensor (still used for keyframe mask_dict)."""
                    if torch.is_tensor(mask):
                        return mask.detach().cpu()
                    return mask

                next_seg_idx = 0
                segment_buffer: Dict[int, Tuple] = {}

                while next_seg_idx < num_total_segments:
                    try:
                        seg_idx, start_idx, mask_dict, segment_output = seg_queue_out.get(timeout=1.0)
                    except Empty:
                        if job_id:
                            _check_cancellation(job_id)
                        # Check if all segment workers are still alive
                        if not any(t.is_alive() for t in seg_workers) and seg_queue_out.empty():
                            logging.error(
                                "All segment workers stopped while waiting for segment %d",
                                next_seg_idx,
                            )
                            break
                        continue
                    segment_buffer[seg_idx] = (start_idx, mask_dict, segment_output)

                    # Process contiguous ready segments in order
                    while next_seg_idx in segment_buffer:
                        start_idx, mask_dict, segment_output = segment_buffer.pop(next_seg_idx)

                        if mask_dict is None or not mask_dict.labels:
                            # No detections — carry forward previous masks
                            for fi in range(
                                start_idx, min(start_idx + step, total_frames)
                            ):
                                if fi not in tracking_results:
                                    tracking_results[fi] = (
                                        {
                                            k: ObjectInfo(
                                                instance_id=v.instance_id,
                                                mask=v.mask,
                                                class_name=v.class_name,
                                                x1=v.x1, y1=v.y1,
                                                x2=v.x2, y2=v.y2,
                                            )
                                            for k, v in sam2_masks.labels.items()
                                        }
                                        if sam2_masks.labels
                                        else {}
                                    )
                                render_in.put((fi, tracking_results.get(fi, {})))
                            if next_seg_idx == 0:
                                _ttfs("first_segment_reconciled (multi-GPU, no detections)")
                            next_seg_idx += 1
                            continue

                        # Normalize keyframe masks to CPU before cross-GPU IoU matching.
                        if _perf_metrics is not None:
                            _t_rc = time.perf_counter()

                        for info in mask_dict.labels.values():
                            info.mask = _mask_to_cpu(info.mask)

                        # IoU match + get local→global remapping
                        global_id_counter, remapping = (
                            mask_dict.update_masks_with_remapping(
                                tracking_dict=sam2_masks,
                                iou_threshold=iou_thresh,
                                objects_count=global_id_counter,
                            )
                        )

                        if not mask_dict.labels:
                            if _perf_metrics is not None:
                                _recon_accum_ms += (time.perf_counter() - _t_rc) * 1000.0
                            for fi in range(
                                start_idx, min(start_idx + step, total_frames)
                            ):
                                tracking_results[fi] = {}
                                render_in.put((fi, {}))
                            if next_seg_idx == 0:
                                _ttfs("first_segment_reconciled (multi-GPU, empty masks)")
                            next_seg_idx += 1
                            continue

                        # Materialize ONLY the last frame for IoU tracking continuity
                        last_fi = segment_output.last_frame_idx()
                        if last_fi is not None:
                            last_objs = segment_output.frame_to_object_dict(
                                last_fi, remapping=remapping, to_cpu=True,
                            )
                            tracking_results[last_fi] = last_objs
                            sam2_masks = MaskDictionary()
                            sam2_masks.labels = copy.deepcopy(last_objs)
                            if last_objs:
                                first_info = next(iter(last_objs.values()))
                                if first_info.mask is not None:
                                    m = first_info.mask
                                    sam2_masks.mask_height = (
                                        m.shape[-2] if m.ndim >= 2 else 0
                                    )
                                    sam2_masks.mask_width = (
                                        m.shape[-1] if m.ndim >= 2 else 0
                                    )

                        if _perf_metrics is not None:
                            _recon_accum_ms += (time.perf_counter() - _t_rc) * 1000.0

                        # Feed LazyFrameObjects to render — GPU->CPU deferred to render workers
                        seen_fi: set = set()
                        for fi in segment_output.frame_indices:
                            if fi not in seen_fi:
                                seen_fi.add(fi)
                                render_in.put((
                                    fi,
                                    LazyFrameObjects(segment_output, fi, remapping),
                                ))

                        if next_seg_idx == 0:
                            _ttfs("first_segment_reconciled (multi-GPU)")
                        next_seg_idx += 1

                for t in seg_workers:
                    t.join()

                if _perf_metrics is not None:
                    _perf_metrics["id_reconciliation_ms"] = _recon_accum_ms
                    _perf_metrics["tracking_total_ms"] = (time.perf_counter() - _t_track) * 1000.0

                logging.info(
                    "Multi-GPU reconciliation complete: %d frames, %d objects",
                    len(tracking_results), global_id_counter,
                )
        finally:
            # Sentinels for render workers — always sent even on error/cancellation
            for _ in r_workers:
                try:
                    render_in.put(None, timeout=5.0)
                except Full:
                    pass

        for t in r_workers:
            t.join()
        writer_thread.join()
        if _publisher_thread is not None:
            _publisher_thread.join(timeout=15)

        if _perf_metrics is not None:
            _perf_metrics["end_to_end_ms"] = (time.perf_counter() - _t_e2e) * 1000.0
            if torch.cuda.is_available():
                _perf_metrics["gpu_peak_mem_mb"] = torch.cuda.max_memory_allocated() / (1024 * 1024)

        logging.info("Grounded-SAM-2 output written to: %s", output_video_path)
        return output_video_path

    finally:
        try:
            shutil.rmtree(frame_dir)
            logging.info("Cleaned up temp frame dir: %s", frame_dir)
        except Exception:
            logging.warning("Failed to clean up temp frame dir: %s", frame_dir)