edgefirst-image 0.17.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
// SPDX-FileCopyrightText: Copyright 2025 Au-Zone Technologies
// SPDX-License-Identifier: Apache-2.0

#![cfg(target_os = "linux")]

use crate::{CPUProcessor, Crop, Error, Flip, ImageProcessorTrait, Result, Rotation};
use edgefirst_tensor::{DType, PixelFormat, Tensor, TensorDyn, TensorMapTrait, TensorTrait};
use four_char_code::FourCharCode;
use g2d_sys::{G2DFormat, G2DPhysical, G2DSurface, G2D};
use std::{os::fd::AsRawFd, time::Instant};

/// Convert a PixelFormat to the G2D-compatible FourCharCode.
fn pixelfmt_to_fourcc(fmt: PixelFormat) -> FourCharCode {
    use four_char_code::four_char_code;
    match fmt {
        PixelFormat::Rgb => four_char_code!("RGB "),
        PixelFormat::Rgba => four_char_code!("RGBA"),
        PixelFormat::Bgra => four_char_code!("BGRA"),
        PixelFormat::Grey => four_char_code!("Y800"),
        PixelFormat::Yuyv => four_char_code!("YUYV"),
        PixelFormat::Vyuy => four_char_code!("VYUY"),
        PixelFormat::Nv12 => four_char_code!("NV12"),
        PixelFormat::Nv16 => four_char_code!("NV16"),
        // Planar formats have no standard FourCC; use RGBA as fallback
        _ => four_char_code!("RGBA"),
    }
}

/// G2DConverter implements the ImageProcessor trait using the NXP G2D
/// library for hardware-accelerated image processing on i.MX platforms.
#[derive(Debug)]
pub struct G2DProcessor {
    g2d: G2D,
}

unsafe impl Send for G2DProcessor {}
unsafe impl Sync for G2DProcessor {}

impl G2DProcessor {
    /// Creates a new G2DConverter instance.
    pub fn new() -> Result<Self> {
        let mut g2d = G2D::new("libg2d.so.2")?;
        g2d.set_bt709_colorspace()?;

        log::debug!("G2DConverter created with version {:?}", g2d.version());
        Ok(Self { g2d })
    }

    /// Returns the G2D library version as defined by _G2D_VERSION in the shared
    /// library.
    pub fn version(&self) -> g2d_sys::Version {
        self.g2d.version()
    }

    fn convert_impl(
        &mut self,
        src_dyn: &TensorDyn,
        dst_dyn: &mut TensorDyn,
        rotation: Rotation,
        flip: Flip,
        crop: Crop,
    ) -> Result<()> {
        if log::log_enabled!(log::Level::Trace) {
            log::trace!(
                "G2D convert: {:?}({:?}/{:?}) → {:?}({:?}/{:?})",
                src_dyn.format(),
                src_dyn.dtype(),
                src_dyn.memory(),
                dst_dyn.format(),
                dst_dyn.dtype(),
                dst_dyn.memory(),
            );
        }

        if src_dyn.dtype() != DType::U8 {
            return Err(Error::NotSupported(
                "G2D only supports u8 source tensors".to_string(),
            ));
        }
        let is_int8_dst = dst_dyn.dtype() == DType::I8;
        if dst_dyn.dtype() != DType::U8 && !is_int8_dst {
            return Err(Error::NotSupported(
                "G2D only supports u8 or i8 destination tensors".to_string(),
            ));
        }

        let src_fmt = src_dyn.format().ok_or(Error::NotAnImage)?;
        let dst_fmt = dst_dyn.format().ok_or(Error::NotAnImage)?;

        // Validate supported format pairs
        use PixelFormat::*;
        match (src_fmt, dst_fmt) {
            (Rgba, Rgba) => {}
            (Rgba, Yuyv) => {}
            (Rgba, Rgb) => {}
            (Yuyv, Rgba) => {}
            (Yuyv, Yuyv) => {}
            (Yuyv, Rgb) => {}
            // VYUY: i.MX8MP G2D hardware rejects VYUY blits (only YUYV/UYVY
            // among packed YUV 4:2:2). ImageProcessor falls through to CPU.
            (Nv12, Rgba) => {}
            (Nv12, Yuyv) => {}
            (Nv12, Rgb) => {}
            (Rgba, Bgra) => {}
            (Yuyv, Bgra) => {}
            (Nv12, Bgra) => {}
            (Bgra, Bgra) => {}
            (s, d) => {
                return Err(Error::NotSupported(format!(
                    "G2D does not support {} to {} conversion",
                    s, d
                )));
            }
        }

        crop.check_crop_dyn(src_dyn, dst_dyn)?;

        let src = src_dyn.as_u8().unwrap();
        // For i8 destinations, reinterpret as u8 for G2D (same byte layout).
        // The XOR 0x80 post-pass is applied after the blit completes.
        let dst = if is_int8_dst {
            // SAFETY: Tensor<i8> and Tensor<u8> have identical memory layout.
            // The T parameter only affects PhantomData<T> (zero-sized) in
            // TensorStorage variants and the typed view from map(). The chroma
            // field (Option<Box<Tensor<T>>>) is also layout-identical. This
            // reinterpreted reference is used only for shape/fd access and the
            // G2D blit (which operates on raw DMA bytes). It does not outlive
            // dst_dyn and is never stored.
            let i8_tensor = dst_dyn.as_i8_mut().unwrap();
            unsafe { &mut *(i8_tensor as *mut Tensor<i8> as *mut Tensor<u8>) }
        } else {
            dst_dyn.as_u8_mut().unwrap()
        };

        let mut src_surface = tensor_to_g2d_surface(src)?;
        let mut dst_surface = tensor_to_g2d_surface(dst)?;

        src_surface.rot = match flip {
            Flip::None => g2d_sys::g2d_rotation_G2D_ROTATION_0,
            Flip::Vertical => g2d_sys::g2d_rotation_G2D_FLIP_V,
            Flip::Horizontal => g2d_sys::g2d_rotation_G2D_FLIP_H,
        };

        dst_surface.rot = match rotation {
            Rotation::None => g2d_sys::g2d_rotation_G2D_ROTATION_0,
            Rotation::Clockwise90 => g2d_sys::g2d_rotation_G2D_ROTATION_90,
            Rotation::Rotate180 => g2d_sys::g2d_rotation_G2D_ROTATION_180,
            Rotation::CounterClockwise90 => g2d_sys::g2d_rotation_G2D_ROTATION_270,
        };

        if let Some(crop_rect) = crop.src_rect {
            src_surface.left = crop_rect.left as i32;
            src_surface.top = crop_rect.top as i32;
            src_surface.right = (crop_rect.left + crop_rect.width) as i32;
            src_surface.bottom = (crop_rect.top + crop_rect.height) as i32;
        }

        let dst_w = dst.width().unwrap();
        let dst_h = dst.height().unwrap();

        // Clear the destination with the letterbox color before blitting the
        // image into the sub-region.
        //
        // g2d_clear does not support 3-byte-per-pixel formats (RGB888, BGR888).
        // For those formats, fall back to CPU fill after the blit.
        let needs_clear = crop.dst_color.is_some()
            && crop.dst_rect.is_some_and(|dst_rect| {
                dst_rect.left != 0
                    || dst_rect.top != 0
                    || dst_rect.width != dst_w
                    || dst_rect.height != dst_h
            });

        if needs_clear && dst_fmt != Rgb {
            if let Some(dst_color) = crop.dst_color {
                let start = Instant::now();
                self.g2d.clear(&mut dst_surface, dst_color)?;
                log::trace!("g2d clear takes {:?}", start.elapsed());
            }
        }

        if let Some(crop_rect) = crop.dst_rect {
            // stride is in pixels; multiply by bytes-per-pixel (== channels()
            // for u8 data) to get the byte offset.  All G2D destination
            // formats are packed, so channels() == bpp always holds here.
            dst_surface.planes[0] += ((crop_rect.top * dst_surface.stride as usize
                + crop_rect.left)
                * dst_fmt.channels()) as u64;

            dst_surface.right = crop_rect.width as i32;
            dst_surface.bottom = crop_rect.height as i32;
            dst_surface.width = crop_rect.width as i32;
            dst_surface.height = crop_rect.height as i32;
        }

        log::trace!("G2D blit: {src_fmt}→{dst_fmt} int8={is_int8_dst}");
        self.g2d.blit(&src_surface, &dst_surface)?;
        self.g2d.finish()?;
        log::trace!("G2D blit complete");

        // CPU fallback for RGB888 (unsupported by g2d_clear)
        if needs_clear && dst_fmt == Rgb {
            if let (Some(dst_color), Some(dst_rect)) = (crop.dst_color, crop.dst_rect) {
                let start = Instant::now();
                CPUProcessor::fill_image_outside_crop_u8(dst, dst_color, dst_rect)?;
                log::trace!("cpu fill takes {:?}", start.elapsed());
            }
        }

        // Apply XOR 0x80 for int8 output (u8→i8 bias conversion).
        // map() issues DMA_BUF_IOCTL_SYNC(START) on the dst fd; for self-allocated
        // CMA buffers this performs cache invalidation via the DrmAttachment.
        // For foreign fds (e.g. the Neutron NPU DMA-BUF imported via from_fd()),
        // the DrmAttachment is None and the sync ioctl is handled by the NPU driver.
        // The map drop issues DMA_BUF_IOCTL_SYNC(END) so the NPU DMA engine sees
        // the CPU-written XOR'd data on the next Invoke().
        if is_int8_dst {
            let start = Instant::now();
            let mut map = dst.map()?;
            crate::cpu::apply_int8_xor_bias(map.as_mut_slice(), dst_fmt);
            log::trace!("g2d int8 XOR 0x80 post-pass takes {:?}", start.elapsed());
        }

        Ok(())
    }
}

impl ImageProcessorTrait for G2DProcessor {
    fn convert(
        &mut self,
        src: &TensorDyn,
        dst: &mut TensorDyn,
        rotation: Rotation,
        flip: Flip,
        crop: Crop,
    ) -> Result<()> {
        self.convert_impl(src, dst, rotation, flip, crop)
    }

    fn draw_decoded_masks(
        &mut self,
        dst: &mut TensorDyn,
        detect: &[crate::DetectBox],
        segmentation: &[crate::Segmentation],
        overlay: crate::MaskOverlay<'_>,
    ) -> Result<()> {
        // G2D can produce the *frame* (background or cleared canvas) via
        // hardware primitives — but has no rasterizer for boxes / masks.
        // If detections are present, defer to another backend.
        if !detect.is_empty() || !segmentation.is_empty() {
            return Err(Error::NotImplemented(
                "G2D does not support drawing detection or segmentation overlays".to_string(),
            ));
        }
        draw_empty_frame_g2d(&mut self.g2d, dst, overlay.background)
    }

    fn draw_proto_masks(
        &mut self,
        dst: &mut TensorDyn,
        detect: &[crate::DetectBox],
        _proto_data: &crate::ProtoData,
        overlay: crate::MaskOverlay<'_>,
    ) -> Result<()> {
        // Same logic as draw_decoded_masks: G2D handles empty-detection
        // frames (clear or blit background) via the 2D hardware.
        if !detect.is_empty() {
            return Err(Error::NotImplemented(
                "G2D does not support drawing detection or segmentation overlays".to_string(),
            ));
        }
        draw_empty_frame_g2d(&mut self.g2d, dst, overlay.background)
    }

    fn set_class_colors(&mut self, _: &[[u8; 4]]) -> Result<()> {
        Err(Error::NotImplemented(
            "G2D does not support setting colors for rendering detection or segmentation overlays"
                .to_string(),
        ))
    }
}

/// Produce the zero-detection frame on `dst` using G2D hardware ops.
///
/// `background == None` → `g2d_clear(dst, 0x00000000)` — actively fills the
/// destination with transparent black using the 2D engine (no CPU touch).
///
/// `background == Some(bg)` → `g2d_blit(bg → dst)` — hardware copy of bg
/// into dst. This is the "draw the cleared overlay onto the background"
/// path; G2D has no pure copy primitive, so we use the blit engine with a
/// 1:1 same-format surface pair, which is the hardware equivalent.
///
/// Both paths `finish()` before returning so dst is coherent for any
/// downstream reader.
fn draw_empty_frame_g2d(
    g2d: &mut G2D,
    dst_dyn: &mut TensorDyn,
    background: Option<&TensorDyn>,
) -> Result<()> {
    if dst_dyn.dtype() != DType::U8 {
        return Err(Error::NotSupported(
            "G2D only supports u8 destination tensors".to_string(),
        ));
    }
    let dst = dst_dyn.as_u8_mut().ok_or(Error::NotAnImage)?;

    // DMA-only: G2D operates on physical addresses. A Mem-backed dst means
    // we're on the wrong backend — surface a dispatch error so the caller
    // can fall back.
    if dst.as_dma().is_none() {
        return Err(Error::NotImplemented(
            "g2d only supports Dma memory".to_string(),
        ));
    }

    let mut dst_surface = tensor_to_g2d_surface(dst)?;

    match background {
        None => {
            // Case 1 — no background, no detections: hardware clear to
            // transparent black. Every byte of dst is written by the 2D
            // engine; no reliance on prior state.
            let start = Instant::now();
            g2d.clear(&mut dst_surface, [0, 0, 0, 0])?;
            g2d.finish()?;
            log::trace!("g2d clear (empty frame) takes {:?}", start.elapsed());
        }
        Some(bg_dyn) => {
            // Case 2 — background, no detections: hardware blit bg → dst.
            // Validate shape/format equivalence; if the caller handed us
            // mismatched surfaces we return a structured error rather than
            // silently producing wrong output.
            if bg_dyn.shape() != dst.shape() {
                return Err(Error::InvalidShape(
                    "background shape does not match dst".into(),
                ));
            }
            if bg_dyn.format() != dst.format() {
                return Err(Error::InvalidShape(
                    "background pixel format does not match dst".into(),
                ));
            }
            if bg_dyn.dtype() != DType::U8 {
                return Err(Error::NotSupported(
                    "G2D only supports u8 background tensors".to_string(),
                ));
            }
            let bg = bg_dyn.as_u8().ok_or(Error::NotAnImage)?;
            if bg.as_dma().is_none() {
                return Err(Error::NotImplemented(
                    "g2d background must be Dma-backed".to_string(),
                ));
            }
            let src_surface = tensor_to_g2d_surface(bg)?;
            let start = Instant::now();
            g2d.blit(&src_surface, &dst_surface)?;
            g2d.finish()?;
            log::trace!("g2d blit (bg→dst) takes {:?}", start.elapsed());
        }
    }
    Ok(())
}

/// Build a `G2DSurface` from a `Tensor<u8>` that carries pixel-format metadata.
///
/// The tensor must be backed by DMA memory and must have a pixel format set.
fn tensor_to_g2d_surface(img: &Tensor<u8>) -> Result<G2DSurface> {
    let fmt = img.format().ok_or(Error::NotAnImage)?;
    let dma = img
        .as_dma()
        .ok_or_else(|| Error::NotImplemented("g2d only supports Dma memory".to_string()))?;
    let phys: G2DPhysical = dma.fd.as_raw_fd().try_into()?;

    // NV12 is a two-plane format: Y plane followed by interleaved UV plane.
    // planes[0] = Y plane start, planes[1] = UV plane start (Y size = width * height)
    //
    // plane_offset is the byte offset within the DMA-BUF where pixel data
    // starts.  G2D works with raw physical addresses so we must add the
    // offset ourselves — the hardware has no concept of a per-plane offset.
    let base_addr = phys.address();
    let luma_offset = img.plane_offset().unwrap_or(0) as u64;
    let planes = if fmt == PixelFormat::Nv12 {
        if img.is_multiplane() {
            // Multiplane: UV in separate DMA-BUF, get its physical address
            let chroma = img.chroma().unwrap();
            let chroma_dma = chroma.as_dma().ok_or_else(|| {
                Error::NotImplemented("g2d multiplane chroma must be DMA-backed".to_string())
            })?;
            let uv_phys: G2DPhysical = chroma_dma.fd.as_raw_fd().try_into()?;
            let chroma_offset = img.chroma().and_then(|c| c.plane_offset()).unwrap_or(0) as u64;
            [
                base_addr + luma_offset,
                uv_phys.address() + chroma_offset,
                0,
            ]
        } else {
            let w = img.width().unwrap();
            let h = img.height().unwrap();
            let stride = img.effective_row_stride().unwrap_or(w);
            let uv_offset = (luma_offset as usize + stride * h) as u64;
            [base_addr + luma_offset, base_addr + uv_offset, 0]
        }
    } else {
        [base_addr + luma_offset, 0, 0]
    };

    let w = img.width().unwrap();
    let h = img.height().unwrap();
    let fourcc = pixelfmt_to_fourcc(fmt);

    // G2D stride is in pixels.  effective_row_stride() returns bytes, so
    // divide by the bytes-per-pixel (channels for u8 data) to convert.
    let stride_pixels = match img.effective_row_stride() {
        Some(s) => {
            let channels = fmt.channels();
            if s % channels != 0 {
                return Err(Error::NotImplemented(
                    "g2d requires row stride to be a multiple of bytes-per-pixel".to_string(),
                ));
            }
            s / channels
        }
        None => w,
    };

    Ok(G2DSurface {
        planes,
        format: G2DFormat::try_from(fourcc)?.format(),
        left: 0,
        top: 0,
        right: w as i32,
        bottom: h as i32,
        stride: stride_pixels as i32,
        width: w as i32,
        height: h as i32,
        blendfunc: 0,
        clrcolor: 0,
        rot: 0,
        global_alpha: 0,
    })
}

#[cfg(feature = "g2d_test_formats")]
#[cfg(test)]
mod g2d_tests {
    use super::*;
    use crate::{CPUProcessor, Flip, G2DProcessor, ImageProcessorTrait, Rect, Rotation};
    use edgefirst_tensor::{
        is_dma_available, DType, PixelFormat, TensorDyn, TensorMapTrait, TensorMemory, TensorTrait,
    };
    use image::buffer::ConvertBuffer;

    #[test]
    #[cfg(target_os = "linux")]
    fn test_g2d_formats_no_resize() {
        for i in [
            PixelFormat::Rgba,
            PixelFormat::Yuyv,
            PixelFormat::Rgb,
            PixelFormat::Grey,
            PixelFormat::Nv12,
        ] {
            for o in [
                PixelFormat::Rgba,
                PixelFormat::Yuyv,
                PixelFormat::Rgb,
                PixelFormat::Grey,
            ] {
                let res = test_g2d_format_no_resize_(i, o);
                if let Err(e) = res {
                    println!("{i} to {o} failed: {e:?}");
                } else {
                    println!("{i} to {o} success");
                }
            }
        }
    }

    fn test_g2d_format_no_resize_(
        g2d_in_fmt: PixelFormat,
        g2d_out_fmt: PixelFormat,
    ) -> Result<(), crate::Error> {
        let dst_width = 1280;
        let dst_height = 720;
        let file = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../testdata/zidane.jpg"
        ))
        .to_vec();
        let src = crate::load_image(&file, Some(PixelFormat::Rgb), None)?;

        // Create DMA buffer for G2D input
        let mut src2 = TensorDyn::image(1280, 720, g2d_in_fmt, DType::U8, Some(TensorMemory::Dma))?;

        let mut cpu_converter = CPUProcessor::new();

        // For PixelFormat::Nv12 input, load from file since CPU doesn't support PixelFormat::Rgb→PixelFormat::Nv12
        if g2d_in_fmt == PixelFormat::Nv12 {
            let nv12_bytes = include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/zidane.nv12"
            ));
            src2.as_u8()
                .unwrap()
                .map()?
                .as_mut_slice()
                .copy_from_slice(nv12_bytes);
        } else {
            cpu_converter.convert(&src, &mut src2, Rotation::None, Flip::None, Crop::no_crop())?;
        }

        let mut g2d_dst = TensorDyn::image(
            dst_width,
            dst_height,
            g2d_out_fmt,
            DType::U8,
            Some(TensorMemory::Dma),
        )?;
        let mut g2d_converter = G2DProcessor::new()?;
        let src2_dyn = src2;
        let mut g2d_dst_dyn = g2d_dst;
        g2d_converter.convert(
            &src2_dyn,
            &mut g2d_dst_dyn,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;
        g2d_dst = {
            let mut __t = g2d_dst_dyn.into_u8().unwrap();
            __t.set_format(g2d_out_fmt)
                .map_err(|e| crate::Error::Internal(e.to_string()))?;
            TensorDyn::from(__t)
        };

        let mut cpu_dst =
            TensorDyn::image(dst_width, dst_height, PixelFormat::Rgb, DType::U8, None)?;
        cpu_converter.convert(
            &g2d_dst,
            &mut cpu_dst,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;

        compare_images(
            &src,
            &cpu_dst,
            0.98,
            &format!("{g2d_in_fmt}_to_{g2d_out_fmt}"),
        )
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_g2d_formats_with_resize() {
        for i in [
            PixelFormat::Rgba,
            PixelFormat::Yuyv,
            PixelFormat::Rgb,
            PixelFormat::Grey,
            PixelFormat::Nv12,
        ] {
            for o in [
                PixelFormat::Rgba,
                PixelFormat::Yuyv,
                PixelFormat::Rgb,
                PixelFormat::Grey,
            ] {
                let res = test_g2d_format_with_resize_(i, o);
                if let Err(e) = res {
                    println!("{i} to {o} failed: {e:?}");
                } else {
                    println!("{i} to {o} success");
                }
            }
        }
    }

    #[test]
    #[cfg(target_os = "linux")]
    fn test_g2d_formats_with_resize_dst_crop() {
        for i in [
            PixelFormat::Rgba,
            PixelFormat::Yuyv,
            PixelFormat::Rgb,
            PixelFormat::Grey,
            PixelFormat::Nv12,
        ] {
            for o in [
                PixelFormat::Rgba,
                PixelFormat::Yuyv,
                PixelFormat::Rgb,
                PixelFormat::Grey,
            ] {
                let res = test_g2d_format_with_resize_dst_crop(i, o);
                if let Err(e) = res {
                    println!("{i} to {o} failed: {e:?}");
                } else {
                    println!("{i} to {o} success");
                }
            }
        }
    }

    fn test_g2d_format_with_resize_(
        g2d_in_fmt: PixelFormat,
        g2d_out_fmt: PixelFormat,
    ) -> Result<(), crate::Error> {
        let dst_width = 600;
        let dst_height = 400;
        let file = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../testdata/zidane.jpg"
        ))
        .to_vec();
        let src = crate::load_image(&file, Some(PixelFormat::Rgb), None)?;

        let mut cpu_converter = CPUProcessor::new();

        let mut reference = TensorDyn::image(
            dst_width,
            dst_height,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Dma),
        )?;
        cpu_converter.convert(
            &src,
            &mut reference,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;

        // Create DMA buffer for G2D input
        let mut src2 = TensorDyn::image(1280, 720, g2d_in_fmt, DType::U8, Some(TensorMemory::Dma))?;

        // For PixelFormat::Nv12 input, load from file since CPU doesn't support PixelFormat::Rgb→PixelFormat::Nv12
        if g2d_in_fmt == PixelFormat::Nv12 {
            let nv12_bytes = include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/zidane.nv12"
            ));
            src2.as_u8()
                .unwrap()
                .map()?
                .as_mut_slice()
                .copy_from_slice(nv12_bytes);
        } else {
            cpu_converter.convert(&src, &mut src2, Rotation::None, Flip::None, Crop::no_crop())?;
        }

        let mut g2d_dst = TensorDyn::image(
            dst_width,
            dst_height,
            g2d_out_fmt,
            DType::U8,
            Some(TensorMemory::Dma),
        )?;
        let mut g2d_converter = G2DProcessor::new()?;
        let src2_dyn = src2;
        let mut g2d_dst_dyn = g2d_dst;
        g2d_converter.convert(
            &src2_dyn,
            &mut g2d_dst_dyn,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;
        g2d_dst = {
            let mut __t = g2d_dst_dyn.into_u8().unwrap();
            __t.set_format(g2d_out_fmt)
                .map_err(|e| crate::Error::Internal(e.to_string()))?;
            TensorDyn::from(__t)
        };

        let mut cpu_dst =
            TensorDyn::image(dst_width, dst_height, PixelFormat::Rgb, DType::U8, None)?;
        cpu_converter.convert(
            &g2d_dst,
            &mut cpu_dst,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;

        compare_images(
            &reference,
            &cpu_dst,
            0.98,
            &format!("{g2d_in_fmt}_to_{g2d_out_fmt}_resized"),
        )
    }

    fn test_g2d_format_with_resize_dst_crop(
        g2d_in_fmt: PixelFormat,
        g2d_out_fmt: PixelFormat,
    ) -> Result<(), crate::Error> {
        let dst_width = 600;
        let dst_height = 400;
        let crop = Crop {
            src_rect: None,
            dst_rect: Some(Rect {
                top: 100,
                left: 100,
                height: 100,
                width: 200,
            }),
            dst_color: None,
        };
        let file = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../testdata/zidane.jpg"
        ))
        .to_vec();
        let src = crate::load_image(&file, Some(PixelFormat::Rgb), None)?;

        let mut cpu_converter = CPUProcessor::new();

        let mut reference = TensorDyn::image(
            dst_width,
            dst_height,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Dma),
        )?;
        reference
            .as_u8()
            .unwrap()
            .map()
            .unwrap()
            .as_mut_slice()
            .fill(128);
        cpu_converter.convert(&src, &mut reference, Rotation::None, Flip::None, crop)?;

        // Create DMA buffer for G2D input
        let mut src2 = TensorDyn::image(1280, 720, g2d_in_fmt, DType::U8, Some(TensorMemory::Dma))?;

        // For PixelFormat::Nv12 input, load from file since CPU doesn't support PixelFormat::Rgb→PixelFormat::Nv12
        if g2d_in_fmt == PixelFormat::Nv12 {
            let nv12_bytes = include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/zidane.nv12"
            ));
            src2.as_u8()
                .unwrap()
                .map()?
                .as_mut_slice()
                .copy_from_slice(nv12_bytes);
        } else {
            cpu_converter.convert(&src, &mut src2, Rotation::None, Flip::None, Crop::no_crop())?;
        }

        let mut g2d_dst = TensorDyn::image(
            dst_width,
            dst_height,
            g2d_out_fmt,
            DType::U8,
            Some(TensorMemory::Dma),
        )?;
        g2d_dst
            .as_u8()
            .unwrap()
            .map()
            .unwrap()
            .as_mut_slice()
            .fill(128);
        let mut g2d_converter = G2DProcessor::new()?;
        let src2_dyn = src2;
        let mut g2d_dst_dyn = g2d_dst;
        g2d_converter.convert(
            &src2_dyn,
            &mut g2d_dst_dyn,
            Rotation::None,
            Flip::None,
            crop,
        )?;
        g2d_dst = {
            let mut __t = g2d_dst_dyn.into_u8().unwrap();
            __t.set_format(g2d_out_fmt)
                .map_err(|e| crate::Error::Internal(e.to_string()))?;
            TensorDyn::from(__t)
        };

        let mut cpu_dst =
            TensorDyn::image(dst_width, dst_height, PixelFormat::Rgb, DType::U8, None)?;
        cpu_converter.convert(
            &g2d_dst,
            &mut cpu_dst,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;

        compare_images(
            &reference,
            &cpu_dst,
            0.98,
            &format!("{g2d_in_fmt}_to_{g2d_out_fmt}_resized_dst_crop"),
        )
    }

    fn compare_images(
        img1: &TensorDyn,
        img2: &TensorDyn,
        threshold: f64,
        name: &str,
    ) -> Result<(), crate::Error> {
        assert_eq!(img1.height(), img2.height(), "Heights differ");
        assert_eq!(img1.width(), img2.width(), "Widths differ");
        assert_eq!(
            img1.format().unwrap(),
            img2.format().unwrap(),
            "PixelFormat differ"
        );
        assert!(
            matches!(img1.format().unwrap(), PixelFormat::Rgb | PixelFormat::Rgba),
            "format must be Rgb or Rgba for comparison"
        );
        let image1 = match img1.format().unwrap() {
            PixelFormat::Rgb => image::RgbImage::from_vec(
                img1.width().unwrap() as u32,
                img1.height().unwrap() as u32,
                img1.as_u8().unwrap().map().unwrap().to_vec(),
            )
            .unwrap(),
            PixelFormat::Rgba => image::RgbaImage::from_vec(
                img1.width().unwrap() as u32,
                img1.height().unwrap() as u32,
                img1.as_u8().unwrap().map().unwrap().to_vec(),
            )
            .unwrap()
            .convert(),

            _ => unreachable!(),
        };

        let image2 = match img2.format().unwrap() {
            PixelFormat::Rgb => image::RgbImage::from_vec(
                img2.width().unwrap() as u32,
                img2.height().unwrap() as u32,
                img2.as_u8().unwrap().map().unwrap().to_vec(),
            )
            .unwrap(),
            PixelFormat::Rgba => image::RgbaImage::from_vec(
                img2.width().unwrap() as u32,
                img2.height().unwrap() as u32,
                img2.as_u8().unwrap().map().unwrap().to_vec(),
            )
            .unwrap()
            .convert(),

            _ => unreachable!(),
        };

        let similarity = image_compare::rgb_similarity_structure(
            &image_compare::Algorithm::RootMeanSquared,
            &image1,
            &image2,
        )
        .expect("Image Comparison failed");

        if similarity.score < threshold {
            image1.save(format!("{name}_1.png")).unwrap();
            image2.save(format!("{name}_2.png")).unwrap();
            return Err(Error::Internal(format!(
                "{name}: converted image and target image have similarity score too low: {} < {}",
                similarity.score, threshold
            )));
        }
        Ok(())
    }

    // =========================================================================
    // PixelFormat::Nv12 Reference Validation Tests
    // These tests compare G2D PixelFormat::Nv12 conversions against ffmpeg-generated references
    // =========================================================================

    fn load_raw_image(
        width: usize,
        height: usize,
        format: PixelFormat,
        memory: Option<TensorMemory>,
        bytes: &[u8],
    ) -> Result<TensorDyn, crate::Error> {
        let img = TensorDyn::image(width, height, format, DType::U8, memory)?;
        let mut map = img.as_u8().unwrap().map()?;
        map.as_mut_slice()[..bytes.len()].copy_from_slice(bytes);
        Ok(img)
    }

    /// Test G2D PixelFormat::Nv12→PixelFormat::Rgba conversion against ffmpeg reference
    #[test]
    #[cfg(target_os = "linux")]
    fn test_g2d_nv12_to_rgba_reference() -> Result<(), crate::Error> {
        if !is_dma_available() {
            return Ok(());
        }
        // Load PixelFormat::Nv12 source
        let src = load_raw_image(
            1280,
            720,
            PixelFormat::Nv12,
            Some(TensorMemory::Dma),
            include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/camera720p.nv12"
            )),
        )?;

        // Load PixelFormat::Rgba reference (ffmpeg-generated)
        let reference = load_raw_image(
            1280,
            720,
            PixelFormat::Rgba,
            None,
            include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/camera720p.rgba"
            )),
        )?;

        // Convert using G2D
        let mut dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Dma),
        )?;
        let mut g2d = G2DProcessor::new()?;
        let src_dyn = src;
        let mut dst_dyn = dst;
        g2d.convert(
            &src_dyn,
            &mut dst_dyn,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;
        dst = {
            let mut __t = dst_dyn.into_u8().unwrap();
            __t.set_format(PixelFormat::Rgba)
                .map_err(|e| crate::Error::Internal(e.to_string()))?;
            TensorDyn::from(__t)
        };

        // Copy to CPU for comparison
        let cpu_dst = TensorDyn::image(1280, 720, PixelFormat::Rgba, DType::U8, None)?;
        cpu_dst
            .as_u8()
            .unwrap()
            .map()?
            .as_mut_slice()
            .copy_from_slice(dst.as_u8().unwrap().map()?.as_slice());

        compare_images(&reference, &cpu_dst, 0.98, "g2d_nv12_to_rgba_reference")
    }

    /// Test G2D PixelFormat::Nv12→PixelFormat::Rgb conversion against ffmpeg reference
    #[test]
    #[cfg(target_os = "linux")]
    fn test_g2d_nv12_to_rgb_reference() -> Result<(), crate::Error> {
        if !is_dma_available() {
            return Ok(());
        }
        // Load PixelFormat::Nv12 source
        let src = load_raw_image(
            1280,
            720,
            PixelFormat::Nv12,
            Some(TensorMemory::Dma),
            include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/camera720p.nv12"
            )),
        )?;

        // Load PixelFormat::Rgb reference (ffmpeg-generated)
        let reference = load_raw_image(
            1280,
            720,
            PixelFormat::Rgb,
            None,
            include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/camera720p.rgb"
            )),
        )?;

        // Convert using G2D
        let mut dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Dma),
        )?;
        let mut g2d = G2DProcessor::new()?;
        let src_dyn = src;
        let mut dst_dyn = dst;
        g2d.convert(
            &src_dyn,
            &mut dst_dyn,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;
        dst = {
            let mut __t = dst_dyn.into_u8().unwrap();
            __t.set_format(PixelFormat::Rgb)
                .map_err(|e| crate::Error::Internal(e.to_string()))?;
            TensorDyn::from(__t)
        };

        // Copy to CPU for comparison
        let cpu_dst = TensorDyn::image(1280, 720, PixelFormat::Rgb, DType::U8, None)?;
        cpu_dst
            .as_u8()
            .unwrap()
            .map()?
            .as_mut_slice()
            .copy_from_slice(dst.as_u8().unwrap().map()?.as_slice());

        compare_images(&reference, &cpu_dst, 0.98, "g2d_nv12_to_rgb_reference")
    }

    /// Test G2D PixelFormat::Yuyv→PixelFormat::Rgba conversion against ffmpeg reference
    #[test]
    #[cfg(target_os = "linux")]
    fn test_g2d_yuyv_to_rgba_reference() -> Result<(), crate::Error> {
        if !is_dma_available() {
            return Ok(());
        }
        // Load PixelFormat::Yuyv source
        let src = load_raw_image(
            1280,
            720,
            PixelFormat::Yuyv,
            Some(TensorMemory::Dma),
            include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/camera720p.yuyv"
            )),
        )?;

        // Load PixelFormat::Rgba reference (ffmpeg-generated)
        let reference = load_raw_image(
            1280,
            720,
            PixelFormat::Rgba,
            None,
            include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/camera720p.rgba"
            )),
        )?;

        // Convert using G2D
        let mut dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Dma),
        )?;
        let mut g2d = G2DProcessor::new()?;
        let src_dyn = src;
        let mut dst_dyn = dst;
        g2d.convert(
            &src_dyn,
            &mut dst_dyn,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;
        dst = {
            let mut __t = dst_dyn.into_u8().unwrap();
            __t.set_format(PixelFormat::Rgba)
                .map_err(|e| crate::Error::Internal(e.to_string()))?;
            TensorDyn::from(__t)
        };

        // Copy to CPU for comparison
        let cpu_dst = TensorDyn::image(1280, 720, PixelFormat::Rgba, DType::U8, None)?;
        cpu_dst
            .as_u8()
            .unwrap()
            .map()?
            .as_mut_slice()
            .copy_from_slice(dst.as_u8().unwrap().map()?.as_slice());

        compare_images(&reference, &cpu_dst, 0.98, "g2d_yuyv_to_rgba_reference")
    }

    /// Test G2D PixelFormat::Yuyv→PixelFormat::Rgb conversion against ffmpeg reference
    #[test]
    #[cfg(target_os = "linux")]
    fn test_g2d_yuyv_to_rgb_reference() -> Result<(), crate::Error> {
        if !is_dma_available() {
            return Ok(());
        }
        // Load PixelFormat::Yuyv source
        let src = load_raw_image(
            1280,
            720,
            PixelFormat::Yuyv,
            Some(TensorMemory::Dma),
            include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/camera720p.yuyv"
            )),
        )?;

        // Load PixelFormat::Rgb reference (ffmpeg-generated)
        let reference = load_raw_image(
            1280,
            720,
            PixelFormat::Rgb,
            None,
            include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/camera720p.rgb"
            )),
        )?;

        // Convert using G2D
        let mut dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Rgb,
            DType::U8,
            Some(TensorMemory::Dma),
        )?;
        let mut g2d = G2DProcessor::new()?;
        let src_dyn = src;
        let mut dst_dyn = dst;
        g2d.convert(
            &src_dyn,
            &mut dst_dyn,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;
        dst = {
            let mut __t = dst_dyn.into_u8().unwrap();
            __t.set_format(PixelFormat::Rgb)
                .map_err(|e| crate::Error::Internal(e.to_string()))?;
            TensorDyn::from(__t)
        };

        // Copy to CPU for comparison
        let cpu_dst = TensorDyn::image(1280, 720, PixelFormat::Rgb, DType::U8, None)?;
        cpu_dst
            .as_u8()
            .unwrap()
            .map()?
            .as_mut_slice()
            .copy_from_slice(dst.as_u8().unwrap().map()?.as_slice());

        compare_images(&reference, &cpu_dst, 0.98, "g2d_yuyv_to_rgb_reference")
    }

    /// Test G2D native PixelFormat::Bgra conversion for all supported source formats.
    /// Compares G2D src→PixelFormat::Bgra against G2D src→PixelFormat::Rgba by verifying R↔B swap.
    #[test]
    #[cfg(target_os = "linux")]
    #[ignore = "G2D on i.MX 8MP rejects BGRA as destination format; re-enable when supported"]
    fn test_g2d_bgra_no_resize() {
        for src_fmt in [
            PixelFormat::Rgba,
            PixelFormat::Yuyv,
            PixelFormat::Nv12,
            PixelFormat::Bgra,
        ] {
            test_g2d_bgra_no_resize_(src_fmt).unwrap_or_else(|e| {
                panic!("{src_fmt} to PixelFormat::Bgra failed: {e:?}");
            });
        }
    }

    fn test_g2d_bgra_no_resize_(g2d_in_fmt: PixelFormat) -> Result<(), crate::Error> {
        let file = include_bytes!(concat!(
            env!("CARGO_MANIFEST_DIR"),
            "/../../testdata/zidane.jpg"
        ))
        .to_vec();
        let src = crate::load_image(&file, Some(PixelFormat::Rgb), None)?;

        // Create DMA buffer for G2D input
        let mut src2 = TensorDyn::image(1280, 720, g2d_in_fmt, DType::U8, Some(TensorMemory::Dma))?;
        let mut cpu_converter = CPUProcessor::new();

        if g2d_in_fmt == PixelFormat::Nv12 {
            let nv12_bytes = include_bytes!(concat!(
                env!("CARGO_MANIFEST_DIR"),
                "/../../testdata/zidane.nv12"
            ));
            src2.as_u8()
                .unwrap()
                .map()?
                .as_mut_slice()
                .copy_from_slice(nv12_bytes);
        } else {
            cpu_converter.convert(&src, &mut src2, Rotation::None, Flip::None, Crop::no_crop())?;
        }

        let mut g2d = G2DProcessor::new()?;

        // Convert to PixelFormat::Bgra via G2D
        let mut bgra_dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Bgra,
            DType::U8,
            Some(TensorMemory::Dma),
        )?;
        let src2_dyn = src2;
        let mut bgra_dst_dyn = bgra_dst;
        g2d.convert(
            &src2_dyn,
            &mut bgra_dst_dyn,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;
        bgra_dst = {
            let mut __t = bgra_dst_dyn.into_u8().unwrap();
            __t.set_format(PixelFormat::Bgra)
                .map_err(|e| crate::Error::Internal(e.to_string()))?;
            TensorDyn::from(__t)
        };

        // Reconstruct src2 from dyn for PixelFormat::Rgba conversion
        let src2 = {
            let mut __t = src2_dyn.into_u8().unwrap();
            __t.set_format(g2d_in_fmt)
                .map_err(|e| crate::Error::Internal(e.to_string()))?;
            TensorDyn::from(__t)
        };

        // Convert to PixelFormat::Rgba via G2D as reference
        let mut rgba_dst = TensorDyn::image(
            1280,
            720,
            PixelFormat::Rgba,
            DType::U8,
            Some(TensorMemory::Dma),
        )?;
        let src2_dyn2 = src2;
        let mut rgba_dst_dyn = rgba_dst;
        g2d.convert(
            &src2_dyn2,
            &mut rgba_dst_dyn,
            Rotation::None,
            Flip::None,
            Crop::no_crop(),
        )?;
        rgba_dst = {
            let mut __t = rgba_dst_dyn.into_u8().unwrap();
            __t.set_format(PixelFormat::Rgba)
                .map_err(|e| crate::Error::Internal(e.to_string()))?;
            TensorDyn::from(__t)
        };

        // Copy both to CPU memory for comparison
        let bgra_cpu = TensorDyn::image(1280, 720, PixelFormat::Bgra, DType::U8, None)?;
        bgra_cpu
            .as_u8()
            .unwrap()
            .map()?
            .as_mut_slice()
            .copy_from_slice(bgra_dst.as_u8().unwrap().map()?.as_slice());

        let rgba_cpu = TensorDyn::image(1280, 720, PixelFormat::Rgba, DType::U8, None)?;
        rgba_cpu
            .as_u8()
            .unwrap()
            .map()?
            .as_mut_slice()
            .copy_from_slice(rgba_dst.as_u8().unwrap().map()?.as_slice());

        // Verify PixelFormat::Bgra output has R↔B swapped vs PixelFormat::Rgba output
        let bgra_map = bgra_cpu.as_u8().unwrap().map()?;
        let rgba_map = rgba_cpu.as_u8().unwrap().map()?;
        let bgra_buf = bgra_map.as_slice();
        let rgba_buf = rgba_map.as_slice();

        assert_eq!(bgra_buf.len(), rgba_buf.len());
        for (i, (bc, rc)) in bgra_buf
            .chunks_exact(4)
            .zip(rgba_buf.chunks_exact(4))
            .enumerate()
        {
            assert_eq!(
                bc[0], rc[2],
                "{g2d_in_fmt} to PixelFormat::Bgra: pixel {i} B mismatch",
            );
            assert_eq!(
                bc[1], rc[1],
                "{g2d_in_fmt} to PixelFormat::Bgra: pixel {i} G mismatch",
            );
            assert_eq!(
                bc[2], rc[0],
                "{g2d_in_fmt} to PixelFormat::Bgra: pixel {i} R mismatch",
            );
            assert_eq!(
                bc[3], rc[3],
                "{g2d_in_fmt} to PixelFormat::Bgra: pixel {i} A mismatch",
            );
        }
        Ok(())
    }

    // =========================================================================
    // tensor_to_g2d_surface offset & stride unit tests
    //
    // These tests verify that plane_offset and effective_row_stride are
    // correctly propagated into the G2DSurface.  They require DMA memory
    // but do NOT require G2D hardware — only the DMA_BUF_IOCTL_PHYS ioctl.
    // =========================================================================

    /// Helper: build a DMA-backed Tensor<u8> with an optional plane_offset
    /// and an optional row stride, then return the G2DSurface.
    fn surface_for(
        width: usize,
        height: usize,
        fmt: PixelFormat,
        offset: Option<usize>,
        row_stride: Option<usize>,
    ) -> Result<G2DSurface, crate::Error> {
        use edgefirst_tensor::TensorMemory;
        let mut t = Tensor::<u8>::image(width, height, fmt, Some(TensorMemory::Dma))?;
        if let Some(o) = offset {
            t.set_plane_offset(o);
        }
        if let Some(s) = row_stride {
            t.set_row_stride_unchecked(s);
        }
        tensor_to_g2d_surface(&t)
    }

    #[test]
    fn g2d_surface_single_plane_no_offset() {
        if !is_dma_available() {
            return;
        }
        let s = surface_for(640, 480, PixelFormat::Rgba, None, None).unwrap();
        // planes[0] must be non-zero (valid physical address), no offset
        assert_ne!(s.planes[0], 0);
        assert_eq!(s.stride, 640);
    }

    #[test]
    fn g2d_surface_single_plane_with_offset() {
        if !is_dma_available() {
            return;
        }
        use edgefirst_tensor::TensorMemory;
        let mut t =
            Tensor::<u8>::image(640, 480, PixelFormat::Rgba, Some(TensorMemory::Dma)).unwrap();
        let s0 = tensor_to_g2d_surface(&t).unwrap();
        t.set_plane_offset(4096);
        let s1 = tensor_to_g2d_surface(&t).unwrap();
        assert_eq!(s1.planes[0], s0.planes[0] + 4096);
    }

    #[test]
    fn g2d_surface_single_plane_zero_offset() {
        if !is_dma_available() {
            return;
        }
        use edgefirst_tensor::TensorMemory;
        let mut t =
            Tensor::<u8>::image(640, 480, PixelFormat::Rgba, Some(TensorMemory::Dma)).unwrap();
        let s_none = tensor_to_g2d_surface(&t).unwrap();
        t.set_plane_offset(0);
        let s_zero = tensor_to_g2d_surface(&t).unwrap();
        // offset=0 should produce the same address as no offset
        assert_eq!(s_none.planes[0], s_zero.planes[0]);
    }

    #[test]
    fn g2d_surface_stride_rgba() {
        if !is_dma_available() {
            return;
        }
        // Default stride: width in pixels = 640
        let s_default = surface_for(640, 480, PixelFormat::Rgba, None, None).unwrap();
        assert_eq!(s_default.stride, 640);

        // Custom stride: 2816 bytes / 4 channels = 704 pixels
        let s_custom = surface_for(640, 480, PixelFormat::Rgba, None, Some(2816)).unwrap();
        assert_eq!(s_custom.stride, 704);
    }

    #[test]
    fn g2d_surface_stride_rgb() {
        if !is_dma_available() {
            return;
        }
        let s_default = surface_for(640, 480, PixelFormat::Rgb, None, None).unwrap();
        assert_eq!(s_default.stride, 640);

        // Padded: 1980 bytes / 3 channels = 660 pixels
        let s_custom = surface_for(640, 480, PixelFormat::Rgb, None, Some(1980)).unwrap();
        assert_eq!(s_custom.stride, 660);
    }

    #[test]
    fn g2d_surface_stride_grey() {
        if !is_dma_available() {
            return;
        }
        // Grey (Y800) may not be supported by all G2D hardware versions
        let s = match surface_for(640, 480, PixelFormat::Grey, None, Some(1024)) {
            Ok(s) => s,
            Err(crate::Error::G2D(..)) => return,
            Err(e) => panic!("unexpected error: {e:?}"),
        };
        // Grey: 1 channel. stride in bytes = stride in pixels
        assert_eq!(s.stride, 1024);
    }

    #[test]
    fn g2d_surface_contiguous_nv12_offset() {
        if !is_dma_available() {
            return;
        }
        use edgefirst_tensor::TensorMemory;
        let mut t =
            Tensor::<u8>::image(640, 480, PixelFormat::Nv12, Some(TensorMemory::Dma)).unwrap();
        let s0 = tensor_to_g2d_surface(&t).unwrap();

        t.set_plane_offset(8192);
        let s1 = tensor_to_g2d_surface(&t).unwrap();

        // Luma plane should shift by offset
        assert_eq!(s1.planes[0], s0.planes[0] + 8192);
        // UV plane = base + offset + stride * height
        // Without offset: UV = base + 640 * 480 = base + 307200
        // With offset 8192: UV = base + 8192 + 640 * 480 = base + 315392
        assert_eq!(s1.planes[1], s0.planes[1] + 8192);
    }

    #[test]
    fn g2d_surface_contiguous_nv12_stride() {
        if !is_dma_available() {
            return;
        }
        // NV12: 1 byte per pixel for Y. stride 640 bytes = 640 pixels.
        let s = surface_for(640, 480, PixelFormat::Nv12, None, None).unwrap();
        assert_eq!(s.stride, 640);

        // Padded stride: 1024 bytes = 1024 pixels (NV12 channels = 1)
        let s_padded = surface_for(640, 480, PixelFormat::Nv12, None, Some(1024)).unwrap();
        assert_eq!(s_padded.stride, 1024);
    }

    #[test]
    fn g2d_surface_multiplane_nv12_offset() {
        if !is_dma_available() {
            return;
        }
        use edgefirst_tensor::TensorMemory;

        // Create luma and chroma as separate DMA tensors
        let mut luma =
            Tensor::<u8>::new(&[480, 640], Some(TensorMemory::Dma), Some("luma")).unwrap();
        let mut chroma =
            Tensor::<u8>::new(&[240, 640], Some(TensorMemory::Dma), Some("chroma")).unwrap();

        // Get baseline physical addresses with no offsets
        let luma_base = {
            let dma = luma.as_dma().unwrap();
            let phys: G2DPhysical = dma.fd.as_raw_fd().try_into().unwrap();
            phys.address()
        };
        let chroma_base = {
            let dma = chroma.as_dma().unwrap();
            let phys: G2DPhysical = dma.fd.as_raw_fd().try_into().unwrap();
            phys.address()
        };

        // Set offsets and build multiplane tensor
        luma.set_plane_offset(4096);
        chroma.set_plane_offset(2048);
        let combined = Tensor::<u8>::from_planes(luma, chroma, PixelFormat::Nv12).unwrap();
        let s = tensor_to_g2d_surface(&combined).unwrap();

        // Luma should include its offset
        assert_eq!(s.planes[0], luma_base + 4096);
        // Chroma should include its offset
        assert_eq!(s.planes[1], chroma_base + 2048);
    }
}