yscv-video 0.2.0

Video decoding (H.264, HEVC), MP4 parsing, and camera I/O
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
//! Direct V4L2 camera capture using raw ioctls — no libc crate, no external
//! dependencies beyond `std`. Uses `extern "C"` declarations for `ioctl`,
//! `mmap`, and `munmap`.
//!
//! This module is only compiled on Linux (`#[cfg(target_os = "linux")]`).

use crate::VideoError;
use std::ops::Deref;
use std::os::unix::io::AsRawFd;

// ---------------------------------------------------------------------------
// C FFI — 3 declarations, zero deps
// ---------------------------------------------------------------------------

unsafe extern "C" {
    fn ioctl(fd: i32, request: IoctlReq, ...) -> i32;
    // `off_t` is `long` — pointer-width, so 32-bit on armhf. Declaring it `i64`
    // mis-passes the argument on 32-bit ARM: mmap then sees a misaligned offset
    // and fails in glibc before the syscall, so V4L2 buffer mmap never happens.
    fn mmap(addr: *mut u8, len: usize, prot: i32, flags: i32, fd: i32, offset: isize) -> *mut u8;
    fn munmap(addr: *mut u8, len: usize) -> i32;
    /// POSIX `close(2)` — used by `V4l2DmaBufGuard::Drop`.
    fn close(fd: i32) -> i32;
}

// ---------------------------------------------------------------------------
// V4L2 ioctl numbers (from <linux/videodev2.h>)
// ---------------------------------------------------------------------------

/// `ioctl`'s second parameter is `unsigned long`: 64-bit on LP64, **32-bit on
/// ILP32** (armhf). Declaring it `u64` breaks the call on 32-bit ARM — AAPCS
/// puts a 64-bit argument in an even-aligned register *pair*, so the kernel
/// reads the request number out of the wrong register and every V4L2 call
/// fails. Measured on an OrangePi Zero H3 with a UVC camera attached: every
/// mode reported "QUERYCAP failed" until this became pointer-width.
type IoctlReq = usize;

// `_IOC(dir, type, nr, size)` from asm-generic/ioctl.h. Deriving the numbers
// from `size_of` rather than hard-coding the LP64 hex is what keeps them right
// on both arches: `v4l2_buffer` is 88 bytes on 64-bit and 68 on 32-bit (a
// 32-bit `struct timeval` and a 32-bit `unsigned long` in its union), and
// `v4l2_format` is 208 against 204, so the constants genuinely differ.
const fn ioc(dir: usize, nr: usize, size: usize) -> IoctlReq {
    (dir << 30) | (size << 16) | (0x56 << 8) | nr
}
const DIR_W: usize = 1;
const DIR_R: usize = 2;
const DIR_RW: usize = 3;

const VIDIOC_QUERYCAP: IoctlReq = ioc(DIR_R, 0, size_of::<V4l2Capability>());
const VIDIOC_S_FMT: IoctlReq = ioc(DIR_RW, 5, size_of::<V4l2Format>());
const VIDIOC_REQBUFS: IoctlReq = ioc(DIR_RW, 8, size_of::<V4l2RequestBuffers>());
const VIDIOC_QUERYBUF: IoctlReq = ioc(DIR_RW, 9, size_of::<V4l2Buffer>());
const VIDIOC_QBUF: IoctlReq = ioc(DIR_RW, 15, size_of::<V4l2Buffer>());
const VIDIOC_DQBUF: IoctlReq = ioc(DIR_RW, 17, size_of::<V4l2Buffer>());
const VIDIOC_STREAMON: IoctlReq = ioc(DIR_W, 18, size_of::<i32>());
const VIDIOC_STREAMOFF: IoctlReq = ioc(DIR_W, 19, size_of::<i32>());
const VIDIOC_S_PARM: IoctlReq = ioc(DIR_RW, 22, size_of::<V4l2StreamParm>());
const VIDIOC_G_CTRL: IoctlReq = ioc(DIR_RW, 27, size_of::<V4l2Control>());
const VIDIOC_S_CTRL: IoctlReq = ioc(DIR_RW, 28, size_of::<V4l2Control>());

// The LP64 numbers these used to be written as, so a layout change cannot drift
// them silently.
#[cfg(target_pointer_width = "64")]
const _: () = {
    assert!(VIDIOC_QUERYCAP == 0x8068_5600);
    assert!(VIDIOC_S_FMT == 0xC0D0_5605);
    assert!(VIDIOC_REQBUFS == 0xC014_5608);
    assert!(VIDIOC_QUERYBUF == 0xC058_5609);
    assert!(VIDIOC_QBUF == 0xC058_560F);
    assert!(VIDIOC_DQBUF == 0xC058_5611);
    assert!(VIDIOC_STREAMON == 0x4004_5612);
    assert!(VIDIOC_STREAMOFF == 0x4004_5613);
    assert!(VIDIOC_S_PARM == 0xC0CC_5616);
};
/// `VIDIOC_EXPBUF` — export a V4L2 buffer as a DMA-BUF file descriptor.
///
/// Requests a `dma-buf` fd for buffer `index` so it can be shared with
/// other kernel subsystems (NPU, GPU, display) without CPU copy.
const VIDIOC_EXPBUF: IoctlReq = ioc(DIR_RW, 16, size_of::<V4l2ExportBuffer>());

/// DMA-BUF access mode flags for `VIDIOC_EXPBUF`.
const O_CLOEXEC: u32 = 0o2000000;
const O_RDWR: u32 = 0o2;

// mmap constants
const PROT_READ: i32 = 0x1;
const PROT_WRITE: i32 = 0x2;
const MAP_SHARED: i32 = 0x01;
const MAP_FAILED: *mut u8 = !0usize as *mut u8;

// V4L2 buffer type / memory type
const V4L2_BUF_TYPE_VIDEO_CAPTURE: u32 = 1;
const V4L2_MEMORY_MMAP: u32 = 1;

// Capability flags
const V4L2_CAP_VIDEO_CAPTURE: u32 = 0x0000_0001;
const V4L2_CAP_STREAMING: u32 = 0x0400_0000;

// Number of mmap'd buffers to request
const NUM_BUFFERS: u32 = 4;

// ---------------------------------------------------------------------------
// Pixel format enum
// ---------------------------------------------------------------------------

/// V4L2 pixel formats supported by this capture module.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum V4l2PixelFormat {
    Yuyv,
    Nv12,
    Mjpeg,
    H264,
}

impl V4l2PixelFormat {
    /// FourCC value matching the Linux kernel definition.
    pub const fn fourcc(self) -> u32 {
        match self {
            Self::Yuyv => 0x5659_5559,  // 'VYUY' little-endian = YUYV
            Self::Nv12 => 0x3231_564E,  // 'NV12'
            Self::Mjpeg => 0x4750_4A4D, // 'MJPG'
            Self::H264 => 0x3436_3248,  // 'H264'
        }
    }
}

// ---------------------------------------------------------------------------
// V4L2 kernel ABI structs (repr(C), exact sizes)
// ---------------------------------------------------------------------------

/// `struct v4l2_capability` — 104 bytes.
#[repr(C)]
struct V4l2Capability {
    driver: [u8; 16],
    card: [u8; 32],
    bus_info: [u8; 32],
    version: u32,
    capabilities: u32,
    device_caps: u32,
    reserved: [u32; 3],
}

/// Pixel format description embedded in `v4l2_format`.
#[repr(C)]
#[derive(Clone, Copy)]
struct V4l2PixFormat {
    width: u32,
    height: u32,
    pixelformat: u32,
    field: u32,
    bytesperline: u32,
    sizeimage: u32,
    colorspace: u32,
    priv_: u32,
    flags: u32,
    // ycbcr_enc / quantization / xfer_func (union area padding)
    ycbcr_enc: u32,
    quantization: u32,
    xfer_func: u32,
}

/// The 200-byte union inside `v4l2_format`. It is **pointer-aligned**: one of
/// its members is `struct v4l2_window`, which carries a `struct v4l2_clip *`.
/// That alignment is why `v4l2_format` is 208 bytes on LP64 (the union starts
/// at offset 8) and 204 on ILP32 (offset 4) — get it wrong and the kernel
/// writes past the end of the struct.
#[repr(C)]
struct V4l2FormatUnion {
    pix: V4l2PixFormat,
    _pad: [u8; 152],
    _align: [usize; 0],
}

/// `struct v4l2_format`. We only use `type_` + the pix format union member.
#[repr(C)]
struct V4l2Format {
    type_: u32,
    fmt: V4l2FormatUnion,
}

/// `struct v4l2_requestbuffers` — 20 bytes.
#[repr(C)]
struct V4l2RequestBuffers {
    count: u32,
    type_: u32,
    memory: u32,
    capabilities: u32,
    flags: u8,
    reserved: [u8; 3],
}

/// `struct timeval` inside `v4l2_buffer`: two `long`s, so it is 16 bytes on
/// LP64 and 8 on ILP32 — and that difference is what moves `v4l2_buffer`'s size
/// (and therefore its ioctl numbers) between the arches.
#[repr(C)]
#[derive(Clone, Copy, Default)]
struct Timeval {
    tv_sec: isize,
    tv_usec: isize,
}

/// `struct v4l2_buffer` — 88 bytes on 64-bit, 68 on 32-bit.
/// The kernel struct has a union for `m` (offset / userptr / planes / fd).
#[repr(C)]
struct V4l2Buffer {
    index: u32,
    type_: u32,
    bytesused: u32,
    flags: u32,
    field: u32,
    timestamp: Timeval,
    timecode: [u8; 16], // v4l2_timecode
    sequence: u32,
    memory: u32,
    // union m { __u32 offset; unsigned long userptr; struct v4l2_plane *planes; __s32 fd; }
    // Its widest member is pointer-sized, so this is `usize`, not `u64`.
    m_offset: usize,
    length: u32,
    reserved2: u32,
    // union { __s32 request_fd; __u32 reserved; }
    request_fd: i32,
}

/// `struct v4l2_exportbuffer` — parameters for `VIDIOC_EXPBUF`.
///
/// Exports a V4L2 buffer as a DMA-BUF file descriptor for zero-copy sharing
/// with other subsystems (NPU, GPU, display).
#[repr(C)]
struct V4l2ExportBuffer {
    type_: u32,
    index: u32,
    plane: u32,
    flags: u32,
    fd: i32,
    reserved: [u32; 11],
}

// ---------------------------------------------------------------------------
// V4l2Camera
// ---------------------------------------------------------------------------

/// Zero-copy V4L2 camera capture handle.
///
/// Opens a `/dev/videoN` device, negotiates format, mmap's kernel buffers,
/// and provides frame capture via `DQBUF` / `QBUF` cycling.
pub struct V4l2Camera {
    /// Held to keep the fd alive (Drop closes it). Field intentionally
    /// not read directly — `fd` below is the working handle.
    #[allow(dead_code)]
    file: std::fs::File,
    fd: i32,
    buffers: Vec<(*mut u8, usize)>,
    width: u32,
    height: u32,
    pixel_format: u32,
    streaming: bool,
}

// SAFETY: The mmap'd pointers are valid for the lifetime of the fd and are
// only accessed through &self / &mut self, so sending across threads is safe
// as long as only one thread accesses the camera at a time (guaranteed by
// &mut self on capture_frame).
unsafe impl Send for V4l2Camera {}

/// `struct v4l2_fract` — a rational; a frame interval is `numerator/denominator`
/// seconds (so 30 fps is 1/30).
#[repr(C)]
#[derive(Clone, Copy)]
struct V4l2Fract {
    numerator: u32,
    denominator: u32,
}

/// `struct v4l2_captureparm` — the capture half of `v4l2_streamparm`'s union.
#[repr(C)]
#[derive(Clone, Copy)]
struct V4l2CaptureParm {
    capability: u32,
    capturemode: u32,
    timeperframe: V4l2Fract,
    extendedmode: u32,
    readbuffers: u32,
    reserved: [u32; 4],
}

/// `struct v4l2_streamparm` — 204 bytes: `type` plus a 200-byte union whose head
/// is the capture parm; the remainder is padding to keep the ioctl size exact.
#[repr(C)]
struct V4l2StreamParm {
    type_: u32,
    capture: V4l2CaptureParm,
    _pad: [u8; 160],
}

/// `struct v4l2_control` — one control id/value pair (VIDIOC_S_CTRL).
#[repr(C)]
struct V4l2Control {
    id: u32,
    value: i32,
}

/// A dequeued V4L2 frame.
///
/// The camera buffer remains owned by this guard until it is dropped. `Drop`
/// then returns the buffer to the driver with `QBUF`, so the kernel cannot
/// DMA into memory while the caller still holds the slice returned by `Deref`.
pub struct V4l2Frame<'a> {
    camera: &'a mut V4l2Camera,
    index: u32,
    ptr: *const u8,
    len: usize,
}

impl Deref for V4l2Frame<'_> {
    type Target = [u8];

    fn deref(&self) -> &Self::Target {
        // SAFETY: the buffer was returned by DQBUF and remains dequeued for
        // the guard's lifetime. The camera cannot be mutably borrowed again
        // until this reference is dropped.
        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
    }
}

impl AsRef<[u8]> for V4l2Frame<'_> {
    fn as_ref(&self) -> &[u8] {
        self
    }
}

impl Drop for V4l2Frame<'_> {
    fn drop(&mut self) {
        // Drop cannot report an ioctl failure. Keeping the buffer dequeued is
        // safer than exposing a live slice after QBUF, so the best effort is
        // made here and the driver error is intentionally ignored.
        let _ = self.camera.requeue_buffer(self.index);
    }
}

impl V4l2Camera {
    /// Request a capture frame rate of `fps` via `VIDIOC_S_PARM`. Best-effort:
    /// the driver clamps to a supported interval, and a device that ignores the
    /// call keeps its default. Call after `open`, before `start_streaming` — a
    /// UVC camera otherwise streams YUYV at its own default (often ~15 fps),
    /// which halves the pipeline rate.
    pub fn set_frame_rate(&mut self, fps: u32) -> Result<(), VideoError> {
        if fps == 0 {
            return Ok(());
        }
        let mut parm: V4l2StreamParm = unsafe { std::mem::zeroed() };
        parm.type_ = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        parm.capture.timeperframe = V4l2Fract {
            numerator: 1,
            denominator: fps,
        };
        let ret = unsafe {
            ioctl(
                self.fd,
                VIDIOC_S_PARM,
                &mut parm as *mut V4l2StreamParm as *mut u8,
            )
        };
        if ret < 0 {
            return Err(VideoError::Source(
                "V4L2: S_PARM (set frame rate) failed".into(),
            ));
        }
        Ok(())
    }

    /// Set a single V4L2 control by id (`VIDIOC_S_CTRL`) — e.g. the auto-exposure
    /// mode or the absolute exposure time. Best-effort per control.
    pub fn set_control(&mut self, id: u32, value: i32) -> Result<(), VideoError> {
        let mut ctrl = V4l2Control { id, value };
        let ret = unsafe {
            ioctl(
                self.fd,
                VIDIOC_S_CTRL,
                &mut ctrl as *mut V4l2Control as *mut u8,
            )
        };
        if ret < 0 {
            return Err(VideoError::Source(format!("V4L2: S_CTRL {id:#x} failed")));
        }
        Ok(())
    }

    /// Read a single V4L2 control by id (`VIDIOC_G_CTRL`).
    ///
    /// The counterpart to [`Self::set_control`], and the half that makes it
    /// possible to freeze an automatic control at whatever the camera has
    /// currently settled on: read the value the automatic mode produced, then
    /// write it back as a manual one.
    pub fn get_control(&mut self, id: u32) -> Result<i32, VideoError> {
        let mut ctrl = V4l2Control { id, value: 0 };
        let ret = unsafe {
            ioctl(
                self.fd,
                VIDIOC_G_CTRL,
                &mut ctrl as *mut V4l2Control as *mut u8,
            )
        };
        if ret < 0 {
            return Err(VideoError::Source(format!("V4L2: G_CTRL {id:#x} failed")));
        }
        Ok(ctrl.value)
    }

    /// Open a V4L2 camera device (e.g. `"/dev/video0"`), set format, and
    /// prepare mmap'd buffers for streaming.
    pub fn open(
        device: &str,
        width: u32,
        height: u32,
        format: V4l2PixelFormat,
    ) -> Result<Self, VideoError> {
        if width == 0 || height == 0 {
            return Err(VideoError::InvalidCameraResolution { width, height });
        }

        let file = std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .open(device)
            .map_err(|e| VideoError::Source(format!("V4L2: cannot open {device}: {e}")))?;

        let fd = file.as_raw_fd();

        // QUERYCAP — verify the device supports video capture + streaming
        let mut cap: V4l2Capability = unsafe { std::mem::zeroed() };
        let ret = unsafe {
            ioctl(
                fd,
                VIDIOC_QUERYCAP,
                &mut cap as *mut V4l2Capability as *mut u8,
            )
        };
        if ret < 0 {
            return Err(VideoError::Source("V4L2: QUERYCAP failed".into()));
        }
        if cap.capabilities & V4L2_CAP_VIDEO_CAPTURE == 0 {
            return Err(VideoError::Source(
                "V4L2: device does not support video capture".into(),
            ));
        }
        if cap.capabilities & V4L2_CAP_STREAMING == 0 {
            return Err(VideoError::Source(
                "V4L2: device does not support streaming I/O".into(),
            ));
        }

        // S_FMT — set desired format
        let mut fmt: V4l2Format = unsafe { std::mem::zeroed() };
        fmt.type_ = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        fmt.fmt.pix.width = width;
        fmt.fmt.pix.height = height;
        fmt.fmt.pix.pixelformat = format.fourcc();
        fmt.fmt.pix.field = 1; // V4L2_FIELD_NONE

        let ret = unsafe { ioctl(fd, VIDIOC_S_FMT, &mut fmt as *mut V4l2Format as *mut u8) };
        if ret < 0 {
            return Err(VideoError::Source("V4L2: S_FMT failed".into()));
        }

        let actual_w = fmt.fmt.pix.width;
        let actual_h = fmt.fmt.pix.height;
        let actual_fmt = fmt.fmt.pix.pixelformat;

        // REQBUFS — request mmap'd buffers
        let mut reqbufs: V4l2RequestBuffers = unsafe { std::mem::zeroed() };
        reqbufs.count = NUM_BUFFERS;
        reqbufs.type_ = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        reqbufs.memory = V4L2_MEMORY_MMAP;

        let ret = unsafe {
            ioctl(
                fd,
                VIDIOC_REQBUFS,
                &mut reqbufs as *mut V4l2RequestBuffers as *mut u8,
            )
        };
        if ret < 0 {
            return Err(VideoError::Source("V4L2: REQBUFS failed".into()));
        }
        if reqbufs.count == 0 {
            return Err(VideoError::Source(
                "V4L2: driver allocated 0 buffers".into(),
            ));
        }

        // QUERYBUF + mmap each buffer
        let mut buffers = Vec::with_capacity(reqbufs.count as usize);
        for i in 0..reqbufs.count {
            let mut buf: V4l2Buffer = unsafe { std::mem::zeroed() };
            buf.index = i;
            buf.type_ = V4L2_BUF_TYPE_VIDEO_CAPTURE;
            buf.memory = V4L2_MEMORY_MMAP;

            let ret = unsafe { ioctl(fd, VIDIOC_QUERYBUF, &mut buf as *mut V4l2Buffer as *mut u8) };
            if ret < 0 {
                // Unmap any already-mapped buffers before returning
                for &(ptr, len) in &buffers {
                    unsafe {
                        munmap(ptr, len);
                    }
                }
                return Err(VideoError::Source(format!(
                    "V4L2: QUERYBUF failed for buffer {i}"
                )));
            }

            let ptr = unsafe {
                mmap(
                    std::ptr::null_mut(),
                    buf.length as usize,
                    PROT_READ | PROT_WRITE,
                    MAP_SHARED,
                    fd,
                    buf.m_offset as isize,
                )
            };
            if ptr == MAP_FAILED {
                for &(p, l) in &buffers {
                    unsafe {
                        munmap(p, l);
                    }
                }
                return Err(VideoError::Source(format!(
                    "V4L2: mmap failed for buffer {i}"
                )));
            }

            buffers.push((ptr, buf.length as usize));
        }

        Ok(Self {
            file,
            fd,
            buffers,
            width: actual_w,
            height: actual_h,
            pixel_format: actual_fmt,
            streaming: false,
        })
    }

    /// Queue all buffers and start the capture stream.
    pub fn start_streaming(&mut self) -> Result<(), VideoError> {
        // Queue all buffers
        for i in 0..self.buffers.len() as u32 {
            let mut buf: V4l2Buffer = unsafe { std::mem::zeroed() };
            buf.index = i;
            buf.type_ = V4L2_BUF_TYPE_VIDEO_CAPTURE;
            buf.memory = V4L2_MEMORY_MMAP;
            let ret =
                unsafe { ioctl(self.fd, VIDIOC_QBUF, &mut buf as *mut V4l2Buffer as *mut u8) };
            if ret < 0 {
                return Err(VideoError::Source(format!(
                    "V4L2: QBUF failed for buffer {i}"
                )));
            }
        }

        // STREAMON
        let mut buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        let ret = unsafe {
            ioctl(
                self.fd,
                VIDIOC_STREAMON,
                &mut buf_type as *mut u32 as *mut u8,
            )
        };
        if ret < 0 {
            return Err(VideoError::Source("V4L2: STREAMON failed".into()));
        }
        self.streaming = true;
        Ok(())
    }

    /// Dequeue the next captured frame without copying.
    ///
    /// The returned guard keeps the V4L2 buffer dequeued. It must be dropped
    /// before the next capture call; dropping it re-queues the buffer.
    pub fn capture_frame(&mut self) -> Result<V4l2Frame<'_>, VideoError> {
        if !self.streaming {
            return Err(VideoError::Source("V4L2: not streaming".into()));
        }

        // DQBUF
        let mut buf: V4l2Buffer = unsafe { std::mem::zeroed() };
        buf.type_ = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;

        let ret = unsafe {
            ioctl(
                self.fd,
                VIDIOC_DQBUF,
                &mut buf as *mut V4l2Buffer as *mut u8,
            )
        };
        if ret < 0 {
            return Err(VideoError::Source("V4L2: DQBUF failed".into()));
        }

        let idx = buf.index as usize;
        let bytes_used = buf.bytesused as usize;
        if idx >= self.buffers.len() {
            return Err(VideoError::Source(format!(
                "V4L2: DQBUF returned invalid buffer index {idx}"
            )));
        }

        let (ptr, len) = self.buffers[idx];
        let actual_len = bytes_used.min(len);

        // SAFETY: ptr is a valid mmap'd region of at least `len` bytes,
        // and we only hold a reference until the next DQBUF (or drop).
        let frame_data = unsafe { std::slice::from_raw_parts(ptr, actual_len) };

        Ok(V4l2Frame {
            camera: self,
            index: buf.index,
            ptr: frame_data.as_ptr(),
            len: frame_data.len(),
        })
    }

    /// Dequeue the next captured frame and return the buffer index along
    /// with a zero-copy guard for its pixel data.
    ///
    /// The index identifies which mmap'd buffer holds the frame; pair it
    /// with [`Self::export_dmabuf`] to obtain a DMA-BUF fd suitable for
    /// sharing with an NPU via `rknn_create_mem_from_fd`.
    ///
    /// The guard must be dropped before another frame-capture method or
    /// `stop_streaming` can borrow the camera.
    pub fn capture_frame_indexed(&mut self) -> Result<(u32, V4l2Frame<'_>), VideoError> {
        if !self.streaming {
            return Err(VideoError::Source("V4L2: not streaming".into()));
        }

        let mut buf: V4l2Buffer = unsafe { std::mem::zeroed() };
        buf.type_ = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        buf.memory = V4L2_MEMORY_MMAP;

        // SAFETY: ioctl(fd, DQBUF, &buf) with a zeroed V4l2Buffer struct.
        let ret = unsafe {
            ioctl(
                self.fd,
                VIDIOC_DQBUF,
                &mut buf as *mut V4l2Buffer as *mut u8,
            )
        };
        if ret < 0 {
            return Err(VideoError::Source("V4L2: DQBUF failed".into()));
        }

        let idx = buf.index as usize;
        let bytes_used = buf.bytesused as usize;
        if idx >= self.buffers.len() {
            return Err(VideoError::Source(format!(
                "V4L2: DQBUF returned invalid buffer index {idx}"
            )));
        }

        let (ptr, len) = self.buffers[idx];
        let actual_len = bytes_used.min(len);

        // SAFETY: ptr is a valid mmap'd region of at least `len` bytes;
        // the returned reference lives until the next DQBUF call (& mut self).
        let frame_data = unsafe { std::slice::from_raw_parts(ptr, actual_len) };

        let frame = V4l2Frame {
            camera: self,
            index: buf.index,
            ptr: frame_data.as_ptr(),
            len: frame_data.len(),
        };
        Ok((buf.index, frame))
    }

    fn requeue_buffer(&mut self, index: u32) -> Result<(), VideoError> {
        let mut qbuf: V4l2Buffer = unsafe { std::mem::zeroed() };
        qbuf.index = index;
        qbuf.type_ = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        qbuf.memory = V4L2_MEMORY_MMAP;
        // SAFETY: qbuf is initialized with a valid dequeued buffer index.
        let ret = unsafe {
            ioctl(
                self.fd,
                VIDIOC_QBUF,
                &mut qbuf as *mut V4l2Buffer as *mut u8,
            )
        };
        if ret < 0 {
            return Err(VideoError::Source("V4L2: QBUF (re-queue) failed".into()));
        }
        Ok(())
    }

    /// Export a V4L2 buffer as a DMA-BUF file descriptor for zero-copy
    /// sharing with an NPU / GPU / display.
    ///
    /// The returned fd can be passed to `RknnBackend::wrap_fd()` to bind
    /// the same physical memory as an NPU input tensor — the camera fills
    /// it and the NPU reads it without any CPU copy.
    ///
    /// The caller is responsible for closing the fd (via `libc::close` or
    /// by wrapping in `std::fs::File::from_raw_fd`) when finished. Prefer
    /// [`Self::export_dmabuf_owned`] for automatic cleanup via RAII.
    pub fn export_dmabuf(&self, buffer_index: u32) -> Result<i32, VideoError> {
        if buffer_index as usize >= self.buffers.len() {
            return Err(VideoError::Source(format!(
                "V4L2: export_dmabuf buffer index {buffer_index} out of range"
            )));
        }
        let mut ebuf = V4l2ExportBuffer {
            type_: V4L2_BUF_TYPE_VIDEO_CAPTURE,
            index: buffer_index,
            plane: 0,
            flags: O_CLOEXEC | O_RDWR,
            fd: -1,
            reserved: [0; 11],
        };
        // SAFETY: ioctl(fd, EXPBUF, &ebuf) writes the exported fd into
        // ebuf.fd on success. Kernel does not retain the pointer.
        let ret = unsafe {
            ioctl(
                self.fd,
                VIDIOC_EXPBUF,
                &mut ebuf as *mut V4l2ExportBuffer as *mut u8,
            )
        };
        if ret < 0 {
            return Err(VideoError::Source(format!(
                "V4L2: VIDIOC_EXPBUF failed for buffer {buffer_index}"
            )));
        }
        if ebuf.fd < 0 {
            return Err(VideoError::Source(
                "V4L2: VIDIOC_EXPBUF returned invalid fd".into(),
            ));
        }
        Ok(ebuf.fd)
    }

    /// Mutable view of a specific mmap'd buffer's pixel data.
    ///
    /// Used together with `export_dmabuf()` to let an NPU wrap the same
    /// region via `rknn_create_mem_from_fd(fd, virt, size, offset)` where
    /// `virt` must point to the userspace view of the DMA-BUF.
    ///
    /// # Safety
    /// The returned slice aliases the mmap'd region. Do not call any
    /// frame-capture method while the slice is live.
    pub fn buffer_mut(&mut self, buffer_index: u32) -> Result<&mut [u8], VideoError> {
        let (ptr, len) = self
            .buffers
            .get(buffer_index as usize)
            .copied()
            .ok_or_else(|| {
                VideoError::Source(format!(
                    "V4L2: buffer_mut index {buffer_index} out of range"
                ))
            })?;
        // SAFETY: ptr is mmap'd, writable (MAP_SHARED | PROT_WRITE); len
        // is the exact length from VIDIOC_QUERYBUF.
        Ok(unsafe { std::slice::from_raw_parts_mut(ptr, len) })
    }

    /// Number of mmap'd buffers currently allocated.
    pub const fn buffer_count(&self) -> usize {
        self.buffers.len()
    }

    /// Frame width in pixels.
    pub const fn width(&self) -> u32 {
        self.width
    }

    /// Frame height in pixels.
    pub const fn height(&self) -> u32 {
        self.height
    }

    /// Active pixel format FourCC code.
    pub const fn pixel_format_fourcc(&self) -> u32 {
        self.pixel_format
    }

    /// Stop the capture stream.
    pub fn stop_streaming(&mut self) -> Result<(), VideoError> {
        if !self.streaming {
            return Ok(());
        }
        let mut buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
        let ret = unsafe {
            ioctl(
                self.fd,
                VIDIOC_STREAMOFF,
                &mut buf_type as *mut u32 as *mut u8,
            )
        };
        if ret < 0 {
            return Err(VideoError::Source("V4L2: STREAMOFF failed".into()));
        }
        self.streaming = false;
        Ok(())
    }

    /// Export a V4L2 buffer as a DMA-BUF and wrap the fd in a RAII guard
    /// that automatically `close(2)`s it on drop. Use this in pipelines
    /// where panic safety matters — leaking dma-buf fds across panic
    /// unwind grows the kernel `fdtable` and eventually denies opens.
    pub fn export_dmabuf_owned(&self, buffer_index: u32) -> Result<V4l2DmaBufGuard, VideoError> {
        let fd = self.export_dmabuf(buffer_index)?;
        Ok(V4l2DmaBufGuard { fd })
    }
}

/// RAII handle around an exported V4L2 DMA-BUF file descriptor.
///
/// `close(fd)` is called automatically on drop. Use [`Self::fd`] to feed
/// the descriptor into `RknnBackend::wrap_fd`. Use [`Self::into_raw`] to
/// take ownership and prevent the auto-close (caller becomes responsible).
pub struct V4l2DmaBufGuard {
    fd: i32,
}

impl V4l2DmaBufGuard {
    /// Read the underlying file descriptor without taking ownership.
    pub const fn fd(&self) -> i32 {
        self.fd
    }

    /// Consume the guard and return the raw fd. Caller is now responsible
    /// for closing it (e.g. via `libc::close`).
    pub const fn into_raw(self) -> i32 {
        let fd = self.fd;
        std::mem::forget(self);
        fd
    }
}

impl Drop for V4l2DmaBufGuard {
    fn drop(&mut self) {
        if self.fd >= 0 {
            // SAFETY: fd was returned by VIDIOC_EXPBUF, owned by us;
            // close(2) is signal-safe and the kernel handles concurrent close races.
            unsafe { close(self.fd) };
        }
    }
}

// SAFETY: a raw fd is just an integer; ownership semantics are enforced
// by the guard's exclusive Drop.
unsafe impl Send for V4l2DmaBufGuard {}
unsafe impl Sync for V4l2DmaBufGuard {}

impl Drop for V4l2Camera {
    fn drop(&mut self) {
        // Best-effort stop streaming
        if self.streaming {
            let _ = self.stop_streaming();
        }
        // Unmap all buffers
        for &(ptr, len) in &self.buffers {
            unsafe {
                munmap(ptr, len);
            }
        }
        // File is closed automatically by dropping self.file
    }
}

// ---------------------------------------------------------------------------
// Tests — struct layout verification
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn v4l2_capability_size() {
        assert_eq!(
            std::mem::size_of::<V4l2Capability>(),
            104,
            "V4l2Capability must be 104 bytes to match kernel ABI"
        );
    }

    #[test]
    fn v4l2_format_size() {
        // struct v4l2_format on 64-bit: type(4) + union fmt(200) + pad to 208 total
        // Our struct: type_(4) + V4l2PixFormat(48) + _pad(152) = 204
        // With alignment, the compiler may round up. The kernel struct is 208.
        let size = std::mem::size_of::<V4l2Format>();
        assert!(
            size >= 204,
            "V4l2Format must be at least 204 bytes, got {size}"
        );
    }

    #[test]
    fn v4l2_requestbuffers_size() {
        assert_eq!(
            std::mem::size_of::<V4l2RequestBuffers>(),
            20,
            "V4l2RequestBuffers must be 20 bytes to match kernel ABI"
        );
    }

    #[test]
    fn pixel_format_fourcc_values() {
        assert_eq!(V4l2PixelFormat::Yuyv.fourcc(), 0x5659_5559);
        assert_eq!(V4l2PixelFormat::Nv12.fourcc(), 0x3231_564E);
        assert_eq!(V4l2PixelFormat::Mjpeg.fourcc(), 0x4750_4A4D);
        assert_eq!(V4l2PixelFormat::H264.fourcc(), 0x3436_3248);
    }

    #[test]
    fn v4l2_pix_format_size() {
        assert_eq!(
            std::mem::size_of::<V4l2PixFormat>(),
            48,
            "V4l2PixFormat must be 48 bytes"
        );
    }
}