avanalyze 0.1.0

Long-running Apple Vision.framework worker that analyses keyframes and emits mediaschema-shaped detections.
Documentation
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
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
#![doc = include_str!("../README.md")]
// #![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(docsrs, feature(doc_cfg))]
#![cfg_attr(docsrs, allow(unused_attributes))]
#![deny(missing_docs)]

//! Long-running Apple Vision.framework service thread.
//!
//! Each worker thread owns an `AppleVisionAnalyzer` and processes keyframes
//! independently. Vision.framework is stateless per-request, so multiple
//! workers can run in parallel.
//!
//! Input: `Request` via crossbeam bounded channel
//! Output: `Reply` via callback back to the processor-local coordinator

#[cfg(target_vendor = "apple")]
use std::panic::{AssertUnwindSafe, catch_unwind};

#[cfg(target_vendor = "apple")]
use bytes::Bytes;
use mediaframe::frame::Dimensions;
#[cfg(target_vendor = "apple")]
use mediaschema::domain::aggregates::video::{
  Aesthetics, AnimalAnalysis, BarcodeDetection, BodyPose3DDetection, BodyPose3DHeightEstimation,
  BodyPose3DJoint, BodyPoseDetection, BodyPoseJoint, BoundingBox, Detection, DocumentSegment,
  FaceDetection, FaceLandmarkRegion, FaceLandmarksDetection, HandChirality, HandPoseDetection,
  HorizonInfo, HumanAnalysis, PersonInstanceMaskDetection, PersonSegmentationMask, SaliencyRegion,
  SubjectDetection, TextDetection,
};
use mediaschema::domain::{ErrorCode, ErrorInfo, Keyframe, KeyframeExtractor, Uuid7};
use mediatime::Timestamp;

// The domain `Keyframe` is generic over its `Id` type; avanalyze
// specialises on `Uuid7` (mediaschema's domain identifier). `Id` was
// previously a wire-record alias for `Bytes`; under the domain
// migration it becomes the typed `Uuid7`.
//
// Held as a doc alias rather than a re-export so the (commented)
// service-framework block keeps compiling against the new identifier
// type without a churn-only rename.
#[cfg(target_vendor = "apple")]
type Id = Uuid7;

// use tracing::{info, warn};

#[cfg(target_vendor = "apple")]
use objc2::{
  encode::{Encode, Encoding},
  rc::Retained,
};
#[cfg(target_vendor = "apple")]
use objc2_core_foundation::{CGPoint, CGRect};
#[cfg(target_vendor = "apple")]
use objc2_core_video::{
  CVPixelBuffer, CVPixelBufferGetBaseAddress, CVPixelBufferGetBytesPerRow,
  CVPixelBufferGetDataSize, CVPixelBufferGetHeight, CVPixelBufferGetPixelFormatType,
  CVPixelBufferGetWidth, CVPixelBufferLockBaseAddress, CVPixelBufferLockFlags,
  CVPixelBufferUnlockBaseAddress, kCVPixelFormatType_OneComponent8,
  kCVPixelFormatType_OneComponent32Float, kCVReturnSuccess,
};
#[cfg(target_vendor = "apple")]
use objc2_foundation::{NSArray, NSData, NSIndexSet, NSNotFound};
#[cfg(target_vendor = "apple")]
use objc2_vision::*;
#[cfg(target_vendor = "apple")]
use smol_str::{SmolStr, StrExt, ToSmolStr};

pub use options::*;

mod options;

#[cfg(target_vendor = "apple")]
#[repr(C, align(16))]
#[derive(Clone, Copy, Debug)]
struct SimdFloat4([f32; 4]);

#[cfg(target_vendor = "apple")]
unsafe impl Encode for SimdFloat4 {
  // `simd_float4` is an `__attribute__((__ext_vector_type__))` type;
  // Clang intentionally emits NO `@encode` for ext-vector elements, so
  // the matching Rust-side encoding is [`Encoding::None`] (formats as
  // empty string), NOT [`Encoding::Unknown`] (formats as `?`).
  //
  // objc2-encode's `Encoding::None` docstring explicitly calls this
  // out as the SIMD-vector case. The previous `Encoding::Unknown`
  // made the wrapping struct render as `{?=[4?]}`, while Vision's
  // `-[VNHumanBodyRecognizedPoint3D position]` returns `{?=[4]}`
  // (Clang refuses to emit an inner element character) — every
  // msg_send for that selector failed verification on macOS 26.x,
  // and the surrounding `catch_unwind` silently swallowed the
  // panic so 3-D pose detections were always dropped to zero.
  const ENCODING: Encoding = Encoding::None;
}

#[cfg(target_vendor = "apple")]
#[repr(C, align(16))]
#[derive(Clone, Copy, Debug)]
struct SimdFloat4x4 {
  columns: [SimdFloat4; 4],
}

#[cfg(target_vendor = "apple")]
unsafe impl Encode for SimdFloat4x4 {
  // Apple's `simd_float4x4` is a struct-of-vectors. Clang reports
  // `@encode(simd_float4x4)` as `{?=[4]}` — outer struct with no name
  // wrapping an array of 4 whose element type Clang refuses to encode
  // (the element is itself an ext-vector, see [`SimdFloat4`] above).
  // The matching Rust encoding therefore uses `Array(4, &None)` so
  // the inner array element formats to an empty string, producing the
  // literal `[4]` Clang emits.
  const ENCODING: Encoding = Encoding::Struct("?", &[Encoding::Array(4, &Encoding::None)]);
}

// ----- Vision → mediaschema coordinate conversion ---------------------------

/// Clamp a finite `f32` into `[0.0, 1.0]`. Callers MUST filter
/// non-finite inputs before invoking this helper — passing `NaN` /
/// `±Inf` is a regression (collapsing them to `0.0` here previously
/// fabricated edge-aligned coordinates that downstream validators
/// accepted as real detections). The `debug_assert!` catches the
/// regression in debug builds without changing release behaviour
/// (`f32::clamp(0.0, 1.0)` on `NaN` returns `NaN`, and on `±Inf`
/// returns the appropriate edge — both of which the domain
/// `NormCoord::try_new` will reject downstream, so we still
/// degrade safely rather than panicking).
#[cfg(target_vendor = "apple")]
#[inline]
fn clamp01(value: f32) -> f32 {
  debug_assert!(
    value.is_finite(),
    "clamp01 expects finite input; got {value}"
  );
  value.clamp(0.0, 1.0)
}

/// Convert a Vision-framework normalized bounding box (lower-left
/// origin, y grows up) into the mediaschema convention (top-left
/// origin, y grows down) and intersect it with the unit square
/// `[0, 1] × [0, 1]`.
///
/// The schema documents `apple-vision convention: floats in [0.0, 1.0],
/// origin top-left` (see `mediaschema::domain ... NormCoord`), while
/// `VNObservation::boundingBox` is documented as a normalized rect in
/// image coordinates where `(0,0)` is the lower-left corner. Vision is
/// empirically loose about staying inside `[0, 1]` — partially
/// off-screen detections can produce `origin.x < 0`,
/// `origin.x + width > 1`, etc., which the validated domain
/// `BoundingBox::try_new` would reject. We clamp every component and
/// return `None` if the resulting rectangle is degenerate
/// (zero-width or zero-height); the detection is then dropped at the
/// engine layer instead of poisoning downstream storage.
///
/// `standardize()` is assumed to have already been called on `rect`;
/// the input `size` is non-negative.
#[cfg(target_vendor = "apple")]
fn vision_bbox_to_schema(rect: CGRect) -> Option<BoundingBox> {
  // Vision lower-left → schema top-left: the top edge in schema space
  // is `1.0 - (origin.y + size.height)`.
  let raw_x = rect.origin.x as f32;
  let raw_y = (1.0 - (rect.origin.y + rect.size.height)) as f32;
  let raw_width = rect.size.width as f32;
  let raw_height = rect.size.height as f32;

  // Front-load the non-finite check: any `NaN` / `±Inf` in the raw
  // rectangle means the box is geometrically meaningless. Drop it
  // instead of letting `clamp01` (which used to collapse non-finite
  // to `0.0`) fabricate an edge-aligned rectangle that downstream
  // validation would accept.
  if !(raw_x.is_finite() && raw_y.is_finite() && raw_width.is_finite() && raw_height.is_finite()) {
    return None;
  }

  // Intersect with the unit square. Compute right/bottom in raw space,
  // then clamp the four edges so we never end up with `x + width > 1`.
  let left = clamp01(raw_x);
  let top = clamp01(raw_y);
  let right = clamp01(raw_x + raw_width);
  let bottom = clamp01(raw_y + raw_height);
  let width = (right - left).max(0.0);
  let height = (bottom - top).max(0.0);
  if width <= 0.0 || height <= 0.0 {
    return None;
  }
  // The clamp logic above guarantees the validating-ctor invariants
  // (finite, `[0, 1]`, positive extent, `left + width <= 1.0`); a
  // failure here would be a regression in the upstream guards, not a
  // real Vision input.
  BoundingBox::try_new(left, top, width, height).ok()
}

/// Flip a Vision normalized point's y axis to match mediaschema's
/// top-left origin and clamp both components into `[0.0, 1.0]`.
/// `BoundingBox`, `Point2D`, `BodyPoseJoint` (2-D), `FaceLandmarkPoint`,
/// and `DocumentSegment` corners all share the top-left convention (see
/// `NormCoord` doc-comment in mediaschema). 3-D joints
/// (`BodyPose3DJoint`) are model-space metres and are NOT flipped or
/// clamped.
///
/// Returns `None` when either input coordinate is non-finite. A `NaN`
/// or `±Inf` from a glitched Vision observation is geometrically
/// meaningless and previously sanitised to `0.0` via `clamp01`, which
/// fabricated edge-aligned coordinates indistinguishable from real
/// detections. The caller decides whether a single bad point drops
/// the entire detection (e.g. a document quad without all four
/// corners) or just the offending point (e.g. one bad joint among
/// many).
#[cfg(target_vendor = "apple")]
#[inline]
fn vision_point_to_schema(x: f64, y: f64) -> Option<(f32, f32)> {
  let x32 = x as f32;
  let flipped_y = (1.0 - y) as f32;
  if !x32.is_finite() || !flipped_y.is_finite() {
    return None;
  }
  Some((clamp01(x32), clamp01(flipped_y)))
}

/// Reject non-finite Vision-derived scalars. `NaN` / `±Inf` from
/// glitched Vision observations would otherwise enter the wire as
/// valid-looking detections and later trip downstream validation or
/// silently fail-open through `<` / `>` comparisons (since every
/// comparison against `NaN` is `false`). Callers convert `None` into
/// either a structured "drop the containing detection" decision or a
/// concrete default (typically `0.0`) — the choice depends on whether
/// the scalar is required geometry/score (drop) or an optional pose
/// angle (default).
#[cfg(target_vendor = "apple")]
#[inline]
fn finite_f32(v: f32) -> Option<f32> {
  if v.is_finite() { Some(v) } else { None }
}

/// Upper bound on a single mask payload (post-packing, 8 bits per
/// pixel) before we refuse to allocate. 64 MiB covers any sane image
/// resolution Apple Vision returns today (8K = ~33 MiB at 8 bits per
/// pixel) and prevents a runaway / corrupted `width * height` from
/// driving the worker process into the allocator's abort path.
#[cfg(target_vendor = "apple")]
const MAX_MASK_BYTES: usize = 64 * 1024 * 1024;

/// Upper bound on the number of landmark points per face-landmark
/// region. Vision's `allPoints` is ~76 points; per-feature regions
/// are smaller. 1024 leaves headroom against future API expansion
/// while still capping a corrupted/adversarial `pointCount`.
#[cfg(target_vendor = "apple")]
const MAX_LANDMARK_POINTS: usize = 1024;

/// Upper bound on the number of detection results from a single
/// Vision request before we refuse to pre-allocate OR iterate the
/// FFI-reported `results` array. Apple's per-frame extractor
/// outputs cap out in the low hundreds at most (text recognition,
/// face capture, etc.); 4096 is a generous defence-in-depth
/// ceiling against a corrupted / adversarial `NSArray` length that
/// would otherwise drive either the initial `Vec::with_capacity`
/// or the in-loop `Vec::push` reallocation into the allocator's
/// abort path. Every `for x in results.iter()` is bounded with
/// `.iter().take(MAX_VISION_RESULTS_PER_FRAME)` so the emitted
/// count cannot exceed the cap, independently of whatever
/// configured `max_results` / `max_segments` / … the call site
/// uses inside the loop.
#[cfg(target_vendor = "apple")]
const MAX_VISION_RESULTS_PER_FRAME: usize = 4096;

/// Upper bound on the number of joints / recognised points per
/// pose observation before we refuse to materialise the joint
/// dictionary via `NSDictionary::to_vecs()`. Apple's body-pose /
/// hand-pose / animal-pose joint counts are fixed by the SDK
/// (~17 body, ~21 hand, ~25 animal); 256 leaves headroom against
/// future API expansion while still capping a corrupted /
/// adversarial `points_by_joint.len()` that would otherwise drive
/// `to_vecs()`'s internal allocations into the abort path before
/// the per-extractor logic can drop the pose.
#[cfg(target_vendor = "apple")]
const MAX_POSE_JOINTS: usize = 256;

/// Hard ceiling on instances per segmentation-mask observation.
#[cfg(target_vendor = "apple")]
const MAX_NESTED_INSTANCES_PER_OBSERVATION: usize = 64;

/// Hard ceiling on labels per recognised-animal observation.
#[cfg(target_vendor = "apple")]
const MAX_NESTED_LABELS_PER_OBSERVATION: usize = 32;

/// Hard ceiling on candidate strings per text-recognition
/// observation. Apple's
/// `VNRecognizedTextObservation::topCandidates(_:)` documents an
/// upper limit of 10 — requesting more violates the Objective-C
/// API contract and can surface as a framework exception or
/// undefined behaviour across OS versions, so we clamp to 10 here
/// even though realistic workloads ask for 1-3 candidates
/// (codex R17 F3).
#[cfg(target_vendor = "apple")]
const MAX_TEXT_CANDIDATES_PER_OBSERVATION: usize = 10;

/// Hard ceiling on saliency regions per frame.
#[cfg(target_vendor = "apple")]
const MAX_SALIENCY_REGIONS_PER_FRAME: usize = 64;

/// Hard ceiling on the total mask count emitted per frame across
/// the inner observation × instance loop. Without this, an outer
/// cap of 4096 observations × an inner cap of 64 instances would
/// permit 256K mask emissions per frame even though each individual
/// mask is capped at [`MAX_MASK_BYTES`]. 256 is a generous total
/// matching realistic Vision output for a single frame.
#[cfg(target_vendor = "apple")]
const MAX_TOTAL_MASKS_PER_FRAME: usize = 256;

/// Hard ceiling on the cumulative mask payload bytes emitted per
/// frame. Even at the per-mask cap, a worst-case 256 masks × 64 MiB
/// = 16 GiB would crush the worker. 256 MiB total is generous for
/// realistic Vision output while bounding the cumulative budget.
#[cfg(target_vendor = "apple")]
const MAX_TOTAL_MASK_BYTES_PER_FRAME: usize = 256 * 1024 * 1024;

/// Hard ceiling on the cumulative ATTEMPTED mask generations per
/// frame, summed across both mask extractors. The emission-only
/// counters (count, bytes) only increment after a successful copy
/// and push; a corrupted Vision result whose generate-copy-u32-fit
/// gates all fail would otherwise drive unbounded
/// `generateMaskForInstances_error` calls (each forcing Vision to
/// compute/allocate a mask buffer) while the emission counters
/// stay below their caps. The attempt budget bounds the
/// failure-path work itself (codex R15 + R16).
///
/// Sized as `4 * MAX_TOTAL_MASKS_PER_FRAME` (= 1024): each emitted
/// mask gets up to 3 failed sibling attempts before the budget
/// trips, which leaves ample headroom for transient Vision
/// failures while keeping the attempt cap tied to the emission
/// cap rather than the much larger general results-array cap.
/// Apple's mask APIs return a small number of masks per frame
/// (low units for segmentation, typically <20 for instance masks),
/// so 1024 attempts is conservative against realistic workloads
/// while still defending against the corrupted-array case.
#[cfg(target_vendor = "apple")]
const MAX_TOTAL_MASK_ATTEMPTS_PER_FRAME: usize = 4 * MAX_TOTAL_MASKS_PER_FRAME;

/// Hard ceiling on the cumulative ATTEMPTED face-landmark points
/// visited per frame across all detections × all 13 named regions.
/// Symmetric with `MAX_TOTAL_MASK_ATTEMPTS_PER_FRAME`: a corrupted
/// observation set where every region's points fail
/// `vision_point_to_schema`'s finite check (or where the parent
/// detection later fails the bbox / min_region_count gates) would
/// otherwise let the helper walk up to
/// `4096 * 13 * MAX_LANDMARK_POINTS` raw points without the
/// per-frame emission budget ever decreasing. Sized as
/// `4 * MAX_FACE_LANDMARK_POINTS_PER_FRAME` so a successful frame
/// can tolerate non-finite/dropped points before the attempt cap
/// trips (codex R17 F1).
#[cfg(target_vendor = "apple")]
const MAX_FACE_LANDMARK_ATTEMPTS_PER_FRAME: usize = 4 * MAX_FACE_LANDMARK_POINTS_PER_FRAME;

/// Hard ceiling on the cumulative face-landmark points emitted per
/// frame across all detections × all 13 named regions × all points.
/// Apple's typical output is at most a few faces × ~76 points each,
/// so 16384 is generous defence-in-depth against the worst-case
/// nested-emission product (4096 × 13 × MAX_LANDMARK_POINTS).
#[cfg(target_vendor = "apple")]
const MAX_FACE_LANDMARK_POINTS_PER_FRAME: usize = 16384;

/// Hard ceiling on the total animal-subject rows emitted per frame.
/// Apple's animal recogniser returns a few species per frame at most;
/// 256 caps the adversarial 4096 × MAX_NESTED_LABELS_PER_OBSERVATION
/// product without restricting real workloads.
#[cfg(target_vendor = "apple")]
const MAX_TOTAL_ANIMAL_SUBJECTS_PER_FRAME: usize = 256;

/// Hard ceiling on the total text detections emitted per frame.
/// 256 caps the adversarial 4096 × MAX_TEXT_CANDIDATES_PER_OBSERVATION
/// product without restricting real text-rich-document workloads.
#[cfg(target_vendor = "apple")]
const MAX_TOTAL_TEXT_DETECTIONS_PER_FRAME: usize = 256;

/// Upper bound on the input image byte length accepted by
/// [`VisionAnalyzer::analyze_keyframe`]. Pre-validates the keyframe
/// payload BEFORE Foundation copies it into an `NSData`, so an
/// oversized or hostile input cannot double the worker's peak
/// memory and drive the allocator into the abort path. 64 MiB
/// covers an extremely generous keyframe (Apple's typical
/// keyframe encoded JPEG is well under 1 MiB); inputs above that
/// surface as a structured `ErrorInfo` instead of an alloc-side
/// crash (codex R17 F1).
#[cfg(target_vendor = "apple")]
const MAX_INPUT_IMAGE_BYTES: usize = 64 * 1024 * 1024;

/// Apple's documented maximum for
/// `VNDetectHumanHandPoseRequest::setMaximumHandCount(_:)` at
/// revision 1 — the request becomes invalid above this. The pinned
/// request revision in this crate is revision 1; configurations
/// requesting more must clamp at extractor build time to avoid an
/// Objective-C exception crossing the FFI boundary (codex R17 F2).
#[cfg(target_vendor = "apple")]
const MAX_HAND_POSE_MAXIMUM_HAND_COUNT: usize = 6;

/// Upper bound on the byte length of an FFI-sourced `NSString`
/// before we refuse to convert it to a Rust `SmolStr` / `String`.
/// Apple's Vision-emitted strings (OCR text, barcode payloads,
/// classification identifiers, joint names) cap out in the low
/// hundreds of bytes for realistic content; 4096 is a generous
/// defence-in-depth ceiling against a corrupted / adversarial
/// `NSString` whose reported length would drive Rust's infallible
/// string allocation into the abort path. Strings exceeding the
/// cap are dropped; callers skip the offending field rather than
/// truncating mid-grapheme.
#[cfg(target_vendor = "apple")]
const MAX_FFI_STRING_BYTES: usize = 4096;

/// Convert an FFI-sourced `NSString` to a Rust `SmolStr` after
/// verifying its UTF-8 byte length is within
/// [`MAX_FFI_STRING_BYTES`]. Returns `None` if the `NSString`'s
/// reported byte length exceeds the bound; callers drop the
/// offending field (text candidate / barcode payload /
/// classification label / joint name) rather than driving the
/// allocator into the abort path. The length query is FFI but
/// allocation-free.
#[cfg(target_vendor = "apple")]
fn ffi_nsstring_to_smolstr(ns_str: &objc2_foundation::NSString) -> Option<SmolStr> {
  // `NSStringEncoding` is a `usize` type alias (objc2_foundation
  // re-exports it from `objc2::ffi::NSUInteger = usize`).
  // `NSUTF8StringEncoding` is the documented value 4.
  const NS_UTF8_STRING_ENCODING: objc2_foundation::NSStringEncoding = 4;
  // `lengthOfBytesUsingEncoding` is exposed as safe by
  // objc2-foundation 0.3.2 — no `unsafe` wrapper required.
  let utf8_len: usize = ns_str.lengthOfBytesUsingEncoding(NS_UTF8_STRING_ENCODING);
  if utf8_len > MAX_FFI_STRING_BYTES {
    return None;
  }
  Some(ns_str.to_smolstr())
}

/// Compute the effective per-extractor cap as
/// `min(user_configured_max, MAX_VISION_RESULTS_PER_FRAME)`. Use
/// this for ALL of: `Vec::with_capacity(cap)`, `.iter().take(cap)`,
/// and the in-loop `if emitted.len() >= cap { break; }` guard.
/// Composing the three around the SAME `cap` value bounds both
/// capacity and emission to the hard ceiling, regardless of what
/// the caller configured.
#[cfg(target_vendor = "apple")]
#[inline]
fn effective_results_cap(user_max: usize) -> usize {
  user_max.min(MAX_VISION_RESULTS_PER_FRAME)
}

/// Validate a byte-length payload pre-`from_raw_parts`. Two
/// preconditions:
///
/// 1. `byte_len <= max_bytes` (caller-provided ceiling against
///    corrupted/adversarial sizes that would drive the bounded
///    allocator into refusal).
/// 2. `byte_len <= isize::MAX as usize` (the
///    [`std::slice::from_raw_parts`] contract for `T: u8`).
///
/// Returns `None` on either violation; the caller propagates that
/// `None` so the detection is dropped rather than triggering UB or
/// the allocator's abort path.
///
/// Currently exercised only by the unit-test suite — the last
/// in-engine caller (the FeaturePrint copy path) was removed when
/// the `feature_print` field migrated to LanceDB. The helper is
/// retained because future FFI byte-slice surfaces will need the
/// same precondition gate.
#[cfg(target_vendor = "apple")]
#[allow(dead_code)]
#[inline]
fn validate_raw_slice_bytes(byte_len: usize, max_bytes: usize) -> Option<()> {
  if byte_len > max_bytes {
    return None;
  }
  if byte_len > isize::MAX as usize {
    return None;
  }
  Some(())
}

/// Validate an element-count payload pre-`from_raw_parts<T>`. Same
/// shape as [`validate_raw_slice_bytes`] but computes
/// `byte_len = elem_count * size_of::<T>()` with overflow checking
/// before the `isize::MAX` comparison, so the helper is safe for
/// element types larger than `u8`.
#[cfg(target_vendor = "apple")]
#[inline]
fn validate_raw_slice_elems<T>(elem_count: usize, max_elems: usize) -> Option<()> {
  if elem_count > max_elems {
    return None;
  }
  let byte_len = elem_count.checked_mul(core::mem::size_of::<T>())?;
  if byte_len > isize::MAX as usize {
    return None;
  }
  Some(())
}

/// Allocate a zero-initialised packed mask buffer with bounded
/// `try_reserve_exact`. Returns `None` on either bound violation or
/// allocator failure — both surface to the caller as a dropped mask
/// detection rather than aborting the process.
#[cfg(target_vendor = "apple")]
fn try_alloc_packed_mask(packed_len: usize) -> Option<Vec<u8>> {
  if packed_len > MAX_MASK_BYTES {
    return None;
  }
  let mut packed: Vec<u8> = Vec::new();
  packed.try_reserve_exact(packed_len).ok()?;
  packed.resize(packed_len, 0u8);
  Some(packed)
}

/// Sanitise a raw face captureQuality reading from Vision.
///
/// Distinguishes three states explicitly:
/// - `Some(finite)` — Vision provided a real measurement; pass it
///   through.
/// - `Some(0.0)` — Vision did NOT provide a value (the underlying
///   `NSNumber?` was `None`). Map to `0.0` so the caller's threshold
///   comparison fails closed for any positive minimum.
/// - `None` — Vision provided a non-finite value (`NaN` / `±Inf`).
///   Caller MUST drop the detection: a non-finite reading is not a
///   real measurement, and substituting `0.0` would silently admit
///   the detection through any `min_capture_quality = 0.0`
///   configuration.
#[cfg(target_vendor = "apple")]
#[inline]
fn sanitize_capture_quality(raw: Option<f32>) -> Option<f32> {
  match raw {
    Some(v) => finite_f32(v),
    None => Some(0.0),
  }
}

/// Sanitise a raw 3-D body-pose height + height-estimation pair.
///
/// Vision's `bodyHeight()` is metres in model space. When the
/// reading is non-finite, both `body_height` AND `height_estimation`
/// must be neutralised together — substituting `0.0` for the height
/// while preserving a `Measured` or `Reference` enum would tell
/// consumers there is a known 0-metre subject. The pair
/// `(0.0, UNKNOWN)` is the truthful encoding of "no estimate
/// available" and the only consistent fallback.
#[cfg(target_vendor = "apple")]
#[inline]
fn sanitize_body_height_pair(
  raw_height: f32,
  measured_or_reference: BodyPose3DHeightEstimation,
) -> (f32, BodyPose3DHeightEstimation) {
  match finite_f32(raw_height) {
    Some(finite) => (finite, measured_or_reference),
    None => (0.0, BodyPose3DHeightEstimation::Unknown),
  }
}

/// Validate mask dimensions BEFORE constructing the raw-parts slice
/// over a `CVPixelBuffer`'s base address. Two preconditions are
/// checked here so the unsafe `std::slice::from_raw_parts` call
/// downstream is sound even against a corrupted or adversarial
/// `CVPixelBuffer`:
///
/// 1. `width * height` (the output payload size after packing to
///    `OneComponent8`) must not exceed [`MAX_MASK_BYTES`].
/// 2. `total_src_len = bytes_per_row * height` (the raw slice
///    length) must fit in `isize::MAX`, which is the
///    [`std::slice::from_raw_parts`] contract.
///
/// Returns `None` on either violation; the caller propagates the
/// `None` so the mask detection is dropped rather than triggering
/// UB.
#[cfg(target_vendor = "apple")]
#[inline]
fn validate_mask_dims_for_slice(width: usize, height: usize, total_src_len: usize) -> Option<()> {
  let output_payload = width.checked_mul(height)?;
  if output_payload > MAX_MASK_BYTES {
    return None;
  }
  if total_src_len > isize::MAX as usize {
    return None;
  }
  Some(())
}

/// Project a face-bbox-relative landmark point into the image's
/// normalized coordinate space (Vision lower-left) using Apple's
/// documented convention: landmark points are normalized within the
/// face's normalized bounding box, NOT directly within the image.
/// `VNImagePointForFaceLandmarkPoint(p, faceBBox, w, h)` performs
/// `imageX = faceBBox.x + p.x * faceBBox.width;
/// imageY = faceBBox.y + p.y * faceBBox.height` (lower-left). Callers
/// then route through [`vision_point_to_schema`] for the schema-side
/// top-left flip + `[0, 1]` clamp + finite check.
#[cfg(target_vendor = "apple")]
#[inline]
fn project_landmark_to_image(point: CGPoint, face_bbox_vision: CGRect) -> CGPoint {
  CGPoint {
    x: face_bbox_vision.origin.x + point.x * face_bbox_vision.size.width,
    y: face_bbox_vision.origin.y + point.y * face_bbox_vision.size.height,
  }
}

/// Derive an axis-aligned bounding box from the min/max of a pose's
/// surviving joint coordinates. Returns `None` when the extent in
/// either axis is zero — a single joint, or joints that are perfectly
/// colinear horizontally/vertically, would otherwise produce a wire
/// box that the validated domain `BoundingBox::try_new` rejects.
/// Callers should skip the pose detection on `None`; the joints alone
/// do not carry enough geometry to construct a valid box.
#[cfg(target_vendor = "apple")]
fn pose_bbox_from_joint_bounds(
  min_x: f32,
  min_y: f32,
  max_x: f32,
  max_y: f32,
) -> Option<BoundingBox> {
  if !(min_x.is_finite() && min_y.is_finite() && max_x.is_finite() && max_y.is_finite()) {
    return None;
  }
  let width = max_x - min_x;
  let height = max_y - min_y;
  if width <= 0.0 || height <= 0.0 {
    return None;
  }
  // Joints are sanitised individually upstream (each goes through
  // `vision_point_to_schema` which clamps to `[0, 1]`), so the
  // derived bbox should satisfy the domain invariants. Drop on the
  // off-chance the validator rejects.
  BoundingBox::try_new(min_x, min_y, width, height).ok()
}

/// Validate a raw Vision `confidence` value against the configured
/// per-request minimum and the wire/domain `Confidence` invariant
/// (finite, in `[0.0, 1.0]`). Returns `None` if the value is
/// non-finite, outside `[0, 1]`, or below `min` — the caller drops
/// the detection in that case. A simple `value < min` threshold
/// previously let `NaN` through (since every NaN comparison is
/// false) and accepted `>1.0` values, both of which mediaschema's
/// domain `Confidence::try_new` rejects.
#[cfg(target_vendor = "apple")]
#[inline]
fn sanitize_confidence(value: f32, min: f32) -> Option<f32> {
  if value.is_finite() && (0.0..=1.0).contains(&value) && value >= min {
    Some(value)
  } else {
    None
  }
}

// ----- CVPixelBuffer RAII lock ----------------------------------------------

/// RAII guard that holds a `CVPixelBufferLockBaseAddress` lock for the
/// lifetime of the guard. `Drop` unlocks even on panic-unwind so the
/// buffer cannot be left in a locked state by a panicking slice index.
#[cfg(target_vendor = "apple")]
struct CVPixelBufferLockGuard<'a> {
  buffer: &'a CVPixelBuffer,
  flags: CVPixelBufferLockFlags,
}

#[cfg(target_vendor = "apple")]
impl<'a> CVPixelBufferLockGuard<'a> {
  /// Acquire a lock on `buffer` with `flags`. Returns `None` if Core
  /// Video refused the lock; on success the guard's `Drop` is
  /// responsible for releasing it.
  #[inline]
  fn lock(buffer: &'a CVPixelBuffer, flags: CVPixelBufferLockFlags) -> Option<Self> {
    // SAFETY: `buffer` is a valid `CVPixelBuffer`; `flags` is a valid
    // `CVPixelBufferLockFlags`. The function is documented as safe to
    // call from any thread.
    let rc = unsafe { CVPixelBufferLockBaseAddress(buffer, flags) };
    if rc == kCVReturnSuccess {
      Some(Self { buffer, flags })
    } else {
      None
    }
  }

  /// Borrow the locked buffer.
  #[inline]
  fn buffer(&self) -> &CVPixelBuffer {
    self.buffer
  }
}

#[cfg(target_vendor = "apple")]
impl Drop for CVPixelBufferLockGuard<'_> {
  fn drop(&mut self) {
    // SAFETY: the corresponding lock was acquired successfully in
    // `lock`; calling unlock with matching flags is required by Core
    // Video. We ignore the return code — even if unlock fails, the
    // buffer is going away with us and there's nothing the caller can
    // do about it.
    let _ = unsafe { CVPixelBufferUnlockBaseAddress(self.buffer, self.flags) };
  }
}

/// Apple Vision analyzer — one per worker thread.
///
/// Construct one [`VisionAnalyzer`] per worker thread via
/// [`VisionAnalyzer::new`]. The analyzer owns retained `VNRequest`
/// Objective-C objects that carry per-call state across
/// `performRequests` / `results()`, so they are *not* safe to share
/// across threads or clone. The upcoming service-framework layer
/// constructs one fresh analyzer per worker rather than cloning a
/// single shared instance — `Clone` is intentionally not implemented to
/// make that contract a compile-time error.
#[cfg(target_vendor = "apple")]
#[derive(Debug)]
pub struct VisionAnalyzer {
  opts: ServiceOptions,
  requests: VisionRequests,
}

#[cfg(target_vendor = "apple")]
#[derive(Debug)]
struct VisionRequests {
  classify: Retained<VNClassifyImageRequest>,
  face_rectangles: Retained<VNDetectFaceRectanglesRequest>,
  face_landmarks: Retained<VNDetectFaceLandmarksRequest>,
  face_quality: Retained<VNDetectFaceCaptureQualityRequest>,
  human_rectangles: Retained<VNDetectHumanRectanglesRequest>,
  body_pose: Retained<VNDetectHumanBodyPoseRequest>,
  body_pose_3d: Retained<VNDetectHumanBodyPose3DRequest>,
  hand_pose: Retained<VNDetectHumanHandPoseRequest>,
  animals: Retained<VNRecognizeAnimalsRequest>,
  animal_body_pose: Retained<VNDetectAnimalBodyPoseRequest>,
  person_instance_mask: Retained<VNGeneratePersonInstanceMaskRequest>,
  person_segmentation: Retained<VNGeneratePersonSegmentationRequest>,
  text: Retained<VNRecognizeTextRequest>,
  barcodes: Retained<VNDetectBarcodesRequest>,
  attention_saliency: Retained<VNGenerateAttentionBasedSaliencyImageRequest>,
  objectness_saliency: Retained<VNGenerateObjectnessBasedSaliencyImageRequest>,
  horizon: Retained<VNDetectHorizonRequest>,
  document_segments: Retained<VNDetectDocumentSegmentationRequest>,
  aesthetics: Retained<VNCalculateImageAestheticsScoresRequest>,
}

#[cfg(target_vendor = "apple")]
fn apple_vision_error(code: ErrorCode, message: impl Into<SmolStr>) -> ErrorInfo {
  ErrorInfo::new(code, message)
}

#[cfg(not(target_vendor = "apple"))]
fn apple_vision_error(code: ErrorCode, message: &'static str) -> ErrorInfo {
  ErrorInfo::new(code, message)
}

#[cfg(target_vendor = "apple")]
impl VisionRequests {
  fn new(opts: ServiceOptions) -> Self {
    unsafe {
      let classify = VNClassifyImageRequest::new();
      classify.setRevision(VNClassifyImageRequestRevision2);

      let face_rectangles = VNDetectFaceRectanglesRequest::new();
      face_rectangles.setRevision(VNDetectFaceRectanglesRequestRevision3);

      let face_landmarks = VNDetectFaceLandmarksRequest::new();
      face_landmarks.setRevision(VNDetectFaceLandmarksRequestRevision3);

      let face_quality = VNDetectFaceCaptureQualityRequest::new();
      face_quality.setRevision(VNDetectFaceCaptureQualityRequestRevision3);

      let human_rectangles = VNDetectHumanRectanglesRequest::new();
      human_rectangles.setUpperBodyOnly(false);
      human_rectangles.setRevision(VNDetectHumanRectanglesRequestRevision2);

      let body_pose = VNDetectHumanBodyPoseRequest::new();
      body_pose.setRevision(VNDetectHumanBodyPoseRequestRevision1);

      let body_pose_3d = VNDetectHumanBodyPose3DRequest::new();
      body_pose_3d.setRevision(VNDetectHumanBodyPose3DRequestRevision1);

      let hand_pose = VNDetectHumanHandPoseRequest::new();
      // Clamp the user-configured hand count to Apple's documented
      // revision-1 maximum. Apple's request becomes invalid above 6
      // and would surface as an Objective-C exception crossing the
      // FFI boundary; clamp here so a stale/misconfigured option
      // value still produces a usable Vision request (codex R17 F2).
      let user_hand_count = opts.hand_pose().maximum_hand_count();
      hand_pose.setMaximumHandCount(user_hand_count.min(MAX_HAND_POSE_MAXIMUM_HAND_COUNT));
      hand_pose.setRevision(VNDetectHumanHandPoseRequestRevision1);

      let animals = VNRecognizeAnimalsRequest::new();
      animals.setRevision(VNRecognizeAnimalsRequestRevision2);

      let animal_body_pose = VNDetectAnimalBodyPoseRequest::new();
      animal_body_pose.setRevision(VNDetectAnimalBodyPoseRequestRevision1);

      let person_instance_mask = VNGeneratePersonInstanceMaskRequest::new();
      person_instance_mask.setRevision(VNGeneratePersonInstanceMaskRequestRevision1);

      let person_segmentation = VNGeneratePersonSegmentationRequest::new();
      person_segmentation.setRevision(VNGeneratePersonSegmentationRequestRevision1);

      let text = VNRecognizeTextRequest::new();
      text.setRevision(VNRecognizeTextRequestRevision3);

      let barcodes = VNDetectBarcodesRequest::new();
      barcodes.setRevision(VNDetectBarcodesRequestRevision4);

      let attention_saliency = VNGenerateAttentionBasedSaliencyImageRequest::new();
      attention_saliency.setRevision(VNGenerateAttentionBasedSaliencyImageRequestRevision2);

      let objectness_saliency = VNGenerateObjectnessBasedSaliencyImageRequest::new();
      objectness_saliency.setRevision(VNGenerateObjectnessBasedSaliencyImageRequestRevision2);

      let horizon = VNDetectHorizonRequest::new();
      horizon.setRevision(VNDetectHorizonRequestRevision1);

      let document_segments = VNDetectDocumentSegmentationRequest::new();
      document_segments.setRevision(VNDetectDocumentSegmentationRequestRevision1);

      let aesthetics = VNCalculateImageAestheticsScoresRequest::new();
      aesthetics.setRevision(VNCalculateImageAestheticsScoresRequestRevision1);

      Self {
        classify,
        face_rectangles,
        face_landmarks,
        face_quality,
        human_rectangles: { human_rectangles },
        body_pose,
        body_pose_3d,
        hand_pose: { hand_pose },
        animals,
        animal_body_pose,
        person_instance_mask,
        person_segmentation,
        text,
        barcodes,
        attention_saliency,
        objectness_saliency,
        horizon,
        document_segments,
        aesthetics,
      }
    }
  }

  fn perform(&self, handler: &VNSequenceRequestHandler, data: &NSData) -> Result<(), ErrorInfo> {
    unsafe {
      let requests = NSArray::from_retained_slice(&[
        Retained::cast_unchecked::<VNRequest>(self.classify.clone()),
        Retained::cast_unchecked::<VNRequest>(self.face_rectangles.clone()),
        Retained::cast_unchecked::<VNRequest>(self.face_landmarks.clone()),
        Retained::cast_unchecked::<VNRequest>(self.face_quality.clone()),
        Retained::cast_unchecked::<VNRequest>(self.human_rectangles.clone()),
        Retained::cast_unchecked::<VNRequest>(self.body_pose.clone()),
        Retained::cast_unchecked::<VNRequest>(self.body_pose_3d.clone()),
        Retained::cast_unchecked::<VNRequest>(self.hand_pose.clone()),
        Retained::cast_unchecked::<VNRequest>(self.animals.clone()),
        Retained::cast_unchecked::<VNRequest>(self.animal_body_pose.clone()),
        Retained::cast_unchecked::<VNRequest>(self.person_instance_mask.clone()),
        Retained::cast_unchecked::<VNRequest>(self.person_segmentation.clone()),
        Retained::cast_unchecked::<VNRequest>(self.text.clone()),
        Retained::cast_unchecked::<VNRequest>(self.barcodes.clone()),
        Retained::cast_unchecked::<VNRequest>(self.attention_saliency.clone()),
        Retained::cast_unchecked::<VNRequest>(self.objectness_saliency.clone()),
        Retained::cast_unchecked::<VNRequest>(self.horizon.clone()),
        Retained::cast_unchecked::<VNRequest>(self.document_segments.clone()),
        Retained::cast_unchecked::<VNRequest>(self.aesthetics.clone()),
      ]);

      handler
        .performRequests_onImageData_error(&requests, data)
        .map_err(|e| {
          // Route NSError's localizedDescription through the bounded
          // FFI-string helper so a pathological error message cannot
          // drive the allocator into the abort path while the worker
          // is already trying to report a failure.
          let raw = e.localizedDescription();
          let message: SmolStr = ffi_nsstring_to_smolstr(&raw).unwrap_or_else(|| {
            SmolStr::new_static("apple-vision request failed (description elided)")
          });
          apple_vision_error(ErrorCode::AppleVisionRequestFailed, message)
        })
    }
  }
}

#[cfg(target_vendor = "apple")]
impl VisionAnalyzer {
  /// Creates a new Apple Vision analyzer with the specified options.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn new(opts: ServiceOptions) -> Self {
    Self {
      requests: VisionRequests::new(opts.clone()),
      opts,
    }
  }

  #[cfg(feature = "tracing")]
  #[allow(dead_code)] // called from the (currently commented) service-framework block
  fn log_request_revisions(&self, svc: &'static str, worker_id: usize) {
    unsafe {
      tracing::info!(
        service = svc,
        worker = worker_id,
        classify_rev = self.requests.classify.revision(),
        face_rectangles_rev = self.requests.face_rectangles.revision(),
        face_landmarks_rev = self.requests.face_landmarks.revision(),
        face_quality_rev = self.requests.face_quality.revision(),
        human_rectangles_rev = self.requests.human_rectangles.revision(),
        body_pose_rev = self.requests.body_pose.revision(),
        body_pose_3d_rev = self.requests.body_pose_3d.revision(),
        hand_pose_rev = self.requests.hand_pose.revision(),
        animals_rev = self.requests.animals.revision(),
        animal_body_pose_rev = self.requests.animal_body_pose.revision(),
        person_instance_mask_rev = self.requests.person_instance_mask.revision(),
        person_segmentation_rev = self.requests.person_segmentation.revision(),
        text_rev = self.requests.text.revision(),
        barcodes_rev = self.requests.barcodes.revision(),
        attention_saliency_rev = self.requests.attention_saliency.revision(),
        objectness_saliency_rev = self.requests.objectness_saliency.revision(),
        horizon_rev = self.requests.horizon.revision(),
        document_segments_rev = self.requests.document_segments.revision(),
        aesthetics_rev = self.requests.aesthetics.revision(),
        "initialized pinned Apple Vision request revisions"
      );
    }
  }

  /// Run every Apple Vision request configured at construction time against
  /// the supplied JPEG bytes and gather the resulting detections into a
  /// fully-populated [`Keyframe`].
  ///
  /// `scene_id`, `keyframe_id`, `pts`, `dimensions`, and `extractor` are
  /// supplied by the caller and attached verbatim to the returned
  /// `Keyframe`; the engine does not derive or generate identifiers or
  /// frame metadata itself. The widened signature (vs. the pre-domain
  /// shape that only took the two ids) is required by
  /// `mediaschema::Keyframe::try_new`, which enforces non-nil ids,
  /// positive `Dimensions`, a `pts` `Timestamp`, and a
  /// `KeyframeExtractor` tag at construction time.
  pub fn analyze_keyframe(
    &self,
    scene_id: Id,
    keyframe_id: Id,
    pts: Timestamp,
    dimensions: Dimensions,
    extractor: KeyframeExtractor,
    jpeg_data: &[u8],
  ) -> Result<Keyframe, ErrorInfo> {
    // Input-byte budget — refuse oversized payloads BEFORE
    // Foundation copies them into an NSData and doubles peak
    // memory. Surface as a structured error so the orchestrator
    // can decide whether to retry, log, or escalate (codex R17 F1).
    if jpeg_data.len() > MAX_INPUT_IMAGE_BYTES {
      return Err(apple_vision_error(
        ErrorCode::AppleVisionRequestFailed,
        SmolStr::new_static("input image exceeds MAX_INPUT_IMAGE_BYTES"),
      ));
    }
    // Construct the keyframe shell BEFORE running Vision so the
    // domain `try_new` invariants (non-nil ids + positive
    // dimensions) surface as structured `ErrorInfo` before we
    // perform the expensive image work.
    let keyframe =
      Keyframe::try_new(keyframe_id, scene_id, pts, dimensions, extractor).map_err(|e| {
        apple_vision_error(
          ErrorCode::AppleVisionRequestFailed,
          SmolStr::from(format!("keyframe construction failed: {e}")),
        )
      })?;
    objc2::rc::autoreleasepool(|_| {
      let ns_data = NSData::with_bytes(jpeg_data);
      let handler = unsafe { VNSequenceRequestHandler::new() };
      self.requests.perform(&handler, &ns_data)?;

      // Shared mask budgets — both `extract_person_instance_masks`
      // and `extract_person_segmentation_masks` charge against the
      // SAME per-frame totals (count, bytes, AND attempts) so the
      // cap is enforced across both surfaces and across both the
      // success and failure paths (codex R14 F1 + R15).
      let mut mask_total_bytes: usize = 0;
      let mut mask_total_count: usize = 0;
      let mut mask_total_attempts: usize = 0;
      let instance_masks = self.extract_person_instance_masks(
        &mut mask_total_bytes,
        &mut mask_total_count,
        &mut mask_total_attempts,
      );
      let segmentation_masks = self.extract_person_segmentation_masks(
        &mut mask_total_bytes,
        &mut mask_total_count,
        &mut mask_total_attempts,
      );

      Ok(
        keyframe
          .with_classifications(self.extract_classifications())
          .with_humans(
            HumanAnalysis::new()
              .with_subjects(self.extract_human_subjects())
              .with_faces(self.extract_faces())
              .with_face_rectangles(self.extract_face_rectangles())
              .with_face_landmarks(self.extract_face_landmarks())
              .with_body_poses(self.extract_body_poses())
              .with_hand_poses(self.extract_hand_poses())
              .with_body_poses_3d(self.extract_body_poses_3d())
              .with_instance_masks(instance_masks)
              .with_segmentation_masks(segmentation_masks),
          )
          .with_animals(
            AnimalAnalysis::new()
              .with_subjects(self.extract_animal_subjects())
              .with_body_poses(self.extract_animal_body_poses()),
          )
          .with_text_detections(self.extract_text_detections())
          .with_barcodes(self.extract_barcodes())
          .with_attention_saliency(self.extract_attention_saliency())
          .with_objectness_saliency(self.extract_objectness_saliency())
          .with_horizon(self.extract_horizon())
          .with_document_segments(self.extract_document_segments())
          .with_aesthetics(self.extract_aesthetics()),
      )
    })
  }

  fn extract_classifications(&self) -> Vec<Detection> {
    let opts = self.opts.classifications();
    let Some(results) = (unsafe { self.requests.classify.results() }) else {
      return Vec::new();
    };

    // Effective cap composes user-configured + hard ceiling so
    // with_capacity, take, and the emission guard all bound to
    // the SAME value (no `Vec::push` reallocation past the cap).
    let cap = effective_results_cap(opts.max_results());
    let mut tags = Vec::with_capacity(cap);
    for obs in results.iter().take(cap) {
      if tags.len() >= cap {
        break;
      }
      let Some(confidence) =
        sanitize_confidence(unsafe { obs.confidence() }, opts.min_confidence())
      else {
        continue;
      };

      let identifier = unsafe { obs.identifier() };
      let Some(label) = ffi_nsstring_to_smolstr(&identifier) else {
        continue;
      };
      let label = normalize_classification_label(label);
      if !label.is_empty()
        && let Ok(detection) = Detection::try_new(label, confidence)
      {
        tags.push(detection);
      }
    }

    tags
  }

  fn extract_faces(&self) -> Vec<FaceDetection> {
    let Some(results) = (unsafe { self.requests.face_quality.results() }) else {
      return Vec::new();
    };
    let opts = self.opts.face_capture();

    let mut faces = Vec::with_capacity(results.len().min(MAX_VISION_RESULTS_PER_FRAME));
    for obs in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      let Some(confidence) =
        sanitize_confidence(unsafe { obs.confidence() }, opts.min_confidence())
      else {
        continue;
      };
      // See `sanitize_capture_quality` for the three-state policy
      // (absent → 0.0, finite → pass-through, non-finite → drop).
      let Some(capture_quality) =
        sanitize_capture_quality(unsafe { obs.faceCaptureQuality() }.map(|q| q.floatValue()))
      else {
        continue;
      };
      if capture_quality < opts.min_capture_quality() {
        continue;
      }

      let Some(bbox) = vision_bbox_to_schema(unsafe { obs.boundingBox() }.standardize()) else {
        continue;
      };
      let roll = unsafe { obs.roll() }
        .map(|v| v.floatValue())
        .and_then(finite_f32)
        .unwrap_or(0.0);
      let yaw = unsafe { obs.yaw() }
        .map(|v| v.floatValue())
        .and_then(finite_f32)
        .unwrap_or(0.0);
      let pitch = unsafe { obs.pitch() }
        .map(|v| v.floatValue())
        .and_then(finite_f32)
        .unwrap_or(0.0);
      if let Ok(face) = FaceDetection::try_new(bbox, confidence, capture_quality, roll, yaw, pitch)
      {
        faces.push(face);
      }
    }

    faces
  }

  fn extract_face_rectangles(&self) -> Vec<FaceDetection> {
    let Some(results) = (unsafe { self.requests.face_rectangles.results() }) else {
      return Vec::new();
    };
    let opts = self.opts.face_rectangles();

    let mut faces = Vec::with_capacity(results.len().min(MAX_VISION_RESULTS_PER_FRAME));
    for obs in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      let Some(confidence) =
        sanitize_confidence(unsafe { obs.confidence() }, opts.min_confidence())
      else {
        continue;
      };

      let Some(bbox) = vision_bbox_to_schema(unsafe { obs.boundingBox() }.standardize()) else {
        continue;
      };
      let roll = unsafe { obs.roll() }
        .map(|v| v.floatValue())
        .and_then(finite_f32)
        .unwrap_or(0.0);
      let yaw = unsafe { obs.yaw() }
        .map(|v| v.floatValue())
        .and_then(finite_f32)
        .unwrap_or(0.0);
      let pitch = unsafe { obs.pitch() }
        .map(|v| v.floatValue())
        .and_then(finite_f32)
        .unwrap_or(0.0);
      // `face_rectangles` carries no capture quality from Vision —
      // default to 0.0 (the type does not range-validate it).
      if let Ok(face) = FaceDetection::try_new(bbox, confidence, 0.0, roll, yaw, pitch) {
        faces.push(face);
      }
    }

    faces
  }

  fn extract_face_landmarks(&self) -> Vec<FaceLandmarksDetection> {
    let Some(results) = (unsafe { self.requests.face_landmarks.results() }) else {
      return Vec::new();
    };
    let opts = self.opts.face_landmarks();

    let mut detections = Vec::with_capacity(results.len().min(MAX_VISION_RESULTS_PER_FRAME));
    // Per-frame budgets:
    // - `total_points_remaining` — emission budget; tentative-
    //   committed (decremented in a shadow during region extraction
    //   and applied to the master only when the detection survives
    //   every gate).
    // - `total_landmark_attempts` — attempt budget; immediately
    //   committed every time `push_face_landmark_region` visits a
    //   region's slice, regardless of whether the parent detection
    //   ultimately survives. Bounds the FAILURE-PATH work that the
    //   emission budget alone could not catch (codex R17 F1, same
    //   policy as `MAX_TOTAL_MASK_ATTEMPTS_PER_FRAME`).
    let mut total_points_remaining: usize = MAX_FACE_LANDMARK_POINTS_PER_FRAME;
    let mut total_landmark_attempts: usize = 0;
    for obs in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      if total_points_remaining == 0
        || total_landmark_attempts >= MAX_FACE_LANDMARK_ATTEMPTS_PER_FRAME
      {
        break;
      }
      let Some(landmarks) = (unsafe { obs.landmarks() }) else {
        continue;
      };
      let Some(confidence) =
        sanitize_confidence(unsafe { landmarks.confidence() }, opts.min_confidence())
      else {
        continue;
      };

      // Capture the face's Vision-coordinate bbox BEFORE the
      // schema-side flip+clamp so we can project landmark points
      // through it. Vision returns landmark points normalized to the
      // face bbox (not the image), per
      // `VNImagePointForFaceLandmarkPoint(p, faceBBox, w, h)` =
      // `(faceBBox.x + p.x * faceBBox.width,
      //   faceBBox.y + p.y * faceBBox.height)`.
      let face_rect_vision = unsafe { obs.boundingBox() }.standardize();
      // Validate the face bbox BEFORE walking landmarks so an
      // obviously-invalid observation does not spend the landmark
      // attempt budget (codex R17 F1 sub-rec). Re-using the same
      // schema-conversion guard the post-extraction commit uses.
      if vision_bbox_to_schema(face_rect_vision).is_none() {
        continue;
      }

      // Tentative emission budget — commit point-budget consumption
      // ONLY after the detection survives every gate. Attempt budget
      // is committed immediately by the helper.
      let mut tentative_remaining = total_points_remaining;
      let regions = extract_face_landmark_regions(
        &landmarks,
        face_rect_vision,
        &mut tentative_remaining,
        &mut total_landmark_attempts,
      );
      if regions.len() < opts.min_region_count() {
        continue;
      }

      let Some(bbox) = vision_bbox_to_schema(face_rect_vision) else {
        continue;
      };
      let Ok(detection) = FaceLandmarksDetection::try_new(bbox, confidence, regions) else {
        // The confidence has already been sanitised; a failure here
        // would be a domain-validator regression rather than real
        // Vision input — skip rather than abort the frame.
        continue;
      };
      // Commit the budget — the detection is being pushed.
      total_points_remaining = tentative_remaining;
      detections.push(detection);
    }

    detections
  }

  fn extract_human_subjects(&self) -> Vec<SubjectDetection> {
    let Some(results) = (unsafe { self.requests.human_rectangles.results() }) else {
      return Vec::new();
    };
    let opts = self.opts.human_subjects();

    let mut humans = Vec::with_capacity(results.len().min(MAX_VISION_RESULTS_PER_FRAME));
    for obs in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      let Some(confidence) =
        sanitize_confidence(unsafe { obs.confidence() }, opts.min_confidence())
      else {
        continue;
      };

      let Some(bbox) = vision_bbox_to_schema(unsafe { obs.boundingBox() }.standardize()) else {
        continue;
      };
      let Ok(detection) = Detection::try_new(SmolStr::new_static("person"), confidence) else {
        continue;
      };
      humans.push(SubjectDetection::new(detection, bbox));
    }

    humans
  }

  fn extract_body_poses(&self) -> Vec<BodyPoseDetection> {
    let Some(results) = (unsafe { self.requests.body_pose.results() }) else {
      return Vec::new();
    };

    let mut body_poses = Vec::with_capacity(results.len().min(MAX_VISION_RESULTS_PER_FRAME));
    for obs in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      let Ok(points_by_joint) = (unsafe {
        obs.recognizedPointsForJointsGroupName_error(VNHumanBodyPoseObservationJointsGroupNameAll)
      }) else {
        continue;
      };

      // Bound the dictionary materialisation: `to_vecs()` allocates
      // two `Vec`s sized to `points_by_joint.len()`, which is FFI-
      // reported. Drop the pose entirely if the joint count
      // exceeds `MAX_POSE_JOINTS` rather than risking an allocator
      // abort on a corrupted/adversarial Vision dictionary.
      if points_by_joint.len() > MAX_POSE_JOINTS {
        continue;
      }
      let (joint_names, points) = points_by_joint.to_vecs();
      let mut joints = Vec::with_capacity(points.len());
      let mut min_x = f32::INFINITY;
      let mut min_y = f32::INFINITY;
      let mut max_x = f32::NEG_INFINITY;
      let mut max_y = f32::NEG_INFINITY;

      for (joint_name, point) in joint_names.into_iter().zip(points) {
        let Some(name) = ffi_nsstring_to_smolstr(&joint_name) else {
          continue;
        };
        if name.is_empty() {
          continue;
        }

        // Vision normalized points are lower-left origin; flip y for the
        // top-left schema convention before recording the joint or
        // deriving the bbox. A non-finite raw coordinate is dropped at
        // the source — partial-joint lists are valid for body pose so
        // we skip just this joint, not the whole pose.
        let Some((x, y)) = vision_point_to_schema(unsafe { point.x() }, unsafe { point.y() })
        else {
          continue;
        };
        let Some(confidence) = sanitize_confidence(
          unsafe { point.confidence() },
          self.opts.body_pose().min_joint_confidence(),
        ) else {
          continue;
        };

        min_x = min_x.min(x);
        min_y = min_y.min(y);
        max_x = max_x.max(x);
        max_y = max_y.max(y);

        let Ok(joint) = BodyPoseJoint::try_new(name, x, y, confidence) else {
          continue;
        };
        joints.push(joint);
      }

      if joints.is_empty() {
        continue;
      }

      let Some(bbox) = pose_bbox_from_joint_bounds(min_x, min_y, max_x, max_y) else {
        // A pose with only one surviving joint (or perfectly colinear
        // joints) cannot produce a valid axis-aligned bbox; skip it
        // rather than emit a zero-extent box that the domain
        // validator would reject.
        continue;
      };
      // Observation confidence carries the per-pose score; sanitise it
      // against the same `[0, 1]` invariant. A non-finite observation
      // confidence cannot be emitted faithfully — drop the pose.
      let Some(pose_confidence) = sanitize_confidence(unsafe { obs.confidence() }, 0.0) else {
        continue;
      };

      joints.sort_by(|lhs, rhs| lhs.name().cmp(rhs.name()));
      if let Ok(pose) = BodyPoseDetection::try_new(bbox, pose_confidence, joints) {
        body_poses.push(pose);
      }
    }

    body_poses
  }

  fn extract_body_poses_3d(&self) -> Vec<BodyPose3DDetection> {
    catch_unwind(AssertUnwindSafe(|| {
      let Some(results) = (unsafe { self.requests.body_pose_3d.results() }) else {
        return Vec::new();
      };
      let Some(group_name) = (unsafe { VNHumanBodyPose3DObservationJointsGroupNameAll }) else {
        return Vec::new();
      };

      let mut body_poses = Vec::with_capacity(results.len().min(MAX_VISION_RESULTS_PER_FRAME));
      for obs in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
        let Ok(points_by_joint) =
          (unsafe { obs.recognizedPointsForJointsGroupName_error(group_name) })
        else {
          continue;
        };

        // Bound the dictionary materialisation: `to_vecs()` allocates
        // two `Vec`s sized to `points_by_joint.len()`, which is FFI-
        // reported. Drop the pose entirely if the joint count
        // exceeds `MAX_POSE_JOINTS` rather than risking an allocator
        // abort on a corrupted/adversarial Vision dictionary.
        if points_by_joint.len() > MAX_POSE_JOINTS {
          continue;
        }
        let (joint_names, points) = points_by_joint.to_vecs();
        let mut joints = Vec::with_capacity(points.len());

        for (joint_name, point) in joint_names.into_iter().zip(points) {
          let Some(name) = ffi_nsstring_to_smolstr(&joint_name) else {
            continue;
          };
          if name.is_empty() {
            continue;
          }

          let Some((x, y, z)) = extract_body_pose_3d_coordinates(&point) else {
            continue;
          };
          let raw_confidence: f32 = unsafe { objc2::msg_send![&*point, confidence] };
          let Some(confidence) = sanitize_confidence(
            raw_confidence,
            self.opts.body_pose_3d().min_joint_confidence(),
          ) else {
            continue;
          };

          let Ok(joint) = BodyPose3DJoint::try_new(name, x, y, z, confidence) else {
            continue;
          };
          joints.push(joint);
        }

        if joints.is_empty() {
          continue;
        }
        let Some(pose_confidence) = sanitize_confidence(unsafe { obs.confidence() }, 0.0) else {
          continue;
        };

        joints.sort_by(|lhs, rhs| lhs.name().cmp(rhs.name()));
        // See `sanitize_body_height_pair` — couples the
        // body_height substitution with the height_estimation enum
        // so `(0.0, UNKNOWN)` is the only fallback for non-finite
        // readings.
        let mapped_estimation =
          map_body_pose_3d_height_estimation(unsafe { obs.heightEstimation() });
        let (body_height, height_estimation) =
          sanitize_body_height_pair(unsafe { obs.bodyHeight() }, mapped_estimation);
        if let Ok(pose) =
          BodyPose3DDetection::try_new(pose_confidence, body_height, height_estimation, joints)
        {
          body_poses.push(pose);
        }
      }

      body_poses
    }))
    .unwrap_or_else(|_| {
      #[cfg(feature = "tracing")]
      tracing::warn!("caught panic while extracting human body pose 3D; returning empty result");
      Vec::new()
    })
  }

  fn extract_hand_poses(&self) -> Vec<HandPoseDetection> {
    let Some(results) = (unsafe { self.requests.hand_pose.results() }) else {
      return Vec::new();
    };

    let mut hand_poses = Vec::with_capacity(results.len().min(MAX_VISION_RESULTS_PER_FRAME));
    for obs in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      let Ok(points_by_joint) = (unsafe {
        obs.recognizedPointsForJointsGroupName_error(VNHumanHandPoseObservationJointsGroupNameAll)
      }) else {
        continue;
      };

      // Bound the dictionary materialisation: `to_vecs()` allocates
      // two `Vec`s sized to `points_by_joint.len()`, which is FFI-
      // reported. Drop the pose entirely if the joint count
      // exceeds `MAX_POSE_JOINTS` rather than risking an allocator
      // abort on a corrupted/adversarial Vision dictionary.
      if points_by_joint.len() > MAX_POSE_JOINTS {
        continue;
      }
      let (joint_names, points) = points_by_joint.to_vecs();
      let mut joints = Vec::with_capacity(points.len());
      let mut min_x = f32::INFINITY;
      let mut min_y = f32::INFINITY;
      let mut max_x = f32::NEG_INFINITY;
      let mut max_y = f32::NEG_INFINITY;

      for (joint_name, point) in joint_names.into_iter().zip(points) {
        let Some(name) = ffi_nsstring_to_smolstr(&joint_name) else {
          continue;
        };
        if name.is_empty() {
          continue;
        }

        // Vision normalized points are lower-left origin; flip y for
        // the top-left schema convention. A non-finite raw coordinate
        // is dropped at the source — partial-joint hand lists are
        // valid so we skip only this joint.
        let Some((x, y)) = vision_point_to_schema(unsafe { point.x() }, unsafe { point.y() })
        else {
          continue;
        };
        let Some(confidence) = sanitize_confidence(
          unsafe { point.confidence() },
          self.opts.hand_pose().min_joint_confidence(),
        ) else {
          continue;
        };

        min_x = min_x.min(x);
        min_y = min_y.min(y);
        max_x = max_x.max(x);
        max_y = max_y.max(y);

        let Ok(joint) = BodyPoseJoint::try_new(name, x, y, confidence) else {
          continue;
        };
        joints.push(joint);
      }

      if joints.is_empty() {
        continue;
      }

      let Some(bbox) = pose_bbox_from_joint_bounds(min_x, min_y, max_x, max_y) else {
        continue;
      };
      let Some(pose_confidence) = sanitize_confidence(unsafe { obs.confidence() }, 0.0) else {
        continue;
      };

      joints.sort_by(|lhs, rhs| lhs.name().cmp(rhs.name()));
      if let Ok(pose) = HandPoseDetection::try_new(
        bbox,
        pose_confidence,
        map_hand_chirality(unsafe { obs.chirality() }),
        joints,
      ) {
        hand_poses.push(pose);
      }
    }

    hand_poses
  }

  fn extract_person_instance_masks(
    &self,
    total_mask_bytes: &mut usize,
    total_mask_count: &mut usize,
    total_mask_attempts: &mut usize,
  ) -> Vec<PersonInstanceMaskDetection> {
    let Some(results) = (unsafe { self.requests.person_instance_mask.results() }) else {
      return Vec::new();
    };
    let opts = self.opts.person_instance_masks();

    // Per-frame budgets — count AND cumulative payload bytes — are
    // SHARED across both mask extractors via the caller's mutable
    // counters, so the cap holds across the keyframe as a whole.
    let mut masks = Vec::new();
    'outer: for observation in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      if *total_mask_count >= MAX_TOTAL_MASKS_PER_FRAME
        || *total_mask_bytes >= MAX_TOTAL_MASK_BYTES_PER_FRAME
      {
        break;
      }
      let Some(confidence) =
        sanitize_confidence(unsafe { observation.confidence() }, opts.min_confidence())
      else {
        continue;
      };

      let instances = unsafe { observation.allInstances() };
      let mut instance_index = instances.firstIndex();
      // Track ATTEMPTS (every iteration), not just successful
      // emissions — otherwise a corrupted NSIndexSet whose entries
      // all fail generation/copy/u32 conversion can drive unbounded
      // traversal at full Vision-call cost per iteration
      // (codex R14 F2).
      let mut visited = 0usize;
      let inner_cap = opts
        .max_instances_per_observation()
        .min(MAX_NESTED_INSTANCES_PER_OBSERVATION);
      while instance_index != NSNotFound as usize {
        if visited >= inner_cap {
          break;
        }
        visited += 1;
        // Per-frame budget check: stop the entire extraction once
        // any ceiling is reached (success-path counters OR the
        // failure-path attempt counter from codex R15).
        if *total_mask_count >= MAX_TOTAL_MASKS_PER_FRAME
          || *total_mask_bytes >= MAX_TOTAL_MASK_BYTES_PER_FRAME
          || *total_mask_attempts >= MAX_TOTAL_MASK_ATTEMPTS_PER_FRAME
        {
          break 'outer;
        }

        // Validate u32-fit of the instance index BEFORE generating
        // or copying the mask — overflowing here would force a
        // costly retry per-iteration; cheaper to skip up-front.
        let Ok(wire_instance_index) = u32::try_from(instance_index) else {
          instance_index = instances.indexGreaterThanIndex(instance_index);
          continue;
        };

        // Charge the per-frame attempt budget BEFORE the
        // expensive Vision call. Even if generation fails (Apple
        // returns Err), it still costs Vision time + intermediate
        // alloc, so the failure path must be frame-budgeted
        // (codex R15 F1).
        *total_mask_attempts = total_mask_attempts.saturating_add(1);
        let selected_instances = NSIndexSet::indexSetWithIndex(instance_index);
        let Ok(mask_buffer) =
          (unsafe { observation.generateMaskForInstances_error(&selected_instances) })
        else {
          instance_index = instances.indexGreaterThanIndex(instance_index);
          continue;
        };

        // Pre-allocation budget check: pass the remaining cumulative
        // budget into the copier so it rejects the mask BEFORE
        // allocating if the packed size would overshoot.
        let remaining_budget = MAX_TOTAL_MASK_BYTES_PER_FRAME.saturating_sub(*total_mask_bytes);
        let Some((bbox, dimensions, data)) =
          copy_instance_mask_buffer(&mask_buffer, remaining_budget)
        else {
          instance_index = instances.indexGreaterThanIndex(instance_index);
          continue;
        };

        let data_len = data.len();
        match PersonInstanceMaskDetection::try_new(
          bbox,
          confidence,
          wire_instance_index,
          dimensions,
          data,
        ) {
          Ok(mask) => {
            *total_mask_bytes = total_mask_bytes.saturating_add(data_len);
            *total_mask_count = total_mask_count.saturating_add(1);
            masks.push(mask);
          }
          Err(_) => {
            // Validator rejected — `dimensions` already verified
            // > 0 and `data` non-empty before reaching here, so
            // this only triggers on a future invariant addition.
          }
        }

        instance_index = instances.indexGreaterThanIndex(instance_index);
      }
    }

    masks
  }

  fn extract_person_segmentation_masks(
    &self,
    total_mask_bytes: &mut usize,
    total_mask_count: &mut usize,
    total_mask_attempts: &mut usize,
  ) -> Vec<PersonSegmentationMask> {
    let Some(results) = (unsafe { self.requests.person_segmentation.results() }) else {
      return Vec::new();
    };
    let opts = self.opts.person_segmentation_masks();

    // Shared per-frame mask budget — counters owned by the caller,
    // also charged by `extract_person_instance_masks`. The cumulative
    // cap holds across BOTH extractors, not per-extractor (codex
    // R14 F1).
    let mut masks = Vec::new();
    for observation in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      if *total_mask_count >= MAX_TOTAL_MASKS_PER_FRAME
        || *total_mask_bytes >= MAX_TOTAL_MASK_BYTES_PER_FRAME
        || *total_mask_attempts >= MAX_TOTAL_MASK_ATTEMPTS_PER_FRAME
      {
        break;
      }
      let Some(confidence) =
        sanitize_confidence(unsafe { observation.confidence() }, opts.min_confidence())
      else {
        continue;
      };

      // Charge the per-frame attempt budget before pulling the
      // pixel buffer and running the copy. Even a failing copy
      // path costs FFI traversal + bounded alloc, so the failure
      // path must be frame-budgeted (codex R15 F1, same policy as
      // the instance-mask extractor).
      *total_mask_attempts = total_mask_attempts.saturating_add(1);
      let pixel_buffer = unsafe { observation.pixelBuffer() };
      // Pre-allocation budget check: refuse the mask before alloc
      // if it would overshoot the per-frame cumulative budget.
      let remaining_budget = MAX_TOTAL_MASK_BYTES_PER_FRAME.saturating_sub(*total_mask_bytes);
      let Some((bbox, dimensions, data)) =
        copy_instance_mask_buffer(&pixel_buffer, remaining_budget)
      else {
        continue;
      };

      let data_len = data.len();
      if let Ok(mask) = PersonSegmentationMask::try_new(bbox, confidence, dimensions, data) {
        *total_mask_bytes = total_mask_bytes.saturating_add(data_len);
        *total_mask_count = total_mask_count.saturating_add(1);
        masks.push(mask);
      }
    }

    masks
  }

  fn extract_animal_subjects(&self) -> Vec<SubjectDetection> {
    unsafe {
      let Some(results) = self.requests.animals.results() else {
        return Vec::new();
      };

      let mut animals = Vec::with_capacity(MAX_TOTAL_ANIMAL_SUBJECTS_PER_FRAME);
      'outer: for obs in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
        if animals.len() >= MAX_TOTAL_ANIMAL_SUBJECTS_PER_FRAME {
          break;
        }
        let labels = obs.labels();
        // Per-frame total cap: animal subjects can't multiply across
        // outer × inner past the hard ceiling. The inner per-obs
        // take cap remains so a single hostile observation can't
        // exhaust the budget on its own either.
        for label in labels.iter().take(MAX_NESTED_LABELS_PER_OBSERVATION) {
          if animals.len() >= MAX_TOTAL_ANIMAL_SUBJECTS_PER_FRAME {
            break 'outer;
          }
          let Some(confidence) =
            sanitize_confidence(label.confidence(), self.opts.animals().min_confidence())
          else {
            continue;
          };
          let identifier = label.identifier();
          let Some(id) = ffi_nsstring_to_smolstr(&identifier) else {
            continue;
          };
          if !id.is_empty()
            && let Some(bbox) = vision_bbox_to_schema(obs.boundingBox().standardize())
            && let Ok(detection) = Detection::try_new(id, confidence)
          {
            animals.push(SubjectDetection::new(detection, bbox));
          }
        }
      }

      animals
    }
  }

  fn extract_animal_body_poses(&self) -> Vec<BodyPoseDetection> {
    let Some(results) = (unsafe { self.requests.animal_body_pose.results() }) else {
      return Vec::new();
    };
    let Some(group_name) = (unsafe { VNAnimalBodyPoseObservationJointsGroupNameAll }) else {
      return Vec::new();
    };

    let mut body_poses = Vec::with_capacity(results.len().min(MAX_VISION_RESULTS_PER_FRAME));
    for obs in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      let Ok(points_by_joint) =
        (unsafe { obs.recognizedPointsForJointsGroupName_error(group_name) })
      else {
        continue;
      };

      // Bound the dictionary materialisation: `to_vecs()` allocates
      // two `Vec`s sized to `points_by_joint.len()`, which is FFI-
      // reported. Drop the pose entirely if the joint count
      // exceeds `MAX_POSE_JOINTS` rather than risking an allocator
      // abort on a corrupted/adversarial Vision dictionary.
      if points_by_joint.len() > MAX_POSE_JOINTS {
        continue;
      }
      let (joint_names, points) = points_by_joint.to_vecs();
      let mut joints = Vec::with_capacity(points.len());
      let mut min_x = f32::INFINITY;
      let mut min_y = f32::INFINITY;
      let mut max_x = f32::NEG_INFINITY;
      let mut max_y = f32::NEG_INFINITY;

      for (joint_name, point) in joint_names.into_iter().zip(points) {
        let Some(name) = ffi_nsstring_to_smolstr(&joint_name) else {
          continue;
        };
        if name.is_empty() {
          continue;
        }

        // Vision normalized points are lower-left origin; flip y for
        // the top-left schema convention. A non-finite raw coordinate
        // is dropped at the source — partial-joint animal-pose lists
        // are valid so we skip only this joint.
        let Some((x, y)) = vision_point_to_schema(unsafe { point.x() }, unsafe { point.y() })
        else {
          continue;
        };
        let Some(confidence) = sanitize_confidence(
          unsafe { point.confidence() },
          self.opts.animal_pose().min_joint_confidence(),
        ) else {
          continue;
        };

        min_x = min_x.min(x);
        min_y = min_y.min(y);
        max_x = max_x.max(x);
        max_y = max_y.max(y);

        let Ok(joint) = BodyPoseJoint::try_new(name, x, y, confidence) else {
          continue;
        };
        joints.push(joint);
      }

      if joints.is_empty() {
        continue;
      }

      let Some(bbox) = pose_bbox_from_joint_bounds(min_x, min_y, max_x, max_y) else {
        continue;
      };
      let Some(pose_confidence) = sanitize_confidence(unsafe { obs.confidence() }, 0.0) else {
        continue;
      };

      joints.sort_by(|lhs, rhs| lhs.name().cmp(rhs.name()));
      if let Ok(pose) = BodyPoseDetection::try_new(bbox, pose_confidence, joints) {
        body_poses.push(pose);
      }
    }

    body_poses
  }

  fn extract_text_detections(&self) -> Vec<TextDetection> {
    let Some(results) = self.requests.text.results() else {
      return Vec::new();
    };

    // Per-frame total cap on emitted text detections — bounds the
    // outer × inner candidate product that codex R13 surfaced.
    let mut text_detections = Vec::with_capacity(MAX_TOTAL_TEXT_DETECTIONS_PER_FRAME);
    'outer: for obs in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      if text_detections.len() >= MAX_TOTAL_TEXT_DETECTIONS_PER_FRAME {
        break;
      }
      // Bound the requested candidate count to the hard per-observation cap
      // — Apple's topCandidates allocates an NSArray sized to the argument.
      let candidate_cap = self
        .opts
        .text()
        .max_candidates_per_observation()
        .min(MAX_TEXT_CANDIDATES_PER_OBSERVATION);
      let candidates = obs.topCandidates(candidate_cap);
      for candidate in candidates.iter().take(candidate_cap) {
        if text_detections.len() >= MAX_TOTAL_TEXT_DETECTIONS_PER_FRAME {
          break 'outer;
        }
        // Bound the candidate string at MAX_FFI_STRING_BYTES before
        // routing through `to_smolstr` so a corrupted/adversarial
        // NSString length cannot drive the allocator into the abort
        // path.
        let raw_string = candidate.string();
        let Some(text) = ffi_nsstring_to_smolstr(&raw_string) else {
          continue;
        };
        if text.len() < self.opts.text().min_text_len() {
          continue;
        }
        let Some(confidence) = sanitize_confidence(candidate.confidence(), 0.0) else {
          continue;
        };
        if let Some(bbox) = vision_bbox_to_schema(unsafe { obs.boundingBox() }.standardize())
          && let Ok(detection) = TextDetection::try_new(text, confidence, bbox)
        {
          text_detections.push(detection);
        }
      }
    }
    text_detections
  }

  fn extract_barcodes(&self) -> Vec<BarcodeDetection> {
    let Some(results) = (unsafe { self.requests.barcodes.results() }) else {
      return Vec::new();
    };
    let opts = self.opts.barcodes();

    let mut barcodes = Vec::with_capacity(results.len().min(MAX_VISION_RESULTS_PER_FRAME));
    for obs in results.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      let Some(confidence) =
        sanitize_confidence(unsafe { obs.confidence() }, opts.min_confidence())
      else {
        continue;
      };

      if let Some(payload) = unsafe { obs.payloadStringValue() } {
        // Bound the payload + symbology at MAX_FFI_STRING_BYTES.
        let Some(s) = ffi_nsstring_to_smolstr(&payload) else {
          continue;
        };
        if s.len() >= opts.min_payload_len()
          && let Some(bbox) = vision_bbox_to_schema(unsafe { obs.boundingBox() }.standardize())
        {
          let raw_sym = unsafe { obs.symbology() };
          let Some(symbology) = ffi_nsstring_to_smolstr(&raw_sym) else {
            continue;
          };
          if let Ok(barcode) = BarcodeDetection::try_new(s, symbology, confidence, bbox) {
            barcodes.push(barcode);
          }
        }
      }
    }
    barcodes
  }

  fn extract_attention_saliency(&self) -> Vec<SaliencyRegion> {
    self.extract_saliency_regions(
      unsafe { self.requests.attention_saliency.results() },
      self.opts.attention_saliency(),
    )
  }

  fn extract_objectness_saliency(&self) -> Vec<SaliencyRegion> {
    self.extract_saliency_regions(
      unsafe { self.requests.objectness_saliency.results() },
      self.opts.objectness_saliency(),
    )
  }

  fn extract_saliency_regions(
    &self,
    observations: Option<Retained<NSArray<VNSaliencyImageObservation>>>,
    opts: AppleVisionSaliencyOptions,
  ) -> Vec<SaliencyRegion> {
    let Some(observations) = observations else {
      return Vec::new();
    };

    // `total_cap` is the per-FRAME (not per-observation) cap.
    // Outer × inner emission must not exceed it. Track running
    // count across observations and stop the outer loop when the
    // budget is exhausted; `.iter().take(remaining)` on the inner
    // loop further bounds each observation's contribution.
    let total_cap = opts.max_regions().min(MAX_SALIENCY_REGIONS_PER_FRAME);
    let mut regions = Vec::with_capacity(total_cap);
    'outer: for observation in observations.iter().take(MAX_VISION_RESULTS_PER_FRAME) {
      if regions.len() >= total_cap {
        break;
      }
      let Some(objects) = (unsafe { observation.salientObjects() }) else {
        continue;
      };
      let remaining = total_cap - regions.len();
      for object in objects.iter().take(remaining) {
        if regions.len() >= total_cap {
          break 'outer;
        }
        let Some(confidence) =
          sanitize_confidence(unsafe { object.confidence() }, opts.min_confidence())
        else {
          continue;
        };

        let Some(bbox) = vision_bbox_to_schema(unsafe { object.boundingBox() }.standardize())
        else {
          continue;
        };
        let Ok(region) = SaliencyRegion::try_new(bbox, confidence) else {
          continue;
        };
        regions.push(region);
      }
    }
    regions
  }

  fn extract_horizon(&self) -> HorizonInfo {
    // Domain `HorizonInfo` has no `Default` impl — `try_new(0.0, 0.0)`
    // is the canonical "no detection" sentinel (both arguments are
    // trivially in-range, so the `try_new` cannot fail).
    let empty = HorizonInfo::try_new(0.0, 0.0).expect("zero confidence + zero angle is in range");
    let Some(results) = (unsafe { self.requests.horizon.results() }) else {
      return empty;
    };
    let Some(observation) = results.iter().next() else {
      return empty;
    };
    let Some(confidence) = sanitize_confidence(
      unsafe { observation.confidence() },
      self.opts.horizon().min_confidence(),
    ) else {
      return empty;
    };

    // Drop the horizon detection entirely if the angle is non-finite —
    // there is no sensible default for a horizon line and downstream
    // visualisation would render a bogus tilt.
    let Some(angle) = finite_f32(unsafe { observation.angle() } as f32) else {
      return empty;
    };
    HorizonInfo::try_new(angle, confidence).unwrap_or(empty)
  }

  fn extract_document_segments(&self) -> Vec<DocumentSegment> {
    let Some(results) = (unsafe { self.requests.document_segments.results() }) else {
      return Vec::new();
    };
    let opts = self.opts.document_segments();

    // Effective cap: user-configured max_segments AND hard ceiling.
    // with_capacity, take, and the emission guard all share `cap`.
    let cap = effective_results_cap(opts.max_segments());
    let mut segments = Vec::with_capacity(cap);
    for observation in results.iter().take(cap) {
      if segments.len() >= cap {
        break;
      }

      let Some(confidence) =
        sanitize_confidence(unsafe { observation.confidence() }, opts.min_confidence())
      else {
        continue;
      };

      // Vision's named corners ("topLeft" etc.) refer to image-space
      // orientation but use the framework's lower-left-origin coordinate
      // system, so each corner's `y` must be flipped to land in the
      // top-left schema convention. The naming still matches afterwards
      // (the corner with the smallest `y` is still the top edge).
      // A non-finite corner means the quad is geometrically meaningless
      // — drop the whole detection rather than fabricate edge-aligned
      // corners that downstream validation would accept as real.
      let (Some(top_left), Some(top_right), Some(bottom_left), Some(bottom_right)) = (
        vision_point_to_schema(
          unsafe { observation.topLeft() }.x,
          unsafe { observation.topLeft() }.y,
        ),
        vision_point_to_schema(
          unsafe { observation.topRight() }.x,
          unsafe { observation.topRight() }.y,
        ),
        vision_point_to_schema(
          unsafe { observation.bottomLeft() }.x,
          unsafe { observation.bottomLeft() }.y,
        ),
        vision_point_to_schema(
          unsafe { observation.bottomRight() }.x,
          unsafe { observation.bottomRight() }.y,
        ),
      ) else {
        continue;
      };

      // Even after per-corner clamping, the resulting quad can be
      // degenerate (coincident corners, zero shoelace area, or
      // self-intersecting) when Vision returned an off-screen segment
      // or near-collinear corners. `DocumentSegment::try_new` runs the
      // full geometry guards (collapsed corners, zero area, bow-tie /
      // inconsistent winding); a failure means the quad is not a real
      // document detection and the segment is dropped.
      let Ok(segment) =
        DocumentSegment::try_new(top_left, top_right, bottom_right, bottom_left, confidence)
      else {
        continue;
      };
      segments.push(segment);
    }

    segments
  }

  fn extract_aesthetics(&self) -> Aesthetics {
    // Domain `Aesthetics` has no `Default` impl — `new(0.0, false)`
    // is the canonical "no detection" sentinel.
    let empty = Aesthetics::new(0.0, false);
    let Some(results) = (unsafe { self.requests.aesthetics.results() }) else {
      return empty;
    };
    let Some(obs) = results.iter().next() else {
      return empty;
    };
    // `NaN < threshold` would fail open. Force a finite check at the
    // gate so a glitched aesthetics score collapses to the default
    // (no detection) instead of being silently admitted to the wire.
    let Some(overall_score) = finite_f32(unsafe { obs.overallScore() }) else {
      return empty;
    };
    if overall_score < self.opts.aesthetics().min_overall_score() {
      return empty;
    }

    Aesthetics::new(overall_score, unsafe { obs.isUtility() })
  }
}

#[cfg(target_vendor = "apple")]
fn normalize_classification_label(label: SmolStr) -> SmolStr {
  label.trim().to_ascii_lowercase_smolstr()
}

#[cfg(target_vendor = "apple")]
fn extract_body_pose_3d_coordinates(
  point: &VNHumanBodyRecognizedPoint3D,
) -> Option<(f32, f32, f32)> {
  let transform: SimdFloat4x4 = unsafe { objc2::msg_send![point, position] };
  let translation = transform.columns.get(3)?;
  let x = translation.0[0];
  let y = translation.0[1];
  let z = translation.0[2];
  if !(x.is_finite() && y.is_finite() && z.is_finite()) {
    return None;
  }
  Some((x, y, z))
}

#[cfg(target_vendor = "apple")]
fn map_hand_chirality(chirality: VNChirality) -> HandChirality {
  match chirality {
    VNChirality::Left => HandChirality::Left,
    VNChirality::Right => HandChirality::Right,
    _ => HandChirality::Unknown,
  }
}

/// Extract every named face-landmark region, projecting each point
/// from face-bbox-relative coordinates into image-normalized
/// coordinates (Vision lower-left) via `face_bbox_vision` before the
/// caller-side schema flip. Without this projection a non-full-frame
/// face emits landmarks in the wrong place but still passes `[0, 1]`
/// validation.
#[cfg(target_vendor = "apple")]
fn extract_face_landmark_regions(
  landmarks: &VNFaceLandmarks2D,
  face_bbox_vision: CGRect,
  total_points_remaining: &mut usize,
  total_landmark_attempts: &mut usize,
) -> Vec<FaceLandmarkRegion> {
  let mut regions = Vec::new();
  for (name, region) in [
    ("allPoints", unsafe { landmarks.allPoints() }),
    ("faceContour", unsafe { landmarks.faceContour() }),
    ("leftEye", unsafe { landmarks.leftEye() }),
    ("rightEye", unsafe { landmarks.rightEye() }),
    ("leftEyebrow", unsafe { landmarks.leftEyebrow() }),
    ("rightEyebrow", unsafe { landmarks.rightEyebrow() }),
    ("nose", unsafe { landmarks.nose() }),
    ("noseCrest", unsafe { landmarks.noseCrest() }),
    ("medianLine", unsafe { landmarks.medianLine() }),
    ("outerLips", unsafe { landmarks.outerLips() }),
    ("innerLips", unsafe { landmarks.innerLips() }),
    ("leftPupil", unsafe { landmarks.leftPupil() }),
    ("rightPupil", unsafe { landmarks.rightPupil() }),
  ] {
    if *total_points_remaining == 0
      || *total_landmark_attempts >= MAX_FACE_LANDMARK_ATTEMPTS_PER_FRAME
    {
      break;
    }
    push_face_landmark_region(
      &mut regions,
      name,
      region,
      face_bbox_vision,
      total_points_remaining,
      total_landmark_attempts,
    );
  }
  regions
}

#[cfg(target_vendor = "apple")]
fn push_face_landmark_region(
  regions: &mut Vec<FaceLandmarkRegion>,
  name: &'static str,
  region: Option<Retained<VNFaceLandmarkRegion2D>>,
  face_bbox_vision: CGRect,
  total_points_remaining: &mut usize,
  total_landmark_attempts: &mut usize,
) {
  if *total_points_remaining == 0
    || *total_landmark_attempts >= MAX_FACE_LANDMARK_ATTEMPTS_PER_FRAME
  {
    return;
  }
  let Some(region) = region else {
    return;
  };

  let point_count = unsafe { region.pointCount() };
  if point_count == 0 {
    return;
  }
  // Pre-validate the raw-slice preconditions
  // (count <= MAX_LANDMARK_POINTS AND count * size_of::<CGPoint>() <= isize::MAX)
  // BEFORE the unsafe slice construction. Same policy as
  // `validate_mask_dims_for_slice` and the FeaturePrint path —
  // every Vision boundary that builds a Rust slice from an FFI
  // pointer goes through a `validate_raw_slice_*` gate.
  if validate_raw_slice_elems::<CGPoint>(point_count, MAX_LANDMARK_POINTS).is_none() {
    return;
  }

  let points_ptr = unsafe { region.normalizedPoints() };
  if points_ptr.is_null() {
    return;
  }

  // Construct the unsafe slice to the CAPPED element count, not
  // the FFI-reported point_count: when remaining < point_count,
  // exposing the full slice to subsequent code would let
  // from_raw_parts trust more elements than we'll read (codex
  // R14 F4). The cap is `point_count.min(remaining_budget)` —
  // already validated against MAX_LANDMARK_POINTS above. Also
  // bound by the remaining attempt budget so we never visit more
  // points than the frame can afford to walk.
  let attempts_remaining =
    MAX_FACE_LANDMARK_ATTEMPTS_PER_FRAME.saturating_sub(*total_landmark_attempts);
  let region_cap = point_count
    .min(*total_points_remaining)
    .min(attempts_remaining);
  if region_cap == 0 {
    return;
  }
  // Charge the ATTEMPT budget for every point we're about to walk,
  // up front and unconditionally. Whether the points later survive
  // finite-checks or the parent detection survives its gates, the
  // walk itself is bounded by this budget (codex R17 F1).
  *total_landmark_attempts = total_landmark_attempts.saturating_add(region_cap);
  // SAFETY: `points_ptr` points at `point_count` valid `CGPoint`s
  // (Vision API contract). `region_cap <= point_count` and
  // `region_cap <= MAX_LANDMARK_POINTS` (verified via
  // `validate_raw_slice_elems::<CGPoint>` above), so the slice
  // length fits both the FFI buffer and the `isize::MAX` contract.
  let points = unsafe { std::slice::from_raw_parts(points_ptr, region_cap) };
  // Domain `FaceLandmarkRegion::try_new` stores points as
  // `(NormCoord, NormCoord)` pairs — pass raw `(f32, f32)` tuples
  // and let the validator handle the wrap. Every point is already
  // sanitised through `vision_point_to_schema` (finite + clamped to
  // `[0, 1]`), so the validator's `NormCoord::try_new` cannot reject.
  let mut emitted_points: Vec<(f32, f32)> = Vec::with_capacity(region_cap);
  for point in points.iter() {
    // Apple's convention: landmark points are normalized within the
    // face's normalized bbox (NOT the image). Project to image-
    // normalized Vision coordinates first, THEN route through
    // `vision_point_to_schema` for the top-left flip + clamp +
    // finite check. A non-finite raw or projected component drops
    // only the offending point; partial-point regions are still
    // meaningful.
    let projected = project_landmark_to_image(*point, face_bbox_vision);
    if let Some((x, y)) = vision_point_to_schema(projected.x, projected.y) {
      emitted_points.push((x, y));
    }
  }
  if emitted_points.is_empty() {
    return;
  }
  let emitted_len = emitted_points.len();
  let Ok(region) = FaceLandmarkRegion::try_new(name, emitted_points) else {
    return;
  };
  // Decrement the shared budget by the number of points actually
  // emitted (finite-rejected points don't consume budget).
  *total_points_remaining = total_points_remaining.saturating_sub(emitted_len);

  regions.push(region);
}

#[cfg(target_vendor = "apple")]
fn map_body_pose_3d_height_estimation(
  estimation: VNHumanBodyPose3DObservationHeightEstimation,
) -> BodyPose3DHeightEstimation {
  if estimation == VNHumanBodyPose3DObservationHeightEstimation::Measured {
    BodyPose3DHeightEstimation::Measured
  } else if estimation == VNHumanBodyPose3DObservationHeightEstimation::Reference {
    BodyPose3DHeightEstimation::Reference
  } else {
    BodyPose3DHeightEstimation::Unknown
  }
}

/// Copy a Vision mask `CVPixelBuffer` into a packed `Bytes` payload plus
/// a normalized bounding box of the foreground.
///
/// The returned payload is **always** 8 bits per pixel
/// (`width * height` bytes); Vision's two supported source formats
/// (`OneComponent32Float`, `OneComponent8`) are both normalised to
/// canonical u8 at the boundary so downstream consumers don't have
/// to disambiguate from the [`Dimensions`] metadata alone. f32 input
/// is mapped `v` → `(v.clamp(0.0, 1.0) * 255.0).round() as u8` with
/// non-finite values collapsing to `0` (background).
///
/// Returns `None` when the buffer is unlockable, has zero extent, a null
/// base address, an unsupported pixel format, fails one of the
/// stride/size sanity checks, or contains no foreground pixels (an
/// all-zero mask is represented by skipping the detection rather than
/// emitting one with a degenerate bbox). The lock is held via
/// [`CVPixelBufferLockGuard`] for the duration of the copy and is
/// released by `Drop` on every exit path — including a panic — so the
/// buffer cannot be left locked.
#[cfg(target_vendor = "apple")]
fn copy_instance_mask_buffer(
  pixel_buffer: &CVPixelBuffer,
  remaining_byte_budget: usize,
) -> Option<(BoundingBox, Dimensions, Bytes)> {
  let guard = CVPixelBufferLockGuard::lock(pixel_buffer, CVPixelBufferLockFlags::ReadOnly)?;
  copy_instance_mask_buffer_locked(guard.buffer(), remaining_byte_budget)
}

/// Internal worker that runs the locked copy and assembles the wire
/// payload. The caller is responsible for holding the
/// [`CVPixelBufferLockGuard`].
///
/// The returned payload is **always** 8 bits per pixel
/// (`width * height` bytes) regardless of the source pixel format.
/// Vision can emit either `kCVPixelFormatType_OneComponent32Float`
/// (4 bytes/pixel) or `kCVPixelFormatType_OneComponent8`
/// (1 byte/pixel); both are normalised to the canonical u8 wire
/// representation so downstream consumers don't have to disambiguate
/// from the [`Dimensions`] metadata alone. The f32 → u8 quantisation
/// is `(v.clamp(0.0, 1.0) * 255.0).round() as u8` with non-finite
/// inputs collapsed to `0` (background); see
/// [`process_mask_bytes_f32`] for the per-pixel logic.
#[cfg(target_vendor = "apple")]
#[allow(non_upper_case_globals)]
fn copy_instance_mask_buffer_locked(
  pixel_buffer: &CVPixelBuffer,
  remaining_byte_budget: usize,
) -> Option<(BoundingBox, Dimensions, Bytes)> {
  let width = CVPixelBufferGetWidth(pixel_buffer);
  let height = CVPixelBufferGetHeight(pixel_buffer);
  if width == 0 || height == 0 {
    return None;
  }
  // Pre-allocation budget check: refuse to allocate this mask if
  // its packed size (`width * height` bytes) would exceed the
  // caller's remaining per-frame budget. This prevents the peak
  // memory from briefly exceeding the per-frame cap by one full
  // mask payload — codex R13 finding F2.
  let output_payload = width.checked_mul(height)?;
  if output_payload > remaining_byte_budget {
    return None;
  }

  let pixel_format = CVPixelBufferGetPixelFormatType(pixel_buffer);
  let bytes_per_row = CVPixelBufferGetBytesPerRow(pixel_buffer);
  let base_address = CVPixelBufferGetBaseAddress(pixel_buffer) as *const u8;
  if base_address.is_null() || bytes_per_row == 0 {
    return None;
  }

  // Total foreground-mask byte count cannot overflow `usize`, and the
  // stride must be wide enough to hold one row of pixels of the
  // expected size — otherwise our row-slice indexing would read past
  // the end of the buffer.
  let bytes_per_pixel: usize = match pixel_format {
    kCVPixelFormatType_OneComponent32Float => core::mem::size_of::<f32>(),
    kCVPixelFormatType_OneComponent8 => 1,
    _ => return None,
  };
  let row_pixel_bytes = width.checked_mul(bytes_per_pixel)?;
  if bytes_per_row < row_pixel_bytes {
    return None;
  }
  let total_src_len = bytes_per_row.checked_mul(height)?;

  // Pre-validate the two mask preconditions that `from_raw_parts`
  // requires (`total_src_len <= isize::MAX`) and that the bounded
  // allocator requires (`width * height <= MAX_MASK_BYTES`).
  // Centralised in `validate_mask_dims_for_slice` so a corrupted or
  // adversarial `CVPixelBuffer` cannot reach the unsafe slice with
  // values that would either trigger UB or drive the worker into
  // the allocator's abort path.
  validate_mask_dims_for_slice(width, height, total_src_len)?;

  // FFI-truth check: `total_src_len = bytes_per_row * height` is
  // derived from the buffer's own metadata, but `CVPixelBufferGetDataSize`
  // reports the actual ALLOCATED size of the buffer's data plane.
  // A malformed buffer with valid `base_address` but inconsistent
  // stride/height metadata could otherwise let `from_raw_parts`
  // create an overlong slice (UB on the row reads). Reject if the
  // computed length exceeds the buffer's reported data size.
  let data_size: usize = CVPixelBufferGetDataSize(pixel_buffer);
  if total_src_len > data_size {
    return None;
  }

  // SAFETY: `base_address` points at a buffer whose allocated size
  // is `CVPixelBufferGetDataSize(pixel_buffer)` (verified just above
  // to be at least `total_src_len`); the buffer is locked by the
  // surrounding `CVPixelBufferLockGuard`. The pre-validation
  // satisfies the `from_raw_parts` contract
  // (`total_src_len <= isize::MAX` AND
  // `total_src_len <= data_size`) regardless of what Core Video
  // reports for the dimensions; the downstream bounded allocator
  // re-checks `width * height` against `MAX_MASK_BYTES`.
  let src = unsafe { std::slice::from_raw_parts(base_address, total_src_len) };

  // The wire `Dimensions` stores `u32`. A mask whose width or height
  // exceeds `u32::MAX` cannot be represented faithfully — we'd have
  // to saturate the dimensions to a value smaller than the actual
  // packed payload, which would silently desynchronise consumers
  // that size buffers from the metadata. Reject overflow here so the
  // detection is dropped rather than poisoning storage.
  let dim_width = u32::try_from(width).ok()?;
  let dim_height = u32::try_from(height).ok()?;

  let (bbox, packed) = match pixel_format {
    kCVPixelFormatType_OneComponent32Float => {
      process_mask_bytes_f32(width, height, bytes_per_row, src)?
    }
    kCVPixelFormatType_OneComponent8 => process_mask_bytes_u8(width, height, bytes_per_row, src)?,
    _ => return None,
  };

  Some((
    bbox,
    Dimensions::new(dim_width, dim_height),
    Bytes::from(packed),
  ))
}

/// Walk an `OneComponent32Float` mask, quantise each pixel to 8 bits,
/// and derive a normalized foreground bbox. Returns `None` for an
/// all-zero mask so the caller skips emitting a detection.
///
/// The result is a `(bbox, packed_bytes)` pair where `packed_bytes`
/// has length `width * height` — i.e. one **u8** per pixel, NOT four
/// `f32` little-endian bytes. Vision emits f32 mask values in
/// `[0.0, 1.0]`; we map `v` → `(v.clamp(0.0, 1.0) * 255.0).round() as
/// u8`. Non-finite values (`NaN`, `±Inf`) collapse to `0`
/// (background), matching Vision's documented "non-finite = no
/// confidence in foreground" convention and keeping the wire payload
/// canonically 8-bit per pixel across both source pixel formats.
#[cfg(target_vendor = "apple")]
fn process_mask_bytes_f32(
  width: usize,
  height: usize,
  bytes_per_row: usize,
  src: &[u8],
) -> Option<(BoundingBox, Vec<u8>)> {
  let src_row_pixel_bytes = width.checked_mul(core::mem::size_of::<f32>())?;
  let packed_len = width.checked_mul(height)?;
  // Bounded allocation: cap at `MAX_MASK_BYTES` and use
  // `try_reserve_exact` so an oversized or corrupted dimensions value
  // returns `None` instead of aborting the worker process via the
  // allocator's OOM path.
  let mut packed = try_alloc_packed_mask(packed_len)?;

  let mut min_x = usize::MAX;
  let mut min_y = usize::MAX;
  let mut max_x = 0usize;
  let mut max_y = 0usize;
  let mut has_foreground = false;

  for row in 0..height {
    let src_start = row.checked_mul(bytes_per_row)?;
    let src_end = src_start.checked_add(src_row_pixel_bytes)?;
    let src_row = src.get(src_start..src_end)?;
    let dst_start = row.checked_mul(width)?;
    let dst_end = dst_start.checked_add(width)?;
    let dst_row = packed.get_mut(dst_start..dst_end)?;
    for col in 0..width {
      let pixel_start = col.checked_mul(4)?;
      let pixel_end = pixel_start.checked_add(4)?;
      let bytes: [u8; 4] = src_row.get(pixel_start..pixel_end)?.try_into().ok()?;
      let value = f32::from_le_bytes(bytes);
      // f32 mask in `[0.0, 1.0]` → u8 mask in `[0, 255]`. Non-finite
      // values (`NaN`, `±Inf`) collapse to `0` (background) — Vision
      // documents non-finite as "no confidence", which is the same
      // semantic as background in the u8 representation.
      let quantised: u8 = if value.is_finite() {
        (value.clamp(0.0, 1.0) * 255.0).round() as u8
      } else {
        0
      };
      *dst_row.get_mut(col)? = quantised;
      if quantised > 0 {
        has_foreground = true;
        min_x = min_x.min(col);
        min_y = min_y.min(row);
        max_x = max_x.max(col);
        max_y = max_y.max(row);
      }
    }
  }

  if !has_foreground {
    // All-zero mask — skip the detection rather than emit one with a
    // degenerate bbox. The validated domain `BoundingBox::try_new`
    // rejects zero-extent boxes, so the previous
    // `BoundingBox::default()` fallback would poison downstream
    // conversion.
    return None;
  }
  let bbox = normalized_bbox_from_pixel_bounds(min_x, min_y, max_x, max_y, width, height)?;
  Some((bbox, packed))
}

/// Walk an `OneComponent8` mask, copy it tightly packed, and derive a
/// normalized foreground bbox. Returns `None` for an all-zero mask.
#[cfg(target_vendor = "apple")]
fn process_mask_bytes_u8(
  width: usize,
  height: usize,
  bytes_per_row: usize,
  src: &[u8],
) -> Option<(BoundingBox, Vec<u8>)> {
  let packed_len = width.checked_mul(height)?;
  // Bounded allocation: see `process_mask_bytes_f32` for the rationale.
  let mut packed = try_alloc_packed_mask(packed_len)?;

  let mut min_x = usize::MAX;
  let mut min_y = usize::MAX;
  let mut max_x = 0usize;
  let mut max_y = 0usize;
  let mut has_foreground = false;

  for row in 0..height {
    let src_start = row.checked_mul(bytes_per_row)?;
    let src_end = src_start.checked_add(width)?;
    let src_row = src.get(src_start..src_end)?;
    let dst_start = row.checked_mul(width)?;
    let dst_end = dst_start.checked_add(width)?;
    let dst_row = packed.get_mut(dst_start..dst_end)?;
    dst_row.copy_from_slice(src_row);
    for (col, value) in dst_row.iter().copied().enumerate() {
      if value > 0 {
        has_foreground = true;
        min_x = min_x.min(col);
        min_y = min_y.min(row);
        max_x = max_x.max(col);
        max_y = max_y.max(row);
      }
    }
  }

  if !has_foreground {
    return None;
  }
  let bbox = normalized_bbox_from_pixel_bounds(min_x, min_y, max_x, max_y, width, height)?;
  Some((bbox, packed))
}

/// Convert the foreground pixel bounds of a `CVPixelBuffer` mask into a
/// normalized [`BoundingBox`] in the top-left schema convention.
///
/// `CVPixelBuffer` rows are stored top-to-bottom in memory (row 0 is the
/// top of the image), so the natural mapping `min_y / height` is already
/// top-left and no y-flip is needed here.
/// Convert integer pixel bounds into a normalized `[0, 1]`
/// `BoundingBox`. The intermediate division is performed in `f64`
/// because R7's bounded mask cap (`MAX_MASK_BYTES = 64 MiB`) admits
/// widths above `2^24`, where consecutive `usize` values round to
/// the same `f32` (mantissa exhaustion). A naive
/// `min_x as f32 / width as f32` then produces `x = 1.0` with a
/// positive width on right-edge foreground at width `2^24 + 1`,
/// which violates the schema's `[0, 1]` invariant.
///
/// `f64` has 52 mantissa bits and represents every `usize` up to
/// `2^52` exactly on 64-bit targets; only the final narrow to `f32`
/// loses precision, which is invariant-safe because the result is
/// in `[0, 1]`. Returns `None` if the final bbox fails the domain
/// validator's `[0, 1]` + non-zero-extent invariants — a corrupted
/// pixel-bound input cannot produce a wire bbox that downstream
/// storage would reject.
#[cfg(target_vendor = "apple")]
fn normalized_bbox_from_pixel_bounds(
  min_x: usize,
  min_y: usize,
  max_x: usize,
  max_y: usize,
  width: usize,
  height: usize,
) -> Option<BoundingBox> {
  if width == 0 || height == 0 {
    return None;
  }
  // Compute all four EDGES in f64, then narrow to f32. The width
  // and height are derived from the narrowed edges (right - left,
  // bottom - top) rather than from a separate f64-division. This
  // guarantees the bbox is internally consistent in f32 arithmetic:
  // `left + width == right` exactly, and `right <= 1.0` by
  // construction (numerator <= denominator).
  //
  // Why edges-then-subtract instead of left-then-width: at widths
  // above the f32 mantissa exhaustion point (2^24+1, 2^25+1, …),
  // separate f32 narrowings of `min_x / width` and `(max_x + 1 - min_x)
  // / width` can land on (1.0, positive) for right-edge foreground,
  // producing `x == 1.0 && w > 0.0` — a bbox the domain validator
  // does NOT reliably reject (its `x + w` check is also f32 and
  // rounds back to 1.0). Edge-based computation eliminates the
  // class entirely: the right edge is constructed directly as a
  // normalized value, not synthesised from `left + width`.
  //
  // `f64` has 52 mantissa bits — every `usize` up to `2^52` is
  // representable exactly on 64-bit targets. Only the final narrow
  // to `f32` loses precision, and only at values close enough to
  // `1.0` that the next-lower f32 differs by `2^-24 ≈ 6e-8`.
  let w64 = width as f64;
  let h64 = height as f64;
  // `max_x + 1` would overflow `usize::MAX`; the caller bounds
  // `max_x < width <= MAX_MASK_BYTES` (well below `usize::MAX`),
  // but use `checked_add` for defence-in-depth.
  let right_pixel = max_x.checked_add(1)?;
  let bottom_pixel = max_y.checked_add(1)?;
  if right_pixel > width || bottom_pixel > height || min_x > max_x || min_y > max_y {
    return None;
  }
  let left = (min_x as f64 / w64) as f32;
  let top = (min_y as f64 / h64) as f32;
  let right = (right_pixel as f64 / w64) as f32;
  let bottom = (bottom_pixel as f64 / h64) as f32;
  let w = right - left;
  let h = bottom - top;
  // Reject pathological f32 narrowings: a foreground bbox whose
  // left or top edge rounded to 1.0 (i.e. mantissa exhaustion
  // pushed an "almost-1.0" value over the line) is geometrically
  // a point, not a region. Drop it rather than emitting an
  // out-of-spec wire bbox.
  if !(left < 1.0 && top < 1.0) {
    return None;
  }
  if !(w > 0.0 && h > 0.0) {
    return None;
  }
  // The validating `try_new` IS the domain bbox — no wire fork to
  // re-check.
  BoundingBox::try_new(left, top, w, h).ok()
}

// ----- Non-macOS stub --------------------------------------------------------

/// Non-macOS stub for [`VisionAnalyzer`]. Apple's Vision.framework is
/// only available on macOS, so on every other target the analyzer
/// always reports an [`ErrorCode::AppleVisionFailed`] platform error
/// rather than producing detections. The README promises the crate
/// compiles cleanly on non-macOS targets so downstream workspaces can
/// keep `avanalyze` in their dep tree unconditionally; this stub is
/// what makes that promise true.
#[cfg(not(target_vendor = "apple"))]
#[derive(Debug)]
pub struct VisionAnalyzer {
  // Keep the options around so a future native cross-platform
  // engine can swap in here without breaking the public API.
  #[allow(dead_code)]
  opts: ServiceOptions,
}

#[cfg(not(target_vendor = "apple"))]
impl VisionAnalyzer {
  /// Construct a non-macOS stub analyzer. The configuration is
  /// retained but unused — every `analyze_keyframe` call returns
  /// [`ErrorCode::AppleVisionFailed`].
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn new(opts: ServiceOptions) -> Self {
    Self { opts }
  }

  /// Non-macOS stub: Apple's Vision.framework is only available on
  /// macOS, so this always returns
  /// [`ErrorCode::AppleVisionFailed`] with an explanatory message.
  /// `_jpeg_data` is ignored.
  pub fn analyze_keyframe(
    &self,
    _scene_id: Uuid7,
    _keyframe_id: Uuid7,
    _pts: Timestamp,
    _dimensions: Dimensions,
    _extractor: KeyframeExtractor,
    _jpeg_data: &[u8],
  ) -> Result<Keyframe, ErrorInfo> {
    Err(apple_vision_error(
      ErrorCode::AppleVisionFailed,
      "Apple Vision.framework is only available on macOS",
    ))
  }
}

#[cfg(test)]
mod tests {
  use mediaschema::domain::aggregates::video::{
    BodyPose3DDetection, BodyPose3DHeightEstimation, HumanAnalysis,
  };

  /// Regression: `HumanAnalysis::with_body_poses_3d` previously dropped
  /// its input on the floor in the wire-types era. The locked domain
  /// builder must still persist the supplied detections. Platform-
  /// independent — the builder does not depend on Vision.
  #[test]
  fn body_poses_3d_survives_through_human_analysis() {
    let pose =
      BodyPose3DDetection::try_new(0.5, 0.0, BodyPose3DHeightEstimation::Unknown, Vec::new())
        .expect("validating ctor on canonical inputs");
    let analysis = HumanAnalysis::new().with_body_poses_3d(vec![pose]);
    assert_eq!(analysis.body_poses_3d_slice().len(), 1);
  }

  /// Non-macOS `VisionAnalyzer` stub must report an Apple-Vision
  /// platform error on every `analyze_keyframe` call.
  #[cfg(not(target_vendor = "apple"))]
  #[test]
  fn non_macos_stub_reports_unavailable() {
    use super::*;
    use core::num::NonZeroU32;
    use mediatime::Timebase;
    let analyzer = VisionAnalyzer::new(ServiceOptions::new());
    let tb = Timebase::new(1, NonZeroU32::new(1000).expect("nonzero den"));
    let err = analyzer
      .analyze_keyframe(
        Uuid7::new(),
        Uuid7::new(),
        Timestamp::new(0, tb),
        Dimensions::new(320, 180),
        KeyframeExtractor::Manual,
        &[],
      )
      .expect_err("stub must return Err");
    assert_eq!(err.code(), ErrorCode::AppleVisionFailed);
  }
}

#[cfg(all(test, target_vendor = "apple"))]
mod macos_tests {
  use super::*;
  use mediaschema::domain::aggregates::video::BoundingBox as DomainBoundingBox;
  use objc2_core_foundation::{CGPoint, CGRect, CGSize};

  /// `vision_bbox_to_schema` must flip y. A Vision rect of
  /// `(0.1, 0.2, 0.3, 0.4)` (lower-left origin) maps to
  /// `(0.1, 1.0 - (0.2 + 0.4), 0.3, 0.4)` = `(0.1, 0.4, 0.3, 0.4)`
  /// in the schema's top-left convention.
  #[test]
  fn vision_bbox_to_schema_flips_y() {
    let rect = CGRect::new(CGPoint::new(0.1, 0.2), CGSize::new(0.3, 0.4));
    let bbox = vision_bbox_to_schema(rect).expect("in-range rect must clamp to itself");
    assert!((bbox.x() - 0.1).abs() < 1e-6, "x: {}", bbox.x());
    assert!((bbox.y() - 0.4).abs() < 1e-6, "y: {}", bbox.y());
    assert!((bbox.width() - 0.3).abs() < 1e-6, "w: {}", bbox.width());
    assert!((bbox.height() - 0.4).abs() < 1e-6, "h: {}", bbox.height());
  }

  /// Lock the flipped full-image result against the validating domain
  /// `BoundingBox::try_new` to ensure the components still satisfy the
  /// `[0, 1]` invariant after the flip.
  #[test]
  fn vision_bbox_to_schema_full_image_round_trip() {
    let rect = CGRect::new(CGPoint::new(0.0, 0.0), CGSize::new(1.0, 1.0));
    let bbox = vision_bbox_to_schema(rect).expect("unit rect must clamp to itself");
    assert_eq!(bbox.x(), 0.0);
    assert_eq!(bbox.y(), 0.0);
    assert_eq!(bbox.width(), 1.0);
    assert_eq!(bbox.height(), 1.0);
    DomainBoundingBox::try_new(bbox.x(), bbox.y(), bbox.width(), bbox.height())
      .expect("full-image bbox stays valid after flip");
  }

  /// A Vision rect that spills off the right edge (`origin.x + width > 1`)
  /// must be clamped to the unit square. Domain `BoundingBox::try_new`
  /// would reject the un-clamped result, so without clamping a partially
  /// off-screen detection would poison downstream conversion.
  #[test]
  fn vision_bbox_clamps_right_spill() {
    // Vision rect: origin (0.8, 0.4), size (0.5, 0.2) — right edge at 1.3.
    let rect = CGRect::new(CGPoint::new(0.8, 0.4), CGSize::new(0.5, 0.2));
    let bbox = vision_bbox_to_schema(rect).expect("partial overlap must produce a bbox");
    // Clamped right edge is 1.0 → width = 0.2 (1.0 - 0.8).
    assert!((bbox.x() - 0.8).abs() < 1e-6, "x: {}", bbox.x());
    assert!((bbox.width() - 0.2).abs() < 1e-6, "w: {}", bbox.width());
    // y in schema space: 1.0 - (0.4 + 0.2) = 0.4 (in-range, no clamp).
    assert!((bbox.y() - 0.4).abs() < 1e-6, "y: {}", bbox.y());
    assert!((bbox.height() - 0.2).abs() < 1e-6, "h: {}", bbox.height());
    DomainBoundingBox::try_new(bbox.x(), bbox.y(), bbox.width(), bbox.height())
      .expect("clamped bbox satisfies the [0,1] invariant");
  }

  /// A Vision rect that spills off the bottom (`origin.y < 0` in
  /// Vision = `y + height > 1` in schema) must be clamped to the unit
  /// square so the domain validator does not reject it.
  #[test]
  fn vision_bbox_clamps_bottom_spill() {
    // Vision rect: origin (0.1, -0.1), size (0.3, 0.4) — Vision bottom edge
    // at y = -0.1, top edge at y = 0.3.
    // Schema: top = 1.0 - (−0.1 + 0.4) = 0.7, bottom = 1.0 - (−0.1) = 1.1.
    let rect = CGRect::new(CGPoint::new(0.1, -0.1), CGSize::new(0.3, 0.4));
    let bbox = vision_bbox_to_schema(rect).expect("partial overlap must produce a bbox");
    // Bottom clamped to 1.0 → height = 1.0 - 0.7 = 0.3.
    assert!((bbox.x() - 0.1).abs() < 1e-6, "x: {}", bbox.x());
    assert!((bbox.y() - 0.7).abs() < 1e-6, "y: {}", bbox.y());
    assert!((bbox.width() - 0.3).abs() < 1e-6, "w: {}", bbox.width());
    assert!((bbox.height() - 0.3).abs() < 1e-6, "h: {}", bbox.height());
    DomainBoundingBox::try_new(bbox.x(), bbox.y(), bbox.width(), bbox.height())
      .expect("clamped bbox satisfies the [0,1] invariant");
  }

  /// A Vision rect entirely outside the unit square must yield `None`
  /// so the detection is skipped rather than producing a degenerate
  /// wire bbox.
  #[test]
  fn vision_bbox_fully_offscreen_yields_none() {
    let rect = CGRect::new(CGPoint::new(1.5, 0.5), CGSize::new(0.3, 0.4));
    assert!(vision_bbox_to_schema(rect).is_none());
  }

  /// A Vision rect that intersects the unit square only at a single
  /// edge must yield `None` (the intersection has zero width).
  #[test]
  fn vision_bbox_edge_only_yields_none() {
    // Right edge at exactly x = 1.0, left edge at x = 1.0 — zero width.
    let rect = CGRect::new(CGPoint::new(1.0, 0.5), CGSize::new(0.0, 0.4));
    assert!(vision_bbox_to_schema(rect).is_none());
  }

  /// `NaN` from Vision (occasionally seen for off-image rects) must
  /// not propagate — the helper sanitises non-finite components to
  /// `0.0`. A `NaN` `origin.x` collapses left and right to 0.0, so the
  /// rectangle has zero width after clamping and is reported as
  /// `None` (the detection is dropped).
  #[test]
  fn vision_bbox_handles_nan_origin() {
    let rect = CGRect::new(CGPoint::new(f64::NAN, 0.0), CGSize::new(0.3, 0.4));
    assert!(vision_bbox_to_schema(rect).is_none());
  }

  /// `NaN` in a single size component still produces a usable
  /// rectangle iff the surviving edges enclose a non-zero area. A
  /// finite `origin.x`/`width` keeps the horizontal extent live; a
  /// `NaN` `origin.y` collapses the vertical extent to zero and the
  /// rectangle is dropped.
  #[test]
  fn vision_bbox_handles_nan_y_origin() {
    let rect = CGRect::new(CGPoint::new(0.1, f64::NAN), CGSize::new(0.3, 0.4));
    assert!(vision_bbox_to_schema(rect).is_none());
  }

  /// 2D points flip y AND clamp to `[0, 1]`. A Vision point that lands
  /// outside `[0, 1]` after the flip is clamped to the unit edge so
  /// downstream validation accepts it.
  #[test]
  fn vision_point_to_schema_flips_y_only() {
    let (x, y) = vision_point_to_schema(0.25, 0.75).expect("finite point");
    assert!((x - 0.25).abs() < 1e-6);
    assert!((y - 0.25).abs() < 1e-6);
  }

  /// Out-of-range Vision points clamp to `[0, 1]`.
  #[test]
  fn vision_point_to_schema_clamps_out_of_range() {
    let (x, y) = vision_point_to_schema(1.2, -0.3).expect("finite point");
    assert_eq!(x, 1.0);
    // `y = 1.0 - (-0.3) = 1.3` → clamped to 1.0.
    assert_eq!(y, 1.0);
  }

  /// Non-finite Vision points are rejected at the source: a `NaN`,
  /// `+Inf`, or `-Inf` in either component returns `None` so the
  /// caller can decide whether to drop the point or the whole
  /// detection. Previously the helper collapsed the bad component to
  /// `0.0` via `clamp01`, which fabricated edge-aligned coordinates
  /// that the domain validator could not distinguish from real
  /// detections.
  #[test]
  fn vision_point_to_schema_rejects_non_finite() {
    assert!(vision_point_to_schema(f64::NAN, 0.5).is_none());
    assert!(vision_point_to_schema(0.5, f64::NAN).is_none());
    assert!(vision_point_to_schema(f64::INFINITY, 0.5).is_none());
    assert!(vision_point_to_schema(0.5, f64::INFINITY).is_none());
    assert!(vision_point_to_schema(f64::NEG_INFINITY, 0.5).is_none());
    assert!(vision_point_to_schema(0.5, f64::NEG_INFINITY).is_none());
    // Finite path still works.
    assert!(vision_point_to_schema(0.1, 0.2).is_some());
  }

  /// A document quad with even one non-finite corner must be dropped
  /// in its entirety — a quad is geometrically meaningless without
  /// all four corners. This test mirrors the per-detection pattern
  /// the extractor uses (`let (Some(tl), Some(tr), Some(bl),
  /// Some(br)) = (...) else { continue; }`): if any corner returns
  /// `None`, the whole quad is rejected. Partial-corner emission
  /// would be a regression.
  #[test]
  fn document_quad_with_non_finite_corner_is_dropped() {
    // Three good corners + one NaN corner — overall the quad must
    // be dropped. We exercise each corner position to confirm the
    // "any None drops the whole quad" semantics.
    let good = (0.1_f64, 0.1_f64);
    let bad = (f64::NAN, 0.5_f64);

    for (tl, tr, bl, br) in [
      (bad, good, good, good),
      (good, bad, good, good),
      (good, good, bad, good),
      (good, good, good, bad),
    ] {
      let result = (
        vision_point_to_schema(tl.0, tl.1),
        vision_point_to_schema(tr.0, tr.1),
        vision_point_to_schema(bl.0, bl.1),
        vision_point_to_schema(br.0, br.1),
      );
      assert!(
        !matches!(result, (Some(_), Some(_), Some(_), Some(_))),
        "quad with non-finite corner survived: {result:?}",
      );
    }
  }

  /// `normalized_bbox_from_pixel_bounds` must NOT flip the y axis —
  /// `CVPixelBuffer` rows are top-to-bottom, so row 0 is the top edge
  /// and the natural mapping `min_y / height` is already in top-left
  /// convention.
  #[test]
  fn pixel_bounds_to_normalized_bbox_does_not_flip() {
    // A 100x100 mask with the foreground rectangle in rows 10..=29,
    // columns 5..=24. The expected normalized bbox is
    // `(5/100, 10/100, 20/100, 20/100)` in top-left convention.
    let bbox = normalized_bbox_from_pixel_bounds(5, 10, 24, 29, 100, 100).expect("valid bbox");
    assert!((bbox.x() - 0.05).abs() < 1e-6);
    assert!((bbox.y() - 0.10).abs() < 1e-6);
    assert!((bbox.width() - 0.20).abs() < 1e-6);
    assert!((bbox.height() - 0.20).abs() < 1e-6);
  }

  /// An all-zero 8-bit mask must yield `None` so the caller skips the
  /// detection. Previously the buffer returned `Some` with
  /// `BoundingBox::default()` (a zero-extent box), which the domain
  /// `BoundingBox::try_new` would later reject.
  #[test]
  fn empty_8bit_mask_yields_none() {
    let src = vec![0u8; 4 * 4]; // 4×4 all-zero mask, tight stride.
    assert!(process_mask_bytes_u8(4, 4, 4, &src).is_none());
  }

  /// An all-zero 32-bit-float mask must also yield `None`. Same
  /// rationale as the 8-bit case.
  #[test]
  fn empty_32fp_mask_yields_none() {
    let src = vec![0u8; 4 * 4 * 4]; // 4×4 all-zero f32 mask.
    assert!(process_mask_bytes_f32(4, 4, 16, &src).is_none());
  }

  /// An 8-bit mask with one foreground pixel at row 1, col 2 of a
  /// 4×4 buffer must round-trip the bbox and the packed bytes.
  #[test]
  fn single_pixel_8bit_mask_round_trip() {
    let mut src = vec![0u8; 16];
    // Row 1, column 2 — stride 4.
    src[6] = 0xFF;
    let (bbox, packed) = process_mask_bytes_u8(4, 4, 4, &src).expect("foreground produces Some");
    assert!((bbox.x() - 0.5).abs() < 1e-6, "x: {}", bbox.x());
    assert!((bbox.y() - 0.25).abs() < 1e-6, "y: {}", bbox.y());
    assert!((bbox.width() - 0.25).abs() < 1e-6, "w: {}", bbox.width());
    assert!((bbox.height() - 0.25).abs() < 1e-6, "h: {}", bbox.height());
    // Packed bytes mirror the input (tight stride === input stride).
    assert_eq!(packed, src);
  }

  /// A 32-fp mask with one foreground pixel quantises to a single u8
  /// in the canonical 8-bit-per-pixel wire payload. `0.75 * 255 =
  /// 191.25 → 191` after `round()`. The packed buffer is `width *
  /// height` bytes, NOT `width * height * size_of::<f32>()`, since
  /// the f32 source is normalised to u8 at the boundary.
  #[test]
  fn single_pixel_32fp_mask_round_trip() {
    let mut src = vec![0u8; 4 * 4 * 4];
    let value: f32 = 0.75;
    let bytes = value.to_le_bytes();
    // Row 1, column 2 — 4 bytes per pixel, 16 bytes per row.
    let src_offset = 16 + 8;
    src[src_offset..src_offset + 4].copy_from_slice(&bytes);
    let (bbox, packed) = process_mask_bytes_f32(4, 4, 16, &src).expect("foreground produces Some");
    assert!((bbox.x() - 0.5).abs() < 1e-6, "x: {}", bbox.x());
    assert!((bbox.y() - 0.25).abs() < 1e-6, "y: {}", bbox.y());
    // Canonical 8-bit payload: 4×4 = 16 bytes.
    assert_eq!(packed.len(), 4 * 4);
    // Row 1, column 2 — 4 bytes per row in the u8 output, so offset = 4 + 2.
    let dst_offset = 4 + 2;
    assert_eq!(packed[dst_offset], 191, "0.75 → 191 after u8 quantisation");
    // Every other byte stays at 0 (background).
    for (idx, &b) in packed.iter().enumerate() {
      if idx != dst_offset {
        assert_eq!(b, 0, "background pixel {idx} must be 0");
      }
    }
  }

  /// f32 mask values at the canonical interior {0.0, 0.5, 1.0} plus a
  /// `NaN` background pixel must quantise to {0, 128, 255, 0} in the
  /// u8 wire payload. Pins the brief's documented mapping.
  #[test]
  fn f32_mask_quantises_canonical_values_and_nan() {
    // 4×1 row: [0.0, 0.5, 1.0, NaN].
    let mut src = vec![0u8; 4 * 4];
    src[0..4].copy_from_slice(&0.0_f32.to_le_bytes());
    src[4..8].copy_from_slice(&0.5_f32.to_le_bytes());
    src[8..12].copy_from_slice(&1.0_f32.to_le_bytes());
    src[12..16].copy_from_slice(&f32::NAN.to_le_bytes());
    let (_, packed) = process_mask_bytes_f32(4, 1, 16, &src).expect("foreground present");
    assert_eq!(packed.len(), 4, "canonical 8-bit-per-pixel payload");
    assert_eq!(packed[0], 0, "0.0 → 0");
    // 0.5 * 255 = 127.5; `round()` ties-to-even on .5 in Rust uses
    // banker's rounding... actually `f32::round()` is half-away-
    // from-zero: 127.5 → 128.
    assert_eq!(packed[1], 128, "0.5 → 128");
    assert_eq!(packed[2], 255, "1.0 → 255");
    assert_eq!(packed[3], 0, "NaN → 0 (background)");
  }

  /// f32 mask values outside `[0, 1]` (e.g. a glitched Vision frame
  /// with negative or super-saturated mask probabilities) must clamp
  /// to the endpoints in the u8 output rather than wrap or silently
  /// produce garbage. `+Inf` and `-Inf` collapse to `0` (background)
  /// like `NaN`.
  #[test]
  fn f32_mask_quantises_out_of_range_and_infinity() {
    // 4×1 row: [-0.5, 1.5, +Inf, -Inf].
    let mut src = vec![0u8; 4 * 4];
    src[0..4].copy_from_slice(&(-0.5_f32).to_le_bytes());
    src[4..8].copy_from_slice(&1.5_f32.to_le_bytes());
    src[8..12].copy_from_slice(&f32::INFINITY.to_le_bytes());
    src[12..16].copy_from_slice(&f32::NEG_INFINITY.to_le_bytes());
    // Foreground = packed[1] (1.5 clamps to 255). The rest collapse
    // to 0 (background), so the mask is technically a single-pixel
    // foreground at column 1.
    let (_, packed) = process_mask_bytes_f32(4, 1, 16, &src).expect("foreground at col 1");
    assert_eq!(packed[0], 0, "-0.5 clamps to 0");
    assert_eq!(packed[1], 255, "1.5 clamps to 255");
    assert_eq!(packed[2], 0, "+Inf → 0 (background)");
    assert_eq!(packed[3], 0, "-Inf → 0 (background)");
  }

  /// A stride wider than `width * bytes_per_pixel` (the buffer has
  /// per-row padding) must still produce the correct tightly-packed
  /// output.
  #[test]
  fn padded_stride_8bit_mask_packs_correctly() {
    // 3×2 mask, stride = 8 (5 bytes of right-padding per row).
    let mut src = vec![0u8; 16];
    src[0] = 1; // row 0, col 0.
    src[10] = 1; // row 1, col 2 (offset 8 + 2).
    let (bbox, packed) = process_mask_bytes_u8(3, 2, 8, &src).expect("foreground produces Some");
    assert_eq!(packed.len(), 3 * 2);
    assert_eq!(packed, [1, 0, 0, 0, 0, 1]);
    // Foreground spans cols 0..=2 and rows 0..=1 — bbox is the whole mask.
    assert!((bbox.x() - 0.0).abs() < 1e-6);
    assert!((bbox.y() - 0.0).abs() < 1e-6);
    assert!((bbox.width() - 1.0).abs() < 1e-6);
    assert!((bbox.height() - 1.0).abs() < 1e-6);
  }

  /// A pose with only one surviving joint cannot derive a non-degenerate
  /// bbox. The helper must report `None` so the pose extractor skips
  /// it instead of emitting a zero-extent box that the domain
  /// validator would reject.
  #[test]
  fn pose_bbox_from_single_joint_yields_none() {
    assert!(pose_bbox_from_joint_bounds(0.5, 0.5, 0.5, 0.5).is_none());
  }

  /// A pose where every joint shares the same x (perfectly vertical
  /// limbs) has zero-width bbox and must be reported as `None`.
  #[test]
  fn pose_bbox_from_vertical_joints_yields_none() {
    assert!(pose_bbox_from_joint_bounds(0.5, 0.1, 0.5, 0.9).is_none());
  }

  /// A pose where every joint shares the same y has zero-height bbox
  /// and must be reported as `None`.
  #[test]
  fn pose_bbox_from_horizontal_joints_yields_none() {
    assert!(pose_bbox_from_joint_bounds(0.1, 0.5, 0.9, 0.5).is_none());
  }

  /// A pose with at least one joint per axis produces a valid bbox.
  #[test]
  fn pose_bbox_from_diagonal_joints_is_valid() {
    let bbox =
      pose_bbox_from_joint_bounds(0.1, 0.2, 0.4, 0.6).expect("non-degenerate joints yield Some");
    assert!((bbox.x() - 0.1).abs() < 1e-6);
    assert!((bbox.y() - 0.2).abs() < 1e-6);
    assert!((bbox.width() - 0.3).abs() < 1e-6);
    assert!((bbox.height() - 0.4).abs() < 1e-6);
    mediaschema::domain::aggregates::video::BoundingBox::try_new(
      bbox.x(),
      bbox.y(),
      bbox.width(),
      bbox.height(),
    )
    .expect("pose-derived bbox satisfies domain invariants");
  }

  /// Non-finite joint coordinates (NaN/Inf from a glitched Vision
  /// observation) must short-circuit before reaching the
  /// `BoundingBox::new` constructor.
  #[test]
  fn pose_bbox_from_nan_joints_yields_none() {
    assert!(pose_bbox_from_joint_bounds(f32::NAN, 0.5, 0.5, 0.5).is_none());
    assert!(pose_bbox_from_joint_bounds(0.1, 0.1, f32::INFINITY, 0.5).is_none());
  }

  /// A document quad whose corners survive per-coord clamp but
  /// collapse to a degenerate shape (e.g. all four corners on a
  /// vertical line because they all clamped to `x = 0.0`) must be
  /// rejected by the domain validator, which the extractor runs
  /// pre-emission.
  #[test]
  fn document_quad_with_collapsed_corners_is_rejected_by_domain() {
    // All four corners at (0.0, 0.0) — collapsed quad.
    let p = (0.0_f32, 0.0_f32);
    assert!(
      mediaschema::domain::aggregates::video::DocumentSegment::try_new(p, p, p, p, 0.9).is_err()
    );
  }

  /// A bow-tie quad (TL & BR swapped) is self-intersecting; the
  /// domain validator rejects it, so the extractor must skip it.
  #[test]
  fn document_quad_bowtie_is_rejected_by_domain() {
    let tl = (0.1_f32, 0.1_f32);
    let tr = (0.9_f32, 0.1_f32);
    let br = (0.1_f32, 0.9_f32);
    let bl = (0.9_f32, 0.9_f32);
    assert!(
      mediaschema::domain::aggregates::video::DocumentSegment::try_new(tl, tr, br, bl, 0.9)
        .is_err()
    );
  }

  /// A well-formed quad passes the domain validator and produces a
  /// valid wire segment.
  #[test]
  fn document_quad_well_formed_is_accepted_by_domain() {
    let tl = (0.1_f32, 0.1_f32);
    let tr = (0.9_f32, 0.1_f32);
    let br = (0.9_f32, 0.9_f32);
    let bl = (0.1_f32, 0.9_f32);
    mediaschema::domain::aggregates::video::DocumentSegment::try_new(tl, tr, br, bl, 0.9)
      .expect("well-formed unit quad is valid");
  }

  // ──────────────── R6 fixes (codex round 6) ────────────────

  /// `finite_f32` returns `Some(v)` only for finite inputs. NaN and
  /// both infinities collapse to `None`.
  #[test]
  fn finite_f32_rejects_non_finite() {
    assert_eq!(finite_f32(0.0), Some(0.0));
    assert_eq!(finite_f32(-1.5), Some(-1.5));
    assert_eq!(finite_f32(1.0), Some(1.0));
    assert_eq!(finite_f32(f32::NAN), None);
    assert_eq!(finite_f32(f32::INFINITY), None);
    assert_eq!(finite_f32(f32::NEG_INFINITY), None);
  }

  /// `try_alloc_packed_mask` enforces a hard upper bound. A request
  /// above `MAX_MASK_BYTES` returns `None` immediately without
  /// touching the allocator, so a corrupted dimensions value cannot
  /// drive the worker into the allocator's abort path.
  #[test]
  fn try_alloc_packed_mask_rejects_oversize() {
    assert!(try_alloc_packed_mask(MAX_MASK_BYTES).is_some());
    assert!(try_alloc_packed_mask(MAX_MASK_BYTES + 1).is_none());
  }

  /// Within the cap, `try_alloc_packed_mask` returns a zero-init
  /// buffer of the requested length.
  #[test]
  fn try_alloc_packed_mask_zero_inits_at_requested_length() {
    let buf = try_alloc_packed_mask(64).expect("64 byte allocation");
    assert_eq!(buf.len(), 64);
    assert!(buf.iter().all(|&b| b == 0));
  }

  /// `process_mask_bytes_u8` and `process_mask_bytes_f32` propagate
  /// the bounded allocation: feeding dimensions whose product
  /// exceeds the cap returns `None` instead of attempting the alloc.
  /// We pick a dimension product just above `MAX_MASK_BYTES`. The
  /// source slice need not be filled with content past the cap —
  /// the function returns at the allocation step before reading any
  /// pixel.
  #[test]
  fn process_mask_bytes_u8_caps_allocation() {
    // (MAX_MASK_BYTES + 1) bytes of packed output. Choose dims that
    // multiply to that value.
    let width = MAX_MASK_BYTES + 1;
    let height = 1;
    // Empty src is fine — the function returns before reading it.
    assert!(process_mask_bytes_u8(width, height, width, &[]).is_none());
  }

  /// Project a face-bbox-relative landmark point into the image's
  /// normalized Vision coordinates. A landmark at the face's centre
  /// (`0.5, 0.5` face-relative) on a face bbox of
  /// `(origin = (0.2, 0.3), size = (0.4, 0.2))` (Vision lower-left)
  /// projects to `(0.2 + 0.5 * 0.4, 0.3 + 0.5 * 0.2) = (0.4, 0.4)`.
  #[test]
  fn project_landmark_to_image_centres_landmark() {
    let face = CGRect::new(CGPoint::new(0.2, 0.3), CGSize::new(0.4, 0.2));
    let projected = project_landmark_to_image(CGPoint::new(0.5, 0.5), face);
    assert!((projected.x - 0.4).abs() < 1e-9);
    assert!((projected.y - 0.4).abs() < 1e-9);
  }

  /// Projection composes with the schema flip. A landmark at the
  /// face's lower-left corner (`(0, 0)` face-relative) on a non-unit
  /// face bbox lands at the face's lower-left in image-normalized
  /// coords. After the schema-side y-flip, the schema-y equals
  /// `1.0 - (face.origin.y + 0 * face.height)`.
  #[test]
  fn project_landmark_then_schema_flip_matches_face_corner() {
    // Face bbox in Vision lower-left: origin (0.2, 0.3), size 0.4×0.2.
    // Face's lower-left landmark = (0, 0) face-relative.
    let face = CGRect::new(CGPoint::new(0.2, 0.3), CGSize::new(0.4, 0.2));
    let projected = project_landmark_to_image(CGPoint::new(0.0, 0.0), face);
    let (sx, sy) =
      vision_point_to_schema(projected.x, projected.y).expect("projected lower-left is finite");
    assert!((sx - 0.2).abs() < 1e-6, "schema-x: {sx}");
    // Vision lower-left at face y = 0.3 → schema-y = 1.0 - 0.3 = 0.7.
    assert!((sy - 0.7).abs() < 1e-6, "schema-y: {sy}");
  }

  /// A non-finite landmark component drops the offending point at
  /// the schema-flip stage even when the face bbox is well-formed.
  /// `project_landmark_to_image` propagates the non-finite component
  /// (`0.2 + NaN * 0.4 = NaN`) and `vision_point_to_schema` rejects
  /// it.
  #[test]
  fn projected_non_finite_landmark_is_rejected() {
    let face = CGRect::new(CGPoint::new(0.2, 0.3), CGSize::new(0.4, 0.2));
    let projected = project_landmark_to_image(CGPoint::new(f64::NAN, 0.5), face);
    assert!(vision_point_to_schema(projected.x, projected.y).is_none());
  }

  // ──────────────── R7 fixes (codex round 7) ────────────────

  /// `sanitize_capture_quality` distinguishes absent from corrupt:
  /// `None` (Vision did not provide a value) collapses to `Some(0.0)`
  /// — fail-closed against any positive threshold; `Some(non_finite)`
  /// collapses to `None` so the caller drops the detection
  /// unconditionally (any `min_capture_quality = 0.0` configuration
  /// would otherwise admit a non-finite reading as a 0.0-quality
  /// face).
  #[test]
  fn sanitize_capture_quality_absent_maps_to_zero() {
    assert_eq!(sanitize_capture_quality(None), Some(0.0));
  }

  #[test]
  fn sanitize_capture_quality_finite_passes_through() {
    assert_eq!(sanitize_capture_quality(Some(0.75)), Some(0.75));
    assert_eq!(sanitize_capture_quality(Some(0.0)), Some(0.0));
    assert_eq!(sanitize_capture_quality(Some(1.0)), Some(1.0));
  }

  /// THE key regression: a non-finite captureQuality must NOT be
  /// substituted with a real value. The previous R6 code returned
  /// `unwrap_or(0.0)` which passed any `min_capture_quality = 0.0`
  /// configuration and admitted the detection. `sanitize_capture_quality`
  /// returns `None` so the caller's `let Some(_) = ... else { continue }`
  /// drops the detection regardless of the configured threshold.
  #[test]
  fn sanitize_capture_quality_non_finite_returns_none() {
    assert_eq!(sanitize_capture_quality(Some(f32::NAN)), None);
    assert_eq!(sanitize_capture_quality(Some(f32::INFINITY)), None);
    assert_eq!(sanitize_capture_quality(Some(f32::NEG_INFINITY)), None);
  }

  /// A finite body_height pairs with whatever height_estimation enum
  /// Vision reported. The pair is forwarded unchanged.
  #[test]
  fn sanitize_body_height_pair_finite_preserves_estimation() {
    let measured = BodyPose3DHeightEstimation::Measured;
    let (h, e) = sanitize_body_height_pair(1.75, measured);
    assert!((h - 1.75).abs() < 1e-6);
    assert_eq!(e, measured);

    let reference = BodyPose3DHeightEstimation::Reference;
    let (h, e) = sanitize_body_height_pair(0.42, reference);
    assert!((h - 0.42).abs() < 1e-6);
    assert_eq!(e, reference);
  }

  /// THE key regression: when body_height is non-finite, the
  /// estimation enum MUST be forced to UNKNOWN. Preserving
  /// MEASURED/REFERENCE while substituting 0.0 would tell consumers
  /// there is a known 0-metre subject — a worse semantic than
  /// "unknown estimate".
  #[test]
  fn sanitize_body_height_pair_non_finite_forces_unknown() {
    for raw in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
      // Even with a Measured input the result must be UNKNOWN.
      let (h, e) = sanitize_body_height_pair(raw, BodyPose3DHeightEstimation::Measured);
      assert_eq!(h, 0.0, "non-finite must collapse to 0.0 (raw = {raw:?})");
      assert_eq!(
        e,
        BodyPose3DHeightEstimation::Unknown,
        "non-finite must force UNKNOWN (raw = {raw:?})",
      );
      // Same for Reference.
      let (h, e) = sanitize_body_height_pair(raw, BodyPose3DHeightEstimation::Reference);
      assert_eq!(h, 0.0);
      assert_eq!(e, BodyPose3DHeightEstimation::Unknown);
    }
  }

  /// `validate_mask_dims_for_slice` rejects an output-payload that
  /// would exceed `MAX_MASK_BYTES`, even when the source slice length
  /// is small. This guards the bounded allocator from being asked
  /// for an impossible amount.
  #[test]
  fn validate_mask_dims_rejects_oversize_output() {
    assert!(validate_mask_dims_for_slice(MAX_MASK_BYTES, 1, 0).is_some());
    assert!(validate_mask_dims_for_slice(MAX_MASK_BYTES + 1, 1, 0).is_none());
  }

  /// `validate_mask_dims_for_slice` rejects a source-slice length
  /// over `isize::MAX`. This is the `from_raw_parts` contract; a
  /// corrupted `CVPixelBuffer` reporting a huge `bytes_per_row *
  /// height` must be dropped before the unsafe slice construction.
  #[test]
  fn validate_mask_dims_rejects_isize_overflow_source() {
    assert!(validate_mask_dims_for_slice(1, 1, isize::MAX as usize).is_some());
    assert!(validate_mask_dims_for_slice(1, 1, (isize::MAX as usize).wrapping_add(1)).is_none());
  }

  /// `width * height` overflow returns `None` (the `checked_mul`
  /// inside).
  #[test]
  fn validate_mask_dims_rejects_dim_overflow() {
    assert!(validate_mask_dims_for_slice(usize::MAX, 2, 0).is_none());
  }

  // ──────────────── R8 fixes (codex round 8) ────────────────

  /// `validate_raw_slice_bytes` rejects payloads above the cap and
  /// above `isize::MAX`, in either order. Re-uses `MAX_MASK_BYTES`
  /// as a representative caller-side ceiling; the helper is generic
  /// and the cap value itself is not load-bearing for this test.
  #[test]
  fn validate_raw_slice_bytes_rejects_over_cap() {
    assert!(validate_raw_slice_bytes(0, MAX_MASK_BYTES).is_some());
    assert!(validate_raw_slice_bytes(MAX_MASK_BYTES, MAX_MASK_BYTES).is_some());
    assert!(validate_raw_slice_bytes(MAX_MASK_BYTES + 1, MAX_MASK_BYTES).is_none());
  }

  /// `validate_raw_slice_bytes` rejects `byte_len > isize::MAX` even
  /// when the caller's cap is `usize::MAX` (i.e. no cap). This pins
  /// the FFI-side `from_raw_parts` contract independently of the
  /// caller-side ceiling.
  #[test]
  fn validate_raw_slice_bytes_rejects_isize_overflow() {
    assert!(validate_raw_slice_bytes(isize::MAX as usize, usize::MAX).is_some());
    assert!(validate_raw_slice_bytes((isize::MAX as usize).wrapping_add(1), usize::MAX).is_none());
  }

  /// `validate_raw_slice_elems::<CGPoint>` rejects element counts
  /// above the caller-provided max regardless of the size_of math.
  #[test]
  fn validate_raw_slice_elems_rejects_over_cap() {
    assert!(
      validate_raw_slice_elems::<CGPoint>(MAX_LANDMARK_POINTS, MAX_LANDMARK_POINTS).is_some()
    );
    assert!(
      validate_raw_slice_elems::<CGPoint>(MAX_LANDMARK_POINTS + 1, MAX_LANDMARK_POINTS).is_none()
    );
  }

  /// `validate_raw_slice_elems::<u8>` rejects when `elem_count *
  /// size_of::<T>()` overflows usize. For `T = u8` size_of is 1 so
  /// the overflow surfaces only on the isize::MAX check.
  #[test]
  fn validate_raw_slice_elems_rejects_byte_overflow() {
    // `usize::MAX / 2 + 2` * 16 (size_of CGPoint with two f64) overflows.
    assert!(validate_raw_slice_elems::<CGPoint>(usize::MAX, usize::MAX).is_none());
  }

  /// The key R8 regression: a 2^24+1-pixel-wide mask with foreground
  /// in the rightmost column previously produced `x = 1.0` with
  /// positive width (because `f32` cannot distinguish `2^24` from
  /// `2^24 + 1`). The f64-intermediate fix should now produce a
  /// `[0, 1]`-valid bbox OR drop the detection — never emit
  /// `x + width > 1.0`.
  #[test]
  fn normalized_bbox_handles_2pow24_plus_one_width() {
    // 2^24 = 16,777,216. Pick a width slightly above the f32
    // mantissa exhaustion point. Foreground = rightmost column.
    let width: usize = (1 << 24) + 1;
    let height: usize = 1;
    let right_col = width - 1;
    let bbox = normalized_bbox_from_pixel_bounds(right_col, 0, right_col, 0, width, height)
      .expect("valid bbox at right edge");
    // Without the f64 fix this would have been `x = 1.0`. With the
    // fix `x = (2^24) / (2^24 + 1)` ≈ 0.99999994 (f32).
    assert!(
      bbox.x() < 1.0,
      "x must remain strictly less than 1.0: {}",
      bbox.x()
    );
    assert!(
      bbox.width() > 0.0,
      "positive foreground width: {}",
      bbox.width()
    );
    // `x + width` MUST satisfy the schema `<= 1.0` invariant
    // (in fact equals 1.0 modulo f32 representation).
    let right_edge = bbox.x() + bbox.width();
    assert!(
      right_edge <= 1.0 + 1e-6,
      "right edge exceeds image: {right_edge}"
    );
  }

  /// The normalizer rejects degenerate input (width or height zero,
  /// or max < min) by returning `None` rather than emitting a wire
  /// bbox the domain validator would reject.
  #[test]
  fn normalized_bbox_rejects_degenerate_input() {
    assert!(normalized_bbox_from_pixel_bounds(0, 0, 10, 10, 0, 100).is_none());
    assert!(normalized_bbox_from_pixel_bounds(0, 0, 10, 10, 100, 0).is_none());
    // max < min (corrupted input)
    assert!(normalized_bbox_from_pixel_bounds(20, 0, 10, 10, 100, 100).is_none());
  }

  // ──────────────── R9 fixes (codex round 9) ────────────────

  /// R8's f64 intermediate fixed the canonical 2^24+1 case but
  /// codex round 9 surfaced that the SAME class returns at
  /// 2^25+1 — `left = 2^25 / (2^25 + 1)` narrows to `1.0` in f32
  /// while `width = 1 / (2^25 + 1)` remains positive. R9's
  /// edge-based fix derives width as `right - left` AFTER both
  /// narrow to f32, AND explicitly rejects `left >= 1.0` after
  /// the narrow.
  ///
  /// Test inputs intentionally span the f32 mantissa-exhaustion
  /// power-of-two boundaries (2^24, 2^25, 2^26) plus the cap
  /// edge — every one must either emit a valid `[0, 1]` bbox OR
  /// return `None`, never `x = 1.0` with positive width.
  #[test]
  fn normalized_bbox_handles_mantissa_exhaustion_boundaries() {
    // Span the boundaries the codex finding called out.
    for shift in 24u32..=25 {
      let width: usize = (1 << shift) + 1;
      let height: usize = 1;
      let right_col = width - 1;
      let result = normalized_bbox_from_pixel_bounds(right_col, 0, right_col, 0, width, height);
      match result {
        None => {
          // Acceptable: the rounding pushed `left` to >= 1.0 and
          // the explicit guard caught it. The detection is dropped,
          // which is the safe semantic.
        }
        Some(bbox) => {
          // If we DO emit a bbox, every invariant must hold —
          // a `[0, 1]`-valid box with positive extent and a right
          // edge that does not exceed the image.
          assert!(
            bbox.x() < 1.0,
            "shift={shift}: x must be < 1.0, got {}",
            bbox.x()
          );
          assert!(
            bbox.width() > 0.0,
            "shift={shift}: width must be > 0.0, got {}",
            bbox.width()
          );
          // f32-safe right-edge check: edge computed directly,
          // not as left + width.
          let right_edge = bbox.x() + bbox.width();
          assert!(
            right_edge <= 1.0 + 1e-6,
            "shift={shift}: right edge exceeds image: {right_edge}",
          );
        }
      }
    }
  }

  /// Same intent at width close to the 64 MiB cap (the largest
  /// allowed width / height combination, where f32 precision
  /// is most degraded).
  #[test]
  fn normalized_bbox_handles_max_mask_bytes_boundary() {
    let width = MAX_MASK_BYTES; // 64 MiB worth of 1-row mask.
    let height = 1usize;
    let right_col = width - 1;
    let result = normalized_bbox_from_pixel_bounds(right_col, 0, right_col, 0, width, height);
    if let Some(bbox) = result {
      assert!(
        bbox.x() < 1.0,
        "x must remain strictly less than 1.0: {}",
        bbox.x()
      );
      assert!(
        bbox.width() > 0.0,
        "positive foreground width: {}",
        bbox.width()
      );
      let right_edge = bbox.x() + bbox.width();
      assert!(
        right_edge <= 1.0 + 1e-6,
        "right edge exceeds image: {right_edge}"
      );
    }
    // `None` is also acceptable — see the previous test's rationale.
  }

  /// `max_x + 1 > width` (corrupted input) must return `None`.
  #[test]
  fn normalized_bbox_rejects_max_above_dimensions() {
    // max_x = width - 1 is OK (right edge); max_x = width is corrupt.
    assert!(normalized_bbox_from_pixel_bounds(0, 0, 100, 0, 100, 1).is_none());
    assert!(normalized_bbox_from_pixel_bounds(0, 0, 0, 100, 1, 100).is_none());
  }

  /// Regression pin: `SimdFloat4x4::ENCODING` must format as
  /// `{?=[4]}` to match Clang's `@encode(simd_float4x4)` and the
  /// runtime metadata of `-[VNHumanBodyRecognizedPoint3D position]`.
  /// The previous `Encoding::Unknown` element rendered as `{?=[4?]}`
  /// and silently broke every msg_send for that selector under
  /// `catch_unwind`. Pinning the string here so a future objc2
  /// upgrade or accidental edit surfaces as a test failure.
  #[test]
  fn simd_float4x4_encoding_matches_clang_at_encode() {
    assert_eq!(SimdFloat4::ENCODING.to_string(), "");
    assert_eq!(SimdFloat4x4::ENCODING.to_string(), "{?=[4]}");
  }
}