File size: 74,815 Bytes
851e5ba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
"""Reframing helpers for the video pipeline."""

from typing import Any
from typing import Dict
from typing import List
from typing import Optional
from pathlib import Path
from typing import Tuple
import cv2
import numpy as np
import re
import shutil
import subprocess
import tempfile
from .common import (
    FACE_PRESENCE_MIN_AREA,
    FACE_PRESENCE_RATE,
    FACE_RATE_WINDOW,
    KENBURNS_FOCUS_Y,
    FIT_DETAIL_MARGIN_FRAC,
    FIT_MAX_FOREGROUND_H,
    FIT_MAX_ZOOM_LEVELS,
    FIT_VISIBLE_LEVELS,
    FIT_ZOOM_HOLD_SECONDS,
    KENBURNS_MIN_SECONDS,
    KENBURNS_SUPERSAMPLE_H,
    KENBURNS_SUPERSAMPLE_W,
    KENBURNS_ZOOM_DELTA,
    LAYOUT_SNAP_WINDOW,
    MIN_LAYOUT_SECONDS,
    OUTPUT_FPS,
    UPSCALE_SHARPEN_FILTER,
    VERTICAL_SCALE_CHAIN,
    logger,
)
from .face_detection import open_haar_cascade, open_yunet_detector
from .scene_context import (
    ContextAnalyzer,
    SceneEvidence,
    build_context_layout_plan,
    context_scene_cuts,
)
from .ffmpeg import (
    build_audio_output_args,
    build_final_video_encode_args,
    clamp_even,
    ffmpeg_escape_filter_path,
    ffprobe_duration,
    ffprobe_has_audio,
    ffprobe_video_size,
    round_to_even,
    run_ffmpeg_command,
    subtitles_filter_fragment,
)
from .broll_overlay import (
    broll_input_args,
    broll_overlay_graph,
    normalize_broll_overlays,
)
from .source_limits import (
    FPS_EPSILON,
    MAX_OUTPUT_FPS,
    fit_within_1080p,
    output_rate_token,
    probe_video_geometry,
)


def detect_optimal_crop_region(
    video_path: Path,
    start_time: float,
    end_time: float,
    target_ratio: float = 9 / 16,
) -> Tuple[int, int, int, int]:
    """Detect optimal crop region using improved face detection."""
    try:
        original_width, original_height = ffprobe_video_size(video_path)

        # Calculate target dimensions and ensure they're even
        if original_width / original_height > target_ratio:
            new_width = round_to_even(int(original_height * target_ratio))
            new_height = round_to_even(original_height)
        else:
            new_width = round_to_even(original_width)
            new_height = round_to_even(int(original_width / target_ratio))

        # Try improved face detection
        face_centers = detect_faces_in_clip(video_path, start_time, end_time)

        # Calculate crop position
        if face_centers:
            # Use weighted average of face centers with temporal consistency
            total_weight = sum(
                area * confidence for _, _, area, confidence in face_centers
            )
            if total_weight > 0:
                weighted_x = (
                    sum(
                        x * area * confidence for x, y, area, confidence in face_centers
                    )
                    / total_weight
                )
                weighted_y = (
                    sum(
                        y * area * confidence for x, y, area, confidence in face_centers
                    )
                    / total_weight
                )

                # Add slight bias towards upper portion for better face framing
                weighted_y = max(0, weighted_y - new_height * 0.1)

                x_offset = max(
                    0, min(int(weighted_x - new_width // 2), original_width - new_width)
                )
                y_offset = max(
                    0,
                    min(
                        int(weighted_y - new_height // 2), original_height - new_height
                    ),
                )

                logger.info(
                    f"Face-centered crop: {len(face_centers)} faces detected with improved algorithm"
                )
            else:
                # Center crop
                x_offset = (
                    (original_width - new_width) // 2
                    if original_width > new_width
                    else 0
                )
                y_offset = (
                    (original_height - new_height) // 2
                    if original_height > new_height
                    else 0
                )
        else:
            # Center crop
            x_offset = (
                (original_width - new_width) // 2 if original_width > new_width else 0
            )
            y_offset = (
                (original_height - new_height) // 2
                if original_height > new_height
                else 0
            )
            logger.info("Using center crop (no faces detected)")

        # Ensure offsets are even too
        x_offset = round_to_even(x_offset)
        y_offset = round_to_even(y_offset)

        logger.info(
            f"Crop dimensions: {new_width}x{new_height} at offset ({x_offset}, {y_offset})"
        )
        return (x_offset, y_offset, new_width, new_height)

    except Exception as e:
        logger.error(f"Error in crop detection: {e}")
        # Fallback to center crop
        original_width, original_height = ffprobe_video_size(video_path)
        if original_width / original_height > target_ratio:
            new_width = round_to_even(int(original_height * target_ratio))
            new_height = round_to_even(original_height)
        else:
            new_width = round_to_even(original_width)
            new_height = round_to_even(int(original_width / target_ratio))

        x_offset = (
            round_to_even((original_width - new_width) // 2)
            if original_width > new_width
            else 0
        )
        y_offset = (
            round_to_even((original_height - new_height) // 2)
            if original_height > new_height
            else 0
        )

        return (x_offset, y_offset, new_width, new_height)


def detect_faces_in_clip(
    video_path: Path, start_time: float, end_time: float
) -> List[Tuple[int, int, int, float]]:
    """
    Improved face detection using multiple methods and temporal consistency.
    Returns list of (x, y, area, confidence) tuples.
    """
    face_centers = []

    try:
        # YuNet (most accurate) with Haar as the last-resort fallback
        yunet, haar_cascade = _open_face_detectors()

        # Try to load DNN face detector (more accurate than Haar)
        dnn_net = None
        try:
            # Load OpenCV's DNN face detector
            prototxt_path = cv2.data.haarcascades.replace(
                "haarcascades", "opencv_face_detector.pbtxt"
            )
            model_path = cv2.data.haarcascades.replace(
                "haarcascades", "opencv_face_detector_uint8.pb"
            )

            # If DNN model files don't exist, we'll fall back to Haar cascade
            import os

            if os.path.exists(prototxt_path) and os.path.exists(model_path):
                dnn_net = cv2.dnn.readNetFromTensorflow(model_path, prototxt_path)
                logger.info("OpenCV DNN face detector loaded as backup")
            else:
                logger.info("OpenCV DNN face detector not available")
        except Exception:
            logger.info("OpenCV DNN face detector failed to load")

        # Sample more frames for better face detection (every 0.5 seconds)
        duration = end_time - start_time
        sample_interval = min(0.5, duration / 10)  # At least 10 samples, max every 0.5s
        sample_times = []

        current_time = start_time
        while current_time < end_time:
            sample_times.append(current_time)
            current_time += sample_interval

        # Ensure we always sample the middle and end
        if duration > 1.0:
            middle_time = start_time + duration / 2
            if middle_time not in sample_times:
                sample_times.append(middle_time)

        sample_times = [t for t in sample_times if t < end_time]
        logger.info(f"Sampling {len(sample_times)} frames for face detection")

        capture = cv2.VideoCapture(str(video_path))
        if not capture.isOpened():
            logger.warning("Unable to open video for face detection: %s", video_path)
            return []

        for sample_time in sample_times:
            try:
                capture.set(cv2.CAP_PROP_POS_MSEC, max(0.0, sample_time) * 1000.0)
                ok, frame_bgr = capture.read()
                if not ok or frame_bgr is None:
                    continue
                height, width = frame_bgr.shape[:2]
                detected_faces = []

                # Try YuNet first (most accurate)
                if yunet is not None:
                    try:
                        for fx, fy, fw, fh, confidence in yunet.detect(frame_bgr):
                            x, y, w, h = int(fx), int(fy), int(fw), int(fh)
                            if w > 30 and h > 30:  # Minimum face size
                                detected_faces.append((x, y, w, h, confidence))
                    except Exception as e:
                        logger.warning(
                            f"YuNet detection failed for frame at {sample_time}s: {e}"
                        )

                # If YuNet didn't find faces, try DNN detector
                if not detected_faces and dnn_net is not None:
                    try:
                        blob = cv2.dnn.blobFromImage(
                            frame_bgr, 1.0, (300, 300), [104, 117, 123]
                        )
                        dnn_net.setInput(blob)
                        detections = dnn_net.forward()

                        for i in range(detections.shape[2]):
                            confidence = detections[0, 0, i, 2]
                            if confidence > 0.5:  # Confidence threshold
                                x1 = int(detections[0, 0, i, 3] * width)
                                y1 = int(detections[0, 0, i, 4] * height)
                                x2 = int(detections[0, 0, i, 5] * width)
                                y2 = int(detections[0, 0, i, 6] * height)

                                w = x2 - x1
                                h = y2 - y1

                                if w > 30 and h > 30:  # Minimum face size
                                    detected_faces.append((x1, y1, w, h, confidence))
                    except Exception as e:
                        logger.warning(
                            f"DNN detection failed for frame at {sample_time}s: {e}"
                        )

                # If still no faces found, use Haar cascade
                if not detected_faces:
                    try:
                        gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)

                        faces = haar_cascade.detectMultiScale(
                            gray,
                            scaleFactor=1.05,  # More sensitive
                            minNeighbors=3,  # Less strict
                            minSize=(40, 40),  # Smaller minimum size
                            maxSize=(
                                int(width * 0.7),
                                int(height * 0.7),
                            ),  # Maximum size limit
                        )

                        for x, y, w, h in faces:
                            # Estimate confidence based on face size and position
                            face_area = w * h
                            relative_size = face_area / (width * height)
                            confidence = min(
                                0.9, 0.3 + relative_size * 2
                            )  # Rough confidence estimate
                            detected_faces.append((x, y, w, h, confidence))
                    except Exception as e:
                        logger.warning(
                            f"Haar cascade detection failed for frame at {sample_time}s: {e}"
                        )

                # Process detected faces
                for x, y, w, h, confidence in detected_faces:
                    face_center_x = x + w // 2
                    face_center_y = y + h // 2
                    face_area = w * h

                    # Filter out very small or very large faces
                    frame_area = width * height
                    relative_area = face_area / frame_area

                    if (
                        0.005 < relative_area < 0.3
                    ):  # Face should be 0.5% to 30% of frame
                        face_centers.append(
                            (face_center_x, face_center_y, face_area, confidence)
                        )

            except Exception as e:
                logger.warning(f"Error detecting faces in frame at {sample_time}s: {e}")
                continue

        capture.release()

        # Remove outliers (faces that are very far from the median position)
        if len(face_centers) > 2:
            face_centers = filter_face_outliers(face_centers)

        logger.info(f"Detected {len(face_centers)} reliable face centers")
        return face_centers

    except Exception as e:
        logger.error(f"Error in face detection: {e}")
        return []


def filter_face_outliers(
    face_centers: List[Tuple[int, int, int, float]],
) -> List[Tuple[int, int, int, float]]:
    """Remove face detections that are outliers (likely false positives)."""
    if len(face_centers) < 3:
        return face_centers

    try:
        # Calculate median position
        x_positions = [x for x, y, area, conf in face_centers]
        y_positions = [y for x, y, area, conf in face_centers]

        median_x = np.median(x_positions)
        median_y = np.median(y_positions)

        # Calculate standard deviation
        std_x = np.std(x_positions)
        std_y = np.std(y_positions)

        # Filter out faces that are more than 2 standard deviations away
        filtered_faces = []
        for face in face_centers:
            x, y, area, conf = face
            if abs(x - median_x) <= 2 * std_x and abs(y - median_y) <= 2 * std_y:
                filtered_faces.append(face)

        logger.info(
            f"Filtered {len(face_centers)} -> {len(filtered_faces)} faces (removed outliers)"
        )
        return (
            filtered_faces if filtered_faces else face_centers
        )  # Return original if all filtered

    except Exception as e:
        logger.warning(f"Error filtering face outliers: {e}")
        return face_centers


def count_scene_cuts(video_path: Path, threshold: float = 0.35) -> int:
    """Count likely scene cuts in a clip using ffmpeg's scene score."""
    result = run_ffmpeg_command(
        [
            "ffmpeg",
            "-i",
            str(video_path),
            "-filter:v",
            f"select='gt(scene,{threshold})',showinfo",
            "-f",
            "null",
            "-",
        ],
        timeout=300,
    )
    if result.returncode != 0:
        return 0
    return len(re.findall(r"pts_time:", result.stderr))


def parse_motion_metadata(path: Path) -> Tuple[List[float], List[float]]:
    times: List[float] = []
    values: List[float] = []
    current_time: Optional[float] = None
    for line in path.read_text(errors="ignore").splitlines():
        time_match = re.search(r"pts_time:([0-9.]+)", line)
        if time_match:
            current_time = float(time_match.group(1))
            continue
        value_match = re.search(r"lavfi\.signalstats\.YAVG=([0-9.]+)", line)
        if value_match and current_time is not None:
            times.append(current_time)
            values.append(float(value_match.group(1)))
            current_time = None
    return times, values


def smooth_values(values: List[float], window: int = 15) -> List[float]:
    if not values:
        return []
    smoothed: List[float] = []
    half = window // 2
    for idx in range(len(values)):
        start = max(0, idx - half)
        end = min(len(values), idx + half + 1)
        smoothed.append(sum(values[start:end]) / (end - start))
    return smoothed


def build_speaker_timeline_from_motion(
    times: List[float],
    left_values: List[float],
    right_values: List[float],
    min_duration: float = 1.0,
) -> List[Dict[str, Any]]:
    if not times or len(left_values) != len(right_values):
        return []

    def normalize(values: List[float]) -> List[float]:
        mean_value = sum(values) / max(len(values), 1)
        return [value / mean_value if mean_value > 0 else 0.0 for value in values]

    left = smooth_values(normalize(left_values))
    right = smooth_values(normalize(right_values))
    if not left or not right:
        return []

    margin = 1.15
    current = 0 if left[0] >= right[0] else 1
    speakers: List[int] = []
    for left_value, right_value in zip(left, right):
        if current == 0 and right_value > left_value * margin:
            current = 1
        elif current == 1 and left_value > right_value * margin:
            current = 0
        speakers.append(current)

    segments: List[Dict[str, Any]] = []
    idx = 0
    while idx < len(speakers):
        end_idx = idx
        while end_idx + 1 < len(speakers) and speakers[end_idx + 1] == speakers[idx]:
            end_idx += 1
        seg_start = times[idx]
        seg_end = times[min(end_idx + 1, len(times) - 1)]
        if seg_end <= seg_start:
            seg_end = seg_start + 0.05
        segments.append(
            {
                "start": seg_start,
                "end": seg_end,
                "speaker": "left" if speakers[idx] == 0 else "right",
            }
        )
        idx = end_idx + 1

    merged: List[Dict[str, Any]] = []
    for segment in segments:
        if merged and segment["end"] - segment["start"] < min_duration:
            merged[-1]["end"] = segment["end"]
            continue
        if merged and merged[-1]["speaker"] == segment["speaker"]:
            merged[-1]["end"] = segment["end"]
            continue
        merged.append(segment)
    return merged


def cluster_two_face_regions(
    face_centers: List[Tuple[int, int, int, float]],
    width: int,
    height: int,
) -> Optional[Dict[str, Dict[str, int]]]:
    """Approximate left/right face regions from sampled face centers."""
    if len(face_centers) < 2:
        return None

    median_x = float(np.median([face[0] for face in face_centers]))
    left_faces = [face for face in face_centers if face[0] <= median_x]
    right_faces = [face for face in face_centers if face[0] > median_x]
    if not left_faces or not right_faces:
        return None

    def region(faces: List[Tuple[int, int, int, float]]) -> Dict[str, int]:
        center_x = int(np.median([face[0] for face in faces]))
        center_y = int(np.median([face[1] for face in faces]))
        face_size = int(np.sqrt(max(1, float(np.median([face[2] for face in faces])))))
        roi_w = max(80, int(face_size * 1.4))
        roi_h = max(70, int(face_size * 0.9))
        roi_x = clamp_even(center_x - roi_w // 2, 0, max(0, width - roi_w))
        roi_y = clamp_even(center_y, 0, max(0, height - roi_h))
        tile_w = min(width, max(160, int(face_size * 2.8)))
        tile_h = min(height, max(160, int(face_size * 2.4)))
        tile_x = clamp_even(center_x - tile_w // 2, 0, max(0, width - tile_w))
        tile_y = clamp_even(center_y - int(tile_h * 0.42), 0, max(0, height - tile_h))
        return {
            "center_x": center_x,
            "center_y": center_y,
            "roi_x": roi_x,
            "roi_y": roi_y,
            "roi_w": round_to_even(min(roi_w, width - roi_x)),
            "roi_h": round_to_even(min(roi_h, height - roi_y)),
            "tile_x": tile_x,
            "tile_y": tile_y,
            "tile_w": round_to_even(min(tile_w, width - tile_x)),
            "tile_h": round_to_even(min(tile_h, height - tile_y)),
        }

    left = region(left_faces)
    right = region(right_faces)
    if abs(right["center_x"] - left["center_x"]) < width * 0.15:
        return None
    return {"left": left, "right": right}


def build_pan_expression(
    timeline: List[Dict[str, Any]], left_x: int, right_x: int, ramp: float = 0.45
) -> str:
    """Eased crop-x expression that glides between two speaker framings.

    Instead of snapping the crop instantly at each speaker change, this ramps
    smoothly over ``ramp`` seconds, giving a natural camera-pan feel.
    """
    if not timeline:
        return str(left_x)

    def x_for(speaker: str) -> int:
        return left_x if speaker == "left" else right_x

    keys: List[Tuple[float, float]] = [(0.0, float(x_for(timeline[0]["speaker"])))]
    for segment in timeline:
        switch_t = max(0.0, float(segment["start"]))
        target = float(x_for(segment["speaker"]))
        if abs(target - keys[-1][1]) < 1.0:
            continue
        keys.append((switch_t, keys[-1][1]))  # hold previous framing until switch
        keys.append((switch_t + ramp, target))  # then ease into the new framing

    cleaned: List[Tuple[float, int]] = []
    for t, x in keys:
        if cleaned and t <= cleaned[-1][0]:
            t = cleaned[-1][0] + 0.01
        cleaned.append((t, int(round(x))))

    if len(cleaned) < 2:
        return str(int(cleaned[0][1]) if cleaned else left_x)
    return build_smooth_pan_expression(cleaned)


def detect_speaker_reframe_plan(
    clip_path: Path,
    output_format: str,
) -> Optional[Dict[str, Any]]:
    """Build a speaker-aware pan or split-screen plan for a trimmed clip."""
    try:
        width, height = ffprobe_video_size(clip_path)
        if width / max(height, 1) <= 1.2:
            return None

        scene_cuts = count_scene_cuts(clip_path)
        if scene_cuts > 2:
            logger.info("Skipping speaker reframe: %d scene cuts detected", scene_cuts)
            return None

        duration = ffprobe_duration(clip_path)
        face_centers = detect_faces_in_clip(clip_path, 0, min(duration, 12.0))
        regions = cluster_two_face_regions(face_centers, width, height)
        if not regions:
            return None

        crop_w = round_to_even(min(width, int(height * 9 / 16)))
        left_x = clamp_even(
            regions["left"]["center_x"] - crop_w // 2,
            0,
            max(0, width - crop_w),
        )
        right_x = clamp_even(
            regions["right"]["center_x"] - crop_w // 2,
            0,
            max(0, width - crop_w),
        )

        if output_format == "vertical_split":
            return {
                "mode": "split",
                "width": width,
                "height": height,
                "regions": regions,
            }

        with tempfile.TemporaryDirectory(prefix="supoclip_motion_") as motion_dir:
            left_motion = Path(motion_dir) / "left.txt"
            right_motion = Path(motion_dir) / "right.txt"
            left = regions["left"]
            right = regions["right"]
            filter_complex = (
                f"[0:v]split=2[l][r];"
                f"[l]crop={left['roi_w']}:{left['roi_h']}:{left['roi_x']}:{left['roi_y']},"
                f"format=gray,tblend=all_mode=difference,signalstats,"
                f"metadata=mode=print:key=lavfi.signalstats.YAVG:file={ffmpeg_escape_filter_path(left_motion)}[lo];"
                f"[r]crop={right['roi_w']}:{right['roi_h']}:{right['roi_x']}:{right['roi_y']},"
                f"format=gray,tblend=all_mode=difference,signalstats,"
                f"metadata=mode=print:key=lavfi.signalstats.YAVG:file={ffmpeg_escape_filter_path(right_motion)}[ro]"
            )
            result = run_ffmpeg_command(
                [
                    "ffmpeg",
                    "-y",
                    "-i",
                    str(clip_path),
                    "-filter_complex",
                    filter_complex,
                    "-map",
                    "[lo]",
                    "-f",
                    "null",
                    "-",
                    "-map",
                    "[ro]",
                    "-f",
                    "null",
                    "-",
                ],
                timeout=300,
            )
            if result.returncode != 0:
                return None
            times, left_values = parse_motion_metadata(left_motion)
            _, right_values = parse_motion_metadata(right_motion)
            timeline = build_speaker_timeline_from_motion(
                times,
                left_values,
                right_values,
            )
            if len(timeline) < 2:
                return None

        return {
            "mode": "pan",
            "width": width,
            "height": height,
            "crop_w": crop_w,
            "crop_h": height,
            "x_expression": build_pan_expression(timeline, left_x, right_x),
            "timeline": timeline,
        }
    except Exception as exc:
        logger.warning("Speaker reframe planning failed: %s", exc)
        return None


def compute_vertical_crop_dims(
    width: int, height: int, target_ratio: float = 9 / 16
) -> Tuple[int, int]:
    """Even-dimensioned 9:16 crop box that fits inside a source frame."""
    if width <= 0 or height <= 0:
        return width, height
    if width / height > target_ratio:
        crop_w = round_to_even(int(height * target_ratio))
        crop_h = round_to_even(height)
    else:
        crop_w = round_to_even(width)
        crop_h = round_to_even(int(width / target_ratio))
    return (
        max(2, min(crop_w, round_to_even(width))),
        max(2, min(crop_h, round_to_even(height))),
    )


def _open_face_detectors():
    """Initialise the YuNet (preferred) + Haar (fallback) face detectors.

    Returns (face_detector_or_None, haar). The YuNet wrapper also exposes a
    MediaPipe-style ``process``/``close`` so older call sites keep working.
    """
    return open_yunet_detector(), open_haar_cascade()


def _detect_face_boxes(frame_bgr, face_detector, haar) -> List[Tuple[float, float, float, float]]:
    """All face boxes (x, y, w, h) in a frame, largest first. Frame-pixel coordinates."""
    h, w = frame_bgr.shape[:2]
    frame_area = float(max(1, w * h))
    boxes: List[Tuple[float, float, float, float, float]] = []

    if face_detector is not None:
        try:
            for fx, fy, fw, fh, conf in face_detector.detect(frame_bgr):
                if fw > 10 and fh > 10:
                    boxes.append((float(fw * fh * conf), float(fx), float(fy), float(fw), float(fh)))
        except Exception as exc:
            logger.debug("YuNet detection failed on frame: %s", exc)

    if not boxes:
        try:
            gray = cv2.cvtColor(frame_bgr, cv2.COLOR_BGR2GRAY)
            min_side = max(14, int(w * 0.04))
            for (fx, fy, fw, fh) in haar.detectMultiScale(
                gray,
                scaleFactor=1.2,  # coarser scale steps -> ~2x faster
                minNeighbors=3,
                minSize=(min_side, min_side),
                maxSize=(int(w * 0.7), int(h * 0.7)),
            ):
                boxes.append((float(fw * fh), float(fx), float(fy), float(fw), float(fh)))
        except Exception:
            pass

    boxes.sort(key=lambda item: item[0], reverse=True)
    kept: List[Tuple[float, float, float, float]] = []
    for _, fx, fy, fw, fh in boxes:
        if (fw * fh) / frame_area < FACE_PRESENCE_MIN_AREA:
            continue
        cx, cy = fx + fw / 2, fy + fh / 2
        if any(k[0] <= cx <= k[0] + k[2] and k[1] <= cy <= k[1] + k[3] for k in kept):
            continue
        kept.append((fx, fy, fw, fh))
        if len(kept) >= 6:
            break
    return kept


def _detect_dominant_face(frame_bgr, face_detector, haar) -> Optional[Tuple[float, float]]:
    """Return (center_x_fraction, area_fraction) of the dominant face, or None."""
    h, w = frame_bgr.shape[:2]
    frame_area = float(max(1, w * h))
    boxes = _detect_face_boxes(frame_bgr, face_detector, haar)
    if not boxes:
        return None
    fx, fy, fw, fh = max(boxes, key=lambda box: box[2] * box[3])
    return (fx + fw / 2.0) / w, (fw * fh) / frame_area


def _scene_cuts_from_diffs(diffs: List[Tuple[float, float]]) -> List[float]:
    """Derive scene-cut timestamps from per-frame difference spikes."""
    if len(diffs) < 3:
        return []
    vals = [d for _, d in diffs]
    mean = sum(vals) / len(vals)
    std = (sum((v - mean) ** 2 for v in vals) / len(vals)) ** 0.5
    threshold = max(14.0, mean + 3.5 * std)
    cuts: List[float] = []
    for i, (t, d) in enumerate(diffs):
        if d <= threshold:
            continue
        if (i == 0 or d >= diffs[i - 1][1]) and (
            i == len(diffs) - 1 or d >= diffs[i + 1][1]
        ):
            cuts.append(t)
    return cuts


def analyze_vertical_clip(
    input_path: Path,
    *,
    sample_fps: float = 3.0,
    proc_width: int = 480,
    analyze_context: bool = True,
) -> Tuple[
    List[Tuple[float, Optional[float], float]],
    List[float],
    List[Tuple[float, List[Tuple[float, float, float, float]]]],
    List[SceneEvidence],
]:
    """Fast single-pass clip analysis: face track + scene cuts in one decode.

    Replaces slow per-sample random seeks (and a separate scene-detect pass) with
    a single sequential ffmpeg decode at low fps/resolution, piped straight into
    lightweight face detection. Scene cuts come from frame differences computed
    in the same pass. Returns (track, scene_cuts, face_samples, context) where track
    entries are (t, center_x_in_source_px or None, area_frac) and face_samples
    are (t, [(x, y, w, h), ...]) in source pixels.

    ``analyze_context=False`` skips optical flow, text components, and histograms
    and returns an empty context list. The reaction detail pass only needs the
    finer face boxes, so it uses that mode.
    """
    if not np.isfinite(sample_fps) or sample_fps <= 0 or proc_width < 2:
        raise ValueError("Analysis requires positive sample_fps and proc_width >= 2")
    width, height = ffprobe_video_size(input_path)
    if width <= 0 or height <= 0:
        return [], [], [], []
    proc_w = round_to_even(min(proc_width, width))
    proc_h = round_to_even(max(2, int(round(proc_w * height / width))))
    frame_bytes = proc_w * proc_h * 3

    command = [
        "ffmpeg", "-v", "error", "-an", "-sn",
        "-i", str(input_path),
        "-vf", f"fps={sample_fps:.3f},scale={proc_w}:{proc_h}",
        "-pix_fmt", "bgr24", "-f", "rawvideo",
        "-threads", "0", "-",
    ]
    try:
        proc = subprocess.Popen(
            command, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL
        )
    except Exception as exc:
        logger.warning("analyze_vertical_clip: ffmpeg spawn failed (%s)", exc)
        return [], [], [], []

    face_detector = None
    track: List[Tuple[float, Optional[float], float]] = []
    face_samples: List[Tuple[float, List[Tuple[float, float, float, float]]]] = []
    diffs: List[Tuple[float, float]] = []
    context_analyzer = ContextAnalyzer() if analyze_context else None
    context: List[SceneEvidence] = []
    prev_small = None
    idx = 0
    scale_x = width / proc_w
    scale_y = height / proc_h
    try:
        face_detector, haar = _open_face_detectors()
        while True:
            raw = proc.stdout.read(frame_bytes)
            if not raw:
                break
            if len(raw) < frame_bytes:
                raise RuntimeError("Video analysis decoder returned an incomplete frame")
            frame = np.frombuffer(raw, dtype=np.uint8).reshape(proc_h, proc_w, 3)
            t = idx / sample_fps
            boxes = _detect_face_boxes(frame, face_detector, haar)
            if context_analyzer is not None:
                context.append(context_analyzer.measure(frame, boxes, t))
            if not boxes:
                track.append((t, None, 0.0))
                face_samples.append((t, []))
            else:
                fx, fy, fw, fh = max(boxes, key=lambda box: box[2] * box[3])
                area = (fw * fh) / float(proc_w * proc_h)
                track.append((t, (fx + fw / 2.0) * scale_x, area))
                face_samples.append(
                    (t, [(bx * scale_x, by * scale_y, bw * scale_x, bh * scale_y) for bx, by, bw, bh in boxes])
                )
            small = cv2.resize(frame, (32, 18)).astype(np.int16)
            if prev_small is not None:
                diffs.append((t, float(np.mean(np.abs(small - prev_small)))))
            prev_small = small
            idx += 1
    finally:
        try:
            proc.stdout.close()
        except Exception:
            pass
        proc.wait()
        if face_detector is not None:
            face_detector.close()

    if proc.returncode != 0:
        raise RuntimeError("Video analysis decoder failed; partial analysis discarded")
    cuts = sorted(set(_scene_cuts_from_diffs(diffs)) | set(context_scene_cuts(context)))
    return track, cuts, face_samples, context


def _median_filter(values: List[float], window: int = 3) -> List[float]:
    """Small median filter to remove single-frame detection spikes."""
    if window <= 1 or len(values) < window:
        return list(values)
    half = window // 2
    out: List[float] = []
    for i in range(len(values)):
        lo = max(0, i - half)
        hi = min(len(values), i + half + 1)
        seg = sorted(values[lo:hi])
        out.append(seg[len(seg) // 2])
    return out


def build_crop_trajectory(
    track: List[Tuple[float, Optional[float], float]],
    width: int,
    crop_w: int,
    *,
    deadzone_frac: float = 0.05,
    smooth_time: float = 0.9,
    max_pan_speed_frac: float = 0.4,
) -> List[Tuple[float, int]]:
    """Turn a raw face-centre track into a smooth, eased crop-x trajectory.

    Returns keyframes [(t, x)] for the crop's left edge. The motion is produced
    by a critically-damped spring (Unity-style SmoothDamp) easing toward a
    comfort-zone target, which gives natural ease-in/ease-out with no overshoot
    and no mechanical ramp-then-stop feel. A deadzone keeps the frame still for
    small head movements; a median pre-filter removes detection spikes. Returns
    [] when there isn't enough signal to track.
    """
    if not track:
        return []
    max_x = max(0, width - crop_w)
    if max_x <= 0:
        return []

    centers: List[Optional[float]] = [c for _, c, _ in track]
    times = [t for t, _, _ in track]
    detected = sum(1 for c in centers if c is not None)
    if detected < max(3, len(centers) // 5):
        return []  # too sparse to trust — caller falls back to a static crop

    # Gap-fill missing detections: forward fill, then back fill.
    last: Optional[float] = None
    for i in range(len(centers)):
        if centers[i] is None:
            centers[i] = last
        else:
            last = centers[i]
    last = None
    for i in range(len(centers) - 1, -1, -1):
        if centers[i] is None:
            centers[i] = last
        else:
            last = centers[i]
    if any(c is None for c in centers):
        return []

    desired = [min(max(c - crop_w / 2.0, 0.0), float(max_x)) for c in centers]
    desired = _median_filter(desired, window=3)

    deadzone = max(2.0, crop_w * deadzone_frac)
    max_speed = max(1.0, width * max_pan_speed_frac)
    smooth_time = max(0.05, smooth_time)
    omega = 2.0 / smooth_time

    # Comfort-zone target: a stable goal that only moves once the subject drifts
    # past the deadzone, so the spring isn't chasing sub-deadzone jitter.
    targets: List[float] = []
    anchor = desired[0]
    for d in desired:
        if d - anchor > deadzone:
            anchor = d - deadzone
        elif anchor - d > deadzone:
            anchor = d + deadzone
        targets.append(anchor)

    # Critically-damped spring toward the comfort-zone target.
    eased: List[float] = []
    cur = float(targets[0])
    vel = 0.0
    for i, tgt in enumerate(targets):
        dt = (times[i] - times[i - 1]) if i > 0 else 0.0
        if dt <= 0:
            eased.append(cur)
            continue
        x = omega * dt
        exp_factor = 1.0 / (1.0 + x + 0.48 * x * x + 0.235 * x * x * x)
        change = cur - tgt
        max_change = max_speed * smooth_time
        change = max(-max_change, min(change, max_change))
        adj_target = cur - change
        temp = (vel + omega * change) * dt
        vel = (vel - omega * temp) * exp_factor
        out = adj_target + (change + temp) * exp_factor
        # Prevent overshoot past the target.
        if (tgt - cur > 0) == (out > tgt):
            out = tgt
            vel = (out - tgt) / dt
        cur = min(max(out, 0.0), float(max_x))
        eased.append(cur)

    # Final low-pass pass: removes residual velocity steps so the piecewise-
    # linear keyframes read as continuous, fluid motion.
    eased = smooth_values(eased, window=5)

    # Keep keyframes fine enough that linear interpolation tracks the smooth
    # curve without visible faceting.
    def simplify(tol: float) -> List[Tuple[float, int]]:
        keys: List[Tuple[float, int]] = [(0.0, int(round(eased[0])))]
        for i in range(1, len(eased)):
            if abs(eased[i] - keys[-1][1]) >= tol:
                keys.append((times[i], int(round(eased[i]))))
        if keys[-1][0] < times[-1]:
            keys.append((times[-1], int(round(eased[-1]))))
        return keys

    tol = max(1.5, crop_w * 0.006)
    keys = simplify(tol)
    while len(keys) > 90:
        tol *= 1.5
        keys = simplify(tol)

    if keys and keys[0][0] > 0.0:
        keys[0] = (0.0, keys[0][1])
    return keys


def trajectory_has_movement(keys: List[Tuple[float, int]], crop_w: int) -> bool:
    """Whether a trajectory pans enough to be worth a moving crop."""
    if len(keys) < 2:
        return False
    xs = [x for _, x in keys]
    return (max(xs) - min(xs)) >= max(8, crop_w * 0.04)


def build_smooth_pan_expression(keys: List[Tuple[float, int]]) -> str:
    """Piecewise-linear ffmpeg crop-x expression interpolating the keyframes.

    Commas are escaped for use inside a quoted filtergraph expression. The
    result is rounded to an even integer for clean chroma subsampling.
    """
    if not keys:
        return "0"
    if len(keys) == 1:
        return str(int(keys[0][1]))

    expr = str(int(keys[-1][1]))
    for i in range(len(keys) - 2, -1, -1):
        t0, x0 = keys[i]
        t1, x1 = keys[i + 1]
        span = max(1e-3, t1 - t0)
        lerp = f"({int(x0)}+({int(x1) - int(x0)})*(t-{t0:.3f})/{span:.3f})"
        expr = f"if(lt(t\\,{t1:.3f})\\,{lerp}\\,{expr})"
    return f"trunc(({expr})/2)*2"


def build_layout_plan(
    track: List[Tuple[float, Optional[float], float]],
    scene_cuts: List[float],
    duration: float,
) -> List[Dict[str, Any]]:
    """Classify a clip into 'face' (tracked crop) and 'fit' (full-frame) shots.

    Talking-head shots become a tracked crop; content shots (tweets, graphs,
    code — no real face) become a full-frame blurred-background fit so nothing
    is cropped off. Boundaries are debounced and snapped to scene cuts.
    """
    if duration <= 0 or not track:
        return [{"start": 0.0, "end": max(0.0, duration), "kind": "fit"}]

    times = [t for t, _, _ in track]
    present = [
        1 if (c is not None and a >= FACE_PRESENCE_MIN_AREA) else 0
        for _, c, a in track
    ]

    # Classify by face-presence RATE over a window: a real talking shot has a
    # face in many frames (even if small/spotty); a content shot has ~none.
    diffs = [times[i] - times[i - 1] for i in range(1, len(times))]
    dt = sorted(diffs)[len(diffs) // 2] if diffs else 0.25
    half = max(1, int(round(FACE_RATE_WINDOW / 2.0 / max(dt, 0.05))))
    smoothed: List[int] = []
    for i in range(len(present)):
        seg = present[max(0, i - half) : min(len(present), i + half + 1)]
        rate = sum(seg) / len(seg)
        smoothed.append(1 if rate >= FACE_PRESENCE_RATE else 0)

    # Build runs of constant layout value.
    runs: List[List[float]] = []
    run_start, run_val = 0.0, smoothed[0]
    for i in range(1, len(times)):
        if smoothed[i] != run_val:
            runs.append([run_start, times[i], run_val])
            run_start, run_val = times[i], smoothed[i]
    runs.append([run_start, duration, run_val])

    def coalesce(rs: List[List[float]]) -> List[List[float]]:
        out = [rs[0][:]]
        for r in rs[1:]:
            if r[2] == out[-1][2]:
                out[-1][1] = r[1]
            else:
                out.append(r[:])
        return out

    # Merge any run shorter than the minimum layout duration (flip + coalesce).
    runs = coalesce(runs)
    changed = True
    while changed and len(runs) > 1:
        changed = False
        for r in runs:
            if r[1] - r[0] < MIN_LAYOUT_SECONDS:
                r[2] = 1 - r[2]
                changed = True
                break
        if changed:
            runs = coalesce(runs)

    # Snap internal boundaries to nearby scene cuts for clean switches.
    cuts = sorted(c for c in (scene_cuts or []) if 0.05 < c < duration - 0.05)
    for i in range(len(runs) - 1):
        boundary = runs[i][1]
        near = [c for c in cuts if abs(c - boundary) <= LAYOUT_SNAP_WINDOW]
        if not near:
            continue
        snapped = min(near, key=lambda c: abs(c - boundary))
        if runs[i][0] + 0.1 < snapped < runs[i + 1][1] - 0.1:
            runs[i][1] = snapped
            runs[i + 1][0] = snapped

    return [
        {"start": r[0], "end": r[1], "kind": "face" if r[2] == 1 else "fit"}
        for r in runs
    ]


def build_scene_crop_expression(
    track: List[Tuple[float, Optional[float], float]],
    scene_cuts: List[float],
    duration: float,
    width: int,
    crop_w: int,
) -> str:
    """Track each camera shot independently, with a hard reset at every cut."""
    boundaries = [0.0, *sorted({c for c in scene_cuts if 0 < c < duration}), duration]
    shots = []
    for start, end in zip(boundaries, boundaries[1:]):
        shot_track = [(t, x, area) for t, x, area in track if start <= t < end]
        keys = build_crop_trajectory(shot_track, width, crop_w)
        if keys:
            # Hold the first/last detected positions to the shot boundaries;
            # never extrapolate an initial movement backwards over a cut.
            keys = [(start, keys[0][1]), *[(t, x) for t, x in keys if start < t < end], (end, keys[-1][1])]
            expression = build_smooth_pan_expression(keys)
        else:
            centers = [x for _, x, _ in shot_track if x is not None]
            center = float(np.median(centers)) if centers else width / 2
            expression = str(clamp_even(int(center - crop_w / 2), 0, width - crop_w))
        shots.append((end, expression))
    result = shots[-1][1]
    for end, expression in reversed(shots[:-1]):
        result = f"if(lt(t\\,{end:.3f})\\,{expression}\\,{result})"
    return result


def kenburns_zoom_fragment(duration: float) -> Optional[str]:
    """Slow linear punch-in fragment producing a 1080x1920 [setsar-ed] stream.

    Zooms through a 1.5x supersampled frame so zoompan's integer crop offsets
    stay sub-pixel in the output (no visible stepping). The frame rate is
    normalised to OUTPUT_FPS *before* zoompan and re-declared on it, because
    zoompan re-times its output at its own fps — matching the two keeps the
    video duration identical and the audio in sync.
    """
    if duration < KENBURNS_MIN_SECONDS:
        return None
    z_expr = (
        f"if(isnan(it)\\,1\\,1+{KENBURNS_ZOOM_DELTA}*min(it/{duration:.3f}\\,1))"
    )
    return (
        f"scale={KENBURNS_SUPERSAMPLE_W}:{KENBURNS_SUPERSAMPLE_H}:flags=lanczos,"
        f"fps={OUTPUT_FPS},"
        f"zoompan=z='{z_expr}':x='(iw-iw/zoom)/2':y='(ih-ih/zoom)*{KENBURNS_FOCUS_Y}'"
        f":d=1:s=1080x1920:fps={OUTPUT_FPS},{UPSCALE_SHARPEN_FILTER},setsar=1"
    )


FIT_CHAIN = (
    "scale=1080:1920:force_original_aspect_ratio=decrease:flags=lanczos,"
    "scale=trunc(iw/2)*2:trunc(ih/2)*2,setsar=1"
)


FitWindow = Tuple[float, float, Optional[int], int]


def plan_fit_windows(
    plan: List[Dict[str, Any]],
    samples: List[SceneEvidence],
    width: int,
    height: int,
) -> List[FitWindow]:
    """Readable crops for the fitted (full-frame) shots of a layout plan.

    Returns [(start, end, crop_w, x)], with crop_w None where the whole frame
    stays visible, or [] when nothing zooms. Each window contains all detail
    measured during it (for text cut by a face crop: the faces and the text
    lines), so text is never pushed off the edge. Zoom sizes come from
    FIT_VISIBLE_LEVELS. A zoom shorter than FIT_ZOOM_HOLD_SECONDS joins a
    neighbour that already shows its detail, otherwise it shows the full frame;
    a fitted shot with no fitted neighbour keeps its zoom.
    """
    if width <= 0 or height <= 0:
        return []
    min_visible = height * 1080 / FIT_MAX_FOREGROUND_H / width
    levels = [level for level in FIT_VISIBLE_LEVELS if level >= min_visible]

    def needed(left: float, right: float) -> float:
        return next((level for level in levels if right - left <= level), 1.0)

    runs: List[Dict[str, Any]] = []

    def add(start: float, end: float, left: float, right: float) -> None:
        if end <= start:
            return
        if right <= left:
            left = right = (left + right) / 2
        left = max(0.0, left - FIT_DETAIL_MARGIN_FRAC)
        right = min(1.0, right + FIT_DETAIL_MARGIN_FRAC)
        if runs and runs[-1]["end"] == start:
            run = runs[-1]
            union = (min(run["left"], left), max(run["right"], right))
            if needed(left, right) == run["level"] and needed(*union) == run["level"]:
                run.update(end=end, left=union[0], right=union[1])
                return
        runs.append({"start": start, "end": end, "left": left, "right": right,
                     "level": needed(left, right), "settled": False})

    for shot in plan:
        if shot["kind"] != "fit":
            continue
        cut_text = shot.get("reason") == "text_cut_by_crop"
        inside = [s for s in samples if shot["start"] <= s.time < shot["end"]]
        if not inside:
            add(shot["start"], shot["end"], 0.0, 1.0)
            continue
        for index, sample in enumerate(inside):
            start = shot["start"] if index == 0 else sample.time
            end = inside[index + 1].time if index + 1 < len(inside) else shot["end"]
            if cut_text:
                add(start, end, sample.protect_left, sample.protect_right)
            else:
                add(start, end, sample.detail_left, sample.detail_right)

    def touching(a: Dict[str, Any], b: Dict[str, Any]) -> bool:
        return abs(a["end"] - b["start"]) < 1e-6 or abs(b["end"] - a["start"]) < 1e-6

    while True:
        short = [r for r in runs if not r["settled"] and r["end"] - r["start"] < FIT_ZOOM_HOLD_SECONDS]
        if not short:
            break
        run = min(short, key=lambda r: r["end"] - r["start"])
        index = runs.index(run)
        neighbours = [
            runs[j] for j in (index - 1, index + 1)
            if 0 <= j < len(runs) and touching(runs[j], run)
        ]
        neighbours.sort(key=lambda r: r["end"] - r["start"], reverse=True)
        host = next((
            n for n in neighbours
            if max(n["right"], run["right"]) - min(n["left"], run["left"]) <= n["level"]
        ), None)
        if not neighbours:
            # A whole fitted shot between crops (or the whole clip) changes
            # layout at its edges anyway, so its zoom causes no extra jump.
            run["settled"] = True
        elif host is not None:
            host.update(
                start=min(host["start"], run["start"]), end=max(host["end"], run["end"]),
                left=min(host["left"], run["left"]), right=max(host["right"], run["right"]),
            )
            runs.remove(run)
        elif run["level"] < 1.0:
            run["level"] = 1.0
        else:
            run["settled"] = True

    # Each size is its own filter branch, so cap how many a clip may use.
    while len({r["level"] for r in runs}) > FIT_MAX_ZOOM_LEVELS:
        smallest, next_size = sorted({r["level"] for r in runs})[:2]
        for run in runs:
            if run["level"] == smallest:
                run["level"] = next_size

    if all(r["level"] >= 1.0 for r in runs):
        return []
    merged: List[Dict[str, Any]] = []
    for run in runs:
        last = merged[-1] if merged else None
        if (
            last is not None and touching(last, run) and last["level"] == run["level"]
            and max(last["right"], run["right"]) - min(last["left"], run["left"]) <= run["level"]
        ):
            last.update(end=run["end"], left=min(last["left"], run["left"]),
                        right=max(last["right"], run["right"]))
        else:
            merged.append(dict(run))
    windows: List[FitWindow] = []
    for run in merged:
        if run["level"] >= 1.0:
            windows.append((run["start"], run["end"], None, 0))
            continue
        crop_w = round_to_even(int(width * run["level"]))
        centre = (run["left"] + run["right"]) / 2 * width
        x = clamp_even(int(centre - crop_w / 2), 0, width - crop_w)
        windows.append((run["start"], run["end"], crop_w, x))
    return windows


def build_fit_layers(
    fit_intervals: List[Tuple[float, float]],
    windows: Optional[List[FitWindow]] = None,
) -> List[Tuple[str, List[Tuple[float, float]]]]:
    """Fitted foreground layers as (filter chain, intervals), one per crop size."""
    if not windows:
        return [(FIT_CHAIN, fit_intervals)]
    layers = []
    for crop_w in sorted({w for _, _, w, _ in windows}, key=lambda w: w or 0):
        mine = [window for window in windows if window[2] == crop_w]
        intervals = [(start, end) for start, end, _, _ in mine]
        if crop_w is None:
            layers.append((FIT_CHAIN, intervals))
            continue
        x_expr = str(mine[-1][3])
        for _, end, _, x in reversed(mine[:-1]):
            x_expr = f"if(lt(t\\,{end:.3f})\\,{x}\\,{x_expr})"
        sharpen = f"{UPSCALE_SHARPEN_FILTER}," if crop_w < 1080 else ""
        layers.append((
            f"crop={crop_w}:ih:x='{x_expr}':y=0,scale=1080:-2:flags=lanczos,{sharpen}setsar=1",
            intervals,
        ))
    return layers


def _enable_expr(intervals: List[Tuple[float, float]]) -> str:
    if not intervals:
        return "0"
    return "+".join(f"between(t\\,{a:.3f}\\,{b:.3f})" for a, b in intervals)


def _fit_overlays(base: str, layers: List[Tuple[str, List[Tuple[float, float]]]], gated: bool) -> str:
    """Chain [ft0].. into [fit0].. and overlay them on ``base`` into [vout]."""
    parts = [f"[ft{i}]{chain}[fit{i}]" for i, (chain, _) in enumerate(layers)]
    current = base
    for i, (_, intervals) in enumerate(layers):
        out = "[vout]" if i == len(layers) - 1 else f"[f{i}]"
        enable = f":enable='{_enable_expr(intervals)}'" if gated else ""
        parts.append(f"{current}[fit{i}]overlay=(W-w)/2:(H-h)/2{enable}{out}")
        current = out
    return ";".join(parts)


def build_full_frame_filter(
    blur_sigma: int = 14, fit_windows: Optional[List[FitWindow]] = None
) -> str:
    """Preserve the complete source on a vertical canvas, without a crop branch.

    ``fit_windows`` (see ``plan_fit_windows``) enlarges content whose detail
    leaves empty margins; without them the whole frame is letterboxed.
    """
    background = (
        "[bgsrc]scale=540:960:force_original_aspect_ratio=increase,crop=540:960,"
        f"gblur=sigma={blur_sigma}:steps=2,scale=1080:1920:flags=bilinear,setsar=1[bg];"
    )
    if not fit_windows:
        return (
            "[0:v]split=2[bgsrc][ftsrc];"
            f"{background}"
            f"[ftsrc]{FIT_CHAIN}[fit];"
            "[bg][fit]overlay=(W-w)/2:(H-h)/2[vout]"
        )
    # Nothing but the fit is shown here, so the last window stays on to the
    # final frame even if the stream runs past the probed duration.
    last = max(range(len(fit_windows)), key=lambda i: fit_windows[i][1])
    fit_windows = [
        (start, max(end, 1e6) if i == last else end, crop_w, x)
        for i, (start, end, crop_w, x) in enumerate(fit_windows)
    ]
    layers = build_fit_layers([(0.0, fit_windows[last][1])], fit_windows)
    sources = "".join(f"[ft{i}]" for i in range(len(layers)))
    return (
        f"[0:v]split={1 + len(layers)}[bgsrc]{sources};"
        f"{background}"
        + _fit_overlays("[bg]", layers, gated=len(layers) > 1)
    )


def build_vertical_compositor_filter(
    crop_chain: str,
    face_intervals: List[Tuple[float, float]],
    fit_intervals: List[Tuple[float, float]],
    blur_sigma: int = 14,
    fit_windows: Optional[List[FitWindow]] = None,
) -> str:
    """filter_complex switching between a tracked face crop and a blurred-
    background full-frame fit over time. Produces a labelled [vout] stream.

    Layers: a blurred fill background (always), the face crop on top during face
    shots (covers the frame), and the centred full-frame fit during content
    shots (background shows around it). ``fit_windows`` splits the fit into
    readable zoomed crops (see ``plan_fit_windows``).
    """
    face_en = _enable_expr(face_intervals)
    # Smooth Gaussian background: blur at half resolution (plenty of detail for a
    # heavy blur) with multiple passes for a true Gaussian falloff, then upscale
    # 2x with bilinear so there's no lanczos ringing/blockiness — a creamy blur.
    head = (
        "[bgsrc]scale=540:960:force_original_aspect_ratio=increase,crop=540:960,"
        f"gblur=sigma={blur_sigma}:steps=2,scale=1080:1920:flags=bilinear,setsar=1[bg];"
        f"[crsrc]{crop_chain}[face];"
    )
    if not fit_windows:
        fit_en = _enable_expr(fit_intervals)
        return (
            "[0:v]split=3[bgsrc][crsrc][ftsrc];"
            f"{head}"
            f"[ftsrc]{FIT_CHAIN}[fit];"
            f"[bg][face]overlay=0:0:enable='{face_en}'[t1];"
            f"[t1][fit]overlay=(W-w)/2:(H-h)/2:enable='{fit_en}'[vout]"
        )
    layers = build_fit_layers(fit_intervals, fit_windows)
    sources = "".join(f"[ft{i}]" for i in range(len(layers)))
    return (
        f"[0:v]split={2 + len(layers)}[bgsrc][crsrc]{sources};"
        f"{head}"
        f"[bg][face]overlay=0:0:enable='{face_en}'[t1];"
        + _fit_overlays("[t1]", layers, gated=True)
    )


def _described(
    kind: str, video_filter: str, mode: str, caption_y: Optional[float]
) -> Dict[str, Any]:
    return {
        "kind": kind,
        "video_filter": video_filter,
        "mode": mode,
        "caption_y": caption_y,
    }


def build_vertical_filter_plan(
    input_path: Path,
    width: int,
    height: int,
    speaker_turns: Optional[List[Dict[str, Any]]] = None,
    speaker_words: Optional[List[Dict[str, Any]]] = None,
) -> Tuple[str, str, Optional[float]]:
    """Build the 9:16 reframing filter for the default vertical mode.

    Returns (filter, mode, caption_y). mode 'vf' is a simple crop chain; mode
    'complex' is a filter_complex producing [vout]. caption_y is a 0-1 output
    fraction that keeps captions off the detected face, or None to keep the
    template default.
    """
    described = describe_vertical_layout(
        input_path, width, height, speaker_turns, speaker_words
    )
    return described["video_filter"], described["mode"], described["caption_y"]


def describe_vertical_layout(
    input_path: Path,
    width: int,
    height: int,
    speaker_turns: Optional[List[Dict[str, Any]]] = None,
    speaker_words: Optional[List[Dict[str, Any]]] = None,
) -> Dict[str, Any]:
    """Same plan as ``build_vertical_filter_plan``, plus a layout ``kind``.

    Kinds the editor keeps whole are ``reaction`` (reactor above the source),
    ``stack`` (side-by-side call tiles) and ``overlap`` (two speakers at once).
    ``crop``, ``speaker``, ``stage``, ``fit`` and ``compositor`` stay on the
    editor's vertical or original crop.

    All-face clips use a face-aware layout when the subject would otherwise
    sit low in a full-height crop (stacked call tiles, a wider stage for one
    webcam, or the whole gallery). Well-framed closeups keep the tracked crop.
    Clips containing content shots use the scene-aware compositor so tweets /
    graphs / slides are shown in full. With diarized speaker turns, multi-person
    wide shots that are not a video-call grid cut to whoever is talking.
    """
    from .talking_head_layout import (
        caption_y_below_subject,
        choose_talking_head_layout,
        dominant_face_bottom,
    )

    crop_w, crop_h = compute_vertical_crop_dims(width, height)
    duration = ffprobe_duration(input_path)

    def bleed_caption(samples) -> Optional[float]:
        bottom = dominant_face_bottom(samples, height)
        if bottom is None:
            return None
        adjusted = caption_y_below_subject(bottom)
        return adjusted if adjusted > 0.805 else None

    # Narrow/portrait source: no horizontal room to crop — static fit, with a
    # slow punch-in so the frame still breathes.
    if crop_w >= width:
        sx, sy, sw, sh = detect_optimal_crop_region(input_path, 0, min(duration, 12.0))
        tail = kenburns_zoom_fragment(duration) or VERTICAL_SCALE_CHAIN
        return _described("crop", f"crop={sw}:{sh}:{sx}:{sy},{tail}", "vf", None)

    # One fast decode pass yields the face track, face boxes, and scene cuts.
    try:
        analyzed = analyze_vertical_clip(input_path)
    except Exception as exc:
        logger.warning("Clip analysis failed (%s); preserving full frame", exc)
        analyzed = ([], [], [])
    track, scene_cuts = analyzed[0], analyzed[1]
    face_samples = analyzed[2] if len(analyzed) > 2 else []
    context = analyzed[3] if len(analyzed) > 3 else []
    plan = (
        build_context_layout_plan(context, scene_cuts, duration, crop_w / width)
        if context else build_layout_plan(track, scene_cuts, duration)
    )
    logger.info("Vertical scene layout: %s", plan)
    try:
        fit_windows = plan_fit_windows(plan, context, width, height) if context else []
    except Exception as exc:
        logger.warning("Readable fit planning failed (%s); keeping the plain fit", exc)
        fit_windows = []
    if fit_windows:
        logger.info("Readable fit windows (start, end, crop_w, x): %s", fit_windows)
    fit_intervals = [(s["start"], s["end"]) for s in plan if s["kind"] == "fit"]
    # Two people who cannot share a 9:16 crop are not slide or sports content.
    # Call/stage layouts and speaker framing still apply; if both decline, that
    # shot keeps the full frame instead of a dominant-face crop.
    content_fits = [
        shot for shot in plan
        if shot["kind"] == "fit" and shot.get("reason") != "interaction_exceeds_crop"
    ]

    # A persistent reaction inset is independent of fit intervals, camera cuts,
    # and speaker labels. Separate it before dominant-face tracking can confuse
    # the inset with the source, or a full-frame fallback discards it.
    from .reaction_layout import choose_reaction_layout, find_reactor_face

    if find_reactor_face(width, height, face_samples):
        # Tiny faces in the source wide shot need more detail than the normal
        # 480px tracking pass. Keep its detections too: a profile/occluded face
        # can be visible to only one of the two scales. The pass only reads
        # face boxes, so skip optical flow, text, and histograms.
        try:
            detailed = analyze_vertical_clip(
                input_path, proc_width=960, analyze_context=False
            )[2]
            combined = []
            for (t, coarse), (_, fine) in zip(face_samples, detailed):
                boxes = []
                for box in sorted(list(coarse) + list(fine), key=lambda f: f[2]*f[3], reverse=True):
                    cx, cy = box[0]+box[2]/2, box[1]+box[3]/2
                    if not any(x <= cx <= x+w and y <= cy <= y+h for x, y, w, h in boxes):
                        boxes.append(box)
                combined.append((t, boxes))
            if len(combined) == len(face_samples):
                face_samples = combined
        except Exception as exc:
            logger.debug("Reaction detail analysis unavailable: %s", exc)
    reaction = choose_reaction_layout(
        input_path, width, height, duration, face_samples, scene_cuts
    )
    if reaction:
        logger.info("Reaction layout: inset %s, %d source sections", reaction['inset'], len(reaction['source_runs']))
        return _described("reaction", reaction["video_filter"], "complex", reaction["caption_y"])

    if all(s["kind"] == "fit" for s in plan) and content_fits:
        return _described("fit", build_full_frame_filter(fit_windows=fit_windows), "complex", 0.80)

    # choose_talking_head_layout already refuses cut-heavy clips (more than
    # four cuts). One jump cut must not drop stage, stack, or gallery layouts.
    talking = (
        choose_talking_head_layout(width, height, face_samples, scene_cuts)
        if not content_fits else None
    )
    if not content_fits and speaker_words and (not talking or talking["kind"] == "stack"):
        # Diarized speakers: cut to whoever is talking on multi-person wide
        # shots, including a pair that does not fit in one 9:16 crop. Slides
        # and other content shots keep the compositor below.
        from .speaker_framing import build_speaker_filter_plan

        try:
            speaker_plan = build_speaker_filter_plan(
                input_path, width, height, crop_w, crop_h, duration,
                speaker_turns or [], speaker_words,
            )
        except Exception as exc:
            logger.warning("Speaker framing failed (%s); tracking dominant face", exc)
            speaker_plan = None
        if speaker_plan:
            speaker_filter, speaker_mode = speaker_plan
            if not talking or speaker_mode == "complex":
                # Overlap gets full-bleed panels even if the wide shot looks
                # like a call. Put captions between the two faces.
                caption_y = 0.5 if speaker_mode == "complex" else bleed_caption(face_samples)
                kind = "overlap" if speaker_mode == "complex" else "speaker"
                return _described(kind, speaker_filter, speaker_mode, caption_y)
    if talking:
        logger.info(
            "Face-aware vertical layout: %s (upscale %.2fx, caption_y %.2f)",
            talking["kind"], talking["upscale"], talking["caption_y"],
        )
        return _described(
            talking["kind"], talking["video_filter"], "complex", talking["caption_y"]
        )
    if all(s["kind"] == "fit" for s in plan):
        return _described("fit", build_full_frame_filter(fit_windows=fit_windows), "complex", 0.80)

    keys = build_crop_trajectory(track, width, crop_w) if track else []
    # A cut by itself is not camera motion. Ken Burns stays available unless
    # the face trajectory actually pans. Real pans still reset at each cut.
    moving = bool(keys and trajectory_has_movement(keys, crop_w))
    static_x = 0
    if moving:
        x_expr = (
            build_scene_crop_expression(track, scene_cuts, duration, width, crop_w)
            if scene_cuts else build_smooth_pan_expression(keys)
        )
        crop_chain = f"crop={crop_w}:{crop_h}:x='{x_expr}':y=0,{VERTICAL_SCALE_CHAIN}"
    else:
        if keys:
            static_x = clamp_even(
                int(np.median([x for _, x in keys])), 0, max(0, width - crop_w)
            )
        else:
            sx, _, _, _ = detect_optimal_crop_region(input_path, 0, min(duration, 12.0))
            static_x = clamp_even(sx, 0, max(0, width - crop_w))
        crop_chain = f"crop={crop_w}:{crop_h}:{static_x}:0,{VERTICAL_SCALE_CHAIN}"

    if not fit_intervals:
        # Static, all-face clip: add the slow Ken Burns punch-in. (The moving
        # tracked crop and the compositor path keep the plain chain — they
        # already have motion, and zoompan's re-timing would fight overlays.)
        if not moving:
            zoom = kenburns_zoom_fragment(duration)
            if zoom:
                return _described(
                    "crop",
                    f"crop={crop_w}:{crop_h}:{static_x}:0,{zoom}",
                    "vf",
                    bleed_caption(face_samples),
                )
        return _described("crop", crop_chain, "vf", bleed_caption(face_samples))

    face_intervals = [(s["start"], s["end"]) for s in plan if s["kind"] == "face"]
    logger.info(
        "Scene-aware vertical layout: %d face shot(s), %d content shot(s)",
        len(face_intervals), len(fit_intervals),
    )
    return _described(
        "compositor",
        build_vertical_compositor_filter(
            crop_chain, face_intervals, fit_intervals, fit_windows=fit_windows
        ),
        "complex",
        bleed_caption(face_samples),
    )


def render_reframed_clip_ffmpeg(
    input_path: Path,
    output_path: Path,
    output_format: str,
    subtitle_ass_path: Optional[Path] = None,
    fonts_dir: Optional[Path] = None,
    speaker_turns: Optional[List[Dict[str, Any]]] = None,
    speaker_words: Optional[List[Dict[str, Any]]] = None,
    vertical_plan: Optional[Tuple[str, str]] = None,
    speaker_plan: Optional[Dict[str, Any]] = None,
    broll_overlays: Optional[List[Dict[str, Any]]] = None,
) -> Tuple[bool, int, int]:
    """Render the final framed clip and (optionally) burn subtitles in one pass.

    Collapsing reframing + subtitle burn into a single encode avoids a whole
    generation of re-encode loss. The pass uses the high-quality profile, CFR
    output and loudness-normalised audio. ``broll_overlays`` (path, start and
    duration on the clip timeline) are composited over the framed picture and
    under the captions.
    """
    width, height = ffprobe_video_size(input_path)
    has_audio = ffprobe_has_audio(input_path)
    subs = (
        subtitles_filter_fragment(subtitle_ass_path, fonts_dir)
        if subtitle_ass_path
        else None
    )
    audio_args = build_audio_output_args(has_audio)
    overlays = (
        normalize_broll_overlays(broll_overlays, ffprobe_duration(input_path))
        if broll_overlays
        else []
    )

    def composited(head: str, head_label: str, out_w: int, out_h: int, tail: str = "", **encode) -> bool:
        graph, label = broll_overlay_graph(head_label, overlays, out_w, out_h)
        post = ",".join(part for part in (subs, tail) if part)
        if post:
            graph = f"{graph};{label}{post}[v]"
            label = "[v]"
        command = [
            "ffmpeg", "-y", "-i", str(input_path),
            *broll_input_args(overlays),
            "-filter_complex", f"{head};{graph}",
            "-map", label, "-map", "0:a?",
            *build_final_video_encode_args(**encode),
            *audio_args,
            "-movflags", "+faststart",
            str(output_path),
        ]
        return run_ffmpeg_command(command).returncode == 0

    if output_format == "original":
        geometry = probe_video_geometry(input_path)
        display_width = geometry.display_width if geometry else width
        display_height = geometry.display_height if geometry else height
        source_fps = geometry.fps if geometry else None
        capped_width, capped_height = fit_within_1080p(display_width, display_height)
        needs_scale = (capped_width, capped_height) != (display_width, display_height)
        needs_fps = source_fps is not None and source_fps > MAX_OUTPUT_FPS + FPS_EPSILON
        out_w, out_h = round_to_even(capped_width), round_to_even(capped_height)
        if overlays:
            # Always scale to the display size: on a non-square-pixel source
            # the coded frame is not the size the overlay is built for.
            ok = composited(
                f"[0:v]scale={out_w}:{out_h}:flags=lanczos,setsar=1[base]", "[base]", out_w, out_h,
                tail="setsar=1",
            )
            return ok, out_w, out_h
        # A source already within 1080p/60 can be copied. Anything above that is
        # re-encoded so original-format output cannot exceed the cap.
        if not subs and not needs_scale and not needs_fps:
            shutil.copyfile(input_path, output_path)
            return True, round_to_even(display_width), round_to_even(display_height)
        filters: List[str] = []
        if needs_scale:
            filters.append(f"scale={out_w}:{out_h}:flags=lanczos,setsar=1")
        if needs_fps and not subs:
            filters.append(f"fps={MAX_OUTPUT_FPS}")
        if subs:
            filters.append(subs)
        if not needs_scale:
            filters.append("setsar=1")
        if subs:
            encode_fps: int | str = OUTPUT_FPS
            encode_level = "4.1"
        elif needs_fps or source_fps is None:
            encode_fps = MAX_OUTPUT_FPS if needs_fps else OUTPUT_FPS
            encode_level = "4.2" if needs_fps else "4.1"
        else:
            # 59.94 stays 60000/1001. Rounding it to 60 would drop or duplicate
            # frames on an NTSC master that is already inside the cap.
            encode_fps = output_rate_token(source_fps)
            encode_level = "4.2" if source_fps > 30 + FPS_EPSILON else "4.1"
        command = [
            "ffmpeg", "-y", "-i", str(input_path),
            "-vf", ",".join(filters),
            *build_final_video_encode_args(fps=encode_fps, level=encode_level),
            *audio_args,
            "-movflags", "+faststart",
            str(output_path),
        ]
        return run_ffmpeg_command(command).returncode == 0, out_w, out_h

    # A caller that already built the split or pan plan (the editor) skips a
    # second face pass and renders that exact layout.
    if speaker_plan is not None:
        plan = speaker_plan
    else:
        plan = (
            detect_speaker_reframe_plan(input_path, output_format)
            if output_format in {"vertical_pan", "vertical_split"}
            else None
        )

    if plan and plan["mode"] == "split":
        left = plan["regions"]["left"]
        right = plan["regions"]["right"]
        vstack_tail = f",{subs}" if subs else ""
        stacked = (
            f"[0:v]split=2[l][r];"
            f"[l]crop={left['tile_w']}:{left['tile_h']}:{left['tile_x']}:{left['tile_y']},"
            f"scale=1080:960:flags=lanczos,{UPSCALE_SHARPEN_FILTER},setsar=1[lv];"
            f"[r]crop={right['tile_w']}:{right['tile_h']}:{right['tile_x']}:{right['tile_y']},"
            f"scale=1080:960:flags=lanczos,{UPSCALE_SHARPEN_FILTER},setsar=1[rv];"
            f"[lv][rv]vstack,setsar=1"
        )
        if overlays:
            return composited(f"{stacked}[base]", "[base]", 1080, 1920), 1080, 1920
        video_filter = f"{stacked}{vstack_tail}[v]"
        command = [
            "ffmpeg", "-y", "-i", str(input_path),
            "-filter_complex", video_filter,
            "-map", "[v]", "-map", "0:a?",
            *build_final_video_encode_args(),
            *audio_args,
            "-movflags", "+faststart",
            str(output_path),
        ]
        return run_ffmpeg_command(command).returncode == 0, 1080, 1920

    if plan and plan["mode"] == "pan":
        video_filter = (
            f"crop={plan['crop_w']}:{plan['crop_h']}:x='{plan['x_expression']}':y=0,"
            f"{VERTICAL_SCALE_CHAIN}"
        )
        if overlays:
            return composited(f"[0:v]{video_filter}[base]", "[base]", 1080, 1920), 1080, 1920
        if subs:
            video_filter = f"{video_filter},{subs}"
        command = [
            "ffmpeg", "-y", "-i", str(input_path),
            "-vf", video_filter,
            *build_final_video_encode_args(),
            *audio_args,
            "-movflags", "+faststart",
            str(output_path),
        ]
        return run_ffmpeg_command(command).returncode == 0, 1080, 1920

    # Default "vertical": face-aware for low webcams and calls, tracked crop
    # for a well-framed closeup, blurred full-frame fit for content shots.
    if output_format == "vertical_fit":
        video_filter, mode = build_full_frame_filter(), "complex"
    elif vertical_plan is not None:
        video_filter, mode = vertical_plan
    else:
        video_filter, mode, _caption_y = build_vertical_filter_plan(
            input_path, width, height, speaker_turns, speaker_words
        )
    if overlays:
        if mode == "complex":
            return composited(video_filter, "[vout]", 1080, 1920), 1080, 1920
        return composited(f"[0:v]{video_filter}[base]", "[base]", 1080, 1920), 1080, 1920
    if mode == "complex":
        if subs:
            graph = f"{video_filter};[vout]{subs}[v]"
            map_label = "[v]"
        else:
            graph = video_filter
            map_label = "[vout]"
        command = [
            "ffmpeg", "-y", "-i", str(input_path),
            "-filter_complex", graph,
            "-map", map_label, "-map", "0:a?",
            *build_final_video_encode_args(),
            *audio_args,
            "-movflags", "+faststart",
            str(output_path),
        ]
        return run_ffmpeg_command(command).returncode == 0, 1080, 1920

    if subs:
        video_filter = f"{video_filter},{subs}"
    command = [
        "ffmpeg", "-y", "-i", str(input_path),
        "-vf", video_filter,
        *build_final_video_encode_args(),
        *audio_args,
        "-movflags", "+faststart",
        str(output_path),
    ]
    return run_ffmpeg_command(command).returncode == 0, 1080, 1920


def caption_probe_plan(input_path: Path, output_format: str, vertical_plan=None) -> Tuple[str, str]:
    """The same composition as the final render, without subtitles or stock footage."""
    if output_format == "vertical_fit":
        return build_full_frame_filter(), "complex"
    if output_format in {"vertical_split", "vertical_pan"}:
        plan = detect_speaker_reframe_plan(input_path, output_format)
        if plan and plan["mode"] == "split":
            left, right = plan["regions"]["left"], plan["regions"]["right"]
            return (f"[0:v]split=2[a][b];[a]crop={left['tile_w']}:{left['tile_h']}:{left['tile_x']}:{left['tile_y']},scale=1080:960:flags=lanczos,{UPSCALE_SHARPEN_FILTER},setsar=1[top];[b]crop={right['tile_w']}:{right['tile_h']}:{right['tile_x']}:{right['tile_y']},scale=1080:960:flags=lanczos,{UPSCALE_SHARPEN_FILTER},setsar=1[bottom];[top][bottom]vstack,setsar=1[vout]", "complex")
        if plan and plan["mode"] == "pan":
            return f"crop={plan['crop_w']}:{plan['crop_h']}:x='{plan['x_expression']}':y=0,{VERTICAL_SCALE_CHAIN}", "vf"
    if vertical_plan is not None:
        return vertical_plan
    width, height = ffprobe_video_size(input_path)
    video_filter, mode, _ = build_vertical_filter_plan(input_path, width, height)
    return video_filter, mode