Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

coderabbit bits

Richie McIlroy2d58a604a7be
diff --git a/Cargo.lock b/Cargo.lock
index 1101b4efe..650f6e4e6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1433,6 +1433,7 @@ dependencies = [
name = "cap-gpu-converters"
version = "0.1.0"
dependencies = [
+ "thiserror 1.0.69",
"wgpu",
"workspace-hack",
]
diff --git a/crates/camera-ffmpeg/src/windows.rs b/crates/camera-ffmpeg/src/windows.rs
index 2efcbdc33..f03d2868f 100644
--- a/crates/camera-ffmpeg/src/windows.rs
+++ b/crates/camera-ffmpeg/src/windows.rs
@@ -1,3 +1,5 @@
+use std::{cell::RefCell, collections::VecDeque};
+
use cap_camera::CapturedFrame;
use cap_camera_windows::PixelFormat;
use ffmpeg::{Packet, format::Pixel, frame::Video as FFVideo};
@@ -14,6 +16,8 @@ pub enum AsFFmpegError {
MjpegDecodeError(String),
#[error("H264 decode error: {0}")]
H264DecodeError(String),
+ #[error("H264 decoder needs more data (non-fatal)")]
+ H264NeedMoreData,
}
fn decode_mjpeg(bytes: &[u8]) -> Result<FFVideo, AsFFmpegError> {
@@ -40,28 +44,164 @@ fn decode_mjpeg(bytes: &[u8]) -> Result<FFVideo, AsFFmpegError> {
Ok(decoded_frame)
}
-fn decode_h264(bytes: &[u8]) -> Result<FFVideo, AsFFmpegError> {
- let codec = ffmpeg::codec::decoder::find(ffmpeg::codec::Id::H264)
- .ok_or_else(|| AsFFmpegError::H264DecodeError("H264 codec not found".to_string()))?;
+pub struct H264Decoder {
+ decoder: ffmpeg::codec::decoder::Video,
+ received_keyframe: bool,
+ frame_buffer: VecDeque<FFVideo>,
+}
- let decoder_context = ffmpeg::codec::context::Context::new_with_codec(codec);
+impl H264Decoder {
+ pub fn new() -> Result<Self, AsFFmpegError> {
+ let codec = ffmpeg::codec::decoder::find(ffmpeg::codec::Id::H264)
+ .ok_or_else(|| AsFFmpegError::H264DecodeError("H264 codec not found".to_string()))?;
- let mut decoder = decoder_context
- .decoder()
- .video()
- .map_err(|e| AsFFmpegError::H264DecodeError(format!("Failed to create decoder: {e}")))?;
+ let decoder_context = ffmpeg::codec::context::Context::new_with_codec(codec);
- let packet = Packet::copy(bytes);
- decoder
- .send_packet(&packet)
- .map_err(|e| AsFFmpegError::H264DecodeError(format!("Failed to send packet: {e}")))?;
+ let decoder = decoder_context.decoder().video().map_err(|e| {
+ AsFFmpegError::H264DecodeError(format!("Failed to create decoder: {e}"))
+ })?;
- let mut decoded_frame = FFVideo::empty();
- decoder
- .receive_frame(&mut decoded_frame)
- .map_err(|e| AsFFmpegError::H264DecodeError(format!("Failed to receive frame: {e}")))?;
+ Ok(Self {
+ decoder,
+ received_keyframe: false,
+ frame_buffer: VecDeque::new(),
+ })
+ }
- Ok(decoded_frame)
+ pub fn decode(&mut self, bytes: &[u8]) -> Result<Option<FFVideo>, AsFFmpegError> {
+ if let Some(frame) = self.frame_buffer.pop_front() {
+ return Ok(Some(frame));
+ }
+
+ if !self.received_keyframe && !Self::contains_keyframe(bytes) {
+ return Ok(None);
+ }
+
+ if Self::contains_keyframe(bytes) {
+ self.received_keyframe = true;
+ }
+
+ let packet = Packet::copy(bytes);
+
+ loop {
+ match self.decoder.send_packet(&packet) {
+ Ok(()) => break,
+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::error::EAGAIN => {
+ self.drain_frames()?;
+ }
+ Err(e) => {
+ return Err(AsFFmpegError::H264DecodeError(format!(
+ "Failed to send packet: {e}"
+ )));
+ }
+ }
+ }
+
+ self.drain_frames()?;
+
+ Ok(self.frame_buffer.pop_front())
+ }
+
+ pub fn flush(&mut self) -> Result<Vec<FFVideo>, AsFFmpegError> {
+ if let Err(e) = self.decoder.send_eof() {
+ if !matches!(e, ffmpeg::Error::Eof) {
+ return Err(AsFFmpegError::H264DecodeError(format!(
+ "Failed to send EOF: {e}"
+ )));
+ }
+ }
+
+ self.drain_frames()?;
+
+ Ok(self.frame_buffer.drain(..).collect())
+ }
+
+ pub fn reset(&mut self) -> Result<(), AsFFmpegError> {
+ *self = Self::new()?;
+ Ok(())
+ }
+
+ fn drain_frames(&mut self) -> Result<(), AsFFmpegError> {
+ loop {
+ let mut decoded_frame = FFVideo::empty();
+ match self.decoder.receive_frame(&mut decoded_frame) {
+ Ok(()) => {
+ self.frame_buffer.push_back(decoded_frame);
+ }
+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::error::EAGAIN => {
+ return Ok(());
+ }
+ Err(ffmpeg::Error::Eof) => {
+ return Ok(());
+ }
+ Err(e) => {
+ return Err(AsFFmpegError::H264DecodeError(format!(
+ "Failed to receive frame: {e}"
+ )));
+ }
+ }
+ }
+ }
+
+ fn contains_keyframe(bytes: &[u8]) -> bool {
+ let mut i = 0;
+ while i + 4 < bytes.len() {
+ if bytes[i] == 0 && bytes[i + 1] == 0 {
+ let (start_code_len, nal_start) = if bytes[i + 2] == 1 {
+ (3, i + 3)
+ } else if bytes[i + 2] == 0 && i + 3 < bytes.len() && bytes[i + 3] == 1 {
+ (4, i + 4)
+ } else {
+ i += 1;
+ continue;
+ };
+
+ if nal_start < bytes.len() {
+ let nal_unit_type = bytes[nal_start] & 0x1F;
+ match nal_unit_type {
+ 5 | 7 | 8 => return true,
+ _ => {}
+ }
+ }
+
+ i += start_code_len;
+ } else {
+ i += 1;
+ }
+ }
+ false
+ }
+}
+
+impl Default for H264Decoder {
+ fn default() -> Self {
+ Self::new().expect("Failed to create H264Decoder")
+ }
+}
+
+thread_local! {
+ static H264_DECODER: RefCell<Option<H264Decoder>> = const { RefCell::new(None) };
+}
+
+fn decode_h264(bytes: &[u8]) -> Result<FFVideo, AsFFmpegError> {
+ H264_DECODER.with(|decoder_cell| {
+ let mut decoder_opt = decoder_cell.borrow_mut();
+
+ if decoder_opt.is_none() {
+ *decoder_opt = Some(H264Decoder::new()?);
+ }
+
+ let decoder = decoder_opt.as_mut().unwrap();
+ decoder
+ .decode(bytes)?
+ .ok_or(AsFFmpegError::H264NeedMoreData)
+ })
+}
+
+pub fn reset_h264_decoder() {
+ H264_DECODER.with(|decoder_cell| {
+ *decoder_cell.borrow_mut() = None;
+ });
}
impl CapturedFrameExt for CapturedFrame {
diff --git a/crates/gpu-converters/Cargo.toml b/crates/gpu-converters/Cargo.toml
index c5970f840..6de3a68e6 100644
--- a/crates/gpu-converters/Cargo.toml
+++ b/crates/gpu-converters/Cargo.toml
@@ -4,6 +4,7 @@ version = "0.1.0"
edition = "2024"
[dependencies]
+thiserror.workspace = true
wgpu.workspace = true
workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/gpu-converters/src/lib.rs b/crates/gpu-converters/src/lib.rs
index 154c9b7f8..54cb953b0 100644
--- a/crates/gpu-converters/src/lib.rs
+++ b/crates/gpu-converters/src/lib.rs
@@ -15,6 +15,53 @@ pub use uyvy_rgba::UYVYToRGBA;
pub use yuyv_nv12::YUYVToNV12;
pub use yuyv_rgba::YUYVToRGBA;
+#[derive(Debug, thiserror::Error)]
+pub enum GpuConverterError {
+ #[error("Failed to request GPU adapter: {0}")]
+ RequestAdapterFailed(#[from] wgpu::RequestAdapterError),
+ #[error("Failed to request GPU device: {0}")]
+ RequestDeviceFailed(#[from] wgpu::RequestDeviceError),
+}
+
+#[derive(Debug)]
+pub enum ConvertError {
+ OddWidth { width: u32 },
+ BufferSizeMismatch { expected: usize, actual: usize },
+ Poll(wgpu::PollError),
+}
+
+impl std::fmt::Display for ConvertError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ match self {
+ Self::OddWidth { width } => {
+ write!(f, "YUYV format requires even width, got {width}")
+ }
+ Self::BufferSizeMismatch { expected, actual } => {
+ write!(
+ f,
+ "buffer size mismatch: expected {expected} bytes, got {actual}"
+ )
+ }
+ Self::Poll(e) => write!(f, "GPU poll error: {e}"),
+ }
+ }
+}
+
+impl std::error::Error for ConvertError {
+ fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
+ match self {
+ Self::Poll(e) => Some(e),
+ _ => None,
+ }
+ }
+}
+
+impl From<wgpu::PollError> for ConvertError {
+ fn from(e: wgpu::PollError) -> Self {
+ Self::Poll(e)
+ }
+}
+
pub struct NV12Input<'a> {
y_data: &'a [u8],
uv_data: &'a [u8],
diff --git a/crates/gpu-converters/src/yuyv.rs b/crates/gpu-converters/src/yuyv.rs
index d2d3021c7..045acf57a 100644
--- a/crates/gpu-converters/src/yuyv.rs
+++ b/crates/gpu-converters/src/yuyv.rs
@@ -6,8 +6,27 @@ pub fn create_input_texture(
data: &[u8],
width: u32,
height: u32,
-) -> wgpu::Texture {
- device.create_texture_with_data(
+) -> Result<wgpu::Texture, String> {
+ if width == 0 {
+ return Err("YUYV texture width must be non-zero".to_string());
+ }
+ if height == 0 {
+ return Err("YUYV texture height must be non-zero".to_string());
+ }
+ if width % 2 != 0 {
+ return Err(format!(
+ "YUYV texture width must be even (got {width}), as YUYV encodes pairs of pixels"
+ ));
+ }
+ let expected_len = (width as usize) * (height as usize) * 2;
+ let actual_len = data.len();
+ if actual_len != expected_len {
+ return Err(format!(
+ "YUYV data length mismatch: expected {expected_len} bytes ({width}x{height}x2), got {actual_len} bytes"
+ ));
+ }
+
+ Ok(device.create_texture_with_data(
queue,
&wgpu::TextureDescriptor {
label: Some("YUYV Texture"),
@@ -25,5 +44,5 @@ pub fn create_input_texture(
},
wgpu::util::TextureDataOrder::MipMajor,
data,
- )
+ ))
}
diff --git a/crates/gpu-converters/src/yuyv_nv12/mod.rs b/crates/gpu-converters/src/yuyv_nv12/mod.rs
index 582e205b8..a82f19cb1 100644
--- a/crates/gpu-converters/src/yuyv_nv12/mod.rs
+++ b/crates/gpu-converters/src/yuyv_nv12/mod.rs
@@ -1,6 +1,6 @@
use wgpu::{self, util::DeviceExt};
-use crate::{util::read_buffer_to_vec, yuyv};
+use crate::{ConvertError, GpuConverterError, util::read_buffer_to_vec, yuyv};
pub struct YUYVToNV12 {
device: wgpu::Device,
@@ -10,7 +10,7 @@ pub struct YUYVToNV12 {
}
impl YUYVToNV12 {
- pub async fn new() -> Self {
+ pub async fn new() -> Result<Self, GpuConverterError> {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
let adapter = instance
@@ -19,13 +19,11 @@ impl YUYVToNV12 {
force_fallback_adapter: false,
compatible_surface: None,
})
- .await
- .unwrap();
+ .await?;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor::default())
- .await
- .unwrap();
+ .await?;
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("YUYV to NV12 Converter"),
@@ -95,12 +93,12 @@ impl YUYVToNV12 {
cache: None,
});
- Self {
+ Ok(Self {
device,
queue,
pipeline,
bind_group_layout,
- }
+ })
}
pub fn convert(
@@ -108,9 +106,22 @@ impl YUYVToNV12 {
yuyv_data: &[u8],
width: u32,
height: u32,
- ) -> Result<(Vec<u8>, Vec<u8>), wgpu::PollError> {
+ ) -> Result<(Vec<u8>, Vec<u8>), ConvertError> {
+ if width % 2 != 0 {
+ return Err(ConvertError::OddWidth { width });
+ }
+
+ let expected_size = (width as usize) * (height as usize) * 2;
+ if yuyv_data.len() != expected_size {
+ return Err(ConvertError::BufferSizeMismatch {
+ expected: expected_size,
+ actual: yuyv_data.len(),
+ });
+ }
+
let yuyv_texture =
- yuyv::create_input_texture(&self.device, &self.queue, yuyv_data, width, height);
+ yuyv::create_input_texture(&self.device, &self.queue, yuyv_data, width, height)
+ .expect("YUYV input validation passed above");
let y_plane_size = (width * height) as u64;
let uv_plane_size = (width * height / 2) as u64;
@@ -210,8 +221,8 @@ impl YUYVToNV12 {
self.queue.submit(std::iter::once(encoder.finish()));
Ok((
- read_buffer_to_vec(&y_read_buffer, &self.device)?,
- read_buffer_to_vec(&uv_read_buffer, &self.device)?,
+ read_buffer_to_vec(&y_read_buffer, &self.device).map_err(ConvertError::Poll)?,
+ read_buffer_to_vec(&uv_read_buffer, &self.device).map_err(ConvertError::Poll)?,
))
}
}
diff --git a/crates/gpu-converters/src/yuyv_rgba/mod.rs b/crates/gpu-converters/src/yuyv_rgba/mod.rs
index 0b0e0a266..dc989bf55 100644
--- a/crates/gpu-converters/src/yuyv_rgba/mod.rs
+++ b/crates/gpu-converters/src/yuyv_rgba/mod.rs
@@ -1,4 +1,5 @@
use crate::{
+ ConvertError, GpuConverterError,
util::{copy_texture_to_buffer_command, read_buffer_to_vec},
yuyv,
};
@@ -11,7 +12,7 @@ pub struct YUYVToRGBA {
}
impl YUYVToRGBA {
- pub async fn new() -> Self {
+ pub async fn new() -> Result<Self, GpuConverterError> {
let instance = wgpu::Instance::new(&wgpu::InstanceDescriptor::default());
let adapter = instance
@@ -20,13 +21,11 @@ impl YUYVToRGBA {
force_fallback_adapter: false,
compatible_surface: None,
})
- .await
- .unwrap();
+ .await?;
let (device, queue) = adapter
.request_device(&wgpu::DeviceDescriptor::default())
- .await
- .unwrap();
+ .await?;
let shader = device.create_shader_module(wgpu::ShaderModuleDescriptor {
label: Some("YUYV to RGBA Converter"),
@@ -76,12 +75,12 @@ impl YUYVToRGBA {
cache: None,
});
- Self {
+ Ok(Self {
device,
queue,
pipeline,
bind_group_layout,
- }
+ })
}
pub fn convert(
@@ -89,9 +88,22 @@ impl YUYVToRGBA {
yuyv_data: &[u8],
width: u32,
height: u32,
- ) -> Result<Vec<u8>, wgpu::PollError> {
+ ) -> Result<Vec<u8>, ConvertError> {
+ if width % 2 != 0 {
+ return Err(ConvertError::OddWidth { width });
+ }
+
+ let expected_size = (width as usize) * (height as usize) * 2;
+ if yuyv_data.len() != expected_size {
+ return Err(ConvertError::BufferSizeMismatch {
+ expected: expected_size,
+ actual: yuyv_data.len(),
+ });
+ }
+
let yuyv_texture =
- yuyv::create_input_texture(&self.device, &self.queue, yuyv_data, width, height);
+ yuyv::create_input_texture(&self.device, &self.queue, yuyv_data, width, height)
+ .expect("YUYV input validation passed above");
let output_texture = self.device.create_texture(&wgpu::TextureDescriptor {
label: Some("YUYV to RGBA Output Texture"),
@@ -148,6 +160,6 @@ impl YUYVToRGBA {
self.queue.submit(std::iter::once(encoder.finish()));
- read_buffer_to_vec(&output_buffer, &self.device)
+ Ok(read_buffer_to_vec(&output_buffer, &self.device)?)
}
}
diff --git a/crates/video-decode/src/avassetreader.rs b/crates/video-decode/src/avassetreader.rs
index 8352278ea..d7e4d1e48 100644
--- a/crates/video-decode/src/avassetreader.rs
+++ b/crates/video-decode/src/avassetreader.rs
@@ -38,7 +38,7 @@ impl AVAssetReaderDecoder {
.map_err(|e| format!("video decoder / {e}"))?;
(
- pixel_to_pixel_format(decoder.format()),
+ pixel_to_pixel_format(decoder.format())?,
decoder.width(),
decoder.height(),
)
@@ -159,13 +159,22 @@ impl<'a> Iterator for FramesIter<'a> {
}
}
-pub fn pixel_to_pixel_format(pixel: avformat::Pixel) -> cv::PixelFormat {
+pub fn pixel_to_pixel_format(pixel: avformat::Pixel) -> Result<cv::PixelFormat, String> {
match pixel {
- avformat::Pixel::NV12 => cv::PixelFormat::_420V,
- avformat::Pixel::YUV420P => cv::PixelFormat::_420V,
- avformat::Pixel::RGBA => cv::PixelFormat::_32_RGBA,
- avformat::Pixel::BGRA => cv::PixelFormat::_32_BGRA,
- _ => cv::PixelFormat::_32_RGBA,
+ avformat::Pixel::NV12 => Ok(cv::PixelFormat::_420V),
+ avformat::Pixel::YUV420P => Ok(cv::PixelFormat::_420V),
+ avformat::Pixel::RGBA => Ok(cv::PixelFormat::_32_RGBA),
+ avformat::Pixel::BGRA => Ok(cv::PixelFormat::_32_BGRA),
+ other => {
+ tracing::error!(
+ pixel_format = ?other,
+ "Unhandled pixel format encountered - no mapping to cv::PixelFormat available"
+ );
+ Err(format!(
+ "Unsupported pixel format: {:?}. Supported formats: NV12, YUV420P, RGBA, BGRA",
+ other
+ ))
+ }
}
}