From f8a8ed4826489a7747f492f8ba9795e3121c74f2 Mon Sep 17 00:00:00 2001 From: _ <_@_> Date: Sat, 9 Sep 2023 13:32:24 -0500 Subject: [PATCH 1/2] expose `bytesused` to users When capturing JPEG frames, v4l will tell us that the JPEG can be as big as the decoded YUV frame, like 4 MB for a 1080p frame. But typically the JPEG is only 500 KB or so. Exposing bytesused allows callers to copy less data and write precisely-sized JPEG frames --- src/stream.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/stream.rs b/src/stream.rs index 8b4ef14..4de58d8 100644 --- a/src/stream.rs +++ b/src/stream.rs @@ -224,6 +224,7 @@ impl ReadStream { unsafe { slice::from_raw_parts(buffer.ptr as *const u8, buffer.length as usize) }; let view = ReadBufferView { flags: buf.flags, + bytesused: buf.bytesused, data, }; @@ -282,10 +283,15 @@ impl AsRawFd for ReadStream { /// Dereferences to a byte slice. pub struct ReadBufferView<'a> { flags: BufFlag, + bytesused: u32, data: &'a [u8], } impl ReadBufferView<'_> { + pub fn bytesused(&self) -> u32 { + self.bytesused + } + /// Returns whether the error flag for this buffer is set. /// /// If this returns `true`, the application should expect data corruption in the buffer data. From 03e81f5d05d1df784fdc904ddf23846de368d05d Mon Sep 17 00:00:00 2001 From: _ <_@_> Date: Sat, 9 Sep 2023 13:40:11 -0500 Subject: [PATCH 2/2] update example to use `bytesused` --- examples/save-jpeg.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/save-jpeg.rs b/examples/save-jpeg.rs index 96c4a9e..1ee0d28 100644 --- a/examples/save-jpeg.rs +++ b/examples/save-jpeg.rs @@ -32,14 +32,16 @@ fn main() -> anyhow::Result<()> { device.capabilities()?.device_capabilities() ); - let capture = device.video_capture(PixFormat::new(u32::MAX, u32::MAX, PixelFormat::JPEG))?; + let capture = device.video_capture(PixFormat::new(u32::MAX, u32::MAX, PixelFormat::MJPG))?; + println!("negotiated format: {:?}", capture.format()); let mut stream = capture.into_stream()?; println!("stream started, waiting for data"); stream.dequeue(|buf| { - file.write_all(&*buf)?; + let bytesused = usize::try_from (buf.bytesused ()).unwrap (); + file.write_all(&buf [0..bytesused])?; println!("wrote file"); Ok(()) })?;