depthai-sys 0.1.3

Low-level FFI crate that builds/links Luxonis DepthAI-Core v3 and exposes Rust bindings.
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
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
#include "wrapper.h"
#include "depthai/depthai.hpp"
#include "depthai/pipeline/node/internal/XLinkIn.hpp"
#include "depthai/pipeline/node/internal/XLinkOut.hpp"
#include "depthai/build/version.hpp"
#include "depthai/common/Point3fRGBA.hpp"
#include "depthai/pipeline/datatype/PointCloudData.hpp"
#include "depthai/pipeline/datatype/RGBDData.hpp"
#include "depthai/pipeline/datatype/EncodedFrame.hpp"
#include "XLink/XLink.h"
#include "XLink/XLinkPublicDefines.h"

// Some nodes were introduced in DepthAI-Core after v3.1.0.
// For older versions, avoid referencing the missing types so this wrapper can still compile.
#if defined(__has_include)
    #if __has_include(<depthai/pipeline/node/Rectification.hpp>)
        #include <depthai/pipeline/node/Rectification.hpp>
        #define DAI_HAS_NODE_RECTIFICATION 1
    #else
        #define DAI_HAS_NODE_RECTIFICATION 0
    #endif

    #if __has_include(<depthai/pipeline/node/NeuralDepth.hpp>)
        #include <depthai/pipeline/node/NeuralDepth.hpp>
        #define DAI_HAS_NODE_NEURAL_DEPTH 1
    #else
        #define DAI_HAS_NODE_NEURAL_DEPTH 0
    #endif

    // Gate node and GateControl were introduced in depthai-core v3.4.0.
    #if __has_include(<depthai/pipeline/node/Gate.hpp>)
        #include <depthai/pipeline/node/Gate.hpp>
        #include <depthai/pipeline/datatype/GateControl.hpp>
        #define DAI_HAS_NODE_GATE 1
    #else
        #define DAI_HAS_NODE_GATE 0
    #endif
#else
    #define DAI_HAS_NODE_RECTIFICATION 0
    #define DAI_HAS_NODE_NEURAL_DEPTH 0
    #define DAI_HAS_NODE_GATE 0
#endif
#include <chrono>
#include <cstring>
#include <cstdlib>
#include <limits>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <type_traits>
#include <unordered_map>
#include <functional>

// Global error storage
static std::string last_error = "";

namespace {
template <typename T>
struct _dai_is_std_optional : std::false_type {};

template <typename U>
struct _dai_is_std_optional<std::optional<U>> : std::true_type {};

template <typename T>
inline constexpr bool _dai_is_std_optional_v = _dai_is_std_optional<std::decay_t<T>>::value;

template <typename T, typename Out>
static bool _dai_optional_to_out(const std::optional<T>& value, Out* out) {
    if(!out) return false;
    if(value.has_value()) {
        *out = static_cast<Out>(value.value());
        return true;
    }
    return false;
}

template <typename T, typename Out>
static bool _dai_optionalish_to_out(const T& value, Out* out) {
    if(!out) return false;
    if constexpr(_dai_is_std_optional_v<T>) {
        return _dai_optional_to_out(value, out);
    } else {
        *out = static_cast<Out>(value);
        return true;
    }
}

struct HostNodeCallbacks {
    dai::DaiHostNodeProcessGroup process = nullptr;
    dai::DaiHostNodeCallback on_start = nullptr;
    dai::DaiHostNodeCallback on_stop = nullptr;
    dai::DaiHostNodeCallback drop = nullptr;
};

struct ThreadedHostNodeCallbacks {
    dai::DaiThreadedHostNodeRun run = nullptr;
    dai::DaiHostNodeCallback on_start = nullptr;
    dai::DaiHostNodeCallback on_stop = nullptr;
    dai::DaiHostNodeCallback drop = nullptr;
};

class RustHostNode : public dai::NodeCRTP<dai::node::HostNode, RustHostNode> {
   public:
    RustHostNode(HostNodeCallbacks callbacks, void* ctx) : callbacks(std::move(callbacks)), ctx(ctx) {}
    ~RustHostNode() override {
        if(callbacks.drop) {
            callbacks.drop(ctx);
        }
    }

    std::shared_ptr<dai::Buffer> processGroup(std::shared_ptr<dai::MessageGroup> in) override {
        if(!callbacks.process) {
            return nullptr;
        }
        auto group_handle = new std::shared_ptr<dai::MessageGroup>(in);
        auto out_handle = callbacks.process(ctx, static_cast<dai::DaiMessageGroup>(group_handle));
        if(!out_handle) {
            return nullptr;
        }
        auto out_ptr = static_cast<std::shared_ptr<dai::Buffer>*>(out_handle);
        std::shared_ptr<dai::Buffer> out = *out_ptr;
        delete out_ptr;
        return out;
    }

    void onStart() override {
        if(callbacks.on_start) {
            callbacks.on_start(ctx);
        }
    }

    void onStop() override {
        if(callbacks.on_stop) {
            callbacks.on_stop(ctx);
        }
    }

   private:
    HostNodeCallbacks callbacks;
    void* ctx = nullptr;
};

class RustThreadedHostNode : public dai::NodeCRTP<dai::node::ThreadedHostNode, RustThreadedHostNode> {
   public:
    RustThreadedHostNode(ThreadedHostNodeCallbacks callbacks, void* ctx) : callbacks(std::move(callbacks)), ctx(ctx) {}
    ~RustThreadedHostNode() override {
        if(callbacks.drop) {
            callbacks.drop(ctx);
        }
    }

    void run() override {
        if(callbacks.run) {
            callbacks.run(ctx);
        }
    }

    void onStart() override {
        if(callbacks.on_start) {
            callbacks.on_start(ctx);
        }
    }

    void onStop() override {
        if(callbacks.on_stop) {
            callbacks.on_stop(ctx);
        }
    }

   private:
    ThreadedHostNodeCallbacks callbacks;
    void* ctx = nullptr;
};
}  // namespace

// Device lifetime management
//
// DepthAI devices generally represent an exclusive connection. Creating multiple `dai::Device()`
// instances without selecting distinct physical devices can fail with:
//   "No available devices (1 connected, but in use)"
//
// The C++ API commonly passes around shared pointers to a single selected device.
// To mirror that behavior across the C ABI, we represent `DaiDevice` as a pointer to a
// heap-allocated `std::shared_ptr<dai::Device>`.
//
// We also keep a process-wide default device which `dai_device_new()` returns (or creates).
static std::mutex g_device_mutex;
static std::weak_ptr<dai::Device> g_default_device;

// Some XLink versions/platforms can report device state as X_LINK_ANY_STATE when queried with
// X_LINK_ANY_STATE, which breaks DepthAI's "find any available device" logic.
// To be more robust in our C ABI, we query per concrete state in priority order and then
// construct `dai::Device` from the returned `DeviceInfo`.
static bool select_first_device_info(dai::DeviceInfo& out) {
    // Prefer devices that can be booted/connected immediately.
    const XLinkDeviceState_t states[] = {
        X_LINK_UNBOOTED,
        X_LINK_BOOTLOADER,
        X_LINK_FLASH_BOOTED,
        X_LINK_GATE,
        X_LINK_GATE_SETUP,
        X_LINK_BOOTED,
    };

    for(const auto state : states) {
        try {
            auto devices = dai::XLinkConnection::getAllConnectedDevices(state, /*skipInvalidDevices=*/true);
            if(!devices.empty()) {
                out = devices.front();
                return true;
            }
        } catch(...) {
            // Ignore and continue to next state.
        }
    }
    return false;
}

namespace dai {

const char* dai_build_version() {
    return dai::build::VERSION;
}
int dai_build_version_major() {
    return dai::build::VERSION_MAJOR;
}
int dai_build_version_minor() {
    return dai::build::VERSION_MINOR;
}
int dai_build_version_patch() {
    return dai::build::VERSION_PATCH;
}
const char* dai_build_pre_release_type() {
    return dai::build::PRE_RELEASE_TYPE;
}
int dai_build_pre_release_version() {
    return dai::build::PRE_RELEASE_VERSION;
}
const char* dai_build_commit() {
    return dai::build::COMMIT;
}
const char* dai_build_commit_datetime() {
    return dai::build::COMMIT_DATETIME;
}
const char* dai_build_build_datetime() {
    return dai::build::BUILD_DATETIME;
}
const char* dai_build_device_version() {
    return dai::build::DEVICE_VERSION;
}
const char* dai_build_bootloader_version() {
    return dai::build::BOOTLOADER_VERSION;
}
const char* dai_build_device_rvc3_version() {
    return dai::build::DEVICE_RVC3_VERSION;
}
const char* dai_build_device_rvc4_version() {
    return dai::build::DEVICE_RVC4_VERSION;
}

// Basic string utilities
char* dai_string_to_cstring(const char* str) {
    if(!str) return nullptr;

    size_t len = strlen(str);
    char* result = static_cast<char*>(malloc(len + 1));
    if(result) {
        strcpy(result, str);
    }
    return result;
}

void dai_free_cstring(char* cstring) {
    if (cstring) {
        free(cstring);
    }
}

// Low-level device operations - direct pointer manipulation
DaiDevice dai_device_new() {
    try {
        dai_clear_last_error();
        std::lock_guard<std::mutex> lock(g_device_mutex);

        // Reuse existing default device if it is still alive and not closed.
        if(auto existing = g_default_device.lock()) {
            try {
                if(!existing->isClosed()) {
                    return static_cast<DaiDevice>(new std::shared_ptr<dai::Device>(existing));
                }
            } catch(...) {
                // If isClosed throws for some reason, fall back to creating a new device.
            }
        }

        // Create new default device.
        // Instead of calling `dai::Device()` (which internally uses getAnyAvailableDevice),
        // explicitly select a concrete state/device and construct from DeviceInfo.
        dai::DeviceInfo info;
        if(!select_first_device_info(info)) {
            // Mirror DepthAI's wording as closely as possible.
            auto numConnected = dai::DeviceBase::getAllAvailableDevices().size();
            if(numConnected > 0) {
                throw std::runtime_error(std::string("No available devices (") + std::to_string(numConnected) +
                                         " connected, but in use)");
            }
            throw std::runtime_error("No available devices");
        }

        auto created = std::make_shared<dai::Device>(info, dai::DeviceBase::DEFAULT_USB_SPEED);
        g_default_device = created;
        return static_cast<DaiDevice>(new std::shared_ptr<dai::Device>(created));
    } catch (const std::exception& e) {
        last_error = std::string("dai_device_new failed: ") + e.what();
        return nullptr;
    }
}

DaiDevice dai_device_clone(DaiDevice device) {
    if(!device) {
        last_error = "dai_device_clone: null device";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::Device>*>(device);
        return static_cast<DaiDevice>(new std::shared_ptr<dai::Device>(*ptr));
    } catch (const std::exception& e) {
        last_error = std::string("dai_device_clone failed: ") + e.what();
        return nullptr;
    }
}

void dai_device_delete(DaiDevice device) {
    if (device) {
        auto dev = static_cast<std::shared_ptr<dai::Device>*>(device);
        // If this is the last strong reference, proactively close the device.
        // Some DepthAI backends can otherwise keep the device marked as "in use"
        // for longer than expected.
        try {
            if(dev->use_count() == 1 && dev->get() && (*dev) && !(*dev)->isClosed()) {
                (*dev)->close();
            }
        } catch(...) {
            // Best-effort: proceed with deletion.
        }
        delete dev;
    }
}

bool dai_device_is_closed(DaiDevice device) {
    if (!device) {
        last_error = "dai_device_is_closed: null device";
        return true;
    }
    try {
        auto dev = static_cast<std::shared_ptr<dai::Device>*>(device);
        if(!dev->get() || !(*dev)) return true;
        return (*dev)->isClosed();
    } catch (const std::exception& e) {
        last_error = std::string("dai_device_is_closed failed: ") + e.what();
        return true;
    }
}

void dai_device_close(DaiDevice device) {
    if (!device) {
        last_error = "dai_device_close: null device";
        return;
    }
    try {
        auto dev = static_cast<std::shared_ptr<dai::Device>*>(device);
        if(!dev->get() || !(*dev)) {
            last_error = "dai_device_close: invalid device";
            return;
        }
        (*dev)->close();
    } catch (const std::exception& e) {
        last_error = std::string("dai_device_close failed: ") + e.what();
    }
}

// Low-level pipeline operations
DaiPipeline dai_pipeline_new() {
    try {
        dai_clear_last_error();
        auto pipeline = new dai::Pipeline();
        return static_cast<DaiPipeline>(pipeline);
    } catch (const std::exception& e) {
        // printf("DEBUG: dai::Pipeline creation failed: %s\n", e.what());
        last_error = std::string("dai_pipeline_new failed: ") + e.what();
        return nullptr;
    }
}

DaiPipeline dai_pipeline_new_ex(bool create_implicit_device) {
    try {
        dai_clear_last_error();
        auto pipeline = new dai::Pipeline(create_implicit_device);
        return static_cast<DaiPipeline>(pipeline);
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_new_ex failed: ") + e.what();
        return nullptr;
    }
}

DaiPipeline dai_pipeline_new_with_device(DaiDevice device) {
    if(!device) {
        last_error = "dai_pipeline_new_with_device: null device";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto dev = static_cast<std::shared_ptr<dai::Device>*>(device);
        if(!dev->get() || !(*dev)) {
            last_error = "dai_pipeline_new_with_device: invalid device";
            return nullptr;
        }
        auto pipeline = new dai::Pipeline(*dev);
        return static_cast<DaiPipeline>(pipeline);
    } catch (const std::exception& e) {
        last_error = std::string("dai_pipeline_new_with_device failed: ") + e.what();
        return nullptr;
    }
}

DaiNode dai_rgbd_build(DaiNode rgbd) {
    if(!rgbd) {
        last_error = "dai_rgbd_build: null rgbd";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto node = static_cast<dai::node::RGBD*>(rgbd);
        auto built = node->build();
        return static_cast<DaiNode>(built.get());
    } catch(const std::exception& e) {
        last_error = std::string("dai_rgbd_build failed: ") + e.what();
        return nullptr;
    }
}

DaiNode dai_rgbd_build_ex(DaiNode rgbd, bool autocreate, int preset_mode, int width, int height, float fps) {
    if(!rgbd) {
        last_error = "dai_rgbd_build_ex: null rgbd";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto node = static_cast<dai::node::RGBD*>(rgbd);

        std::optional<float> fpsOpt = std::nullopt;
        if(fps > 0.0f) {
            fpsOpt = fps;
        }

        auto mode = static_cast<dai::node::StereoDepth::PresetMode>(preset_mode);
        auto built = node->build(autocreate, mode, {width, height}, fpsOpt);
        return static_cast<DaiNode>(built.get());
    } catch(const std::exception& e) {
        last_error = std::string("dai_rgbd_build_ex failed: ") + e.what();
        return nullptr;
    }
}

void dai_pipeline_delete(DaiPipeline pipeline) {
    if (pipeline) {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        delete pipe;
    }
}

bool dai_pipeline_start(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_start: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        pipe->start();
        return true;
    } catch (const std::exception& e) {
        last_error = std::string("dai_pipeline_start failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_is_running(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_is_running: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        return pipe->isRunning();
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_is_running failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_is_built(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_is_built: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        return pipe->isBuilt();
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_is_built failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_build(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_build: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        pipe->build();
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_build failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_wait(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_wait: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        pipe->wait();
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_wait failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_stop(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_stop: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        pipe->stop();
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_stop failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_run(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_run: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        pipe->run();
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_run failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_process_tasks(DaiPipeline pipeline, bool wait_for_tasks, double timeout_seconds) {
    if(!pipeline) {
        last_error = "dai_pipeline_process_tasks: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        pipe->processTasks(wait_for_tasks, timeout_seconds);
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_process_tasks failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_set_xlink_chunk_size(DaiPipeline pipeline, int size_bytes) {
    if(!pipeline) {
        last_error = "dai_pipeline_set_xlink_chunk_size: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        pipe->setXLinkChunkSize(size_bytes);
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_set_xlink_chunk_size failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_set_sipp_buffer_size(DaiPipeline pipeline, int size_bytes) {
    if(!pipeline) {
        last_error = "dai_pipeline_set_sipp_buffer_size: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        pipe->setSippBufferSize(size_bytes);
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_set_sipp_buffer_size failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_set_sipp_dma_buffer_size(DaiPipeline pipeline, int size_bytes) {
    if(!pipeline) {
        last_error = "dai_pipeline_set_sipp_dma_buffer_size: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        pipe->setSippDmaBufferSize(size_bytes);
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_set_sipp_dma_buffer_size failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_set_camera_tuning_blob_path(DaiPipeline pipeline, const char* path) {
    if(!pipeline) {
        last_error = "dai_pipeline_set_camera_tuning_blob_path: null pipeline";
        return false;
    }
    if(!path) {
        last_error = "dai_pipeline_set_camera_tuning_blob_path: null path";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        // Interpret input as UTF-8.
        pipe->setCameraTuningBlobPath(std::filesystem::u8path(path));
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_set_camera_tuning_blob_path failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_set_openvino_version(DaiPipeline pipeline, int version) {
    if(!pipeline) {
        last_error = "dai_pipeline_set_openvino_version: null pipeline";
        return false;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        pipe->setOpenVINOVersion(static_cast<dai::OpenVINO::Version>(version));
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_set_openvino_version failed: ") + e.what();
        return false;
    }
}

char* dai_pipeline_serialize_to_json(DaiPipeline pipeline, bool include_assets) {
    if(!pipeline) {
        last_error = "dai_pipeline_serialize_to_json: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto j = pipe->serializeToJson(include_assets);
        auto dumped = j.dump();
        return dai_string_to_cstring(dumped.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_serialize_to_json failed: ") + e.what();
        return nullptr;
    }
}

char* dai_pipeline_get_schema_json(DaiPipeline pipeline, int serialization_type) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_schema_json: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        // We expose schema as JSON regardless of requested serialization type.
        auto schema = pipe->getPipelineSchema(static_cast<dai::SerializationType>(serialization_type));
        nlohmann::json j = schema;
        auto dumped = j.dump();
        return dai_string_to_cstring(dumped.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_schema_json failed: ") + e.what();
        return nullptr;
    }
}

char* dai_pipeline_get_all_nodes_json(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_all_nodes_json: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto nodes = pipe->getAllNodes();
        nlohmann::json j = nlohmann::json::array();
        for(const auto& n : nodes) {
            if(!n) continue;
            nlohmann::json item;
            item["id"] = n->id;
            item["alias"] = n->getAlias();
            item["name"] = std::string(n->getName());
            j.push_back(std::move(item));
        }
        auto dumped = j.dump();
        return dai_string_to_cstring(dumped.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_all_nodes_json failed: ") + e.what();
        return nullptr;
    }
}

char* dai_pipeline_get_source_nodes_json(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_source_nodes_json: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto nodes = pipe->getSourceNodes();
        nlohmann::json j = nlohmann::json::array();
        for(const auto& n : nodes) {
            if(!n) continue;
            nlohmann::json item;
            item["id"] = n->id;
            item["alias"] = n->getAlias();
            item["name"] = std::string(n->getName());
            j.push_back(std::move(item));
        }
        auto dumped = j.dump();
        return dai_string_to_cstring(dumped.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_source_nodes_json failed: ") + e.what();
        return nullptr;
    }
}

DaiNode dai_pipeline_get_node_by_id(DaiPipeline pipeline, int id) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_node_by_id: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto n = pipe->getNode(static_cast<dai::Node::Id>(id));
        if(!n) {
            return nullptr;
        }
        return static_cast<DaiNode>(n.get());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_node_by_id failed: ") + e.what();
        return nullptr;
    }
}

bool dai_pipeline_remove_node(DaiPipeline pipeline, DaiNode node) {
    if(!pipeline) {
        last_error = "dai_pipeline_remove_node: null pipeline";
        return false;
    }
    if(!node) {
        last_error = "dai_pipeline_remove_node: null node";
        return false;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto target = static_cast<dai::Node*>(node);
        auto nodes = pipe->getAllNodes();
        for(const auto& n : nodes) {
            if(n && n.get() == target) {
                pipe->remove(n);
                return true;
            }
        }
        last_error = "dai_pipeline_remove_node: node not found in pipeline";
        return false;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_remove_node failed: ") + e.what();
        return false;
    }
}

char* dai_pipeline_get_connections_json(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_connections_json: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto conns = pipe->getConnections();
        nlohmann::json j = nlohmann::json::array();
        for(const auto& c : conns) {
            nlohmann::json item;
            item["outputId"] = c.outputId;
            item["outputGroup"] = c.outputGroup;
            item["outputName"] = c.outputName;
            item["inputId"] = c.inputId;
            item["inputGroup"] = c.inputGroup;
            item["inputName"] = c.inputName;
            j.push_back(std::move(item));
        }
        auto dumped = j.dump();
        return dai_string_to_cstring(dumped.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_connections_json failed: ") + e.what();
        return nullptr;
    }
}

char* dai_pipeline_get_connection_map_json(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_connection_map_json: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto cmap = pipe->getConnectionMap();

        // JSON object keyed by input node id (as string), value is list of connections.
        nlohmann::json j = nlohmann::json::object();
        for(const auto& kv : cmap) {
            const auto inputId = kv.first;
            const auto& set = kv.second;

            nlohmann::json arr = nlohmann::json::array();
            for(const auto& c : set) {
                nlohmann::json item;
                auto outNode = c.outputNode.lock();
                auto inNode = c.inputNode.lock();
                item["outputId"] = outNode ? outNode->id : -1;
                item["outputGroup"] = c.outputGroup;
                item["outputName"] = c.outputName;
                item["inputId"] = inNode ? inNode->id : inputId;
                item["inputGroup"] = c.inputGroup;
                item["inputName"] = c.inputName;
                arr.push_back(std::move(item));
            }

            j[std::to_string(inputId)] = std::move(arr);
        }

        auto dumped = j.dump();
        return dai_string_to_cstring(dumped.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_connection_map_json failed: ") + e.what();
        return nullptr;
    }
}

bool dai_pipeline_is_calibration_data_available(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_is_calibration_data_available: null pipeline";
        return false;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        return pipe->isCalibrationDataAvailable();
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_is_calibration_data_available failed: ") + e.what();
        return false;
    }
}

char* dai_pipeline_get_calibration_data_json(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_calibration_data_json: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        nlohmann::json j;
        if(pipe->isCalibrationDataAvailable()) {
            auto calib = pipe->getCalibrationData();
            j = calib.eepromToJson();
        } else {
            j = nullptr;
        }
        auto dumped = j.dump();
        return dai_string_to_cstring(dumped.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_calibration_data_json failed: ") + e.what();
        return nullptr;
    }
}

bool dai_pipeline_set_calibration_data_json(DaiPipeline pipeline, const char* eeprom_data_json) {
    if(!pipeline) {
        last_error = "dai_pipeline_set_calibration_data_json: null pipeline";
        return false;
    }
    if(!eeprom_data_json) {
        last_error = "dai_pipeline_set_calibration_data_json: null eeprom_data_json";
        return false;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto j = nlohmann::json::parse(eeprom_data_json);
        if(j.is_null()) {
            last_error = "dai_pipeline_set_calibration_data_json: null is not supported";
            return false;
        }
        auto calib = dai::CalibrationHandler::fromJson(j);
        pipe->setCalibrationData(std::move(calib));
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_set_calibration_data_json failed: ") + e.what();
        return false;
    }
}

char* dai_pipeline_get_global_properties_json(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_global_properties_json: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto props = pipe->getGlobalProperties();
        nlohmann::json j = props;
        auto dumped = j.dump();
        return dai_string_to_cstring(dumped.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_global_properties_json failed: ") + e.what();
        return nullptr;
    }
}

bool dai_pipeline_set_global_properties_json(DaiPipeline pipeline, const char* json) {
    if(!pipeline) {
        last_error = "dai_pipeline_set_global_properties_json: null pipeline";
        return false;
    }
    if(!json) {
        last_error = "dai_pipeline_set_global_properties_json: null json";
        return false;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto j = nlohmann::json::parse(json);
        dai::GlobalProperties props = j.get<dai::GlobalProperties>();
        pipe->setGlobalProperties(std::move(props));
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_set_global_properties_json failed: ") + e.what();
        return false;
    }
}

char* dai_pipeline_get_board_config_json(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_board_config_json: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto cfg = pipe->getBoardConfig();
        nlohmann::json j = cfg;
        auto dumped = j.dump();
        return dai_string_to_cstring(dumped.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_board_config_json failed: ") + e.what();
        return nullptr;
    }
}

bool dai_pipeline_set_board_config_json(DaiPipeline pipeline, const char* json) {
    if(!pipeline) {
        last_error = "dai_pipeline_set_board_config_json: null pipeline";
        return false;
    }
    if(!json) {
        last_error = "dai_pipeline_set_board_config_json: null json";
        return false;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto j = nlohmann::json::parse(json);
        dai::BoardConfig cfg = j.get<dai::BoardConfig>();
        pipe->setBoardConfig(std::move(cfg));
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_set_board_config_json failed: ") + e.what();
        return false;
    }
}

char* dai_pipeline_get_device_config_json(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_device_config_json: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto cfg = pipe->getDeviceConfig();
        // `dai::Device::Config` (alias of `dai::DeviceBase::Config`) doesn't provide
        // a nlohmann::json implicit conversion in all DepthAI versions.
        // Build a stable JSON representation manually.
        nlohmann::json j;
        j["version"] = static_cast<int>(cfg.version);
        j["board"] = cfg.board;
        j["nonExclusiveMode"] = cfg.nonExclusiveMode;
        if(cfg.outputLogLevel.has_value()) {
            j["outputLogLevel"] = static_cast<int>(cfg.outputLogLevel.value());
        } else {
            j["outputLogLevel"] = nullptr;
        }
        if(cfg.logLevel.has_value()) {
            j["logLevel"] = static_cast<int>(cfg.logLevel.value());
        } else {
            j["logLevel"] = nullptr;
        }
        auto dumped = j.dump();
        return dai_string_to_cstring(dumped.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_device_config_json failed: ") + e.what();
        return nullptr;
    }
}

char* dai_pipeline_get_eeprom_data_json(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_eeprom_data_json: null pipeline";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto opt = pipe->getEepromData();
        nlohmann::json j;
        if(opt.has_value()) {
            j = opt.value();
        } else {
            j = nullptr;
        }
        auto dumped = j.dump();
        return dai_string_to_cstring(dumped.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_eeprom_data_json failed: ") + e.what();
        return nullptr;
    }
}

bool dai_pipeline_set_eeprom_data_json(DaiPipeline pipeline, const char* json) {
    if(!pipeline) {
        last_error = "dai_pipeline_set_eeprom_data_json: null pipeline";
        return false;
    }
    if(!json) {
        last_error = "dai_pipeline_set_eeprom_data_json: null json";
        return false;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);

        auto j = nlohmann::json::parse(json);
        if(j.is_null()) {
            pipe->setEepromData(std::nullopt);
        } else {
            dai::EepromData data = j.get<dai::EepromData>();
            pipe->setEepromData(std::move(data));
        }
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_set_eeprom_data_json failed: ") + e.what();
        return false;
    }
}

uint32_t dai_pipeline_get_eeprom_id(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_eeprom_id: null pipeline";
        return 0;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        return pipe->getEepromId();
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_get_eeprom_id failed: ") + e.what();
        return 0;
    }
}

bool dai_pipeline_enable_holistic_record_json(DaiPipeline pipeline, const char* record_config_json) {
    if(!pipeline) {
        last_error = "dai_pipeline_enable_holistic_record_json: null pipeline";
        return false;
    }
    if(!record_config_json) {
        last_error = "dai_pipeline_enable_holistic_record_json: null record_config_json";
        return false;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto j = nlohmann::json::parse(record_config_json);
        dai::RecordConfig cfg = j.get<dai::RecordConfig>();
        pipe->enableHolisticRecord(cfg);
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_enable_holistic_record_json failed: ") + e.what();
        return false;
    }
}

bool dai_pipeline_enable_holistic_replay(DaiPipeline pipeline, const char* path_to_recording) {
    if(!pipeline) {
        last_error = "dai_pipeline_enable_holistic_replay: null pipeline";
        return false;
    }
    if(!path_to_recording) {
        last_error = "dai_pipeline_enable_holistic_replay: null path_to_recording";
        return false;
    }
    try {
        dai_clear_last_error();
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        pipe->enableHolisticReplay(std::string(path_to_recording));
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_enable_holistic_replay failed: ") + e.what();
        return false;
    }
}

DaiNode dai_pipeline_create_host_node(DaiPipeline pipeline,
                                      void* ctx,
                                      DaiHostNodeProcessGroup process_cb,
                                      DaiHostNodeCallback on_start_cb,
                                      DaiHostNodeCallback on_stop_cb,
                                      DaiHostNodeCallback drop_cb) {
    if(!pipeline) {
        last_error = "dai_pipeline_create_host_node: null pipeline";
        return nullptr;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        HostNodeCallbacks callbacks{process_cb, on_start_cb, on_stop_cb, drop_cb};
        auto node = std::make_shared<RustHostNode>(std::move(callbacks), ctx);
        pipe->add(node);
        return static_cast<DaiNode>(node.get());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_create_host_node failed: ") + e.what();
        return nullptr;
    }
}

DaiNode dai_pipeline_create_threaded_host_node(DaiPipeline pipeline,
                                               void* ctx,
                                               DaiThreadedHostNodeRun run_cb,
                                               DaiHostNodeCallback on_start_cb,
                                               DaiHostNodeCallback on_stop_cb,
                                               DaiHostNodeCallback drop_cb) {
    if(!pipeline) {
        last_error = "dai_pipeline_create_threaded_host_node: null pipeline";
        return nullptr;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        ThreadedHostNodeCallbacks callbacks{run_cb, on_start_cb, on_stop_cb, drop_cb};
        auto node = std::make_shared<RustThreadedHostNode>(std::move(callbacks), ctx);
        pipe->add(node);
        return static_cast<DaiNode>(node.get());
    } catch(const std::exception& e) {
        last_error = std::string("dai_pipeline_create_threaded_host_node failed: ") + e.what();
        return nullptr;
    }
}

// Backwards-compatible alias. Historically the Rust wrapper exposed `start_default()`,
// but DepthAI's `dai::Pipeline` already manages a default device internally.
bool dai_pipeline_start_default(DaiPipeline pipeline) {
    return dai_pipeline_start(pipeline);
}

DaiDevice dai_pipeline_get_default_device(DaiPipeline pipeline) {
    if(!pipeline) {
        last_error = "dai_pipeline_get_default_device: null pipeline";
        return nullptr;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto dev = pipe->getDefaultDevice();
        if(!dev) {
            last_error = "dai_pipeline_get_default_device: pipeline has no default device";
            return nullptr;
        }
        return static_cast<DaiDevice>(new std::shared_ptr<dai::Device>(std::move(dev)));
    } catch (const std::exception& e) {
        last_error = std::string("dai_pipeline_get_default_device failed: ") + e.what();
        return nullptr;
    }
}

// Generic node creation / linking
using NodeCreator = std::function<dai::Node*(dai::Pipeline*)>;

#define REGISTER_NODE(name) registry[#name] = [](dai::Pipeline* p) { return p->create<name>().get(); }

static std::unordered_map<std::string, NodeCreator>& get_node_registry() {
    static std::unordered_map<std::string, NodeCreator> registry;
    if (registry.empty()) {
        REGISTER_NODE(dai::node::Camera);
        REGISTER_NODE(dai::node::ColorCamera);
        REGISTER_NODE(dai::node::MonoCamera);
        REGISTER_NODE(dai::node::StereoDepth);
        REGISTER_NODE(dai::node::ImageAlign);
        REGISTER_NODE(dai::node::RGBD);
        REGISTER_NODE(dai::node::VideoEncoder);
        REGISTER_NODE(dai::node::NeuralNetwork);
        REGISTER_NODE(dai::node::ImageManip);
        REGISTER_NODE(dai::node::Script);
        REGISTER_NODE(dai::node::SystemLogger);
        REGISTER_NODE(dai::node::SpatialLocationCalculator);
        REGISTER_NODE(dai::node::FeatureTracker);
        REGISTER_NODE(dai::node::ObjectTracker);
        REGISTER_NODE(dai::node::IMU);
        REGISTER_NODE(dai::node::EdgeDetector);
        REGISTER_NODE(dai::node::Warp);
        REGISTER_NODE(dai::node::AprilTag);
        REGISTER_NODE(dai::node::DetectionParser);
        REGISTER_NODE(dai::node::PointCloud);
        REGISTER_NODE(dai::node::Sync);
        REGISTER_NODE(dai::node::ToF);
        REGISTER_NODE(dai::node::UVC);
        REGISTER_NODE(dai::node::DetectionNetwork);
        REGISTER_NODE(dai::node::SpatialDetectionNetwork);
        REGISTER_NODE(dai::node::BenchmarkIn);
        REGISTER_NODE(dai::node::BenchmarkOut);

    #if DAI_HAS_NODE_RECTIFICATION
        REGISTER_NODE(dai::node::Rectification);
    #endif

        REGISTER_NODE(dai::node::MessageDemux);

    #if DAI_HAS_NODE_NEURAL_DEPTH
        REGISTER_NODE(dai::node::NeuralDepth);
    #endif

        REGISTER_NODE(dai::node::SPIIn);
        REGISTER_NODE(dai::node::SPIOut);
        REGISTER_NODE(dai::node::Thermal);

        // XLink nodes are in internal namespace but we expose them as dai::node::XLinkIn/Out
        registry["dai::node::XLinkIn"] = [](dai::Pipeline* p) { return p->create<dai::node::internal::XLinkIn>().get(); };
        registry["dai::node::XLinkOut"] = [](dai::Pipeline* p) { return p->create<dai::node::internal::XLinkOut>().get(); };
    }
    return registry;
}

DaiNode dai_pipeline_create_node_by_name(DaiPipeline pipeline, const char* name) {
    if (!pipeline || !name) {
        last_error = "dai_pipeline_create_node_by_name: null pipeline or name";
        return nullptr;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto& registry = get_node_registry();
        auto it = registry.find(name);
        if (it != registry.end()) {
            return static_cast<DaiNode>(it->second(pipe));
        }
        
        last_error = std::string("dai_pipeline_create_node_by_name: unknown node name: ") + name;
        return nullptr;
    } catch (const std::exception& e) {
        last_error = std::string("dai_pipeline_create_node_by_name failed: ") + e.what();
        return nullptr;
    }
}

// Forward declarations for helpers defined later in this file.
static inline bool _dai_cstr_empty(const char* s);
static inline dai::Node::Input* _dai_pick_input_for_output(dai::Node* toNode, dai::Node::Output* output, const char* in_group);

DaiOutput dai_node_get_output(DaiNode node, const char* group, const char* name) {
    if(!node) {
        last_error = "dai_node_get_output: null node";
        return nullptr;
    }
    if(_dai_cstr_empty(name)) {
        last_error = "dai_node_get_output: empty name";
        return nullptr;
    }
    try {
        auto n = static_cast<dai::Node*>(node);
        dai::Node::Output* out = group ? n->getOutputRef(std::string(group), std::string(name)) : n->getOutputRef(std::string(name));
        if(!out) {
            last_error = "dai_node_get_output: output not found";
            return nullptr;
        }
        return static_cast<DaiOutput>(out);
    } catch(const std::exception& e) {
        last_error = std::string("dai_node_get_output failed: ") + e.what();
        return nullptr;
    }
}

DaiInput dai_node_get_input(DaiNode node, const char* group, const char* name) {
    if(!node) {
        last_error = "dai_node_get_input: null node";
        return nullptr;
    }
    if(_dai_cstr_empty(name)) {
        last_error = "dai_node_get_input: empty name";
        return nullptr;
    }
    try {
        auto n = static_cast<dai::Node*>(node);
        dai::Node::Input* in = group ? n->getInputRef(std::string(group), std::string(name)) : n->getInputRef(std::string(name));
        if(!in) {
            last_error = "dai_node_get_input: input not found";
            return nullptr;
        }
        return static_cast<DaiInput>(in);
    } catch(const std::exception& e) {
        last_error = std::string("dai_node_get_input failed: ") + e.what();
        return nullptr;
    }
}

int dai_node_get_id(DaiNode node) {
    if(!node) {
        last_error = "dai_node_get_id: null node";
        return -1;
    }
    try {
        dai_clear_last_error();
        auto n = static_cast<dai::Node*>(node);
        return n->id;
    } catch(const std::exception& e) {
        last_error = std::string("dai_node_get_id failed: ") + e.what();
        return -1;
    }
}

char* dai_node_get_alias(DaiNode node) {
    if(!node) {
        last_error = "dai_node_get_alias: null node";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto n = static_cast<dai::Node*>(node);
        auto s = n->getAlias();
        return dai_string_to_cstring(s.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_node_get_alias failed: ") + e.what();
        return nullptr;
    }
}

bool dai_node_set_alias(DaiNode node, const char* alias) {
    if(!node) {
        last_error = "dai_node_set_alias: null node";
        return false;
    }
    if(!alias) {
        last_error = "dai_node_set_alias: null alias";
        return false;
    }
    try {
        dai_clear_last_error();
        auto n = static_cast<dai::Node*>(node);
        n->setAlias(std::string(alias));
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_node_set_alias failed: ") + e.what();
        return false;
    }
}

char* dai_node_get_name(DaiNode node) {
    if(!node) {
        last_error = "dai_node_get_name: null node";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto n = static_cast<dai::Node*>(node);
        const char* name = n->getName();
        if(!name) {
            return dai_string_to_cstring("");
        }
        return dai_string_to_cstring(name);
    } catch(const std::exception& e) {
        last_error = std::string("dai_node_get_name failed: ") + e.what();
        return nullptr;
    }
}

bool dai_output_link(DaiOutput from, DaiNode to, const char* in_group, const char* in_name) {
    if(!from || !to) {
        last_error = "dai_output_link: null from/to";
        return false;
    }
    try {
        auto out = static_cast<dai::Node::Output*>(from);
        auto toNode = static_cast<dai::Node*>(to);

        const bool inSpecified = !_dai_cstr_empty(in_name);
        dai::Node::Input* input = nullptr;

        if(inSpecified) {
            const std::string inNameStr(in_name);
            const std::optional<std::string> inGroupStr = in_group ? std::optional<std::string>(std::string(in_group)) : std::nullopt;

            auto try_find_on_node = [&](dai::Node* n) -> dai::Node::Input* {
                if(!n) return nullptr;

                // Most nodes expose their inputs directly via getInputRef(name).
                if(inGroupStr.has_value()) {
                    if(auto* i = n->getInputRef(inGroupStr.value(), inNameStr)) return i;
                }
                if(auto* i = n->getInputRef(inNameStr)) return i;

                // Some nodes (e.g. Sync-based host nodes) keep dynamic inputs under an InputMap named "inputs".
                // When callers don't specify a group, try that common map name as a fallback.
                if(!inGroupStr.has_value()) {
                    if(auto* i = n->getInputRef(std::string("inputs"), inNameStr)) return i;
                }

                return nullptr;
            };

            // First try on the target node itself.
            input = try_find_on_node(toNode);

            // If not found, try any subnodes (e.g. RGBD -> Sync subnode).
            if(!input) {
                for(const auto& child : toNode->getNodeMap()) {
                    input = try_find_on_node(child.get());
                    if(input) break;
                }
            }

            if(!input) {
                last_error = "dai_output_link: input not found";
                return false;
            }
        } else {
            input = _dai_pick_input_for_output(toNode, out, in_group);
        }

        if(!input) {
            last_error = "dai_output_link: no compatible input found";
            return false;
        }
        out->link(*input);
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_output_link failed: ") + e.what();
        return false;
    }
}

bool dai_output_link_input(DaiOutput from, DaiInput to) {
    if(!from || !to) {
        last_error = "dai_output_link_input: null from/to";
        return false;
    }
    try {
        auto out = static_cast<dai::Node::Output*>(from);
        auto in = static_cast<dai::Node::Input*>(to);
        out->link(*in);
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_output_link_input failed: ") + e.what();
        return false;
    }
}

int dai_device_get_platform(DaiDevice device) {
    if(!device) {
        last_error = "dai_device_get_platform: null device";
        return -1;
    }
    try {
        auto dev = static_cast<std::shared_ptr<dai::Device>*>(device);
        if(!dev->get() || !(*dev)) {
            last_error = "dai_device_get_platform: invalid device";
            return -1;
        }
        return static_cast<int>((*dev)->getPlatform());
    } catch(const std::exception& e) {
        last_error = std::string("dai_device_get_platform failed: ") + e.what();
        return -1;
    }
}

void dai_device_set_ir_laser_dot_projector_intensity(DaiDevice device, float intensity) {
    if(!device) {
        last_error = "dai_device_set_ir_laser_dot_projector_intensity: null device";
        return;
    }
    try {
        auto dev = static_cast<std::shared_ptr<dai::Device>*>(device);
        if(!dev->get() || !(*dev)) {
            last_error = "dai_device_set_ir_laser_dot_projector_intensity: invalid device";
            return;
        }
        (*dev)->setIrLaserDotProjectorIntensity(intensity);
    } catch(const std::exception& e) {
        last_error = std::string("dai_device_set_ir_laser_dot_projector_intensity failed: ") + e.what();
    }
}

static inline dai::node::StereoDepth* _dai_as_stereo(DaiNode stereo) {
    return static_cast<dai::node::StereoDepth*>(stereo);
}

void dai_stereo_set_subpixel(DaiNode stereo, bool enable) {
    if(!stereo) {
        last_error = "dai_stereo_set_subpixel: null stereo";
        return;
    }
    try {
        _dai_as_stereo(stereo)->setSubpixel(enable);
    } catch(const std::exception& e) {
        last_error = std::string("dai_stereo_set_subpixel failed: ") + e.what();
    }
}

void dai_stereo_set_extended_disparity(DaiNode stereo, bool enable) {
    if(!stereo) {
        last_error = "dai_stereo_set_extended_disparity: null stereo";
        return;
    }
    try {
        _dai_as_stereo(stereo)->setExtendedDisparity(enable);
    } catch(const std::exception& e) {
        last_error = std::string("dai_stereo_set_extended_disparity failed: ") + e.what();
    }
}

void dai_stereo_set_default_profile_preset(DaiNode stereo, int preset_mode) {
    if(!stereo) {
        last_error = "dai_stereo_set_default_profile_preset: null stereo";
        return;
    }
    try {
        _dai_as_stereo(stereo)->setDefaultProfilePreset(static_cast<dai::node::StereoDepth::PresetMode>(preset_mode));
    } catch(const std::exception& e) {
        last_error = std::string("dai_stereo_set_default_profile_preset failed: ") + e.what();
    }
}

void dai_stereo_set_left_right_check(DaiNode stereo, bool enable) {
    if(!stereo) {
        last_error = "dai_stereo_set_left_right_check: null stereo";
        return;
    }
    try {
        _dai_as_stereo(stereo)->setLeftRightCheck(enable);
    } catch(const std::exception& e) {
        last_error = std::string("dai_stereo_set_left_right_check failed: ") + e.what();
    }
}

void dai_stereo_set_rectify_edge_fill_color(DaiNode stereo, int color) {
    if(!stereo) {
        last_error = "dai_stereo_set_rectify_edge_fill_color: null stereo";
        return;
    }
    try {
        _dai_as_stereo(stereo)->setRectifyEdgeFillColor(color);
    } catch(const std::exception& e) {
        last_error = std::string("dai_stereo_set_rectify_edge_fill_color failed: ") + e.what();
    }
}

void dai_stereo_enable_distortion_correction(DaiNode stereo, bool enable) {
    if(!stereo) {
        last_error = "dai_stereo_enable_distortion_correction: null stereo";
        return;
    }
    try {
        _dai_as_stereo(stereo)->enableDistortionCorrection(enable);
    } catch(const std::exception& e) {
        last_error = std::string("dai_stereo_enable_distortion_correction failed: ") + e.what();
    }
}

void dai_stereo_set_output_size(DaiNode stereo, int width, int height) {
    if(!stereo) {
        last_error = "dai_stereo_set_output_size: null stereo";
        return;
    }
    try {
        _dai_as_stereo(stereo)->setOutputSize(width, height);
    } catch(const std::exception& e) {
        last_error = std::string("dai_stereo_set_output_size failed: ") + e.what();
    }
}

void dai_stereo_set_output_keep_aspect_ratio(DaiNode stereo, bool keep) {
    if(!stereo) {
        last_error = "dai_stereo_set_output_keep_aspect_ratio: null stereo";
        return;
    }
    try {
        _dai_as_stereo(stereo)->setOutputKeepAspectRatio(keep);
    } catch(const std::exception& e) {
        last_error = std::string("dai_stereo_set_output_keep_aspect_ratio failed: ") + e.what();
    }
}

void dai_stereo_initial_set_left_right_check_threshold(DaiNode stereo, int threshold) {
    if(!stereo) {
        last_error = "dai_stereo_initial_set_left_right_check_threshold: null stereo";
        return;
    }
    try {
        auto s = _dai_as_stereo(stereo);
        if(!s->initialConfig) {
            last_error = "dai_stereo_initial_set_left_right_check_threshold: initialConfig is null";
            return;
        }
        s->initialConfig->setLeftRightCheckThreshold(threshold);
    } catch(const std::exception& e) {
        last_error = std::string("dai_stereo_initial_set_left_right_check_threshold failed: ") + e.what();
    }
}

void dai_stereo_initial_set_threshold_filter_max_range(DaiNode stereo, int max_range) {
    if(!stereo) {
        last_error = "dai_stereo_initial_set_threshold_filter_max_range: null stereo";
        return;
    }
    try {
        auto s = _dai_as_stereo(stereo);
        if(!s->initialConfig) {
            last_error = "dai_stereo_initial_set_threshold_filter_max_range: initialConfig is null";
            return;
        }
        s->initialConfig->postProcessing.thresholdFilter.maxRange = max_range;
    } catch(const std::exception& e) {
        last_error = std::string("dai_stereo_initial_set_threshold_filter_max_range failed: ") + e.what();
    }
}

void dai_rgbd_set_depth_unit(DaiNode rgbd, int depth_unit) {
    if(!rgbd) {
        last_error = "dai_rgbd_set_depth_unit: null rgbd";
        return;
    }
    try {
        auto r = static_cast<dai::node::RGBD*>(rgbd);
        r->setDepthUnit(static_cast<dai::StereoDepthConfig::AlgorithmControl::DepthUnit>(depth_unit));
    } catch(const std::exception& e) {
        last_error = std::string("dai_rgbd_set_depth_unit failed: ") + e.what();
    }
}

static inline dai::node::ImageAlign* _dai_as_image_align(DaiNode align) {
    return static_cast<dai::node::ImageAlign*>(align);
}

void dai_image_align_set_run_on_host(DaiNode align, bool run_on_host) {
    if(!align) {
        last_error = "dai_image_align_set_run_on_host: null align";
        return;
    }
    try {
        _dai_as_image_align(align)->setRunOnHost(run_on_host);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_align_set_run_on_host failed: ") + e.what();
    }
}

void dai_image_align_set_output_size(DaiNode align, int width, int height) {
    if(!align) {
        last_error = "dai_image_align_set_output_size: null align";
        return;
    }
    try {
        _dai_as_image_align(align)->setOutputSize(width, height);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_align_set_output_size failed: ") + e.what();
    }
}

void dai_image_align_set_out_keep_aspect_ratio(DaiNode align, bool keep) {
    if(!align) {
        last_error = "dai_image_align_set_out_keep_aspect_ratio: null align";
        return;
    }
    try {
        _dai_as_image_align(align)->setOutKeepAspectRatio(keep);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_align_set_out_keep_aspect_ratio failed: ") + e.what();
    }
}

static inline dai::node::ImageManip* _dai_as_image_manip(DaiNode manip) {
    return static_cast<dai::node::ImageManip*>(manip);
}

static inline dai::node::VideoEncoder* _dai_as_video_encoder(DaiNode encoder) {
    return static_cast<dai::node::VideoEncoder*>(encoder);
}

// Helper to validate and cast a DaiBuffer to ImageManipConfig.
// 
// Error handling contract:
// - Returns nullptr on failure (null cfg or wrong type)
// - Sets global last_error with context-specific message
// - Callers MUST check return value and return early on nullptr
// - Error is propagated to Rust via dai_get_last_error()
//
// This pattern ensures all validation failures are consistently reported
// to the Rust layer without requiring per-function error handling.
static inline std::shared_ptr<dai::ImageManipConfig> _dai_as_image_manip_config(DaiBuffer cfg, const char* ctx) {
    if(!cfg) {
        last_error = std::string(ctx) + ": null cfg";
        return nullptr;
    }
    auto base_ptr = static_cast<std::shared_ptr<dai::Buffer>*>(cfg);
    auto typed = std::dynamic_pointer_cast<dai::ImageManipConfig>(*base_ptr);
    if(!typed) {
        last_error = std::string(ctx) + ": cfg is not ImageManipConfig";
        return nullptr;
    }
    return typed;
}

void dai_image_manip_set_num_frames_pool(DaiNode manip, int num_frames_pool) {
    if(!manip) {
        last_error = "dai_image_manip_set_num_frames_pool: null manip";
        return;
    }
    try {
        _dai_as_image_manip(manip)->setNumFramesPool(num_frames_pool);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_set_num_frames_pool failed: ") + e.what();
    }
}

void dai_image_manip_set_max_output_frame_size(DaiNode manip, int max_frame_size) {
    if(!manip) {
        last_error = "dai_image_manip_set_max_output_frame_size: null manip";
        return;
    }
    try {
        _dai_as_image_manip(manip)->setMaxOutputFrameSize(max_frame_size);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_set_max_output_frame_size failed: ") + e.what();
    }
}

void dai_image_manip_set_run_on_host(DaiNode manip, bool run_on_host) {
    if(!manip) {
        last_error = "dai_image_manip_set_run_on_host: null manip";
        return;
    }
    try {
        _dai_as_image_manip(manip)->setRunOnHost(run_on_host);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_set_run_on_host failed: ") + e.what();
    }
}

void dai_image_manip_set_backend(DaiNode manip, int backend) {
    if(!manip) {
        last_error = "dai_image_manip_set_backend: null manip";
        return;
    }
    try {
        _dai_as_image_manip(manip)->setBackend(static_cast<dai::node::ImageManip::Backend>(backend));
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_set_backend failed: ") + e.what();
    }
}

void dai_image_manip_set_performance_mode(DaiNode manip, int performance_mode) {
    if(!manip) {
        last_error = "dai_image_manip_set_performance_mode: null manip";
        return;
    }
    try {
        _dai_as_image_manip(manip)->setPerformanceMode(static_cast<dai::node::ImageManip::PerformanceMode>(performance_mode));
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_set_performance_mode failed: ") + e.what();
    }
}

bool dai_image_manip_run_on_host(DaiNode manip) {
    if(!manip) {
        last_error = "dai_image_manip_run_on_host: null manip";
        return false;
    }
    try {
        return _dai_as_image_manip(manip)->runOnHost();
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_run_on_host failed: ") + e.what();
        return false;
    }
}

void dai_image_manip_run(DaiNode manip) {
    if(!manip) {
        last_error = "dai_image_manip_run: null manip";
        return;
    }
    try {
        _dai_as_image_manip(manip)->run();
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_run failed: ") + e.what();
    }
}

void dai_video_encoder_set_default_profile_preset(DaiNode encoder, float fps, int profile) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_default_profile_preset: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setDefaultProfilePreset(
            fps,
            static_cast<dai::VideoEncoderProperties::Profile>(profile)
        );
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_default_profile_preset failed: ") + e.what();
    }
}

void dai_video_encoder_set_num_frames_pool(DaiNode encoder, int frames) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_num_frames_pool: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setNumFramesPool(frames);
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_num_frames_pool failed: ") + e.what();
    }
}

int dai_video_encoder_get_num_frames_pool(DaiNode encoder) {
    if(!encoder) {
        last_error = "dai_video_encoder_get_num_frames_pool: null encoder";
        return 0;
    }
    try {
        return _dai_as_video_encoder(encoder)->getNumFramesPool();
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_get_num_frames_pool failed: ") + e.what();
        return 0;
    }
}

void dai_video_encoder_set_rate_control_mode(DaiNode encoder, int mode) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_rate_control_mode: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setRateControlMode(
            static_cast<dai::VideoEncoderProperties::RateControlMode>(mode)
        );
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_rate_control_mode failed: ") + e.what();
    }
}

int dai_video_encoder_get_rate_control_mode(DaiNode encoder) {
    if(!encoder) {
        last_error = "dai_video_encoder_get_rate_control_mode: null encoder";
        return 0;
    }
    try {
        return static_cast<int>(_dai_as_video_encoder(encoder)->getRateControlMode());
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_get_rate_control_mode failed: ") + e.what();
        return 0;
    }
}

void dai_video_encoder_set_profile(DaiNode encoder, int profile) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_profile: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setProfile(
            static_cast<dai::VideoEncoderProperties::Profile>(profile)
        );
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_profile failed: ") + e.what();
    }
}

int dai_video_encoder_get_profile(DaiNode encoder) {
    if(!encoder) {
        last_error = "dai_video_encoder_get_profile: null encoder";
        return 0;
    }
    try {
        return static_cast<int>(_dai_as_video_encoder(encoder)->getProfile());
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_get_profile failed: ") + e.what();
        return 0;
    }
}

void dai_video_encoder_set_bitrate(DaiNode encoder, int bitrate) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_bitrate: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setBitrate(bitrate);
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_bitrate failed: ") + e.what();
    }
}

int dai_video_encoder_get_bitrate(DaiNode encoder) {
    if(!encoder) {
        last_error = "dai_video_encoder_get_bitrate: null encoder";
        return 0;
    }
    try {
        return _dai_as_video_encoder(encoder)->getBitrate();
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_get_bitrate failed: ") + e.what();
        return 0;
    }
}

void dai_video_encoder_set_bitrate_kbps(DaiNode encoder, int bitrate_kbps) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_bitrate_kbps: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setBitrateKbps(bitrate_kbps);
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_bitrate_kbps failed: ") + e.what();
    }
}

int dai_video_encoder_get_bitrate_kbps(DaiNode encoder) {
    if(!encoder) {
        last_error = "dai_video_encoder_get_bitrate_kbps: null encoder";
        return 0;
    }
    try {
        return _dai_as_video_encoder(encoder)->getBitrateKbps();
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_get_bitrate_kbps failed: ") + e.what();
        return 0;
    }
}

void dai_video_encoder_set_keyframe_frequency(DaiNode encoder, int freq) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_keyframe_frequency: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setKeyframeFrequency(freq);
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_keyframe_frequency failed: ") + e.what();
    }
}

int dai_video_encoder_get_keyframe_frequency(DaiNode encoder) {
    if(!encoder) {
        last_error = "dai_video_encoder_get_keyframe_frequency: null encoder";
        return 0;
    }
    try {
        return _dai_as_video_encoder(encoder)->getKeyframeFrequency();
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_get_keyframe_frequency failed: ") + e.what();
        return 0;
    }
}

void dai_video_encoder_set_num_bframes(DaiNode encoder, int num_bframes) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_num_bframes: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setNumBFrames(num_bframes);
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_num_bframes failed: ") + e.what();
    }
}

int dai_video_encoder_get_num_bframes(DaiNode encoder) {
    if(!encoder) {
        last_error = "dai_video_encoder_get_num_bframes: null encoder";
        return 0;
    }
    try {
        return _dai_as_video_encoder(encoder)->getNumBFrames();
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_get_num_bframes failed: ") + e.what();
        return 0;
    }
}

void dai_video_encoder_set_quality(DaiNode encoder, int quality) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_quality: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setQuality(quality);
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_quality failed: ") + e.what();
    }
}

int dai_video_encoder_get_quality(DaiNode encoder) {
    if(!encoder) {
        last_error = "dai_video_encoder_get_quality: null encoder";
        return 0;
    }
    try {
        return _dai_as_video_encoder(encoder)->getQuality();
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_get_quality failed: ") + e.what();
        return 0;
    }
}

void dai_video_encoder_set_lossless(DaiNode encoder, bool lossless) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_lossless: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setLossless(lossless);
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_lossless failed: ") + e.what();
    }
}

bool dai_video_encoder_get_lossless(DaiNode encoder) {
    if(!encoder) {
        last_error = "dai_video_encoder_get_lossless: null encoder";
        return false;
    }
    try {
        return _dai_as_video_encoder(encoder)->getLossless();
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_get_lossless failed: ") + e.what();
        return false;
    }
}

void dai_video_encoder_set_frame_rate(DaiNode encoder, float frame_rate) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_frame_rate: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setFrameRate(frame_rate);
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_frame_rate failed: ") + e.what();
    }
}

float dai_video_encoder_get_frame_rate(DaiNode encoder) {
    if(!encoder) {
        last_error = "dai_video_encoder_get_frame_rate: null encoder";
        return 0.0f;
    }
    try {
        return _dai_as_video_encoder(encoder)->getFrameRate();
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_get_frame_rate failed: ") + e.what();
        return 0.0f;
    }
}

void dai_video_encoder_set_max_output_frame_size(DaiNode encoder, int max_frame_size) {
    if(!encoder) {
        last_error = "dai_video_encoder_set_max_output_frame_size: null encoder";
        return;
    }
    try {
        _dai_as_video_encoder(encoder)->setMaxOutputFrameSize(max_frame_size);
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_set_max_output_frame_size failed: ") + e.what();
    }
}

int dai_video_encoder_get_max_output_frame_size(DaiNode encoder) {
    if(!encoder) {
        last_error = "dai_video_encoder_get_max_output_frame_size: null encoder";
        return 0;
    }
    try {
        return _dai_as_video_encoder(encoder)->getMaxOutputFrameSize();
    } catch(const std::exception& e) {
        last_error = std::string("dai_video_encoder_get_max_output_frame_size failed: ") + e.what();
        return 0;
    }
}

DaiBuffer dai_image_manip_config_new() {
    try {
        auto cfg = std::make_shared<dai::ImageManipConfig>();
        return new std::shared_ptr<dai::Buffer>(std::static_pointer_cast<dai::Buffer>(std::move(cfg)));
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_new failed: ") + e.what();
        return nullptr;
    }
}

DaiBuffer dai_image_manip_get_initial_config(DaiNode manip) {
    if(!manip) {
        last_error = "dai_image_manip_get_initial_config: null manip";
        return nullptr;
    }
    try {
        auto m = _dai_as_image_manip(manip);
        if(!m->initialConfig) {
            last_error = "dai_image_manip_get_initial_config: initialConfig is null";
            return nullptr;
        }
        return new std::shared_ptr<dai::Buffer>(std::static_pointer_cast<dai::Buffer>(m->initialConfig));
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_get_initial_config failed: ") + e.what();
        return nullptr;
    }
}

void dai_image_manip_config_clear_ops(DaiBuffer cfg) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_clear_ops");
        if(!c) return;
        c->clearOps();
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_clear_ops failed: ") + e.what();
    }
}

void dai_image_manip_config_add_crop_xywh(DaiBuffer cfg, uint32_t x, uint32_t y, uint32_t w, uint32_t h) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_add_crop_xywh");
        if(!c) return;
        c->addCrop(x, y, w, h);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_add_crop_xywh failed: ") + e.what();
    }
}

void dai_image_manip_config_add_crop_rect(DaiBuffer cfg, float x, float y, float w, float h, bool normalized_coords) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_add_crop_rect");
        if(!c) return;
        dai::Rect r;
        r.x = x;
        r.y = y;
        r.width = w;
        r.height = h;
        r.hasNormalized = true;
        r.normalized = normalized_coords;
        c->addCrop(r, normalized_coords);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_add_crop_rect failed: ") + e.what();
    }
}

void dai_image_manip_config_add_crop_rotated_rect(DaiBuffer cfg, float cx, float cy, float w, float h, float angle_deg, bool normalized_coords) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_add_crop_rotated_rect");
        if(!c) return;
        dai::Point2f center(cx, cy, normalized_coords);
        dai::Size2f size(w, h, normalized_coords);
        dai::RotatedRect rr(center, size, angle_deg);
        c->addCropRotatedRect(rr, normalized_coords);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_add_crop_rotated_rect failed: ") + e.what();
    }
}

void dai_image_manip_config_add_scale(DaiBuffer cfg, float scale_x, float scale_y) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_add_scale");
        if(!c) return;
        c->addScale(scale_x, scale_y);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_add_scale failed: ") + e.what();
    }
}

void dai_image_manip_config_add_rotate_deg(DaiBuffer cfg, float angle_deg) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_add_rotate_deg");
        if(!c) return;
        c->addRotateDeg(angle_deg);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_add_rotate_deg failed: ") + e.what();
    }
}

void dai_image_manip_config_add_rotate_deg_center(DaiBuffer cfg, float angle_deg, float center_x, float center_y) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_add_rotate_deg_center");
        if(!c) return;
        c->addRotateDeg(angle_deg, dai::Point2f(center_x, center_y, true));
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_add_rotate_deg_center failed: ") + e.what();
    }
}

void dai_image_manip_config_add_flip_horizontal(DaiBuffer cfg) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_add_flip_horizontal");
        if(!c) return;
        c->addFlipHorizontal();
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_add_flip_horizontal failed: ") + e.what();
    }
}

void dai_image_manip_config_add_flip_vertical(DaiBuffer cfg) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_add_flip_vertical");
        if(!c) return;
        c->addFlipVertical();
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_add_flip_vertical failed: ") + e.what();
    }
}

void dai_image_manip_config_add_transform_affine(DaiBuffer cfg, const float* matrix4) {
    if(!matrix4) {
        last_error = "dai_image_manip_config_add_transform_affine: null matrix4";
        return;
    }
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_add_transform_affine");
        if(!c) return;
        std::array<float, 4> m{{matrix4[0], matrix4[1], matrix4[2], matrix4[3]}};
        c->addTransformAffine(m);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_add_transform_affine failed: ") + e.what();
    }
}

void dai_image_manip_config_add_transform_perspective(DaiBuffer cfg, const float* matrix9) {
    if(!matrix9) {
        last_error = "dai_image_manip_config_add_transform_perspective: null matrix9";
        return;
    }
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_add_transform_perspective");
        if(!c) return;
        std::array<float, 9> m{{
            matrix9[0], matrix9[1], matrix9[2],
            matrix9[3], matrix9[4], matrix9[5],
            matrix9[6], matrix9[7], matrix9[8],
        }};
        c->addTransformPerspective(m);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_add_transform_perspective failed: ") + e.what();
    }
}

void dai_image_manip_config_add_transform_four_points(DaiBuffer cfg, const float* src8, const float* dst8, bool normalized_coords) {
    if(!src8 || !dst8) {
        last_error = "dai_image_manip_config_add_transform_four_points: null src8 or dst8";
        return;
    }
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_add_transform_four_points");
        if(!c) return;

        std::array<dai::Point2f, 4> src{{
            dai::Point2f(src8[0], src8[1], normalized_coords),
            dai::Point2f(src8[2], src8[3], normalized_coords),
            dai::Point2f(src8[4], src8[5], normalized_coords),
            dai::Point2f(src8[6], src8[7], normalized_coords),
        }};
        std::array<dai::Point2f, 4> dst{{
            dai::Point2f(dst8[0], dst8[1], normalized_coords),
            dai::Point2f(dst8[2], dst8[3], normalized_coords),
            dai::Point2f(dst8[4], dst8[5], normalized_coords),
            dai::Point2f(dst8[6], dst8[7], normalized_coords),
        }};

        c->addTransformFourPoints(src, dst, normalized_coords);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_add_transform_four_points failed: ") + e.what();
    }
}

void dai_image_manip_config_set_output_size(DaiBuffer cfg, uint32_t w, uint32_t h, int resize_mode) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_set_output_size");
        if(!c) return;
        c->setOutputSize(w, h, static_cast<dai::ImageManipConfig::ResizeMode>(resize_mode));
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_set_output_size failed: ") + e.what();
    }
}

void dai_image_manip_config_set_output_center(DaiBuffer cfg, bool center) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_set_output_center");
        if(!c) return;
        c->setOutputCenter(center);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_set_output_center failed: ") + e.what();
    }
}

void dai_image_manip_config_set_colormap(DaiBuffer cfg, int colormap) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_set_colormap");
        if(!c) return;
        c->setColormap(static_cast<dai::Colormap>(colormap));
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_set_colormap failed: ") + e.what();
    }
}

void dai_image_manip_config_set_background_color_rgb(DaiBuffer cfg, uint32_t red, uint32_t green, uint32_t blue) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_set_background_color_rgb");
        if(!c) return;
        c->setBackgroundColor(red, green, blue);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_set_background_color_rgb failed: ") + e.what();
    }
}

void dai_image_manip_config_set_background_color_gray(DaiBuffer cfg, uint32_t val) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_set_background_color_gray");
        if(!c) return;
        c->setBackgroundColor(val);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_set_background_color_gray failed: ") + e.what();
    }
}

void dai_image_manip_config_set_frame_type(DaiBuffer cfg, int frame_type) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_set_frame_type");
        if(!c) return;
        c->setFrameType(static_cast<dai::ImgFrame::Type>(frame_type));
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_set_frame_type failed: ") + e.what();
    }
}

void dai_image_manip_config_set_undistort(DaiBuffer cfg, bool undistort) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_set_undistort");
        if(!c) return;
        c->setUndistort(undistort);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_set_undistort failed: ") + e.what();
    }
}

bool dai_image_manip_config_get_undistort(DaiBuffer cfg) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_get_undistort");
        if(!c) return false;
        return c->getUndistort();
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_get_undistort failed: ") + e.what();
        return false;
    }
}

void dai_image_manip_config_set_reuse_previous_image(DaiBuffer cfg, bool reuse) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_set_reuse_previous_image");
        if(!c) return;
        c->setReusePreviousImage(reuse);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_set_reuse_previous_image failed: ") + e.what();
    }
}

void dai_image_manip_config_set_skip_current_image(DaiBuffer cfg, bool skip) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_set_skip_current_image");
        if(!c) return;
        c->setSkipCurrentImage(skip);
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_set_skip_current_image failed: ") + e.what();
    }
}

bool dai_image_manip_config_get_reuse_previous_image(DaiBuffer cfg) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_get_reuse_previous_image");
        if(!c) return false;
        return c->getReusePreviousImage();
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_get_reuse_previous_image failed: ") + e.what();
        return false;
    }
}

bool dai_image_manip_config_get_skip_current_image(DaiBuffer cfg) {
    try {
        auto c = _dai_as_image_manip_config(cfg, "dai_image_manip_config_get_skip_current_image");
        if(!c) return false;
        return c->getSkipCurrentImage();
    } catch(const std::exception& e) {
        last_error = std::string("dai_image_manip_config_get_skip_current_image failed: ") + e.what();
        return false;
    }
}

// Wrapper-owned pointcloud view. PointCloudData::getPointsRGB() returns by value, so we
// store the returned vector and expose a stable pointer + length to Rust.
struct DaiPointCloudView {
    std::shared_ptr<dai::PointCloudData> msg;
    std::vector<dai::Point3fRGBA> points;
};

DaiPointCloud dai_queue_get_pointcloud(DaiDataQueue queue, int timeout_ms) {
    if(!queue) {
        last_error = "dai_queue_get_pointcloud: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        std::shared_ptr<dai::PointCloudData> pcl;
        if(timeout_ms < 0) {
            pcl = (*ptr)->get<dai::PointCloudData>();
        } else {
            bool timedOut = false;
            pcl = (*ptr)->get<dai::PointCloudData>(std::chrono::milliseconds(timeout_ms), timedOut);
            if(timedOut) return nullptr;
        }
        if(!pcl) return nullptr;

        auto view = new DaiPointCloudView();
        view->msg = pcl;
        view->points = pcl->getPointsRGB();
        return static_cast<DaiPointCloud>(view);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_get_pointcloud failed: ") + e.what();
        return nullptr;
    }
}

DaiPointCloud dai_queue_try_get_pointcloud(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_try_get_pointcloud: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        auto pcl = (*ptr)->tryGet<dai::PointCloudData>();
        if(!pcl) return nullptr;
        auto view = new DaiPointCloudView();
        view->msg = pcl;
        view->points = pcl->getPointsRGB();
        return static_cast<DaiPointCloud>(view);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_try_get_pointcloud failed: ") + e.what();
        return nullptr;
    }
}

int dai_pointcloud_get_width(DaiPointCloud pcl) {
    if(!pcl) {
        last_error = "dai_pointcloud_get_width: null pointcloud";
        return 0;
    }
    auto view = static_cast<DaiPointCloudView*>(pcl);
    return static_cast<int>(view->msg ? view->msg->getWidth() : 0);
}

int dai_pointcloud_get_height(DaiPointCloud pcl) {
    if(!pcl) {
        last_error = "dai_pointcloud_get_height: null pointcloud";
        return 0;
    }
    auto view = static_cast<DaiPointCloudView*>(pcl);
    return static_cast<int>(view->msg ? view->msg->getHeight() : 0);
}

const DaiPoint3fRGBA* dai_pointcloud_get_points_rgba(DaiPointCloud pcl) {
    if(!pcl) {
        last_error = "dai_pointcloud_get_points_rgba: null pointcloud";
        return nullptr;
    }
    auto view = static_cast<DaiPointCloudView*>(pcl);
    if(view->points.empty()) return nullptr;
    return reinterpret_cast<const DaiPoint3fRGBA*>(view->points.data());
}

size_t dai_pointcloud_get_points_rgba_len(DaiPointCloud pcl) {
    if(!pcl) {
        last_error = "dai_pointcloud_get_points_rgba_len: null pointcloud";
        return 0;
    }
    auto view = static_cast<DaiPointCloudView*>(pcl);
    return view->points.size();
}

void dai_pointcloud_release(DaiPointCloud pcl) {
    if(pcl) {
        auto view = static_cast<DaiPointCloudView*>(pcl);
        delete view;
    }
}

DaiRGBDData dai_queue_get_rgbd(DaiDataQueue queue, int timeout_ms) {
    if(!queue) {
        last_error = "dai_queue_get_rgbd: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        std::shared_ptr<dai::RGBDData> rgbd;
        if(timeout_ms < 0) {
            rgbd = (*ptr)->get<dai::RGBDData>();
        } else {
            bool timedOut = false;
            rgbd = (*ptr)->get<dai::RGBDData>(std::chrono::milliseconds(timeout_ms), timedOut);
            if(timedOut) return nullptr;
        }
        if(!rgbd) return nullptr;
        return static_cast<DaiRGBDData>(new std::shared_ptr<dai::RGBDData>(rgbd));
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_get_rgbd failed: ") + e.what();
        return nullptr;
    }
}

DaiRGBDData dai_queue_try_get_rgbd(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_try_get_rgbd: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        auto rgbd = (*ptr)->tryGet<dai::RGBDData>();
        if(!rgbd) return nullptr;
        return static_cast<DaiRGBDData>(new std::shared_ptr<dai::RGBDData>(rgbd));
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_try_get_rgbd failed: ") + e.what();
        return nullptr;
    }
}

DaiImgFrame dai_rgbd_get_rgb_frame(DaiRGBDData rgbd) {
    if(!rgbd) {
        last_error = "dai_rgbd_get_rgb_frame: null rgbd";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::RGBDData>*>(rgbd);
#if DAI_HAS_NODE_GATE  // v3.4.0+: getRGBFrame() returns optional<FrameVariant>
        auto opt = (*ptr)->getRGBFrame();
        if(!opt) return nullptr;
        auto* img = std::get_if<std::shared_ptr<dai::ImgFrame>>(&opt.value());
        if(!img || !*img) return nullptr;
        return new std::shared_ptr<dai::ImgFrame>(*img);
#else
        auto frame = (*ptr)->getRGBFrame();
        if(!frame) return nullptr;
        return new std::shared_ptr<dai::ImgFrame>(frame);
#endif
    } catch(const std::exception& e) {
        last_error = std::string("dai_rgbd_get_rgb_frame failed: ") + e.what();
        return nullptr;
    }
}

DaiImgFrame dai_rgbd_get_depth_frame(DaiRGBDData rgbd) {
    if(!rgbd) {
        last_error = "dai_rgbd_get_depth_frame: null rgbd";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::RGBDData>*>(rgbd);
#if DAI_HAS_NODE_GATE  // v3.4.0+: getDepthFrame() returns optional<FrameVariant>
        auto opt = (*ptr)->getDepthFrame();
        if(!opt) return nullptr;
        auto* img = std::get_if<std::shared_ptr<dai::ImgFrame>>(&opt.value());
        if(!img || !*img) return nullptr;
        return new std::shared_ptr<dai::ImgFrame>(*img);
#else
        auto frame = (*ptr)->getDepthFrame();
        if(!frame) return nullptr;
        return new std::shared_ptr<dai::ImgFrame>(frame);
#endif
    } catch(const std::exception& e) {
        last_error = std::string("dai_rgbd_get_depth_frame failed: ") + e.what();
        return nullptr;
    }
}

void dai_rgbd_release(DaiRGBDData rgbd) {
    if(rgbd) {
        auto ptr = static_cast<std::shared_ptr<dai::RGBDData>*>(rgbd);
        delete ptr;
    }
}

DaiMessageGroup dai_message_group_clone(DaiMessageGroup group) {
    if(!group) {
        last_error = "dai_message_group_clone: null group";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageGroup>*>(group);
        return new std::shared_ptr<dai::MessageGroup>(*ptr);
    } catch(const std::exception& e) {
        last_error = std::string("dai_message_group_clone failed: ") + e.what();
        return nullptr;
    }
}

void dai_message_group_release(DaiMessageGroup group) {
    if(group) {
        auto ptr = static_cast<std::shared_ptr<dai::MessageGroup>*>(group);
        delete ptr;
    }
}

DaiBuffer dai_message_group_get_buffer(DaiMessageGroup group, const char* name) {
    if(!group) {
        last_error = "dai_message_group_get_buffer: null group";
        return nullptr;
    }
    if(_dai_cstr_empty(name)) {
        last_error = "dai_message_group_get_buffer: empty name";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageGroup>*>(group);
        auto msg = (*ptr)->get(std::string(name));
        if(!msg) return nullptr;
        auto buf = std::dynamic_pointer_cast<dai::Buffer>(msg);
        if(!buf) return nullptr;
        return new std::shared_ptr<dai::Buffer>(buf);
    } catch(const std::exception& e) {
        last_error = std::string("dai_message_group_get_buffer failed: ") + e.what();
        return nullptr;
    }
}

DaiImgFrame dai_message_group_get_img_frame(DaiMessageGroup group, const char* name) {
    if(!group) {
        last_error = "dai_message_group_get_img_frame: null group";
        return nullptr;
    }
    if(_dai_cstr_empty(name)) {
        last_error = "dai_message_group_get_img_frame: empty name";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageGroup>*>(group);
        auto msg = (*ptr)->get(std::string(name));
        if(!msg) return nullptr;
        auto frame = std::dynamic_pointer_cast<dai::ImgFrame>(msg);
        if(!frame) return nullptr;
        return new std::shared_ptr<dai::ImgFrame>(frame);
    } catch(const std::exception& e) {
        last_error = std::string("dai_message_group_get_img_frame failed: ") + e.what();
        return nullptr;
    }
}

DaiBuffer dai_buffer_new(size_t size) {
    try {
        auto buf = std::make_shared<dai::Buffer>(size);
        return new std::shared_ptr<dai::Buffer>(std::move(buf));
    } catch(const std::exception& e) {
        last_error = std::string("dai_buffer_new failed: ") + e.what();
        return nullptr;
    }
}

void dai_buffer_release(DaiBuffer buffer) {
    if(buffer) {
        auto ptr = static_cast<std::shared_ptr<dai::Buffer>*>(buffer);
        delete ptr;
    }
}

void dai_buffer_set_data(DaiBuffer buffer, const void* data, size_t len) {
    if(!buffer) {
        last_error = "dai_buffer_set_data: null buffer";
        return;
    }
    if(!data && len > 0) {
        last_error = "dai_buffer_set_data: null data";
        return;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::Buffer>*>(buffer);
        std::vector<std::uint8_t> bytes;
        bytes.resize(len);
        if(len > 0) {
            std::memcpy(bytes.data(), data, len);
        }
        (*ptr)->setData(std::move(bytes));
    } catch(const std::exception& e) {
        last_error = std::string("dai_buffer_set_data failed: ") + e.what();
    }
}

DaiBuffer dai_input_get_buffer(DaiInput input) {
    if(!input) {
        last_error = "dai_input_get_buffer: null input";
        return nullptr;
    }
    try {
        auto in = static_cast<dai::Node::Input*>(input);
        auto msg = in->get<dai::Buffer>();
        if(!msg) return nullptr;
        return new std::shared_ptr<dai::Buffer>(msg);
    } catch(const std::exception& e) {
        last_error = std::string("dai_input_get_buffer failed: ") + e.what();
        return nullptr;
    }
}

DaiBuffer dai_input_try_get_buffer(DaiInput input) {
    if(!input) {
        last_error = "dai_input_try_get_buffer: null input";
        return nullptr;
    }
    try {
        auto in = static_cast<dai::Node::Input*>(input);
        auto msg = in->tryGet<dai::Buffer>();
        if(!msg) return nullptr;
        return new std::shared_ptr<dai::Buffer>(msg);
    } catch(const std::exception& e) {
        last_error = std::string("dai_input_try_get_buffer failed: ") + e.what();
        return nullptr;
    }
}

DaiImgFrame dai_input_get_img_frame(DaiInput input) {
    if(!input) {
        last_error = "dai_input_get_img_frame: null input";
        return nullptr;
    }
    try {
        auto in = static_cast<dai::Node::Input*>(input);
        auto msg = in->get<dai::ImgFrame>();
        if(!msg) return nullptr;
        return new std::shared_ptr<dai::ImgFrame>(msg);
    } catch(const std::exception& e) {
        last_error = std::string("dai_input_get_img_frame failed: ") + e.what();
        return nullptr;
    }
}

DaiImgFrame dai_input_try_get_img_frame(DaiInput input) {
    if(!input) {
        last_error = "dai_input_try_get_img_frame: null input";
        return nullptr;
    }
    try {
        auto in = static_cast<dai::Node::Input*>(input);
        auto msg = in->tryGet<dai::ImgFrame>();
        if(!msg) return nullptr;
        return new std::shared_ptr<dai::ImgFrame>(msg);
    } catch(const std::exception& e) {
        last_error = std::string("dai_input_try_get_img_frame failed: ") + e.what();
        return nullptr;
    }
}

DaiInputQueue dai_input_create_input_queue(DaiInput input, unsigned int max_size, bool blocking) {
    if(!input) {
        last_error = "dai_input_create_input_queue: null input";
        return nullptr;
    }
    try {
        auto in = static_cast<dai::Node::Input*>(input);
        auto q = in->createInputQueue(max_size, blocking);
        if(!q) return nullptr;
        return static_cast<DaiInputQueue>(new std::shared_ptr<dai::InputQueue>(std::move(q)));
    } catch(const std::exception& e) {
        last_error = std::string("dai_input_create_input_queue failed: ") + e.what();
        return nullptr;
    }
}

void dai_input_queue_delete(DaiInputQueue queue) {
    if(queue) {
        auto ptr = static_cast<std::shared_ptr<dai::InputQueue>*>(queue);
        delete ptr;
    }
}

void dai_input_queue_send(DaiInputQueue queue, DaiDatatype msg) {
    if(!queue || !msg) {
        last_error = "dai_input_queue_send: null queue/msg";
        return;
    }
    try {
        auto q = static_cast<std::shared_ptr<dai::InputQueue>*>(queue);
        auto m = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        if(!q->get() || !(*q)) {
            last_error = "dai_input_queue_send: invalid queue";
            return;
        }
        if(!m->get() || !(*m)) {
            last_error = "dai_input_queue_send: invalid msg";
            return;
        }
        (*q)->send(*m);
    } catch(const std::exception& e) {
        last_error = std::string("dai_input_queue_send failed: ") + e.what();
    }
}

void dai_output_send_buffer(DaiOutput output, DaiBuffer buffer) {
    if(!output || !buffer) {
        last_error = "dai_output_send_buffer: null output/buffer";
        return;
    }
    try {
        auto out = static_cast<dai::Node::Output*>(output);
        auto buf = static_cast<std::shared_ptr<dai::Buffer>*>(buffer);
        out->send(*buf);
    } catch(const std::exception& e) {
        last_error = std::string("dai_output_send_buffer failed: ") + e.what();
    }
}

void dai_output_send_img_frame(DaiOutput output, DaiImgFrame frame) {
    if(!output || !frame) {
        last_error = "dai_output_send_img_frame: null output/frame";
        return;
    }
    try {
        auto out = static_cast<dai::Node::Output*>(output);
        auto img = static_cast<std::shared_ptr<dai::ImgFrame>*>(frame);
        out->send(*img);
    } catch(const std::exception& e) {
        last_error = std::string("dai_output_send_img_frame failed: ") + e.what();
    }
}

static inline std::string _dai_opt_cstr(const char* s) {
    return s ? std::string(s) : std::string();
}

static inline bool _dai_cstr_empty(const char* s) {
    return s == nullptr || *s == '\0';
}

static inline int _dai_score_port_name(const std::string& name, bool isOutput) {
    // Heuristic only; compatibility checks decide feasibility.
    // Prefer commonly-used/default ports and avoid raw/metadata ports.
    int score = 0;
    auto has = [&](const char* needle) { return name.find(needle) != std::string::npos; };

    if(name == "out") score += 100;
    if(isOutput) {
        if(has("video")) score += 90;
        if(has("preview")) score += 85;
        if(has("isp")) score += 80;
        if(has("passthrough")) score += 40;
        if(has("rgbd")) score += 70;
        if(has("pcl")) score += 60;
        if(has("depth")) score += 60;
        if(has("raw")) score -= 30;
        if(has("meta")) score -= 20;
        if(has("metadata")) score -= 20;
        if(has("control")) score -= 10;
    } else {
        if(has("input")) score += 80;
        if(has("inColor")) score += 70;
        if(has("inDepth")) score += 70;
        if(name == "in") score += 60;
        if(name == "inSync") score -= 10;
    }
    return score;
}

static inline std::vector<dai::Node::Output*> _dai_collect_outputs(dai::Node* node) {
    std::vector<dai::Node::Output*> outs;
    if(!node) return outs;
    auto refs = node->getOutputRefs();
    outs.insert(outs.end(), refs.begin(), refs.end());
    auto maps = node->getOutputMapRefs();
    for(auto* m : maps) {
        if(!m) continue;
        for(auto& kv : *m) {
            outs.push_back(&kv.second);
        }
    }
    return outs;
}

static inline std::vector<dai::Node::Input*> _dai_collect_inputs(dai::Node* node) {
    std::vector<dai::Node::Input*> ins;
    if(!node) return ins;
    auto refs = node->getInputRefs();
    ins.insert(ins.end(), refs.begin(), refs.end());
    auto maps = node->getInputMapRefs();
    for(auto* m : maps) {
        if(!m) continue;
        for(auto& kv : *m) {
            ins.push_back(&kv.second);
        }
    }
    return ins;
}

static inline bool _dai_group_matches(const std::string& portGroup, const char* filterGroup) {
    if(filterGroup == nullptr) return true;
    return portGroup == std::string(filterGroup);
}

static inline dai::Node::Output* _dai_pick_output_for_input(dai::Node* fromNode, dai::Node::Input* input, const char* out_group) {
    if(!fromNode || !input) return nullptr;
    dai::Node::Output* best = nullptr;
    int bestScore = std::numeric_limits<int>::min();
    for(auto* o : _dai_collect_outputs(fromNode)) {
        if(!o) continue;
        if(!_dai_group_matches(o->getGroup(), out_group)) continue;
        if(!o->canConnect(*input)) continue;
        int score = _dai_score_port_name(o->getName(), /*isOutput=*/true);
        if(o->getGroup().empty()) score += 2;
        if(score > bestScore) {
            bestScore = score;
            best = o;
        }
    }
    return best;
}

static inline dai::Node::Input* _dai_pick_input_for_output(dai::Node* toNode, dai::Node::Output* output, const char* in_group) {
    if(!toNode || !output) return nullptr;
    dai::Node::Input* best = nullptr;
    int bestScore = std::numeric_limits<int>::min();
    for(auto* i : _dai_collect_inputs(toNode)) {
        if(!i) continue;
        if(!_dai_group_matches(i->getGroup(), in_group)) continue;
        if(!output->canConnect(*i)) continue;
        int score = _dai_score_port_name(i->getName(), /*isOutput=*/false);
        if(i->getGroup().empty()) score += 2;
        if(score > bestScore) {
            bestScore = score;
            best = i;
        }
    }
    return best;
}

bool dai_node_link(DaiNode from, const char* out_group, const char* out_name, DaiNode to, const char* in_group, const char* in_name) {
    if (!from || !to) {
        last_error = "dai_node_link: null from/to";
        return false;
    }
    try {
        auto fromNode = static_cast<dai::Node*>(from);
        auto toNode = static_cast<dai::Node*>(to);

        dai::Node::Output* out = nullptr;
        dai::Node::Input* input = nullptr;

        const bool outSpecified = !_dai_cstr_empty(out_name);
        const bool inSpecified = !_dai_cstr_empty(in_name);

        if(outSpecified) {
            out = out_group ? fromNode->getOutputRef(std::string(out_group), std::string(out_name)) : fromNode->getOutputRef(std::string(out_name));
            if(!out) {
                last_error = "dai_node_link: output not found";
                return false;
            }
        }
        if(inSpecified) {
            input = in_group ? toNode->getInputRef(std::string(in_group), std::string(in_name)) : toNode->getInputRef(std::string(in_name));
            if(!input) {
                last_error = "dai_node_link: input not found";
                return false;
            }
        }

        if(!outSpecified && !inSpecified) {
            // Choose the best compatible pair.
            dai::Node::Output* bestOut = nullptr;
            dai::Node::Input* bestIn = nullptr;
            int bestScore = std::numeric_limits<int>::min();
            for(auto* o : _dai_collect_outputs(fromNode)) {
                if(!o) continue;
                if(!_dai_group_matches(o->getGroup(), out_group)) continue;
                for(auto* i : _dai_collect_inputs(toNode)) {
                    if(!i) continue;
                    if(!_dai_group_matches(i->getGroup(), in_group)) continue;
                    if(!o->canConnect(*i)) continue;
                    int score = _dai_score_port_name(o->getName(), /*isOutput=*/true) + _dai_score_port_name(i->getName(), /*isOutput=*/false);
                    if(o->getGroup().empty()) score += 2;
                    if(i->getGroup().empty()) score += 2;
                    if(score > bestScore) {
                        bestScore = score;
                        bestOut = o;
                        bestIn = i;
                    }
                }
            }
            out = bestOut;
            input = bestIn;
        } else if(!outSpecified && inSpecified) {
            out = _dai_pick_output_for_input(fromNode, input, out_group);
        } else if(outSpecified && !inSpecified) {
            input = _dai_pick_input_for_output(toNode, out, in_group);
        }

        if(!out || !input) {
            last_error = "dai_node_link: no compatible ports found";
            return false;
        }

        out->link(*input);
        return true;
    } catch (const std::exception& e) {
        last_error = std::string("dai_node_link failed: ") + e.what();
        return false;
    }
}

bool dai_node_unlink(DaiNode from, const char* out_group, const char* out_name, DaiNode to, const char* in_group, const char* in_name) {
    if (!from || !to) {
        last_error = "dai_node_unlink: null from/to";
        return false;
    }
    try {
        auto fromNode = static_cast<dai::Node*>(from);
        auto toNode = static_cast<dai::Node*>(to);

        dai::Node::Output* out = nullptr;
        dai::Node::Input* input = nullptr;

        const bool outSpecified = !_dai_cstr_empty(out_name);
        const bool inSpecified = !_dai_cstr_empty(in_name);

        if(outSpecified) {
            out = out_group ? fromNode->getOutputRef(std::string(out_group), std::string(out_name)) : fromNode->getOutputRef(std::string(out_name));
            if(!out) {
                last_error = "dai_node_unlink: output not found";
                return false;
            }
        }
        if(inSpecified) {
            input = in_group ? toNode->getInputRef(std::string(in_group), std::string(in_name)) : toNode->getInputRef(std::string(in_name));
            if(!input) {
                last_error = "dai_node_unlink: input not found";
                return false;
            }
        }

        if(!outSpecified || !inSpecified) {
            // Find an actual existing connection between `fromNode` and `toNode` that matches any provided filters.
            dai::Node::Output* bestOut = nullptr;
            dai::Node::Input* bestIn = nullptr;
            int bestScore = std::numeric_limits<int>::min();

            auto outputs = outSpecified ? std::vector<dai::Node::Output*>{out} : _dai_collect_outputs(fromNode);
            for(auto* o : outputs) {
                if(!o) continue;
                if(!_dai_group_matches(o->getGroup(), out_group)) continue;
                for(const auto& c : o->getConnections()) {
                    if(c.in == nullptr) continue;
                    auto inNode = c.inputNode.lock();
                    if(!inNode) continue;
                    if(inNode.get() != toNode) continue;
                    if(!_dai_group_matches(c.inputGroup, in_group)) continue;
                    if(inSpecified && c.inputName != std::string(in_name)) continue;

                    int score = _dai_score_port_name(o->getName(), /*isOutput=*/true) + _dai_score_port_name(c.inputName, /*isOutput=*/false);
                    if(score > bestScore) {
                        bestScore = score;
                        bestOut = o;
                        bestIn = c.in;
                    }
                }
            }
            out = bestOut;
            input = bestIn;
        }

        if(!out || !input) {
            last_error = "dai_node_unlink: no matching connection found";
            return false;
        }
        out->unlink(*input);
        return true;
    } catch (const std::exception& e) {
        last_error = std::string("dai_node_unlink failed: ") + e.what();
        return false;
    }
}

DaiInput dai_hostnode_get_input(DaiNode node, const char* name) {
    if(!node) {
        last_error = "dai_hostnode_get_input: null node";
        return nullptr;
    }
    if(_dai_cstr_empty(name)) {
        last_error = "dai_hostnode_get_input: empty name";
        return nullptr;
    }
    try {
        auto host = dynamic_cast<dai::node::HostNode*>(static_cast<dai::Node*>(node));
        if(!host) {
            last_error = "dai_hostnode_get_input: node is not a HostNode";
            return nullptr;
        }
        auto& input = host->inputs[std::string(name)];
        return static_cast<DaiInput>(&input);
    } catch(const std::exception& e) {
        last_error = std::string("dai_hostnode_get_input failed: ") + e.what();
        return nullptr;
    }
}

void dai_hostnode_run_sync_on_host(DaiNode node) {
    if(!node) {
        last_error = "dai_hostnode_run_sync_on_host: null node";
        return;
    }
    try {
        auto host = dynamic_cast<dai::node::HostNode*>(static_cast<dai::Node*>(node));
        if(!host) {
            last_error = "dai_hostnode_run_sync_on_host: node is not a HostNode";
            return;
        }
        host->runSyncingOnHost();
    } catch(const std::exception& e) {
        last_error = std::string("dai_hostnode_run_sync_on_host failed: ") + e.what();
    }
}

void dai_hostnode_run_sync_on_device(DaiNode node) {
    if(!node) {
        last_error = "dai_hostnode_run_sync_on_device: null node";
        return;
    }
    try {
        auto host = dynamic_cast<dai::node::HostNode*>(static_cast<dai::Node*>(node));
        if(!host) {
            last_error = "dai_hostnode_run_sync_on_device: node is not a HostNode";
            return;
        }
        host->runSyncingOnDevice();
    } catch(const std::exception& e) {
        last_error = std::string("dai_hostnode_run_sync_on_device failed: ") + e.what();
    }
}

void dai_hostnode_send_processing_to_pipeline(DaiNode node, bool send) {
    if(!node) {
        last_error = "dai_hostnode_send_processing_to_pipeline: null node";
        return;
    }
    try {
        auto host = dynamic_cast<dai::node::HostNode*>(static_cast<dai::Node*>(node));
        if(!host) {
            last_error = "dai_hostnode_send_processing_to_pipeline: node is not a HostNode";
            return;
        }
        host->sendProcessingToPipeline(send);
    } catch(const std::exception& e) {
        last_error = std::string("dai_hostnode_send_processing_to_pipeline failed: ") + e.what();
    }
}

static inline bool _dai_assign_input_desc(dai::Node::InputDescription& desc,
                                          const char* name,
                                          const char* group) {
    if(name && *name) {
        desc.name = std::string(name);
    }
    if(group && *group) {
        desc.group = std::string(group);
    }
    return true;
}

DaiInput dai_threaded_hostnode_create_input(DaiNode node,
                                            const char* name,
                                            const char* group,
                                            bool blocking,
                                            int queue_size,
                                            bool wait_for_message) {
    if(!node) {
        last_error = "dai_threaded_hostnode_create_input: null node";
        return nullptr;
    }
    try {
        auto host = dynamic_cast<dai::node::ThreadedHostNode*>(static_cast<dai::Node*>(node));
        if(!host) {
            last_error = "dai_threaded_hostnode_create_input: node is not a ThreadedHostNode";
            return nullptr;
        }
        dai::Node::InputDescription desc;
        _dai_assign_input_desc(desc, name, group);
        desc.blocking = blocking;
        if(queue_size > 0) {
            desc.queueSize = queue_size;
        }
        desc.waitForMessage = wait_for_message;
        auto* input = new dai::Node::Input(*host, desc, true);
        return static_cast<DaiInput>(input);
    } catch(const std::exception& e) {
        last_error = std::string("dai_threaded_hostnode_create_input failed: ") + e.what();
        return nullptr;
    }
}

DaiOutput dai_threaded_hostnode_create_output(DaiNode node,
                                              const char* name,
                                              const char* group) {
    if(!node) {
        last_error = "dai_threaded_hostnode_create_output: null node";
        return nullptr;
    }
    try {
        auto host = dynamic_cast<dai::node::ThreadedHostNode*>(static_cast<dai::Node*>(node));
        if(!host) {
            last_error = "dai_threaded_hostnode_create_output: node is not a ThreadedHostNode";
            return nullptr;
        }
        dai::Node::OutputDescription desc;
        if(name && *name) {
            desc.name = std::string(name);
        }
        if(group && *group) {
            desc.group = std::string(group);
        }
        auto* output = new dai::Node::Output(*host, desc, true);
        return static_cast<DaiOutput>(output);
    } catch(const std::exception& e) {
        last_error = std::string("dai_threaded_hostnode_create_output failed: ") + e.what();
        return nullptr;
    }
}

bool dai_threaded_node_is_running(DaiNode node) {
    if(!node) {
        last_error = "dai_threaded_node_is_running: null node";
        return false;
    }
    try {
        auto threaded = dynamic_cast<dai::ThreadedNode*>(static_cast<dai::Node*>(node));
        if(!threaded) {
            last_error = "dai_threaded_node_is_running: node is not a ThreadedNode";
            return false;
        }
        return threaded->isRunning();
    } catch(const std::exception& e) {
        last_error = std::string("dai_threaded_node_is_running failed: ") + e.what();
        return false;
    }
}

// Low-level camera operations
DaiOutput dai_camera_request_full_resolution_output(DaiCameraNode camera) {
    if (!camera) {
        last_error = "dai_camera_request_full_resolution_output: null camera";
        return nullptr;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        dai::Node::Output* output = cam->requestFullResolutionOutput();
        return static_cast<DaiOutput>(output);
    } catch (const std::exception& e) {
        last_error = std::string("dai_camera_request_full_resolution_output failed: ") + e.what();
        return nullptr;
    }
}

DaiOutput dai_camera_request_full_resolution_output_ex(DaiCameraNode camera, int type, float fps, bool use_highest_resolution) {
    if (!camera) {
        last_error = "dai_camera_request_full_resolution_output_ex: null camera";
        return nullptr;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        std::optional<dai::ImgFrame::Type> opt_type = (type >= 0) ? std::optional<dai::ImgFrame::Type>(static_cast<dai::ImgFrame::Type>(type))
                                                                  : std::nullopt;
        std::optional<float> opt_fps = (fps > 0.0f) ? std::optional<float>(fps) : std::nullopt;
        dai::Node::Output* output = cam->requestFullResolutionOutput(opt_type, opt_fps, use_highest_resolution);
        return static_cast<DaiOutput>(output);
    } catch (const std::exception& e) {
        last_error = std::string("dai_camera_request_full_resolution_output_ex failed: ") + e.what();
        return nullptr;
    }
}

bool dai_camera_build(DaiCameraNode camera, int board_socket, int sensor_width, int sensor_height, float sensor_fps) {
    if(!camera) {
        last_error = "dai_camera_build: null camera";
        return false;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        auto socket = static_cast<dai::CameraBoardSocket>(board_socket);

        std::optional<std::pair<uint32_t, uint32_t>> opt_res = std::nullopt;
        if(sensor_width > 0 && sensor_height > 0) {
            opt_res = std::make_pair(static_cast<uint32_t>(sensor_width), static_cast<uint32_t>(sensor_height));
        }
        std::optional<float> opt_fps = (sensor_fps > 0.0f) ? std::optional<float>(sensor_fps) : std::nullopt;

        cam->build(socket, opt_res, opt_fps);
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_build failed: ") + e.what();
        return false;
    }
}

int dai_camera_get_board_socket(DaiCameraNode camera) {
    if(!camera) {
        last_error = "dai_camera_get_board_socket: null camera";
        return -1;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        return static_cast<int>(cam->getBoardSocket());
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_get_board_socket failed: ") + e.what();
        return -1;
    }
}

uint32_t dai_camera_get_max_width(DaiCameraNode camera) {
    if(!camera) {
        last_error = "dai_camera_get_max_width: null camera";
        return 0;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        return cam->getMaxWidth();
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_get_max_width failed: ") + e.what();
        return 0;
    }
}

uint32_t dai_camera_get_max_height(DaiCameraNode camera) {
    if(!camera) {
        last_error = "dai_camera_get_max_height: null camera";
        return 0;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        return cam->getMaxHeight();
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_get_max_height failed: ") + e.what();
        return 0;
    }
}

void dai_camera_set_sensor_type(DaiCameraNode camera, int sensor_type) {
    if(!camera) {
        last_error = "dai_camera_set_sensor_type: null camera";
        return;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        cam->setSensorType(static_cast<dai::CameraSensorType>(sensor_type));
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_set_sensor_type failed: ") + e.what();
    }
}

int dai_camera_get_sensor_type(DaiCameraNode camera) {
    if(!camera) {
        last_error = "dai_camera_get_sensor_type: null camera";
        return -1;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        return static_cast<int>(cam->getSensorType());
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_get_sensor_type failed: ") + e.what();
        return -1;
    }
}

void dai_camera_set_raw_num_frames_pool(DaiCameraNode camera, int num) {
    if(!camera) {
        last_error = "dai_camera_set_raw_num_frames_pool: null camera";
        return;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        cam->setRawNumFramesPool(num);
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_set_raw_num_frames_pool failed: ") + e.what();
    }
}

void dai_camera_set_max_size_pool_raw(DaiCameraNode camera, int size) {
    if(!camera) {
        last_error = "dai_camera_set_max_size_pool_raw: null camera";
        return;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        cam->setMaxSizePoolRaw(size);
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_set_max_size_pool_raw failed: ") + e.what();
    }
}

void dai_camera_set_isp_num_frames_pool(DaiCameraNode camera, int num) {
    if(!camera) {
        last_error = "dai_camera_set_isp_num_frames_pool: null camera";
        return;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        cam->setIspNumFramesPool(num);
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_set_isp_num_frames_pool failed: ") + e.what();
    }
}

void dai_camera_set_max_size_pool_isp(DaiCameraNode camera, int size) {
    if(!camera) {
        last_error = "dai_camera_set_max_size_pool_isp: null camera";
        return;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        cam->setMaxSizePoolIsp(size);
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_set_max_size_pool_isp failed: ") + e.what();
    }
}

void dai_camera_set_num_frames_pools(DaiCameraNode camera, int raw, int isp, int outputs) {
    if(!camera) {
        last_error = "dai_camera_set_num_frames_pools: null camera";
        return;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        cam->setNumFramesPools(raw, isp, outputs);
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_set_num_frames_pools failed: ") + e.what();
    }
}

void dai_camera_set_max_size_pools(DaiCameraNode camera, int raw, int isp, int outputs) {
    if(!camera) {
        last_error = "dai_camera_set_max_size_pools: null camera";
        return;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        cam->setMaxSizePools(raw, isp, outputs);
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_set_max_size_pools failed: ") + e.what();
    }
}

void dai_camera_set_outputs_num_frames_pool(DaiCameraNode camera, int num) {
    if(!camera) {
        last_error = "dai_camera_set_outputs_num_frames_pool: null camera";
        return;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        cam->setOutputsNumFramesPool(num);
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_set_outputs_num_frames_pool failed: ") + e.what();
    }
}

void dai_camera_set_outputs_max_size_pool(DaiCameraNode camera, int size) {
    if(!camera) {
        last_error = "dai_camera_set_outputs_max_size_pool: null camera";
        return;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        cam->setOutputsMaxSizePool(size);
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_set_outputs_max_size_pool failed: ") + e.what();
    }
}

int dai_camera_get_raw_num_frames_pool(DaiCameraNode camera) {
    if(!camera) {
        last_error = "dai_camera_get_raw_num_frames_pool: null camera";
        return 0;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        return cam->getRawNumFramesPool();
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_get_raw_num_frames_pool failed: ") + e.what();
        return 0;
    }
}

int dai_camera_get_max_size_pool_raw(DaiCameraNode camera) {
    if(!camera) {
        last_error = "dai_camera_get_max_size_pool_raw: null camera";
        return 0;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        return cam->getMaxSizePoolRaw();
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_get_max_size_pool_raw failed: ") + e.what();
        return 0;
    }
}

int dai_camera_get_isp_num_frames_pool(DaiCameraNode camera) {
    if(!camera) {
        last_error = "dai_camera_get_isp_num_frames_pool: null camera";
        return 0;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        return cam->getIspNumFramesPool();
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_get_isp_num_frames_pool failed: ") + e.what();
        return 0;
    }
}

int dai_camera_get_max_size_pool_isp(DaiCameraNode camera) {
    if(!camera) {
        last_error = "dai_camera_get_max_size_pool_isp: null camera";
        return 0;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        return cam->getMaxSizePoolIsp();
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_get_max_size_pool_isp failed: ") + e.what();
        return 0;
    }
}

bool dai_camera_get_outputs_num_frames_pool(DaiCameraNode camera, int* out_num) {
    if(!camera || !out_num) {
        last_error = "dai_camera_get_outputs_num_frames_pool: null camera or out_num";
        return false;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        auto value = cam->getOutputsNumFramesPool();
        return _dai_optionalish_to_out(value, out_num);
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_get_outputs_num_frames_pool failed: ") + e.what();
        return false;
    }
}

bool dai_camera_get_outputs_max_size_pool(DaiCameraNode camera, size_t* out_size) {
    if(!camera || !out_size) {
        last_error = "dai_camera_get_outputs_max_size_pool: null camera or out_size";
        return false;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        auto value = cam->getOutputsMaxSizePool();
        return _dai_optionalish_to_out(value, out_size);
    } catch(const std::exception& e) {
        last_error = std::string("dai_camera_get_outputs_max_size_pool failed: ") + e.what();
        return false;
    }
}
DaiCameraNode dai_pipeline_create_camera(DaiPipeline pipeline, int board_socket) {
    if (!pipeline) {
        last_error = "dai_pipeline_create_camera: null pipeline";
        return nullptr;
    }
    try {
        auto pipe = static_cast<dai::Pipeline*>(pipeline);
        auto cameraBuilder = pipe->create<dai::node::Camera>();
        auto socket = static_cast<dai::CameraBoardSocket>(board_socket);
        auto camera = cameraBuilder->build(socket);
        return static_cast<DaiCameraNode>(camera.get());
    } catch (const std::exception& e) {
        last_error = std::string("dai_pipeline_create_camera failed: ") + e.what();
        return nullptr;
    }
}

DaiOutput dai_camera_request_output(DaiCameraNode camera, int width, int height, int type, int resize_mode, float fps, int enable_undistortion) {
    if (!camera) {
        last_error = "dai_camera_request_output: null camera";
        return nullptr;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        std::pair<uint32_t, uint32_t> size(static_cast<uint32_t>(width), static_cast<uint32_t>(height));
        std::optional<dai::ImgFrame::Type> opt_type = (type >= 0) ? std::optional<dai::ImgFrame::Type>(static_cast<dai::ImgFrame::Type>(type)) : std::nullopt;
        dai::ImgResizeMode resize = static_cast<dai::ImgResizeMode>(resize_mode);
        std::optional<float> opt_fps = (fps > 0.0f) ? std::optional<float>(fps) : std::nullopt;
        std::optional<bool> opt_undist = (enable_undistortion >= 0) ? std::optional<bool>(enable_undistortion != 0) : std::nullopt;
        dai::Node::Output* output = cam->requestOutput(size, opt_type, resize, opt_fps, opt_undist);
        return static_cast<DaiOutput>(output);
    } catch (const std::exception& e) {
        last_error = std::string("dai_camera_request_output failed: ") + e.what();
        return nullptr;
    }
}

DaiDataQueue dai_output_create_queue(DaiOutput output, unsigned int max_size, bool blocking) {
    if (!output) {
        last_error = "dai_output_create_queue: null output";
        return nullptr;
    }
    try {
        auto out = static_cast<dai::Node::Output*>(output);
        auto queue = out->createOutputQueue(max_size, blocking);
        return new std::shared_ptr<dai::MessageQueue>(queue);
    } catch (const std::exception& e) {
        last_error = std::string("dai_output_create_queue failed: ") + e.what();
        return nullptr;
    }
}

void dai_queue_delete(DaiDataQueue queue) {
    if(queue) {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        delete ptr;
    }
}

char* dai_queue_get_name(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_get_name: null queue";
        return nullptr;
    }
    try {
        dai_clear_last_error();
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        if(!ptr->get() || !(*ptr)) {
            last_error = "dai_queue_get_name: invalid queue";
            return nullptr;
        }
        auto name = (*ptr)->getName();
        return dai_string_to_cstring(name.c_str());
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_get_name failed: ") + e.what();
        return nullptr;
    }
}

bool dai_queue_set_name(DaiDataQueue queue, const char* name) {
    if(!queue || !name) {
        last_error = "dai_queue_set_name: null queue/name";
        return false;
    }
    try {
        dai_clear_last_error();
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        if(!ptr->get() || !(*ptr)) {
            last_error = "dai_queue_set_name: invalid queue";
            return false;
        }
        (*ptr)->setName(std::string(name));
        return true;
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_set_name failed: ") + e.what();
        return false;
    }
}

bool dai_queue_is_closed(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_is_closed: null queue";
        return true;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        if(!ptr->get() || !(*ptr)) {
            last_error = "dai_queue_is_closed: invalid queue";
            return true;
        }
        return (*ptr)->isClosed();
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_is_closed failed: ") + e.what();
        return true;
    }
}

void dai_queue_close(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_close: null queue";
        return;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        if(!ptr->get() || !(*ptr)) {
            last_error = "dai_queue_close: invalid queue";
            return;
        }
        (*ptr)->close();
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_close failed: ") + e.what();
    }
}

void dai_queue_set_blocking(DaiDataQueue queue, bool blocking) {
    if(!queue) {
        last_error = "dai_queue_set_blocking: null queue";
        return;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        if(!ptr->get() || !(*ptr)) {
            last_error = "dai_queue_set_blocking: invalid queue";
            return;
        }
        (*ptr)->setBlocking(blocking);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_set_blocking failed: ") + e.what();
    }
}

bool dai_queue_get_blocking(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_get_blocking: null queue";
        return false;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        if(!ptr->get() || !(*ptr)) {
            last_error = "dai_queue_get_blocking: invalid queue";
            return false;
        }
        return (*ptr)->getBlocking();
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_get_blocking failed: ") + e.what();
        return false;
    }
}

void dai_queue_set_max_size(DaiDataQueue queue, unsigned int max_size) {
    if(!queue) {
        last_error = "dai_queue_set_max_size: null queue";
        return;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        if(!ptr->get() || !(*ptr)) {
            last_error = "dai_queue_set_max_size: invalid queue";
            return;
        }
        (*ptr)->setMaxSize(max_size);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_set_max_size failed: ") + e.what();
    }
}

unsigned int dai_queue_get_max_size(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_get_max_size: null queue";
        return 0;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        if(!ptr->get() || !(*ptr)) {
            last_error = "dai_queue_get_max_size: invalid queue";
            return 0;
        }
        return (*ptr)->getMaxSize();
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_get_max_size failed: ") + e.what();
        return 0;
    }
}

unsigned int dai_queue_get_size(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_get_size: null queue";
        return 0;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        if(!ptr->get() || !(*ptr)) {
            last_error = "dai_queue_get_size: invalid queue";
            return 0;
        }
        return (*ptr)->getSize();
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_get_size failed: ") + e.what();
        return 0;
    }
}

unsigned int dai_queue_is_full(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_is_full: null queue";
        return 0;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        if(!ptr->get() || !(*ptr)) {
            last_error = "dai_queue_is_full: invalid queue";
            return 0;
        }
        return (*ptr)->isFull();
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_is_full failed: ") + e.what();
        return 0;
    }
}

bool dai_queue_has(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_has: null queue";
        return false;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        if(!ptr->get() || !(*ptr)) {
            last_error = "dai_queue_has: invalid queue";
            return false;
        }
        return (*ptr)->has();
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_has failed: ") + e.what();
        return false;
    }
}

struct _DaiDatatypeArray {
    std::vector<DaiDatatype> elems;
};

static inline DaiDatatypeArray _dai_make_datatype_array(const std::vector<std::shared_ptr<dai::ADatatype>>& msgs) {
    auto out = new _DaiDatatypeArray();
    out->elems.reserve(msgs.size());
    for(const auto& m : msgs) {
        out->elems.push_back(static_cast<DaiDatatype>(new std::shared_ptr<dai::ADatatype>(m)));
    }
    return static_cast<DaiDatatypeArray>(out);
}

DaiDatatype dai_queue_get(DaiDataQueue queue, int timeout_ms) {
    if(!queue) {
        last_error = "dai_queue_get: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        std::shared_ptr<dai::ADatatype> msg;
        if(timeout_ms < 0) {
            msg = (*ptr)->get();
        } else {
            bool timedOut = false;
            msg = (*ptr)->get(std::chrono::milliseconds(timeout_ms), timedOut);
            if(timedOut) {
                return nullptr;
            }
        }
        if(!msg) return nullptr;
        return static_cast<DaiDatatype>(new std::shared_ptr<dai::ADatatype>(std::move(msg)));
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_get failed: ") + e.what();
        return nullptr;
    }
}

DaiDatatype dai_queue_try_get(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_try_get: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        auto msg = (*ptr)->tryGet();
        if(!msg) return nullptr;
        return static_cast<DaiDatatype>(new std::shared_ptr<dai::ADatatype>(std::move(msg)));
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_try_get failed: ") + e.what();
        return nullptr;
    }
}

DaiDatatype dai_queue_front(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_front: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        auto msg = (*ptr)->front();
        if(!msg) return nullptr;
        return static_cast<DaiDatatype>(new std::shared_ptr<dai::ADatatype>(std::move(msg)));
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_front failed: ") + e.what();
        return nullptr;
    }
}

DaiDatatypeArray dai_queue_try_get_all(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_try_get_all: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        auto msgs = (*ptr)->tryGetAll();
        return _dai_make_datatype_array(msgs);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_try_get_all failed: ") + e.what();
        return nullptr;
    }
}

DaiDatatypeArray dai_queue_get_all(DaiDataQueue queue, int timeout_ms, bool* has_timedout) {
    if(has_timedout) {
        *has_timedout = false;
    }
    if(!queue) {
        last_error = "dai_queue_get_all: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        std::vector<std::shared_ptr<dai::ADatatype>> msgs;
        if(timeout_ms < 0) {
            msgs = (*ptr)->getAll();
        } else {
            bool timedOut = false;
            msgs = (*ptr)->getAll(std::chrono::milliseconds(timeout_ms), timedOut);
            if(has_timedout) {
                *has_timedout = timedOut;
            }
        }
        return _dai_make_datatype_array(msgs);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_get_all failed: ") + e.what();
        return nullptr;
    }
}

struct _DaiQueueCallbackState {
    void* ctx = nullptr;
    dai::DaiQueueCallback cb = nullptr;
    dai::DaiHostNodeCallback drop = nullptr;
    ~_DaiQueueCallbackState() {
        if(drop) {
            drop(ctx);
        }
    }
};

int dai_queue_add_callback(DaiDataQueue queue, void* ctx, uintptr_t cb, uintptr_t drop_cb) {
    if(!queue) {
        last_error = "dai_queue_add_callback: null queue";
        return -1;
    }
    if(cb == 0) {
        last_error = "dai_queue_add_callback: null callback";
        return -1;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        auto cb_fn = reinterpret_cast<DaiQueueCallback>(cb);
        auto drop_fn = drop_cb == 0 ? nullptr : reinterpret_cast<DaiHostNodeCallback>(drop_cb);
        auto state = std::make_shared<_DaiQueueCallbackState>();
        state->ctx = ctx;
        state->cb = cb_fn;
        state->drop = drop_fn;

        auto id = (*ptr)->addCallback([state](std::string name, std::shared_ptr<dai::ADatatype> msg) {
            if(!state || !state->cb) return;
            // Transfer ownership of a new shared_ptr handle to the Rust side.
            auto handle = new std::shared_ptr<dai::ADatatype>(std::move(msg));
            state->cb(state->ctx, name.c_str(), static_cast<DaiDatatype>(handle));
        });
        return static_cast<int>(id);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_add_callback failed: ") + e.what();
        return -1;
    }
}

bool dai_queue_remove_callback(DaiDataQueue queue, int callback_id) {
    if(!queue) {
        last_error = "dai_queue_remove_callback: null queue";
        return false;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        return (*ptr)->removeCallback(static_cast<dai::MessageQueue::CallbackId>(callback_id));
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_remove_callback failed: ") + e.what();
        return false;
    }
}

void dai_queue_send(DaiDataQueue queue, DaiDatatype msg) {
    if(!queue || !msg) {
        last_error = "dai_queue_send: null queue/msg";
        return;
    }
    try {
        auto q = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        auto m = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        (*q)->send(*m);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_send failed: ") + e.what();
    }
}

bool dai_queue_send_timeout(DaiDataQueue queue, DaiDatatype msg, int timeout_ms) {
    if(!queue || !msg) {
        last_error = "dai_queue_send_timeout: null queue/msg";
        return false;
    }
    try {
        auto q = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        auto m = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        const int t = timeout_ms < 0 ? 0 : timeout_ms;
        return (*q)->send(*m, std::chrono::milliseconds(t));
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_send_timeout failed: ") + e.what();
        return false;
    }
}

bool dai_queue_try_send(DaiDataQueue queue, DaiDatatype msg) {
    if(!queue || !msg) {
        last_error = "dai_queue_try_send: null queue/msg";
        return false;
    }
    try {
        auto q = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        auto m = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        return (*q)->trySend(*m);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_try_send failed: ") + e.what();
        return false;
    }
}

DaiImgFrame dai_queue_get_frame(DaiDataQueue queue, int timeout_ms) {
    if(!queue) {
        last_error = "dai_queue_get_frame: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        std::shared_ptr<dai::ImgFrame> frame;
        if(timeout_ms < 0) {
            frame = (*ptr)->get<dai::ImgFrame>();
        } else {
            bool timedOut = false;
            frame = (*ptr)->get<dai::ImgFrame>(std::chrono::milliseconds(timeout_ms), timedOut);
            if(timedOut) {
                return nullptr;
            }
        }
        if(!frame) {
            return nullptr;
        }
        return new std::shared_ptr<dai::ImgFrame>(frame);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_get_frame failed: ") + e.what();
        return nullptr;
    }
}

DaiImgFrame dai_queue_try_get_frame(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_try_get_frame: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        auto frame = (*ptr)->tryGet<dai::ImgFrame>();
        if(!frame) {
            return nullptr;
        }
        return new std::shared_ptr<dai::ImgFrame>(frame);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_try_get_frame failed: ") + e.what();
        return nullptr;
    }
}

DaiEncodedFrame dai_queue_get_encoded_frame(DaiDataQueue queue, int timeout_ms) {
    if(!queue) {
        last_error = "dai_queue_get_encoded_frame: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        std::shared_ptr<dai::EncodedFrame> frame;
        if(timeout_ms < 0) {
            frame = (*ptr)->get<dai::EncodedFrame>();
        } else {
            bool timedOut = false;
            frame = (*ptr)->get<dai::EncodedFrame>(std::chrono::milliseconds(timeout_ms), timedOut);
            if(timedOut) {
                return nullptr;
            }
        }
        if(!frame) {
            return nullptr;
        }
        return new std::shared_ptr<dai::EncodedFrame>(frame);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_get_encoded_frame failed: ") + e.what();
        return nullptr;
    }
}

DaiEncodedFrame dai_queue_try_get_encoded_frame(DaiDataQueue queue) {
    if(!queue) {
        last_error = "dai_queue_try_get_encoded_frame: null queue";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::MessageQueue>*>(queue);
        auto frame = (*ptr)->tryGet<dai::EncodedFrame>();
        if(!frame) {
            return nullptr;
        }
        return new std::shared_ptr<dai::EncodedFrame>(frame);
    } catch(const std::exception& e) {
        last_error = std::string("dai_queue_try_get_encoded_frame failed: ") + e.what();
        return nullptr;
    }
}

void dai_datatype_release(DaiDatatype msg) {
    if(msg) {
        auto ptr = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        delete ptr;
    }
}

DaiDatatype dai_datatype_clone(DaiDatatype msg) {
    if(!msg) {
        last_error = "dai_datatype_clone: null msg";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        if(!ptr->get() || !(*ptr)) return nullptr;
        return static_cast<DaiDatatype>(new std::shared_ptr<dai::ADatatype>(*ptr));
    } catch(const std::exception& e) {
        last_error = std::string("dai_datatype_clone failed: ") + e.what();
        return nullptr;
    }
}

int dai_datatype_get_datatype_enum(DaiDatatype msg) {
    if(!msg) {
        last_error = "dai_datatype_get_datatype_enum: null msg";
        return -1;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        if(!ptr->get() || !(*ptr)) return -1;
        return static_cast<int>((*ptr)->getDatatype());
    } catch(const std::exception& e) {
        last_error = std::string("dai_datatype_get_datatype_enum failed: ") + e.what();
        return -1;
    }
}

DaiImgFrame dai_datatype_as_img_frame(DaiDatatype msg) {
    if(!msg) {
        last_error = "dai_datatype_as_img_frame: null msg";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        auto frame = std::dynamic_pointer_cast<dai::ImgFrame>(*ptr);
        if(!frame) return nullptr;
        return new std::shared_ptr<dai::ImgFrame>(std::move(frame));
    } catch(const std::exception& e) {
        last_error = std::string("dai_datatype_as_img_frame failed: ") + e.what();
        return nullptr;
    }
}

DaiEncodedFrame dai_datatype_as_encoded_frame(DaiDatatype msg) {
    if(!msg) {
        last_error = "dai_datatype_as_encoded_frame: null msg";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        auto frame = std::dynamic_pointer_cast<dai::EncodedFrame>(*ptr);
        if(!frame) return nullptr;
        return new std::shared_ptr<dai::EncodedFrame>(std::move(frame));
    } catch(const std::exception& e) {
        last_error = std::string("dai_datatype_as_encoded_frame failed: ") + e.what();
        return nullptr;
    }
}

DaiPointCloud dai_datatype_as_pointcloud(DaiDatatype msg) {
    if(!msg) {
        last_error = "dai_datatype_as_pointcloud: null msg";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        auto pcl = std::dynamic_pointer_cast<dai::PointCloudData>(*ptr);
        if(!pcl) return nullptr;

        auto view = new DaiPointCloudView();
        view->msg = pcl;
        view->points = pcl->getPointsRGB();
        return static_cast<DaiPointCloud>(view);
    } catch(const std::exception& e) {
        last_error = std::string("dai_datatype_as_pointcloud failed: ") + e.what();
        return nullptr;
    }
}

DaiRGBDData dai_datatype_as_rgbd(DaiDatatype msg) {
    if(!msg) {
        last_error = "dai_datatype_as_rgbd: null msg";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        auto rgbd = std::dynamic_pointer_cast<dai::RGBDData>(*ptr);
        if(!rgbd) return nullptr;
        return static_cast<DaiRGBDData>(new std::shared_ptr<dai::RGBDData>(std::move(rgbd)));
    } catch(const std::exception& e) {
        last_error = std::string("dai_datatype_as_rgbd failed: ") + e.what();
        return nullptr;
    }
}

DaiBuffer dai_datatype_as_buffer(DaiDatatype msg) {
    if(!msg) {
        last_error = "dai_datatype_as_buffer: null msg";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        auto buf = std::dynamic_pointer_cast<dai::Buffer>(*ptr);
        if(!buf) return nullptr;
        return static_cast<DaiBuffer>(new std::shared_ptr<dai::Buffer>(std::move(buf)));
    } catch(const std::exception& e) {
        last_error = std::string("dai_datatype_as_buffer failed: ") + e.what();
        return nullptr;
    }
}

DaiMessageGroup dai_datatype_as_message_group(DaiDatatype msg) {
    if(!msg) {
        last_error = "dai_datatype_as_message_group: null msg";
        return nullptr;
    }
    try {
        auto ptr = static_cast<std::shared_ptr<dai::ADatatype>*>(msg);
        auto group = std::dynamic_pointer_cast<dai::MessageGroup>(*ptr);
        if(!group) return nullptr;
        return static_cast<DaiMessageGroup>(new std::shared_ptr<dai::MessageGroup>(std::move(group)));
    } catch(const std::exception& e) {
        last_error = std::string("dai_datatype_as_message_group failed: ") + e.what();
        return nullptr;
    }
}

size_t dai_datatype_array_len(DaiDatatypeArray arr) {
    if(!arr) {
        return 0;
    }
    auto ptr = static_cast<_DaiDatatypeArray*>(arr);
    return ptr->elems.size();
}

DaiDatatype dai_datatype_array_take(DaiDatatypeArray arr, size_t index) {
    if(!arr) {
        last_error = "dai_datatype_array_take: null array";
        return nullptr;
    }
    auto ptr = static_cast<_DaiDatatypeArray*>(arr);
    if(index >= ptr->elems.size()) {
        last_error = "dai_datatype_array_take: index out of bounds";
        return nullptr;
    }
    auto out = ptr->elems[index];
    ptr->elems[index] = nullptr;
    return out;
}

void dai_datatype_array_free(DaiDatatypeArray arr) {
    if(!arr) {
        return;
    }
    auto ptr = static_cast<_DaiDatatypeArray*>(arr);
    for(auto& h : ptr->elems) {
        if(h) {
            // Release any remaining elements (ones not taken by the caller).
            delete static_cast<std::shared_ptr<dai::ADatatype>*>(h);
            h = nullptr;
        }
    }
    delete ptr;
}

// Low-level frame operations
void* dai_frame_get_data(DaiImgFrame frame) {
    if (!frame) {
        last_error = "dai_frame_get_data: null frame";
        return nullptr;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::ImgFrame>*>(frame);
        if(!sharedFrame->get()) {
            return nullptr;
        }
        return (*sharedFrame)->getData().data();
    } catch (const std::exception& e) {
        last_error = std::string("dai_frame_get_data failed: ") + e.what();
        return nullptr;
    }
}

int dai_frame_get_width(DaiImgFrame frame) {
    if (!frame) {
        last_error = "dai_frame_get_width: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::ImgFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return (*sharedFrame)->getWidth();
    } catch (const std::exception& e) {
        last_error = std::string("dai_frame_get_width failed: ") + e.what();
        return 0;
    }
}

int dai_frame_get_height(DaiImgFrame frame) {
    if (!frame) {
        last_error = "dai_frame_get_height: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::ImgFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return (*sharedFrame)->getHeight();
    } catch (const std::exception& e) {
        last_error = std::string("dai_frame_get_height failed: ") + e.what();
        return 0;
    }
}

int dai_frame_get_type(DaiImgFrame frame) {
    if (!frame) {
        last_error = "dai_frame_get_type: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::ImgFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return static_cast<int>((*sharedFrame)->getType());
    } catch (const std::exception& e) {
        last_error = std::string("dai_frame_get_type failed: ") + e.what();
        return 0;
    }
}

size_t dai_frame_get_size(DaiImgFrame frame) {
    if (!frame) {
        last_error = "dai_frame_get_size: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::ImgFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return (*sharedFrame)->getData().size();
    } catch (const std::exception& e) {
        last_error = std::string("dai_frame_get_size failed: ") + e.what();
        return 0;
    }
}

void dai_frame_release(DaiImgFrame frame) {
    if(frame) {
        auto ptr = static_cast<std::shared_ptr<dai::ImgFrame>*>(frame);
        delete ptr;
    }
}

void* dai_encoded_frame_get_data(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_data: null frame";
        return nullptr;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return nullptr;
        }
        return (*sharedFrame)->getData().data();
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_data failed: ") + e.what();
        return nullptr;
    }
}

size_t dai_encoded_frame_get_data_size(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_data_size: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return (*sharedFrame)->getData().size();
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_data_size failed: ") + e.what();
        return 0;
    }
}

uint32_t dai_encoded_frame_get_frame_offset(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_frame_offset: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return (*sharedFrame)->frameOffset;
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_frame_offset failed: ") + e.what();
        return 0;
    }
}

uint32_t dai_encoded_frame_get_frame_size(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_frame_size: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return (*sharedFrame)->frameSize;
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_frame_size failed: ") + e.what();
        return 0;
    }
}

int dai_encoded_frame_get_width(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_width: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return static_cast<int>((*sharedFrame)->getWidth());
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_width failed: ") + e.what();
        return 0;
    }
}

int dai_encoded_frame_get_height(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_height: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return static_cast<int>((*sharedFrame)->getHeight());
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_height failed: ") + e.what();
        return 0;
    }
}

int dai_encoded_frame_get_profile(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_profile: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return static_cast<int>((*sharedFrame)->getProfile());
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_profile failed: ") + e.what();
        return 0;
    }
}

int dai_encoded_frame_get_frame_type(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_frame_type: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return static_cast<int>((*sharedFrame)->getFrameType());
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_frame_type failed: ") + e.what();
        return 0;
    }
}

int dai_encoded_frame_get_quality(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_quality: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return static_cast<int>((*sharedFrame)->getQuality());
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_quality failed: ") + e.what();
        return 0;
    }
}

int dai_encoded_frame_get_bitrate(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_bitrate: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return static_cast<int>((*sharedFrame)->getBitrate());
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_bitrate failed: ") + e.what();
        return 0;
    }
}

bool dai_encoded_frame_get_lossless(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_lossless: null frame";
        return false;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return false;
        }
        return (*sharedFrame)->getLossless();
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_lossless failed: ") + e.what();
        return false;
    }
}

int dai_encoded_frame_get_instance_num(DaiEncodedFrame frame) {
    if(!frame) {
        last_error = "dai_encoded_frame_get_instance_num: null frame";
        return 0;
    }
    try {
        auto sharedFrame = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        if(!sharedFrame->get()) {
            return 0;
        }
        return static_cast<int>((*sharedFrame)->getInstanceNum());
    } catch(const std::exception& e) {
        last_error = std::string("dai_encoded_frame_get_instance_num failed: ") + e.what();
        return 0;
    }
}

void dai_encoded_frame_release(DaiEncodedFrame frame) {
    if(frame) {
        auto ptr = static_cast<std::shared_ptr<dai::EncodedFrame>*>(frame);
        delete ptr;
    }
}

// Low-level utility functions  
int dai_device_get_connected_camera_sockets(DaiDevice device, int* sockets, int max_count) {
    if (!device || !sockets) {
        last_error = "dai_device_get_connected_camera_sockets: null device or sockets";
        return 0;
    }
    try {
        auto dev = static_cast<std::shared_ptr<dai::Device>*>(device);
        if(!dev->get() || !(*dev)) {
            last_error = "dai_device_get_connected_camera_sockets: invalid device";
            return 0;
        }
        auto connected = (*dev)->getConnectedCameras();
        int count = 0;
        for (const auto& socket : connected) {
            if (count >= max_count) break;
            sockets[count] = static_cast<int>(socket);
            count++;
        }
        return count;
    } catch (const std::exception& e) {
        last_error = std::string("dai_device_get_connected_camera_sockets failed: ") + e.what();
        return 0;
    }
}

const char* dai_camera_socket_name(int socket) {
    try {
        auto board_socket = static_cast<dai::CameraBoardSocket>(socket);
        static std::string name = toString(board_socket);
        return name.c_str();
    } catch (const std::exception& e) {
        last_error = std::string("dai_camera_socket_name failed: ") + e.what();
        return "UNKNOWN";
    }
}

// Error handling
const char* dai_get_last_error() {
    if(last_error.empty()) {
        return nullptr;
    }
    return last_error.c_str();
}

void dai_clear_last_error() {
    last_error.clear();
}

// ---------------------------------------------------------------------------
// v3.4.0+ Gate node API
// ---------------------------------------------------------------------------

// Send a Buffer (or Buffer subtype, e.g. GateControl) through an InputQueue.
// This performs the necessary Buffer -> ADatatype upcast internally so callers
// don't need to create an intermediate DaiDatatype handle.
void dai_input_queue_send_buffer(DaiInputQueue queue, DaiBuffer buffer) {
    if (!queue || !buffer) {
        last_error = "dai_input_queue_send_buffer: null queue/buffer";
        return;
    }
    try {
        auto q = static_cast<std::shared_ptr<dai::InputQueue>*>(queue);
        auto buf = static_cast<std::shared_ptr<dai::Buffer>*>(buffer);
        if (!q->get() || !(*q)) {
            last_error = "dai_input_queue_send_buffer: invalid queue";
            return;
        }
        if (!buf->get() || !(*buf)) {
            last_error = "dai_input_queue_send_buffer: invalid buffer";
            return;
        }
        // Upcast Buffer → ADatatype so InputQueue::send accepts the message.
        std::shared_ptr<dai::ADatatype> msg = std::static_pointer_cast<dai::ADatatype>(*buf);
        (*q)->send(msg);
    } catch (const std::exception& e) {
        last_error = std::string("dai_input_queue_send_buffer failed: ") + e.what();
    }
}

DaiNode dai_pipeline_create_gate(DaiPipeline pipeline) {
#if DAI_HAS_NODE_GATE
    if (!pipeline) {
        last_error = "dai_pipeline_create_gate: null pipeline";
        return nullptr;
    }
    try {
        auto* pip = static_cast<dai::Pipeline*>(pipeline);
        auto gate = pip->create<dai::node::Gate>();
        return static_cast<DaiNode>(gate.get());
    } catch (const std::exception& e) {
        last_error = std::string("dai_pipeline_create_gate failed: ") + e.what();
        return nullptr;
    }
#else
    last_error = "dai_pipeline_create_gate: Gate node is not available in this version of depthai-core (requires v3.4.0+)";
    return nullptr;
#endif
}

void dai_gate_set_run_on_host(DaiNode gate, bool run_on_host) {
#if DAI_HAS_NODE_GATE
    if (!gate) {
        last_error = "dai_gate_set_run_on_host: null gate";
        return;
    }
    try {
        auto* g = static_cast<dai::node::Gate*>(gate);
        g->setRunOnHost(run_on_host);
    } catch (const std::exception& e) {
        last_error = std::string("dai_gate_set_run_on_host failed: ") + e.what();
    }
#else
    last_error = "dai_gate_set_run_on_host: Gate node is not available in this version of depthai-core (requires v3.4.0+)";
#endif
}

bool dai_gate_run_on_host(DaiNode gate) {
#if DAI_HAS_NODE_GATE
    if (!gate) {
        last_error = "dai_gate_run_on_host: null gate";
        return false;
    }
    try {
        auto* g = static_cast<dai::node::Gate*>(gate);
        return g->runOnHost();
    } catch (const std::exception& e) {
        last_error = std::string("dai_gate_run_on_host failed: ") + e.what();
        return false;
    }
#else
    last_error = "dai_gate_run_on_host: Gate node is not available in this version of depthai-core (requires v3.4.0+)";
    return false;
#endif
}

DaiBuffer dai_gate_control_open_all() {
#if DAI_HAS_NODE_GATE
    try {
        auto ctrl = dai::GateControl::openGate();
        return new std::shared_ptr<dai::Buffer>(std::static_pointer_cast<dai::Buffer>(ctrl));
    } catch (const std::exception& e) {
        last_error = std::string("dai_gate_control_open_all failed: ") + e.what();
        return nullptr;
    }
#else
    last_error = "dai_gate_control_open_all: GateControl is not available in this version of depthai-core (requires v3.4.0+)";
    return nullptr;
#endif
}

DaiBuffer dai_gate_control_close() {
#if DAI_HAS_NODE_GATE
    try {
        auto ctrl = dai::GateControl::closeGate();
        return new std::shared_ptr<dai::Buffer>(std::static_pointer_cast<dai::Buffer>(ctrl));
    } catch (const std::exception& e) {
        last_error = std::string("dai_gate_control_close failed: ") + e.what();
        return nullptr;
    }
#else
    last_error = "dai_gate_control_close: GateControl is not available in this version of depthai-core (requires v3.4.0+)";
    return nullptr;
#endif
}

DaiBuffer dai_gate_control_open_n(int num_messages, int fps) {
#if DAI_HAS_NODE_GATE
    try {
        auto ctrl = dai::GateControl::openGate(num_messages, fps);
        return new std::shared_ptr<dai::Buffer>(std::static_pointer_cast<dai::Buffer>(ctrl));
    } catch (const std::exception& e) {
        last_error = std::string("dai_gate_control_open_n failed: ") + e.what();
        return nullptr;
    }
#else
    last_error = "dai_gate_control_open_n: GateControl is not available in this version of depthai-core (requires v3.4.0+)";
    return nullptr;
#endif
}

// ---------------------------------------------------------------------------
// v3.4.0+ Camera additions
// ---------------------------------------------------------------------------

DaiOutput dai_camera_request_isp_output(DaiCameraNode camera, float fps) {
#if DAI_HAS_NODE_GATE
    if (!camera) {
        last_error = "dai_camera_request_isp_output: null camera";
        return nullptr;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        std::optional<float> opt_fps = (fps > 0.0f) ? std::optional<float>(fps) : std::nullopt;
        dai::Node::Output* output = cam->requestIspOutput(opt_fps);
        return static_cast<DaiOutput>(output);
    } catch (const std::exception& e) {
        last_error = std::string("dai_camera_request_isp_output failed: ") + e.what();
        return nullptr;
    }
#else
    last_error = "dai_camera_request_isp_output: requestIspOutput is not available in this version of depthai-core (requires v3.4.0+)";
    return nullptr;
#endif
}

void dai_camera_set_image_orientation(DaiCameraNode camera, int orientation) {
#if DAI_HAS_NODE_GATE
    if (!camera) {
        last_error = "dai_camera_set_image_orientation: null camera";
        return;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        cam->setImageOrientation(static_cast<dai::CameraImageOrientation>(orientation));
    } catch (const std::exception& e) {
        last_error = std::string("dai_camera_set_image_orientation failed: ") + e.what();
    }
#else
    last_error = "dai_camera_set_image_orientation: setImageOrientation is not available in this version of depthai-core (requires v3.4.0+)";
#endif
}

int dai_camera_get_image_orientation(DaiCameraNode camera) {
#if DAI_HAS_NODE_GATE
    if (!camera) {
        last_error = "dai_camera_get_image_orientation: null camera";
        return -1;
    }
    try {
        auto cam = static_cast<dai::node::Camera*>(camera);
        return static_cast<int>(cam->getImageOrientation());
    } catch (const std::exception& e) {
        last_error = std::string("dai_camera_get_image_orientation failed: ") + e.what();
        return -1;
    }
#else
    last_error = "dai_camera_get_image_orientation: getImageOrientation is not available in this version of depthai-core (requires v3.4.0+)";
    return -1;
#endif
}

} // namespace dai