edgefirst-image 0.38.0

High-performance image processing with hardware acceleration for edge AI
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
// SPDX-FileCopyrightText: Copyright 2025 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0

use edgefirst_tensor::{DetectBox, ProtoData, Segmentation};
use std::panic::AssertUnwindSafe;
use std::ptr::NonNull;
use std::thread::JoinHandle;
use tokio::sync::mpsc::{Sender, WeakSender};

use super::processor::GLProcessorST;
use super::shaders::check_gl_error;
use super::{EglDisplayKind, Int8InterpolationMode, TransferBackend};
use crate::{ConvertOptions, Error, ImageProcessorTrait};
use edgefirst_tensor::TensorDyn;

#[allow(clippy::type_complexity)]
enum GLProcessorMessage {
    ImageConvert(
        SendablePtr<TensorDyn>,
        SendablePtr<TensorDyn>,
        ConvertOptions,
        bool, // defer: skip the per-tile glFinish (batch); flush syncs once
        tokio::sync::oneshot::Sender<Result<(), Error>>,
    ),
    /// Convert without the terminal CPU sync, replying with a native
    /// fence fd guarding the GPU work (the GL→NPU handoff). `Ok(None)` =
    /// converted with blocking semantics (no fence on this platform).
    ImageConvertFenced(
        SendablePtr<TensorDyn>,
        SendablePtr<TensorDyn>,
        ConvertOptions,
        tokio::sync::oneshot::Sender<Result<Option<super::CompletionFence>, Error>>,
    ),
    /// Complete any deferred batch render with a single GPU sync.
    Flush(tokio::sync::oneshot::Sender<Result<(), Error>>),
    SetColors(
        Vec<[u8; 4]>,
        tokio::sync::oneshot::Sender<Result<(), Error>>,
    ),
    SetBoxLineWidth(u32, tokio::sync::oneshot::Sender<Result<(), Error>>),
    DrawDecodedMasks(
        SendablePtr<TensorDyn>,
        SendablePtr<DetectBox>,
        SendablePtr<Segmentation>,
        f32,                            // opacity
        Option<SendablePtr<TensorDyn>>, // background
        Option<[f32; 4]>,               // content region
        crate::ColorMode,
        tokio::sync::oneshot::Sender<Result<(), Error>>,
    ),
    DrawProtoMasks(
        SendablePtr<TensorDyn>,
        SendablePtr<DetectBox>,
        SendablePtr<ProtoData>,
        f32,                            // opacity
        Option<SendablePtr<TensorDyn>>, // background
        Option<[f32; 4]>,               // content region
        crate::ColorMode,
        tokio::sync::oneshot::Sender<Result<(), Error>>,
    ),
    SetInt8Interpolation(
        Int8InterpolationMode,
        tokio::sync::oneshot::Sender<Result<(), Error>>,
    ),
    /// Set the colorimetry/performance trade-off (`ColorimetryMode`).
    SetColorimetryMode(
        crate::ColorimetryMode,
        tokio::sync::oneshot::Sender<Result<(), Error>>,
    ),
    /// Set how resizing converts resample (`Interpolation`).
    SetInterpolation(
        crate::Interpolation,
        tokio::sync::oneshot::Sender<Result<(), Error>>,
    ),
    /// Test hook (issue #175): make every zero-copy destination import fail.
    #[cfg(test)]
    SetFailDstImport(bool, tokio::sync::oneshot::Sender<Result<(), Error>>),
    /// Snapshot the EGLImage cache counters (steady-state import assertions).
    EglCacheStats(tokio::sync::oneshot::Sender<Result<super::cache::GlCacheStats, Error>>),
    /// Snapshot the per-convert source-feed counters (zero-copy observability).
    ConvertStats(tokio::sync::oneshot::Sender<Result<super::cache::ConvertStats, Error>>),
    PboCreate(
        usize, // buffer size in bytes
        tokio::sync::oneshot::Sender<Result<u32, Error>>,
    ),
    PboMap(
        u32,   // buffer_id
        usize, // size
        tokio::sync::oneshot::Sender<Result<edgefirst_tensor::PboMapping, Error>>,
    ),
    PboUnmap(
        u32, // buffer_id
        tokio::sync::oneshot::Sender<Result<(), Error>>,
    ),
    PboDelete(u32), // fire-and-forget, no reply
    CudaRegisterBuffer(u32, tokio::sync::oneshot::Sender<Option<usize>>),
    CudaMap(usize, tokio::sync::oneshot::Sender<Option<(usize, usize)>>),
    CudaUnmap(usize),      // fire-and-forget
    CudaUnregister(usize), // fire-and-forget
}

/// Compute the flat element count for a PBO image buffer of the given format.
///
/// NV12 and NV16 are semiplanar with non-trivial element counts; all other
/// formats use `width * height * channels`.
///
/// Returns `None` on `usize` overflow. A wrapped element count would size
/// the PBO too small and corrupt memory on readback, so callers must treat
/// `None` as an invalid-dimensions error (the same way they already reject
/// a zero count).
fn pbo_elem_count(
    width: usize,
    height: usize,
    format: edgefirst_tensor::PixelFormat,
) -> Option<usize> {
    // Element count == product of the canonical image shape (the PBO holds u8,
    // one byte per element). Delegating to `allocation_shape` keeps the combined
    // semi-planar height in lockstep with every other consumer (and is exact
    // for odd heights — `height*3/2` truncation under-sized odd-H NV12 by a
    // row, and the old NV24 arm fell through to `channels` = far too small).
    // `checked_mul` so a wrapped count can't silently undersize the PBO.
    format
        .allocation_shape(width, height)?
        .iter()
        .try_fold(1usize, |acc, &d| acc.checked_mul(d))
}

/// Compute the tensor shape for a PBO image of the given format — the canonical
/// [`PixelFormat::allocation_shape`] (Planar `[C,H,W]`, SemiPlanar `[total_h, W]`
/// with the odd-height-exact combined-plane height, Packed `[H,W,C]`).
fn pbo_shape(width: usize, height: usize, format: edgefirst_tensor::PixelFormat) -> Vec<usize> {
    format
        .allocation_shape(width, height)
        .unwrap_or_else(|| vec![height, width, format.channels()])
}

/// Best-effort registration of a freshly-created PBO with CUDA GL interop.
///
/// When libcudart is present, asks the GL worker (where the GL context is
/// current) to call `cudaGraphicsGLRegisterBuffer` for `buffer_id`, then
/// attaches a [`CudaHandle`] so `cuda_map()` can later yield a linear,
/// 256-byte-aligned device pointer for TensorRT. On any failure (no CUDA,
/// channel closed, registration rejected) the handle is left unset and the
/// PBO is still usable as a normal CPU/GL buffer.
fn register_pbo_cuda<T>(
    tensor: &mut edgefirst_tensor::Tensor<T>,
    buffer_id: u32,
    size: usize,
    sender: &Sender<GLProcessorMessage>,
) where
    T: num_traits::Num + Clone + std::fmt::Debug + Send + Sync + edgefirst_tensor::Element,
{
    if !edgefirst_tensor::is_cuda_available() {
        return;
    }
    let (tx, rx) = tokio::sync::oneshot::channel();
    if sender
        .blocking_send(GLProcessorMessage::CudaRegisterBuffer(buffer_id, tx))
        .is_ok()
    {
        if let Ok(Some(resource)) = rx.blocking_recv() {
            let ops = std::sync::Arc::new(GlCudaOps {
                sender: sender.downgrade(),
            });
            tensor.set_cuda_handle(edgefirst_tensor::CudaHandle::new_gl(
                resource as *mut std::ffi::c_void,
                size,
                ops,
            ));
        }
    }
}

/// Implements PboOps by sending commands to the GL thread.
///
/// Uses a `WeakSender` so that PBO images don't keep the GL thread's channel
/// alive. When the `GLProcessorThreaded` is dropped, its `Sender` is the last
/// strong reference — dropping it closes the channel and lets the GL thread
/// exit. PBO operations after that return `PboDisconnected`.
struct GlPboOps {
    sender: WeakSender<GLProcessorMessage>,
    /// Which GL worker owns the context these buffers live in. Compared
    /// against [`GL_WORKER`] so a re-entrant map is serviced inline ONLY by
    /// the worker whose context actually holds the buffer — a different
    /// processor's worker must still go through the channel.
    worker_id: u64,
}

/// Next id handed to a GL worker. Ids are per-process and never reused.
static NEXT_GL_WORKER_ID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);

/// Identity and PBO bookkeeping of the GL worker running on this thread.
struct GlWorkerState {
    id: u64,
    /// Full per-message serialization: this thread holds the process-wide GL
    /// lock for the whole message, so no other worker can run until it returns.
    serializes: bool,
    /// Buffers currently `glMapBufferRange`-ed against this context.
    mapped: std::collections::HashSet<u32>,
}

thread_local! {
    /// `Some(state)` on a GL worker thread, `None` everywhere else.
    ///
    /// This exists because a GL message handler can itself need a PBO map:
    /// a mask draw into a PBO destination the caller holds mapped reads it
    /// back through `TensorTrait::map` -> `PboHandle::acquire_map` ->
    /// `GlPboOps::map_buffer`. Routing that through the channel would have the
    /// worker `blocking_send` to the queue it is itself the only consumer of —
    /// a self-deadlock (observed: a 1-in-5 hang on the desktop NVIDIA PBO path).
    /// The worker already holds the context current on this thread, so it
    /// performs the map directly instead.
    ///
    /// The mapped-buffer set lives here rather than on the worker's stack so the
    /// inline path and the message path share one view of which buffers are
    /// mapped — `glMapBufferRange` on an already-mapped buffer is undefined
    /// behaviour, and the two paths must not be able to double-map.
    static GL_WORKER: std::cell::RefCell<Option<GlWorkerState>> =
        const { std::cell::RefCell::new(None) };
}

/// The mapped-PBO set for the current GL worker thread, or `None` off-worker.
/// The closure must not re-enter `GL_WORKER` (keep it to set bookkeeping — no
/// GL calls inside).
fn with_worker_mapped<R>(f: impl FnOnce(&mut std::collections::HashSet<u32>) -> R) -> Option<R> {
    GL_WORKER.with(|c| c.borrow_mut().as_mut().map(|s| f(&mut s.mapped)))
}

/// True when the calling thread is the GL worker that owns `worker_id`.
fn on_owning_gl_worker(worker_id: u64) -> bool {
    GL_WORKER.with(|c| matches!(*c.borrow(), Some(ref s) if s.id == worker_id))
}

/// True when this thread is a GL worker holding the process-wide per-message
/// lock, so no other worker can make progress until this message returns.
fn on_serializing_gl_worker() -> bool {
    GL_WORKER.with(|c| matches!(*c.borrow(), Some(ref s) if s.serializes))
}

/// A PBO owned by another worker's context, reached from a worker holding the
/// process-wide per-message lock. The owning worker cannot take that lock until
/// this message returns, so sending to it would never be answered.
fn cross_context_pbo_error(op: &str, buffer_id: u32) -> edgefirst_tensor::Error {
    edgefirst_tensor::Error::InvalidOperation(format!(
        "PBO {buffer_id}: cannot {op} a buffer owned by another GL context while \
         this one holds the serialization lock; convert it through the processor \
         that created it"
    ))
}

thread_local! {
    /// Set when a re-entrant inline PBO op panicked; the worker loop folds it
    /// into `poisoned` after the message that raised it.
    static GL_WORKER_POISON: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// Run a re-entrant PBO op inline on the owning worker, turning a panic into
/// an error exactly as the channel path's `reply_caught` does.
///
/// The unwind MUST stop here. `PboHandle::acquire_map` publishes
/// `MapState::Mapping` before calling `map_buffer` and clears it only on
/// return, so a panic crossing it strands that handle in `Mapping` and every
/// later map on it waits on the condvar forever.
fn inline_gl_op<T>(what: &str, f: impl FnOnce() -> Result<T, Error>) -> Result<T, Error> {
    match std::panic::catch_unwind(AssertUnwindSafe(f)) {
        Ok(result) => result,
        Err(e) => {
            GL_WORKER_POISON.with(|p| p.set(true));
            Err(Error::Internal(format!(
                "GL thread panicked during {what}: {}",
                panic_message(e.as_ref()),
            )))
        }
    }
}

// SAFETY: GlPboOps runs every GL operation on the thread owning the context --
// via the channel, or inline when that thread is already this one (see
// `GL_WORKER`). `map_buffer` returns a CPU-visible pointer from `glMapBufferRange`
// that remains valid until `unmap_buffer` calls `glUnmapBuffer` on the GL thread.
// `delete_buffer` sends a fire-and-forget deletion command to the GL thread.
unsafe impl edgefirst_tensor::PboOps for GlPboOps {
    fn map_buffer(
        &self,
        buffer_id: u32,
        size: usize,
    ) -> edgefirst_tensor::Result<edgefirst_tensor::PboMapping> {
        // Re-entrant call from inside a GL message handler on the worker that
        // owns this context (e.g. a mask draw reading back into a mapped PBO
        // destination). The context is already current on this thread,
        // and sending would block on the queue this thread alone drains.
        if on_owning_gl_worker(self.worker_id) {
            return inline_gl_op("PboMap", || pbo_map_on_gl_thread(buffer_id, size)).map_err(|e| {
                edgefirst_tensor::Error::NotImplemented(format!("GL PBO map failed: {e:?}"))
            });
        }
        // Foreign context, and this thread holds the lock the owner needs.
        if on_serializing_gl_worker() {
            return Err(cross_context_pbo_error("map", buffer_id));
        }
        let sender = self
            .sender
            .upgrade()
            .ok_or(edgefirst_tensor::Error::PboDisconnected)?;
        let (tx, rx) = tokio::sync::oneshot::channel();
        sender
            .blocking_send(GLProcessorMessage::PboMap(buffer_id, size, tx))
            .map_err(|_| edgefirst_tensor::Error::PboDisconnected)?;
        rx.blocking_recv()
            .map_err(|_| edgefirst_tensor::Error::PboDisconnected)?
            .map_err(|e| {
                edgefirst_tensor::Error::NotImplemented(format!("GL PBO map failed: {e:?}"))
            })
    }

    fn unmap_buffer(&self, buffer_id: u32) -> edgefirst_tensor::Result<()> {
        // See `map_buffer` — same re-entrancy, same reasoning.
        if on_owning_gl_worker(self.worker_id) {
            return inline_gl_op("PboUnmap", || pbo_unmap_on_gl_thread(buffer_id)).map_err(|e| {
                edgefirst_tensor::Error::NotImplemented(format!("GL PBO unmap failed: {e:?}"))
            });
        }
        // See `map_buffer`.
        if on_serializing_gl_worker() {
            return Err(cross_context_pbo_error("unmap", buffer_id));
        }
        let sender = self
            .sender
            .upgrade()
            .ok_or(edgefirst_tensor::Error::PboDisconnected)?;
        let (tx, rx) = tokio::sync::oneshot::channel();
        sender
            .blocking_send(GLProcessorMessage::PboUnmap(buffer_id, tx))
            .map_err(|_| edgefirst_tensor::Error::PboDisconnected)?;
        rx.blocking_recv()
            .map_err(|_| edgefirst_tensor::Error::PboDisconnected)?
            .map_err(|e| {
                edgefirst_tensor::Error::NotImplemented(format!("GL PBO unmap failed: {e:?}"))
            })
    }

    fn delete_buffer(&self, buffer_id: u32) {
        // See `map_buffer` — a drop mid-convert must not queue to itself.
        if on_owning_gl_worker(self.worker_id) {
            with_worker_mapped(|set| set.remove(&buffer_id));
            // Reached from `PboHandle::Drop`; an unwind out of a drop that is
            // itself unwinding aborts the process.
            let _ = inline_gl_op("PboDelete", || {
                unsafe { edgefirst_gl::gl::DeleteBuffers(1, &buffer_id) };
                Ok(())
            });
            return;
        }
        if let Some(sender) = self.sender.upgrade() {
            // See `map_buffer`: blocking here would deadlock the same way.
            if on_serializing_gl_worker() {
                if sender
                    .try_send(GLProcessorMessage::PboDelete(buffer_id))
                    .is_err()
                {
                    log::warn!(
                        "PBO {buffer_id}: cross-context delete skipped to avoid a deadlock; \
                         the buffer is freed when its context is destroyed"
                    );
                }
                return;
            }
            let _ = sender.blocking_send(GLProcessorMessage::PboDelete(buffer_id));
        }
    }
}

/// Routes CUDA GL-interop map/unmap/unregister to the GL thread.
///
/// Mirrors [`GlPboOps`]: holds a [`WeakSender`] so a registered PBO doesn't
/// keep the GL thread's channel alive. The CUDA primitives
/// (`cudaGraphicsMapResources` etc.) require the GL context to be current,
/// so they must execute on the dedicated GL worker thread.
struct GlCudaOps {
    sender: WeakSender<GLProcessorMessage>,
}

impl edgefirst_tensor::CudaGlOps for GlCudaOps {
    fn map(&self, resource: *mut std::ffi::c_void) -> Option<(*mut std::ffi::c_void, usize)> {
        let sender = self.sender.upgrade()?;
        let (tx, rx) = tokio::sync::oneshot::channel();
        sender
            .blocking_send(GLProcessorMessage::CudaMap(resource as usize, tx))
            .ok()?;
        rx.blocking_recv()
            .ok()?
            .map(|(p, l)| (p as *mut std::ffi::c_void, l))
    }

    fn unmap(&self, resource: *mut std::ffi::c_void) {
        if let Some(sender) = self.sender.upgrade() {
            let _ = sender.blocking_send(GLProcessorMessage::CudaUnmap(resource as usize));
        }
    }

    fn unregister(&self, resource: *mut std::ffi::c_void) {
        if let Some(sender) = self.sender.upgrade() {
            let _ = sender.blocking_send(GLProcessorMessage::CudaUnregister(resource as usize));
        }
    }
}

/// OpenGL multi-threaded image converter. The actual conversion is done in a
/// separate rendering thread, as OpenGL contexts are not thread-safe. This can
/// be safely sent between threads. The `convert()` call sends the conversion
/// request to the rendering thread and waits for the result.
#[derive(Debug)]
pub struct GLProcessorThreaded {
    // This is only None when the converter is being dropped.
    handle: Option<JoinHandle<()>>,

    // This is only None when the converter is being dropped.
    sender: Option<Sender<GLProcessorMessage>>,
    /// Identity of this processor's worker thread, handed to every `GlPboOps`
    /// it creates so a re-entrant map can be matched to the owning context.
    worker_id: u64,
    /// The PBOs this processor handed out, shared with its worker's
    /// `GLProcessorST`: only these may be bound in the worker's context.
    owned_pbos: std::sync::Arc<super::processor::OwnedPbos>,
    /// Immutable capability surface (transfer backend, float render
    /// support, serialization policy), captured once from the worker at
    /// construction. See `PlatformCaps` in `platform/mod.rs`.
    caps: super::platform::PlatformCaps,
}

unsafe impl Send for GLProcessorThreaded {}
unsafe impl Sync for GLProcessorThreaded {}

struct SendablePtr<T: Send> {
    ptr: NonNull<T>,
    len: usize,
}

unsafe impl<T> Send for SendablePtr<T> where T: Send {}

/// Extract a human-readable message from a `catch_unwind` panic payload.
fn panic_message(info: &(dyn std::any::Any + Send)) -> String {
    if let Some(s) = info.downcast_ref::<&str>() {
        s.to_string()
    } else if let Some(s) = info.downcast_ref::<String>() {
        s.clone()
    } else {
        "unknown panic".to_string()
    }
}

fn reply_caught<T>(
    result: std::thread::Result<crate::Result<T>>,
    resp: tokio::sync::oneshot::Sender<crate::Result<T>>,
    poisoned: &mut bool,
    what: &str,
) {
    let _ = resp.send(match result {
        Ok(res) => res,
        Err(e) => {
            *poisoned = true;
            Err(crate::Error::Internal(format!(
                "GL thread panicked during {what}: {}",
                panic_message(e.as_ref()),
            )))
        }
    });
}

fn reject_poisoned_message(msg: GLProcessorMessage) {
    let poison_err =
        crate::Error::Internal("GL context is poisoned after a prior panic".to_string());
    match msg {
        GLProcessorMessage::ImageConvertFenced(.., resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::ImageConvert(.., resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::Flush(resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::DrawDecodedMasks(.., resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::DrawProtoMasks(.., resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::SetColors(_, resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::SetBoxLineWidth(_, resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::SetInt8Interpolation(_, resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::SetColorimetryMode(_, resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::SetInterpolation(_, resp) => {
            let _ = resp.send(Err(poison_err));
        }
        #[cfg(test)]
        GLProcessorMessage::SetFailDstImport(_, resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::EglCacheStats(resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::ConvertStats(resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::PboCreate(_, resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::PboMap(_, _, resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::PboUnmap(_, resp) => {
            let _ = resp.send(Err(poison_err));
        }
        GLProcessorMessage::PboDelete(_) => {}
        GLProcessorMessage::CudaRegisterBuffer(_, resp) => {
            let _ = resp.send(None);
        }
        GLProcessorMessage::CudaMap(_, resp) => {
            let _ = resp.send(None);
        }
        // GL context is poisoned/dead — the GL buffer is unusable, so unmapping/
        // unregistering the CUDA interop is moot (the resource is reclaimed at
        // process exit). Same accepted "GL is gone" no-op as PboDelete above.
        GLProcessorMessage::CudaUnmap(_) => {}
        GLProcessorMessage::CudaUnregister(_) => {}
    }
}

fn run_gl_worker(
    worker_id: u64,
    owned_pbos: std::sync::Arc<super::processor::OwnedPbos>,
    kind: Option<EglDisplayKind>,
    capacity: Option<usize>,
    mut recv: tokio::sync::mpsc::Receiver<GLProcessorMessage>,
    create_ctx_send: tokio::sync::oneshot::Sender<Result<super::platform::PlatformCaps, Error>>,
) {
    // Creation runs under the global lifecycle lock on Linux
    // (bring-up races on some embedded drivers); ANGLE serializes
    // display-level entry points internally, so macOS needs none
    // (validated by the A0 lifecycle-churn spike leg).
    #[cfg(target_os = "linux")]
    let init_result = {
        let _guard = super::context::GL_MUTEX
            .lock()
            .unwrap_or_else(|e| e.into_inner());
        GLProcessorST::new(kind, capacity)
    };
    // macOS: ANGLE/Metal serializes display-level entry points
    // internally. Android: the system EGL is specification-conformant
    // thread-safe. Neither needs the Linux lifecycle lock.
    #[cfg(any(target_os = "macos", target_os = "ios", target_os = "android"))]
    let init_result = GLProcessorST::new(kind, capacity);
    // Windows: ANGLE's D3D11 backend drives one immediate device context
    // (and one state manager) per display from every GL context and is not
    // safe to use from two threads at once: a processor bringing up its
    // context (shader compiles, texture allocation) while another converted
    // crashed with an access violation. Lifecycle and messages therefore
    // share NON_LINUX_GL_MUTEX there; per-message locking is the ANGLE Full
    // policy anyway.
    #[cfg(target_os = "windows")]
    let init_result = {
        let _guard = NON_LINUX_GL_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
        GLProcessorST::new(kind, capacity)
    };
    let mut gl_converter = match init_result {
        Ok(gl) => gl,
        Err(e) => {
            let _ = create_ctx_send.send(Err(e));
            return;
        }
    };
    gl_converter.owned_pbos = owned_pbos;
    // Capability surface captured ONCE before the message loop —
    // immutable for the worker's life, never re-probed per message.
    let caps = gl_converter.platform_caps();
    let _ = create_ctx_send.send(Ok(caps));
    let mut poisoned = false;
    // Tracks which PBO buffer_ids currently have an outstanding GL
    // mapping, scoped to this one GL context/thread -- the ONE
    // place every PboOps call against this context's buffers
    // actually serializes, regardless of which `PboHandle`
    // (edgefirst-tensor) issued the `PboMap`/`PboUnmap` message.
    // `PboHandle::acquire_map`'s own per-handle `Mutex<MapState>`
    // enforces "at most one mapping" WITHIN one handle, including
    // read-sharing (several readers reuse ONE mapping without ever
    // re-sending `PboMap` here) -- but it has no visibility into a
    // SEPARATE `PboHandle` for the same real `buffer_id`, which
    // task 11's cross-cdylib PBO import made newly reachable: a
    // producer's own tensor and a reconstructed cross-package
    // consumer tensor for the same `buffer_id` are two independent
    // `PboHandle`s, each believing it is the only mapper.
    // `glMapBufferRange` on an already-mapped buffer is undefined
    // behaviour per the GL spec, so THIS set -- not the per-handle
    // mutex, which never sees another handle's calls -- is what
    // actually prevents that.
    // Install this thread's GL-worker identity and its mapped-PBO set. Both
    // the message path and the re-entrant inline path read them from here —
    // see [`GL_WORKER`] for why the inline path has to exist at all.
    GL_WORKER.with(|c| {
        *c.borrow_mut() = Some(GlWorkerState {
            id: worker_id,
            // Set once the policy below is resolved.
            serializes: false,
            mapped: std::collections::HashSet::new(),
        });
    });
    // Clear on every exit path, including unwind, so a recycled thread id can
    // never inherit a dead worker's identity.
    struct GlWorkerSlot;
    impl Drop for GlWorkerSlot {
        fn drop(&mut self) {
            GL_WORKER.with(|c| *c.borrow_mut() = None);
            GL_WORKER_POISON.with(|p| p.set(false));
        }
    }
    let _gl_worker_slot = GlWorkerSlot;
    // Per-message serialization policy: Full where the platform
    // demands it (`caps.serialize_gl` — Vivante/galcore is not
    // thread-safe for concurrent GL across contexts), LifecycleOnly
    // everywhere else — multiple processors then run GL work in
    // parallel, each on its own thread + context. See the GL_MUTEX
    // doc comment in context.rs. EDGEFIRST_GL_SERIALIZE overrides
    // per-driver defaults (full = escape hatch for unknown-bad
    // drivers; lifecycle = force-parallel).
    let serialize_per_msg = match std::env::var("EDGEFIRST_GL_SERIALIZE").as_deref() {
        Ok("full") => true,
        Ok("lifecycle") => {
            // The per-message lock is what makes ANGLE's per-display state
            // manager safe here: `LAST_ACTIVE_CONTEXT` and the per-message
            // context re-sync it drives are documented as touched only under
            // it, and concurrent GL on this backend has crashed this box.
            #[cfg(target_os = "windows")]
            log::warn!(
                "EDGEFIRST_GL_SERIALIZE=lifecycle drops the per-message lock the ANGLE/D3D11 context re-sync relies on; concurrent GL across processors is not supported on this backend"
            );
            false
        }
        _ => caps.serialize_gl,
    };
    log::debug!(
        "GL serialization policy: {}",
        if serialize_per_msg {
            "Full (per-message global lock)"
        } else {
            "LifecycleOnly (parallel across processors)"
        }
    );
    GL_WORKER.with(|c| {
        if let Some(state) = c.borrow_mut().as_mut() {
            state.serializes = serialize_per_msg;
        }
    });
    while let Some(msg) = recv.blocking_recv() {
        // Full policy: one processor's message at a time, process-wide.
        // Linux locks GL_MUTEX (messages must also exclude the locked
        // lifecycle operations — on Vivante a convert racing a context
        // bring-up is part of the driver bug class). macOS has no
        // lifecycle lock (ANGLE serializes display entry points
        // internally), so message-vs-message exclusion suffices —
        // needed on virtualized GPUs, where concurrent GL across
        // contexts mis-renders (paravirtual Metal, macOS CI runners).
        #[cfg(target_os = "linux")]
        let _guard = serialize_per_msg.then(|| {
            super::context::GL_MUTEX
                .lock()
                .unwrap_or_else(|e| e.into_inner())
        });
        #[cfg(any(
            target_os = "macos",
            target_os = "ios",
            target_os = "android",
            target_os = "windows"
        ))]
        let _guard =
            serialize_per_msg.then(|| NON_LINUX_GL_MUTEX.lock().unwrap_or_else(|e| e.into_inner()));

        // After a panic, the GL context is in an undefined state. Reject
        // all subsequent messages with an error rather than risking wrong
        // output or a GPU hang from corrupted GL state. This follows the
        // same pattern as std::sync::Mutex poisoning.
        if poisoned {
            reject_poisoned_message(msg);
            continue;
        }

        // Platform pre-message hook (ANGLE/D3D11 re-syncs this context's
        // state when another processor's context issued the last commands;
        // a no-op elsewhere). Runs under the lock taken above.
        gl_converter.begin_gpu_pass();
        handle_gl_message(msg, &mut gl_converter, &mut poisoned);
        // A re-entrant inline PBO op reports its panic here: `inline_gl_op`
        // converted it to an error so it could not unwind into the tensor
        // crate, which means `reply_caught` never saw it.
        poisoned |= GL_WORKER_POISON.with(|p| p.replace(false));
        // Per-pass platform texture attachments (macOS pbuffer
        // binds) are released once the message's GPU work has
        // synced; deferred batches keep theirs until Flush.
        gl_converter.end_gpu_pass_if_synced();
    }
    // Explicitly drop under the mutex so EGL teardown is serialized
    // (Linux, and Windows for the D3D11 reason above; ANGLE teardown is
    // display-internal on macOS).
    #[cfg(target_os = "linux")]
    let _guard = super::context::GL_MUTEX
        .lock()
        .unwrap_or_else(|e| e.into_inner());
    #[cfg(target_os = "windows")]
    let _guard = NON_LINUX_GL_MUTEX.lock().unwrap_or_else(|e| e.into_inner());
    drop(gl_converter);
}

/// Per-message serialization lock for the platforms without a Linux-style
/// `GL_MUTEX` (macOS/iOS, Android, Windows) — taken per message under the
/// Full policy, and on Windows also around processor bring-up/teardown.
#[cfg(not(target_os = "linux"))]
static NON_LINUX_GL_MUTEX: std::sync::Mutex<()> = std::sync::Mutex::new(());

/// Take [`NON_LINUX_GL_MUTEX`] on behalf of a caller outside the GL worker
/// threads. Poison-tolerant, like every other user of it.
///
/// Windows leaf tests MUST hold this guard for their whole body: any test
/// that brings up an ANGLE display or a GL context does so on the test's own
/// thread, and the lib test binary runs other tests whose GL workers are
/// alive at the same time. ANGLE's D3D11 backend drives one immediate device
/// context per display from every GL context and is not safe to use from two
/// threads at once — the access-violation pattern documented on
/// [`run_gl_worker`], which takes the same lock around bring-up and teardown.
#[cfg(target_os = "windows")]
pub(super) fn lifecycle_guard() -> std::sync::MutexGuard<'static, ()> {
    NON_LINUX_GL_MUTEX.lock().unwrap_or_else(|e| e.into_inner())
}

fn handle_gl_message(
    msg: GLProcessorMessage,
    gl_converter: &mut GLProcessorST,
    poisoned: &mut bool,
) {
    match msg {
        GLProcessorMessage::ImageConvert(src, dst, options, defer, resp) => {
            handle_image_convert(src, dst, (options, defer), resp, gl_converter, poisoned);
        }
        GLProcessorMessage::ImageConvertFenced(src, dst, options, resp) => {
            handle_image_convert_fenced(src, dst, options, resp, gl_converter, poisoned);
        }
        GLProcessorMessage::Flush(resp) => {
            let result = std::panic::catch_unwind(AssertUnwindSafe(|| gl_converter.flush()));
            reply_caught(result, resp, poisoned, "Flush");
        }
        GLProcessorMessage::DrawDecodedMasks(
            dst,
            det,
            seg,
            opacity,
            bg,
            content_region,
            color_mode,
            resp,
        ) => {
            handle_draw_decoded_masks(
                dst,
                det,
                seg,
                (opacity, bg, content_region, color_mode),
                resp,
                gl_converter,
                poisoned,
            );
        }
        GLProcessorMessage::DrawProtoMasks(
            dst,
            det,
            proto_data,
            opacity,
            bg,
            content_region,
            color_mode,
            resp,
        ) => {
            handle_draw_proto_masks(
                dst,
                det,
                proto_data,
                (opacity, bg, content_region, color_mode),
                resp,
                gl_converter,
                poisoned,
            );
        }
        GLProcessorMessage::SetColors(colors, resp) => {
            let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
                gl_converter.set_class_colors(&colors)
            }));
            reply_caught(result, resp, poisoned, "SetColors");
        }
        GLProcessorMessage::SetBoxLineWidth(width, resp) => {
            let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
                gl_converter.set_box_line_width(width)
            }));
            reply_caught(result, resp, poisoned, "SetBoxLineWidth");
        }
        GLProcessorMessage::SetColorimetryMode(mode, resp) => {
            let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
                gl_converter.set_colorimetry_mode(mode);
                Ok(())
            }));
            reply_caught(result, resp, poisoned, "SetColorimetryMode");
        }
        GLProcessorMessage::SetInterpolation(mode, resp) => {
            let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
                gl_converter.set_interpolation(mode);
                Ok(())
            }));
            reply_caught(result, resp, poisoned, "SetInterpolation");
        }
        GLProcessorMessage::SetInt8Interpolation(mode, resp) => {
            let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
                gl_converter.set_int8_interpolation_mode(mode);
                Ok(())
            }));
            reply_caught(result, resp, poisoned, "SetInt8Interpolation");
        }
        #[cfg(test)]
        GLProcessorMessage::SetFailDstImport(fail, resp) => {
            let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
                gl_converter.fail_dst_import = fail;
                Ok(())
            }));
            reply_caught(result, resp, poisoned, "SetFailDstImport");
        }
        GLProcessorMessage::EglCacheStats(resp) => {
            let result =
                std::panic::catch_unwind(AssertUnwindSafe(|| Ok(gl_converter.egl_cache_stats())));
            reply_caught(result, resp, poisoned, "EglCacheStats");
        }
        GLProcessorMessage::ConvertStats(resp) => {
            let result =
                std::panic::catch_unwind(AssertUnwindSafe(|| Ok(gl_converter.convert_stats())));
            reply_caught(result, resp, poisoned, "ConvertStats");
        }
        GLProcessorMessage::PboCreate(size, resp) => {
            handle_pbo_create(size, resp, poisoned);
        }
        GLProcessorMessage::PboMap(buffer_id, size, resp) => {
            handle_pbo_map(buffer_id, size, resp, poisoned);
        }
        GLProcessorMessage::PboUnmap(buffer_id, resp) => {
            handle_pbo_unmap(buffer_id, resp, poisoned);
        }
        GLProcessorMessage::PboDelete(buffer_id) => {
            handle_pbo_delete(buffer_id, poisoned);
        }
        GLProcessorMessage::CudaRegisterBuffer(buffer_id, resp) => {
            // CUDA GL-interop must run on the GL-context thread.
            let _ = resp.send(edgefirst_tensor::gl_register_buffer(buffer_id));
        }
        GLProcessorMessage::CudaMap(resource, resp) => {
            // Auto-flush: if a batched `convert_deferred` is still
            // owed its single GPU sync, complete it before CUDA maps
            // the buffer — otherwise the device could read a render
            // still in flight. This makes `cuda_map()` correct on a
            // batched output with no API change (the caller pays the
            // sync it would have owed anyway).
            gl_converter.flush_pending();
            let _ = resp.send(edgefirst_tensor::gl_map_resource(resource));
        }
        GLProcessorMessage::CudaUnmap(resource) => {
            edgefirst_tensor::gl_unmap_resource(resource);
        }
        GLProcessorMessage::CudaUnregister(resource) => {
            edgefirst_tensor::gl_unregister_resource(resource);
        }
    }
}

fn handle_image_convert(
    src: SendablePtr<TensorDyn>,
    mut dst: SendablePtr<TensorDyn>,
    geom: (ConvertOptions, bool),
    resp: tokio::sync::oneshot::Sender<Result<(), Error>>,
    gl_converter: &mut GLProcessorST,
    poisoned: &mut bool,
) {
    let (options, defer) = geom;
    // SAFETY: This is safe because the convert() function waits for the resp to
    // be sent before dropping the borrow for src and dst
    let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
        let src = unsafe { src.ptr.as_ref() };
        let dst = unsafe { dst.ptr.as_mut() };
        // A deferred convert skips the per-tile glFinish and
        // leaves a single sync owed at Flush; an eager convert
        // finishes as usual.
        if defer {
            gl_converter.convert_deferred(src, dst, Some(options))
        } else {
            gl_converter.convert(src, dst, Some(options))
        }
    }));
    reply_caught(result, resp, poisoned, "ImageConvert");
}

fn handle_image_convert_fenced(
    src: SendablePtr<TensorDyn>,
    mut dst: SendablePtr<TensorDyn>,
    options: ConvertOptions,
    resp: tokio::sync::oneshot::Sender<Result<Option<super::CompletionFence>, Error>>,
    gl_converter: &mut GLProcessorST,
    poisoned: &mut bool,
) {
    // SAFETY: as ImageConvert — convert_with_fence()
    // blocks on the reply before the borrows drop.
    let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
        let src = unsafe { src.ptr.as_ref() };
        let dst = unsafe { dst.ptr.as_mut() };
        gl_converter.convert_fenced(src, dst, options)
    }));
    reply_caught(result, resp, poisoned, "ImageConvertFenced");
}

fn handle_draw_decoded_masks(
    mut dst: SendablePtr<TensorDyn>,
    det: SendablePtr<DetectBox>,
    seg: SendablePtr<Segmentation>,
    overlay: (
        f32,
        Option<SendablePtr<TensorDyn>>,
        Option<[f32; 4]>,
        crate::ColorMode,
    ),
    resp: tokio::sync::oneshot::Sender<Result<(), Error>>,
    gl_converter: &mut GLProcessorST,
    poisoned: &mut bool,
) {
    let (opacity, bg, content_region, color_mode) = overlay;
    // SAFETY: This is safe because the draw_decoded_masks() function waits for the
    // resp to be sent before dropping the borrow for dst, detect,
    // segmentation, and background
    let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
        let dst = unsafe { dst.ptr.as_mut() };
        let det = unsafe { std::slice::from_raw_parts(det.ptr.as_ptr(), det.len) };
        let seg = unsafe { std::slice::from_raw_parts(seg.ptr.as_ptr(), seg.len) };
        let bg_ref = bg.map(|p| unsafe { &*p.ptr.as_ptr() });
        gl_converter.draw_decoded_masks(
            dst,
            det,
            seg,
            crate::MaskOverlay {
                background: bg_ref,
                opacity,
                content_region,
                color_mode,
            },
        )
    }));
    reply_caught(result, resp, poisoned, "DrawDecodedMasks");
}

fn handle_draw_proto_masks(
    mut dst: SendablePtr<TensorDyn>,
    det: SendablePtr<DetectBox>,
    proto_data: SendablePtr<ProtoData>,
    overlay: (
        f32,
        Option<SendablePtr<TensorDyn>>,
        Option<[f32; 4]>,
        crate::ColorMode,
    ),
    resp: tokio::sync::oneshot::Sender<Result<(), Error>>,
    gl_converter: &mut GLProcessorST,
    poisoned: &mut bool,
) {
    let (opacity, bg, content_region, color_mode) = overlay;
    // SAFETY: Same safety invariant as DrawDecodedMasks — caller
    // blocks on resp before dropping borrows.
    let result = std::panic::catch_unwind(AssertUnwindSafe(|| {
        let dst = unsafe { dst.ptr.as_mut() };
        let det = unsafe { std::slice::from_raw_parts(det.ptr.as_ptr(), det.len) };
        let bg_ref = bg.map(|p| unsafe { &*p.ptr.as_ptr() });
        let proto_data = unsafe { proto_data.ptr.as_ref() };
        gl_converter.draw_proto_masks(
            dst,
            det,
            proto_data,
            crate::MaskOverlay {
                background: bg_ref,
                opacity,
                content_region,
                color_mode,
            },
        )
    }));
    reply_caught(result, resp, poisoned, "DrawProtoMasks");
}

fn handle_pbo_create(
    size: usize,
    resp: tokio::sync::oneshot::Sender<Result<u32, Error>>,
    poisoned: &mut bool,
) {
    let result = std::panic::catch_unwind(AssertUnwindSafe(|| unsafe {
        let mut id: u32 = 0;
        edgefirst_gl::gl::GenBuffers(1, &mut id);
        edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, id);
        edgefirst_gl::gl::BufferData(
            edgefirst_gl::gl::PIXEL_PACK_BUFFER,
            size as isize,
            std::ptr::null(),
            edgefirst_gl::gl::STREAM_COPY,
        );
        edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, 0);
        match check_gl_error("PboCreate", 0) {
            Ok(()) => Ok(id),
            Err(e) => {
                edgefirst_gl::gl::DeleteBuffers(1, &id);
                Err(e)
            }
        }
    }));
    reply_caught(result, resp, poisoned, "PboCreate");
}

/// Perform a PBO map on the calling thread, which MUST be the GL worker that
/// owns the buffer (context already current). Shared by the message handler and
/// the re-entrant inline path so the dedup rule is enforced identically.
fn pbo_map_on_gl_thread(
    buffer_id: u32,
    size: usize,
) -> Result<edgefirst_tensor::PboMapping, Error> {
    let already = with_worker_mapped(|set| !set.insert(buffer_id)).unwrap_or(false);
    if already {
        return Err(Error::OpenGl(format!(
            "PBO buffer {buffer_id} is already mapped in this GL context \
             (a producer and a reconstructed cross-package consumer may \
             both hold a live tensor over it)"
        )));
    }
    let result = std::panic::catch_unwind(AssertUnwindSafe(|| unsafe {
        edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, buffer_id);
        let ptr = edgefirst_gl::gl::MapBufferRange(
            edgefirst_gl::gl::PIXEL_PACK_BUFFER,
            0,
            size as isize,
            edgefirst_gl::gl::MAP_READ_BIT | edgefirst_gl::gl::MAP_WRITE_BIT,
        );
        edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, 0);
        if ptr.is_null() {
            Err(Error::OpenGl("glMapBufferRange returned null".to_string()))
        } else {
            Ok(edgefirst_tensor::PboMapping {
                ptr: ptr as *mut u8,
                size,
            })
        }
    }));
    if !matches!(result, Ok(Ok(_))) {
        // The map did not take — release the reservation so a retry is not
        // permanently blocked by a mapping that never happened.
        with_worker_mapped(|set| set.remove(&buffer_id));
    }
    match result {
        Ok(result) => result,
        // Reaches whichever boundary the caller has: `handle_pbo_map` on the
        // message path, `inline_gl_op` on the re-entrant one.
        Err(panic) => std::panic::resume_unwind(panic),
    }
}

/// Unmap counterpart of [`pbo_map_on_gl_thread`]; same thread requirement.
fn pbo_unmap_on_gl_thread(buffer_id: u32) -> Result<(), Error> {
    // Always release the reservation, matching `PboHandle::release_map`'s
    // "state returns to Unmapped either way" contract.
    with_worker_mapped(|set| set.remove(&buffer_id));
    unsafe {
        edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, buffer_id);
        let ok = edgefirst_gl::gl::UnmapBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER);
        edgefirst_gl::gl::BindBuffer(edgefirst_gl::gl::PIXEL_PACK_BUFFER, 0);
        if ok == edgefirst_gl::gl::FALSE {
            Err(Error::OpenGl(
                "PBO data was corrupted during mapping".into(),
            ))
        } else {
            check_gl_error("PboUnmap", 0)
        }
    }
}

fn handle_pbo_map(
    buffer_id: u32,
    size: usize,
    resp: tokio::sync::oneshot::Sender<Result<edgefirst_tensor::PboMapping, Error>>,
    poisoned: &mut bool,
) {
    let result =
        std::panic::catch_unwind(AssertUnwindSafe(|| pbo_map_on_gl_thread(buffer_id, size)));
    reply_caught(result, resp, poisoned, "PboMap");
}

fn handle_pbo_unmap(
    buffer_id: u32,
    resp: tokio::sync::oneshot::Sender<Result<(), Error>>,
    poisoned: &mut bool,
) {
    let result = std::panic::catch_unwind(AssertUnwindSafe(|| pbo_unmap_on_gl_thread(buffer_id)));
    reply_caught(result, resp, poisoned, "PboUnmap");
}

fn handle_pbo_delete(buffer_id: u32, poisoned: &mut bool) {
    // Defensive: a live mapping should never reach here
    // (PboHandle::Drop unmaps before deleting), but a
    // stale reservation for a since-deleted (and
    // possibly buffer-id-recycled) buffer would
    // otherwise wrongly block every future map of a NEW
    // buffer that reuses the same id.
    with_worker_mapped(|set| set.remove(&buffer_id));
    if let Err(e) = std::panic::catch_unwind(AssertUnwindSafe(|| unsafe {
        edgefirst_gl::gl::DeleteBuffers(1, &buffer_id);
    })) {
        *poisoned = true;
        log::error!(
            "GL thread panicked during PboDelete: {}",
            panic_message(e.as_ref()),
        );
    }
}

impl GLProcessorThreaded {
    /// Creates a new OpenGL multi-threaded image converter whose import
    /// caches use the environment/default capacity.
    pub fn new(kind: Option<EglDisplayKind>) -> Result<Self, Error> {
        Self::with_cache_capacity(kind, None)
    }

    /// As [`new`](Self::new), with an explicit per-cache import capacity —
    /// [`ImageProcessorConfig::egl_cache_capacity`], which documents what the
    /// number bounds and takes precedence over the environment.
    ///
    /// [`ImageProcessorConfig::egl_cache_capacity`]: crate::ImageProcessorConfig::egl_cache_capacity
    pub fn with_cache_capacity(
        kind: Option<EglDisplayKind>,
        capacity: Option<usize>,
    ) -> Result<Self, Error> {
        let worker_id = NEXT_GL_WORKER_ID.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let (send, recv) = tokio::sync::mpsc::channel::<GLProcessorMessage>(1);

        let (create_ctx_send, create_ctx_recv) = tokio::sync::oneshot::channel();

        let owned_pbos = std::sync::Arc::<super::processor::OwnedPbos>::default();
        let worker_owned = owned_pbos.clone();
        let handle = std::thread::spawn(move || {
            run_gl_worker(
                worker_id,
                worker_owned,
                kind,
                capacity,
                recv,
                create_ctx_send,
            );
        });

        let caps = match create_ctx_recv.blocking_recv() {
            Ok(Err(e)) => return Err(e),
            Err(_) => {
                return Err(Error::Internal(
                    "GL converter error messaging closed without update".to_string(),
                ));
            }
            Ok(Ok(caps)) => caps,
        };

        Ok(Self {
            handle: Some(handle),
            sender: Some(send),
            worker_id,
            owned_pbos,
            caps,
        })
    }
}

impl ImageProcessorTrait for GLProcessorThreaded {
    fn convert(
        &mut self,
        src: &TensorDyn,
        dst: &mut TensorDyn,
        options: Option<ConvertOptions>,
    ) -> crate::Result<()> {
        let options = options.unwrap_or_default();
        let (err_send, err_recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::ImageConvert(
                SendablePtr {
                    ptr: NonNull::from(src),
                    len: 1,
                },
                SendablePtr {
                    ptr: NonNull::from(dst),
                    len: 1,
                },
                options,
                false, // eager: finish per convert
                err_send,
            ))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        err_recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    fn convert_deferred(
        &mut self,
        src: &TensorDyn,
        dst: &mut TensorDyn,
        options: Option<ConvertOptions>,
    ) -> crate::Result<()> {
        let options = options.unwrap_or_default();
        let (err_send, err_recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::ImageConvert(
                SendablePtr {
                    ptr: NonNull::from(src),
                    len: 1,
                },
                SendablePtr {
                    ptr: NonNull::from(dst),
                    len: 1,
                },
                options,
                true, // defer: skip glFinish; flush() syncs the batch once
                err_send,
            ))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        err_recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    fn flush(&mut self) -> crate::Result<()> {
        let (err_send, err_recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::Flush(err_send))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        err_recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    fn draw_decoded_masks(
        &mut self,
        dst: &mut TensorDyn,
        detect: &[crate::DetectBox],
        segmentation: &[crate::Segmentation],
        overlay: crate::MaskOverlay<'_>,
    ) -> crate::Result<()> {
        let (err_send, err_recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::DrawDecodedMasks(
                SendablePtr {
                    ptr: NonNull::from(dst),
                    len: 1,
                },
                SendablePtr {
                    ptr: NonNull::new(detect.as_ptr() as *mut DetectBox).unwrap(),
                    len: detect.len(),
                },
                SendablePtr {
                    ptr: NonNull::new(segmentation.as_ptr() as *mut Segmentation).unwrap(),
                    len: segmentation.len(),
                },
                overlay.opacity,
                overlay.background.map(|bg| SendablePtr {
                    ptr: NonNull::from(bg).cast::<TensorDyn>(),
                    len: 1,
                }),
                overlay.content_region,
                overlay.color_mode,
                err_send,
            ))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        err_recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    fn draw_proto_masks(
        &mut self,
        dst: &mut TensorDyn,
        detect: &[DetectBox],
        proto_data: &ProtoData,
        overlay: crate::MaskOverlay<'_>,
    ) -> crate::Result<()> {
        let (err_send, err_recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::DrawProtoMasks(
                SendablePtr {
                    ptr: NonNull::from(dst),
                    len: 1,
                },
                SendablePtr {
                    ptr: NonNull::new(detect.as_ptr() as *mut DetectBox).unwrap(),
                    len: detect.len(),
                },
                SendablePtr {
                    ptr: NonNull::from(proto_data).cast::<ProtoData>(),
                    len: 1,
                },
                overlay.opacity,
                overlay.background.map(|bg| SendablePtr {
                    ptr: NonNull::from(bg).cast::<TensorDyn>(),
                    len: 1,
                }),
                overlay.content_region,
                overlay.color_mode,
                err_send,
            ))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        err_recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    fn set_class_colors(&mut self, colors: &[[u8; 4]]) -> Result<(), crate::Error> {
        let (err_send, err_recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::SetColors(colors.to_vec(), err_send))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        err_recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    fn set_box_line_width(&mut self, width: u32) -> Result<(), crate::Error> {
        crate::check_box_line_width(width)?;
        let (err_send, err_recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::SetBoxLineWidth(width, err_send))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        err_recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }
}

impl GLProcessorThreaded {
    /// Sets the colorimetry/performance trade-off (see
    /// [`crate::ColorimetryMode`]). The `EDGEFIRST_COLORIMETRY` environment
    /// variable takes precedence — when set, this call logs and keeps the
    /// env-selected mode.
    pub fn set_colorimetry_mode(&mut self, mode: crate::ColorimetryMode) -> Result<(), Error> {
        let (err_send, err_recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::SetColorimetryMode(mode, err_send))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        err_recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    /// Sets how resizing converts resample (see [`crate::Interpolation`]).
    pub fn set_interpolation(&mut self, mode: crate::Interpolation) -> Result<(), Error> {
        let (err_send, err_recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::SetInterpolation(mode, err_send))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        err_recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    /// Test hook (issue #175): make every zero-copy DESTINATION import fail,
    /// the way a driver that refuses the buffer does, so the fallback to the
    /// mapped-texture readback is exercised on a host whose driver accepts
    /// every destination. The failure is injected at the import itself, so
    /// what a test drives is the production trigger.
    #[cfg(test)]
    pub(crate) fn set_fail_dst_import(&mut self, fail: bool) -> Result<(), Error> {
        let (err_send, err_recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::SetFailDstImport(fail, err_send))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        err_recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    /// Sets the interpolation mode for int8 proto textures.
    pub fn set_int8_interpolation_mode(
        &mut self,
        mode: Int8InterpolationMode,
    ) -> Result<(), crate::Error> {
        let (err_send, err_recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::SetInt8Interpolation(mode, err_send))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        err_recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    /// Snapshot the EGLImage cache counters (src, dst, NV R8) from the GL
    /// thread. Steady-state tests capture this after warmup and after an
    /// N-frame loop over a fixed buffer pool and assert
    /// [`total_misses`](super::cache::GlCacheStats::total_misses) stays flat —
    /// any increase means a convert re-imported a buffer it should have found
    /// cached (the cache-behavior equality gate for GL refactors).
    pub fn egl_cache_stats(&self) -> Result<super::cache::GlCacheStats, Error> {
        let (send, recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::EglCacheStats(send))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    /// Convert and return a native sync-fence fd that signals when the
    /// GPU work completes, instead of blocking the CPU on `glFinish` —
    /// the GL→NPU handoff (`EGL_ANDROID_native_fence_sync`).
    ///
    /// `Ok(None)` means the convert completed with the normal blocking
    /// semantics (platform/driver has no native fence, or a pure-CPU-
    /// readback path was taken) — the destination is already safe to
    /// read. `Ok(Some(fd))` means the caller (or the NPU runtime, via
    /// `ANeuralNetworksExecution_startComputeWithDependencies`) must wait
    /// on the fd before consuming the destination buffer.
    pub fn convert_with_fence(
        &mut self,
        src: &TensorDyn,
        dst: &mut TensorDyn,
        options: Option<ConvertOptions>,
    ) -> Result<Option<super::CompletionFence>, Error> {
        let options = options.unwrap_or_default();
        use crate::ImageProcessorTrait as _;
        if !self.caps.native_fence_sync {
            // No fence on this display: the plain blocking convert IS the
            // fenced contract with `None` — skip the special round-trip.
            self.convert(src, dst, Some(options))?;
            return Ok(None);
        }
        let (send, recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::ImageConvertFenced(
                SendablePtr {
                    ptr: NonNull::from(src),
                    len: 1,
                },
                SendablePtr {
                    ptr: NonNull::from(dst),
                    len: 1,
                },
                options,
                send,
            ))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    /// Snapshot the per-convert source-feed counters from the GL thread.
    /// A pipeline that expects end-to-end zero-copy asserts
    /// [`src_uploads`](super::cache::ConvertStats::src_uploads) stays flat
    /// (every frame fed by import, never by a CPU map + upload).
    pub fn convert_stats(&self) -> Result<super::cache::ConvertStats, Error> {
        let (send, recv) = tokio::sync::oneshot::channel();
        self.sender
            .as_ref()
            .ok_or_else(|| Error::Internal("GL processor is shutting down".to_string()))?
            .blocking_send(GLProcessorMessage::ConvertStats(send))
            .map_err(|_| Error::Internal("GL converter thread exited".to_string()))?;
        recv.blocking_recv().map_err(|_| {
            Error::Internal("GL converter error messaging closed without update".to_string())
        })?
    }

    /// Create a PBO-backed [`Tensor<u8>`](edgefirst_tensor::Tensor) image on the GL thread.
    ///
    /// Declared [`CpuAccess::ReadWrite`](edgefirst_tensor::CpuAccess): the GL
    /// readback maps the buffer on the CPU itself (repack, BGRA swap, row
    /// spread), and a narrower declaration buys no cheaper PBO mapping.
    pub fn create_pbo_image(
        &self,
        width: usize,
        height: usize,
        format: edgefirst_tensor::PixelFormat,
    ) -> Result<edgefirst_tensor::Tensor<u8>, Error> {
        let sender = self
            .sender
            .as_ref()
            .ok_or(Error::OpenGl("GL processor is shutting down".to_string()))?;

        let size = pbo_elem_count(width, height, format)
            .filter(|&s| s != 0)
            .ok_or_else(|| Error::OpenGl("Invalid image dimensions".to_string()))?;

        // Allocate PBO on the GL thread
        let (tx, rx) = tokio::sync::oneshot::channel();
        sender
            .blocking_send(GLProcessorMessage::PboCreate(size, tx))
            .map_err(|_| Error::OpenGl("GL thread channel closed".to_string()))?;
        let buffer_id = rx
            .blocking_recv()
            .map_err(|_| Error::OpenGl("GL thread did not respond".to_string()))??;

        let ops: std::sync::Arc<dyn edgefirst_tensor::PboOps> = std::sync::Arc::new(GlPboOps {
            sender: sender.downgrade(),
            worker_id: self.worker_id,
        });
        let owned_ops = ops.clone();

        let shape = pbo_shape(width, height, format);

        let pbo_tensor =
            edgefirst_tensor::PboTensor::<u8>::from_pbo(buffer_id, size, &shape, None, ops)
                .map_err(|e| Error::OpenGl(format!("PBO tensor creation failed: {e:?}")))?;
        let mut tensor = edgefirst_tensor::Tensor::from_pbo(pbo_tensor)
            .map_err(|e| Error::OpenGl(format!("PBO tensor wrap failed: {e:?}")))?;
        tensor
            .set_format(format)
            .map_err(|e| Error::OpenGl(format!("Failed to set format on PBO tensor: {e:?}")))?;
        // Register the PBO with CUDA (best-effort; no-op without libcudart) so
        // `cuda_map()` can yield a device pointer — matching the float PBO path
        // in `create_pbo_image_dtype`. Without this, u8 PBOs were never
        // CUDA-interop-capable, so the codec's nvJPEG backend (and any CUDA
        // consumer) could not use a `create_image`-allocated PBO destination.
        // The i8 transmute by the caller preserves the attached handle.
        register_pbo_cuda(&mut tensor, buffer_id, size, sender);
        self.owned_pbos.insert(tensor.pbo_vtable_ptr(), &owned_ops);
        Ok(tensor)
    }

    /// Create a PBO-backed [`TensorDyn`] image on the GL thread with the given dtype.
    ///
    /// Sizes the underlying GL buffer by `elems * dtype.size()` and wraps it in
    /// the appropriately-typed [`PboTensor`]. Supports `DType::U8`, `DType::F16`,
    /// and `DType::F32`; returns an error for other dtypes.
    pub(crate) fn create_pbo_image_dtype(
        &self,
        width: usize,
        height: usize,
        format: edgefirst_tensor::PixelFormat,
        dtype: edgefirst_tensor::DType,
    ) -> Result<TensorDyn, Error> {
        let sender = self
            .sender
            .as_ref()
            .ok_or(Error::OpenGl("GL processor is shutting down".to_string()))?;

        let elems = pbo_elem_count(width, height, format)
            .filter(|&e| e != 0)
            .ok_or_else(|| Error::OpenGl("Invalid image dimensions".to_string()))?;

        let size = elems
            .checked_mul(dtype.size())
            .ok_or_else(|| Error::OpenGl("PBO size overflow".to_string()))?;

        // Allocate PBO on the GL thread
        let (tx, rx) = tokio::sync::oneshot::channel();
        sender
            .blocking_send(GLProcessorMessage::PboCreate(size, tx))
            .map_err(|_| Error::OpenGl("GL thread channel closed".to_string()))?;
        let buffer_id = rx
            .blocking_recv()
            .map_err(|_| Error::OpenGl("GL thread did not respond".to_string()))??;

        let ops: std::sync::Arc<dyn edgefirst_tensor::PboOps> = std::sync::Arc::new(GlPboOps {
            sender: sender.downgrade(),
            worker_id: self.worker_id,
        });
        let owned_ops = ops.clone();

        let shape = pbo_shape(width, height, format);

        let map_err = |e: edgefirst_tensor::Error| {
            Error::OpenGl(format!("PBO tensor creation failed: {e:?}"))
        };
        let set_err = |e: edgefirst_tensor::Error| {
            Error::OpenGl(format!("Failed to set format on PBO tensor: {e:?}"))
        };

        let tensor = match dtype {
            edgefirst_tensor::DType::U8 => {
                let pbo =
                    edgefirst_tensor::PboTensor::<u8>::from_pbo(buffer_id, size, &shape, None, ops)
                        .map_err(map_err)?;
                let mut t = edgefirst_tensor::Tensor::from_pbo(pbo).map_err(map_err)?;
                t.set_format(format).map_err(set_err)?;
                register_pbo_cuda(&mut t, buffer_id, size, sender);
                TensorDyn::from(t)
            }
            edgefirst_tensor::DType::F16 => {
                let pbo = edgefirst_tensor::PboTensor::<edgefirst_tensor::f16>::from_pbo(
                    buffer_id, size, &shape, None, ops,
                )
                .map_err(map_err)?;
                let mut t = edgefirst_tensor::Tensor::from_pbo(pbo).map_err(map_err)?;
                t.set_format(format).map_err(set_err)?;
                register_pbo_cuda(&mut t, buffer_id, size, sender);
                TensorDyn::from(t)
            }
            edgefirst_tensor::DType::F32 => {
                let pbo = edgefirst_tensor::PboTensor::<f32>::from_pbo(
                    buffer_id, size, &shape, None, ops,
                )
                .map_err(map_err)?;
                let mut t = edgefirst_tensor::Tensor::from_pbo(pbo).map_err(map_err)?;
                t.set_format(format).map_err(set_err)?;
                register_pbo_cuda(&mut t, buffer_id, size, sender);
                TensorDyn::from(t)
            }
            other => return Err(Error::OpenGl(format!("unsupported PBO dtype {other:?}"))),
        };
        self.owned_pbos.insert(tensor.pbo_vtable_ptr(), &owned_ops);
        Ok(tensor)
    }

    /// Returns the active transfer backend.
    pub(crate) fn transfer_backend(&self) -> TransferBackend {
        self.caps.transfer_backend
    }

    /// Report which float dtypes the GPU can render to.
    ///
    /// Values are probed once at construction time and adjusted for
    /// Vivante GC7000UL, whose float readback latency (170-320 ms) makes
    /// GL float destinations impractical; `ImageProcessor::convert()` falls
    /// back to CPU float output (normalized to `[0, 1]`) for these targets.
    pub(crate) fn supported_render_dtypes(&self) -> crate::RenderDtypeSupport {
        self.caps.render_dtypes
    }

    /// The CPU access `convert` needs on a `format`/`dtype` destination held
    /// in `memory` when it renders it from an RGBA or NV source (`Write` for
    /// a host-memory readback, else `None`), or `None` when it declines it to
    /// the CPU fallback.
    pub(crate) fn dst_cpu_access(
        &self,
        memory: edgefirst_tensor::TensorMemory,
        format: edgefirst_tensor::PixelFormat,
        dtype: edgefirst_tensor::DType,
    ) -> Option<edgefirst_tensor::CpuAccess> {
        use edgefirst_tensor::{CpuAccess, DType, PixelFormat, TensorMemory};
        let renders = match dtype {
            DType::U8 | DType::I8 => GLProcessorST::dst_format_renderable(
                self.caps.transfer_backend,
                memory,
                format,
                self.caps.has_bgra,
            ),
            DType::F16 | DType::F32 => {
                super::float_dispatch::classify_float_render(
                    PixelFormat::Rgba,
                    format,
                    dtype,
                    memory,
                    self.caps.render_dtypes,
                    <super::platform::Platform as super::platform::GlPlatform>::ZERO_COPY_FLOAT,
                ) != super::float_dispatch::FloatRenderPath::None
            }
            _ => false,
        };
        let readback = matches!(memory, TensorMemory::Mem | TensorMemory::Shm);
        renders.then_some(if readback {
            CpuAccess::Write
        } else {
            CpuAccess::None
        })
    }
}

impl Drop for GLProcessorThreaded {
    fn drop(&mut self) {
        // Closing the channel ends the worker loop, which drops the
        // `GLProcessorST` it owns; that `Drop` pays any device submission an
        // open batch still owes. The join is what makes it ordered before this
        // returns -- and it has to happen on the worker, which is the thread
        // holding the context.
        drop(self.sender.take());
        let _ = self.handle.take().and_then(|h| h.join().ok());
    }
}

// `pbo_elem_count` / `pbo_shape` are pure (no GL), so they are unit-testable
// without a GPU. The overflow→None arm of `pbo_elem_count` guards against an
// undersized PBO allocation, so it is worth pinning explicitly.
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
    use super::{pbo_elem_count, pbo_shape, GLProcessorThreaded, GlPboOps};
    use edgefirst_tensor::{PixelFormat, TensorTrait};

    #[test]
    fn elem_count_per_format() {
        // Packed RGBA: w*h*4.
        assert_eq!(pbo_elem_count(8, 4, PixelFormat::Rgba), Some(8 * 4 * 4));
        // Packed RGB: w*h*3.
        assert_eq!(pbo_elem_count(8, 4, PixelFormat::Rgb), Some(8 * 4 * 3));
        // NV12 semiplanar: w*h*3/2.
        assert_eq!(pbo_elem_count(8, 4, PixelFormat::Nv12), Some(8 * 4 * 3 / 2));
        // NV16 semiplanar: w*h*2.
        assert_eq!(pbo_elem_count(8, 4, PixelFormat::Nv16), Some(8 * 4 * 2));
    }

    #[test]
    fn elem_count_overflow_is_none() {
        // w*h already overflows usize → None (never a wrapped, undersized count).
        assert_eq!(pbo_elem_count(usize::MAX, 2, PixelFormat::Rgba), None);
        // w*h fits but *channels overflows → None.
        assert_eq!(pbo_elem_count(usize::MAX, 1, PixelFormat::Rgb), None);
    }

    #[test]
    fn shape_per_format() {
        // Planar: [channels, height, width].
        assert_eq!(pbo_shape(8, 4, PixelFormat::PlanarRgb), vec![3, 4, 8]);
        // SemiPlanar NV12: [height*3/2, width].
        assert_eq!(pbo_shape(8, 4, PixelFormat::Nv12), vec![4 * 3 / 2, 8]);
        // SemiPlanar NV16: [height*2, width].
        assert_eq!(pbo_shape(8, 4, PixelFormat::Nv16), vec![4 * 2, 8]);
        // Packed: [height, width, channels].
        assert_eq!(pbo_shape(8, 4, PixelFormat::Rgba), vec![4, 8, 4]);
    }

    /// Regression test for the cross-handle PBO map race task 11's review
    /// found: `PboHandle::acquire_map`'s per-handle `Mutex<MapState>`
    /// (`edgefirst-tensor`) has no visibility into a SEPARATE `PboHandle`
    /// for the same real `buffer_id` -- exactly what a cross-cdylib
    /// reconstructed consumer tensor now is, alongside the producer's own
    /// tensor, since task 11 wired a real `kind::PBO` `import_descriptor`
    /// arm. Simulates that with two independent `PboTensor`s built
    /// directly (rather than through the full descriptor/vtable round
    /// trip, which needs a second compiled `.so` to be meaningful) that
    /// both point at the SAME real GL buffer via a fresh [`GlPboOps`]
    /// wrapping the SAME sender -- exactly the relationship `import_descriptor`'s
    /// PBO arm produces between a producer's handle and a reconstructed
    /// one. Without `mapped_pbo_buffers`, the second map would reach
    /// `glMapBufferRange` on an already-mapped buffer (undefined
    /// behaviour); this asserts it is refused instead, and that the
    /// refusal is a real, releasable reservation rather than a permanently
    /// stuck `buffer_id`.
    #[test]
    #[cfg(any(target_os = "linux", target_os = "windows"))] // PBO destinations: Linux + Windows
    fn concurrent_maps_from_two_independent_handles_on_one_buffer_do_not_corrupt_gl_state() {
        let gl = match GLProcessorThreaded::new(None) {
            Ok(gl) => gl,
            Err(e) => {
                crate::test_support::report_skip(&format!(
                    "concurrent_maps_from_two_independent_handles... - \
                     OpenGL not available: {e:?}"
                ));
                return;
            }
        };
        let tensor_a = gl
            .create_pbo_image(64, 64, PixelFormat::Rgba)
            .expect("a PBO on a live GL context");
        let buffer_id = tensor_a.pbo_id().expect("just created a PBO tensor");
        let size = tensor_a.capacity_bytes();
        let shape = tensor_a.shape().to_vec();

        // A second, independent PboHandle for the IDENTICAL real buffer --
        // same relationship a producer's handle and a reconstructed
        // consumer's handle have to the same GL context.
        let ops_b: std::sync::Arc<dyn edgefirst_tensor::PboOps> = std::sync::Arc::new(GlPboOps {
            sender: gl.sender.as_ref().unwrap().downgrade(),
            worker_id: gl.worker_id,
        });
        let tensor_b =
            edgefirst_tensor::PboTensor::<u8>::from_pbo(buffer_id, size, &shape, None, ops_b)
                .expect("from_pbo against a real, already-created buffer_id must succeed");

        // tensor_a maps first and holds the mapping open.
        let map_a = tensor_a.map().expect("first map must succeed");

        // tensor_b's own Mutex<MapState> starts at Unmapped and knows
        // nothing about tensor_a's outstanding mapping -- without the
        // GL-thread-level fix this reaches glMapBufferRange a second time.
        let map_b_result = tensor_b.map();
        // `glMapBufferRange` on an already-mapped buffer is UNDEFINED
        // BEHAVIOUR per the GL spec, not guaranteed to fail cleanly on
        // every driver -- so this asserts the SPECIFIC refusal
        // `mapped_pbo_buffers` produces (matching this file's own error
        // text), not merely "some error occurred", which a
        // driver-dependent null return could also produce and would make
        // this test pass even with the fix reverted.
        let Err(map_b_err) = map_b_result else {
            panic!(
                "a second, independent handle mapping the SAME real buffer while the \
                     first mapping is still open must be refused, not silently succeed"
            );
        };
        let msg = format!("{map_b_err:?}");
        assert!(
            msg.contains("already mapped"),
            "must be refused specifically by the GL-thread-level reservation check \
             (mapped_pbo_buffers), not some other error path: {msg}"
        );

        drop(map_a);

        // Once the first mapping releases, the SAME second handle must be
        // able to map successfully -- proves the refusal above was a real,
        // releasable reservation, not a permanently stuck buffer_id.
        let map_b_after = tensor_b.map();
        assert!(
            map_b_after.is_ok(),
            "after the first handle's mapping releases, the second handle must be able to \
             map the same buffer: {map_b_after:?}"
        );
    }
}