Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Add native camera frame support and async camera muxer
Richie McIlroy140547c942e6
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 30a7ec1d4..406c04fa8 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -649,10 +649,18 @@ fn spawn_camera_watcher(app_handle: AppHandle) {)};- if should_check && let Some(selected_id) = camera_id {- let available = is_camera_available(&selected_id);+ if should_check && let Some(ref selected_id) = camera_id {+ let available = is_camera_available(selected_id);+ debug!(+ "Camera watcher: checking availability for {:?}, available={}, is_marked={}",+ selected_id, available, is_marked+ );if !available && !is_marked {+ warn!(+ "Camera watcher: camera {:?} detected as unavailable, pausing recording",+ selected_id+ );let mut app = state.write().await;if let Err(err) = app.handle_input_disconnect(RecordingInputKind::Camera)@@ -674,7 +682,21 @@ fn spawn_camera_watcher(app_handle: AppHandle) {}fn is_camera_available(id: &DeviceOrModelID) -> bool {- cap_camera::list_cameras().any(|info| match id {+ let cameras: Vec<_> = cap_camera::list_cameras().collect();+ debug!(+ "is_camera_available: looking for {:?} in {} cameras",+ id,+ cameras.len()+ );+ for camera in &cameras {+ debug!(+ " - device_id={}, model_id={:?}, name={}",+ camera.device_id(),+ camera.model_id(),+ camera.display_name()+ );+ }+ cameras.iter().any(|info| match id {DeviceOrModelID::DeviceID(device_id) => info.device_id() == device_id,DeviceOrModelID::ModelID(model_id) => {info.model_id().is_some_and(|existing| existing == model_id)diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 2794eefc0..a5a0ecc00 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -76,12 +76,12 @@ pub enum InProgressRecording {progressive_upload: InstantMultipartUpload,video_upload_info: VideoUploadInfo,common: InProgressRecordingCommon,- // camera isn't used as part of recording pipeline so we hold lock herecamera_feed: Option<Arc<CameraFeedLock>>,},Studio {handle: studio_recording::ActorHandle,common: InProgressRecordingCommon,+ camera_feed: Option<Arc<CameraFeedLock>>,},}@@ -674,6 +674,7 @@ pub async fn start_recording(Ok(InProgressRecording::Studio {handle,common: common.clone(),+ camera_feed: camera_feed.clone(),})}RecordingMode::Instant => {diff --git a/crates/enc-ffmpeg/src/video/h264.rs b/crates/enc-ffmpeg/src/video/h264.rsindex 9935d3779..e709c7d80 100644--- a/crates/enc-ffmpeg/src/video/h264.rs+++ b/crates/enc-ffmpeg/src/video/h264.rs@@ -8,7 +8,7 @@ use ffmpeg::{frame,threading::Config,};-use tracing::{debug, error};+use tracing::{debug, error, trace};use crate::base::EncoderBase;@@ -24,6 +24,7 @@ pub struct H264EncoderBuilder {input_config: VideoInfo,preset: H264Preset,output_size: Option<(u32, u32)>,+ external_conversion: bool,}#[derive(Clone, Copy)]@@ -54,6 +55,7 @@ impl H264EncoderBuilder {bpp: Self::QUALITY_BPP,preset: H264Preset::Ultrafast,output_size: None,+ external_conversion: false,}}@@ -76,6 +78,11 @@ impl H264EncoderBuilder {Ok(self)}+ pub fn with_external_conversion(mut self) -> Self {+ self.external_conversion = true;+ self+ }+pub fn build(self,output: &mut format::context::Output,@@ -110,6 +117,7 @@ impl H264EncoderBuilder {output_width,output_height,self.bpp,+ self.external_conversion,) {Ok(encoder) => {debug!("Using encoder {}", codec_name);@@ -133,6 +141,7 @@ impl H264EncoderBuilder {output_width: u32,output_height: u32,bpp: f32,+ external_conversion: bool,) -> Result<H264Encoder, H264EncoderError> {let encoder_supports_input_format = codec.video()@@ -147,10 +156,12 @@ impl H264EncoderBuilder {} else {needs_pixel_conversion = true;let format = ffmpeg::format::Pixel::NV12;- debug!(- "Converting from {:?} to {:?} for H264 encoding",- input_config.pixel_format, format- );+ if !external_conversion {+ debug!(+ "Converting from {:?} to {:?} for H264 encoding",+ input_config.pixel_format, format+ );+ }format};@@ -164,14 +175,20 @@ impl H264EncoderBuilder {let needs_scaling =output_width != input_config.width || output_height != input_config.height;- if needs_scaling {+ if needs_scaling && !external_conversion {debug!("Scaling video frames for H264 encoding from {}x{} to {}x{}",input_config.width, input_config.height, output_width, output_height);}- let converter = if needs_pixel_conversion || needs_scaling {+ let converter = if external_conversion {+ debug!(+ "External conversion enabled, skipping internal converter. Expected input: {:?} {}x{}",+ output_format, output_width, output_height+ );+ None+ } else if needs_pixel_conversion || needs_scaling {let flags = if needs_scaling {ffmpeg::software::scaling::flag::Flags::BICUBIC} else {@@ -245,6 +262,9 @@ impl H264EncoderBuilder {output_format,output_width,output_height,+ input_format: input_config.pixel_format,+ input_width: input_config.width,+ input_height: input_config.height,})}}@@ -256,6 +276,19 @@ pub struct H264Encoder {output_format: format::Pixel,output_width: u32,output_height: u32,+ input_format: format::Pixel,+ input_width: u32,+ input_height: u32,+}++pub struct ConversionRequirements {+ pub input_format: format::Pixel,+ pub input_width: u32,+ pub input_height: u32,+ pub output_format: format::Pixel,+ pub output_width: u32,+ pub output_height: u32,+ pub needs_conversion: bool,}#[derive(thiserror::Error, Debug)]@@ -273,6 +306,21 @@ impl H264Encoder {H264EncoderBuilder::new(input_config)}+ pub fn conversion_requirements(&self) -> ConversionRequirements {+ let needs_conversion = self.input_format != self.output_format+ || self.input_width != self.output_width+ || self.input_height != self.output_height;+ ConversionRequirements {+ input_format: self.input_format,+ input_width: self.input_width,+ input_height: self.input_height,+ output_format: self.output_format,+ output_width: self.output_width,+ output_height: self.output_height,+ needs_conversion,+ }+ }+pub fn queue_frame(&mut self,mut frame: frame::Video,@@ -300,6 +348,32 @@ impl H264Encoder {Ok(())}+ pub fn queue_preconverted_frame(+ &mut self,+ mut frame: frame::Video,+ timestamp: Duration,+ output: &mut format::context::Output,+ ) -> Result<(), QueueFrameError> {+ trace!(+ "Encoding pre-converted frame: format={:?}, size={}x{}, expected={:?} {}x{}",+ frame.format(),+ frame.width(),+ frame.height(),+ self.output_format,+ self.output_width,+ self.output_height+ );++ self.base+ .update_pts(&mut frame, timestamp, &mut self.encoder);++ self.base+ .send_frame(&frame, output, &mut self.encoder)+ .map_err(QueueFrameError::Encode)?;++ Ok(())+ }+pub fn flush(&mut self, output: &mut format::context::Output) -> Result<(), ffmpeg::Error> {self.base.process_eof(output, &mut self.encoder)}diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.tomlindex e5e1d9ee0..43e712cd3 100644--- a/crates/recording/Cargo.toml+++ b/crates/recording/Cargo.toml@@ -20,6 +20,7 @@ cap-cursor-info = { path = "../cursor-info" }cap-camera = { path = "../camera", features = ["serde", "specta"] }cap-camera-ffmpeg = { path = "../camera-ffmpeg" }cap-enc-ffmpeg = { path = "../enc-ffmpeg" }+cap-frame-converter = { path = "../frame-converter" }cap-timestamp = { path = "../timestamp" }scap-ffmpeg = { path = "../scap-ffmpeg" }diff --git a/crates/recording/src/feeds/camera.rs b/crates/recording/src/feeds/camera.rsindex e8baae294..8de67cc35 100644--- a/crates/recording/src/feeds/camera.rs+++ b/crates/recording/src/feeds/camera.rs@@ -19,6 +19,7 @@ use tokio::{runtime::Runtime, sync::oneshot, task::LocalSet};use tracing::{debug, error, info, trace, warn};use crate::ffmpeg::FFmpegVideoFrame;+use crate::output_pipeline::NativeCameraFrame;const CAMERA_INIT_TIMEOUT: Duration = Duration::from_secs(4);@@ -26,6 +27,7 @@ const CAMERA_INIT_TIMEOUT: Duration = Duration::from_secs(4);pub struct CameraFeed {state: State,senders: Vec<flume::Sender<FFmpegVideoFrame>>,+ native_senders: Vec<flume::Sender<NativeCameraFrame>>,on_ready: Vec<oneshot::Sender<()>>,on_disconnect: Vec<Box<dyn Fn() + Send>>,}@@ -139,6 +141,7 @@ impl Default for CameraFeed {attached: None,}),senders: Vec::new(),+ native_senders: Vec::new(),on_ready: Vec::new(),on_disconnect: Vec::new(),}@@ -203,6 +206,8 @@ pub struct RemoveInput;pub struct AddSender(pub flume::Sender<FFmpegVideoFrame>);+pub struct AddNativeSender(pub flume::Sender<NativeCameraFrame>);+pub struct ListenForReady(pub oneshot::Sender<()>);pub struct OnFeedDisconnect(pub Box<dyn Fn() + Send>);@@ -239,6 +244,8 @@ struct LockedCameraInputReconnected {struct NewFrame(FFmpegVideoFrame);+struct NewNativeFrame(NativeCameraFrame);+struct Unlock;struct FinalizePendingRelease {@@ -249,6 +256,7 @@ fn spawn_camera_setup(id: DeviceOrModelID,actor_ref: ActorRef<CameraFeed>,new_frame_recipient: Recipient<NewFrame>,+ native_frame_recipient: Recipient<NewNativeFrame>,flow: CameraSetupFlow,) -> (ReadyFuture, SyncSender<()>) {let (ready_tx, ready_rx) = oneshot::channel::<Result<InputConnected, SetInputError>>();@@ -269,7 +277,9 @@ fn spawn_camera_setup(std::thread::spawn(move || {LocalSet::new().block_on(&runtime, async move {- let handle = match setup_camera(&id, new_frame_recipient).await {+ let setup_result = setup_camera(&id, new_frame_recipient, native_frame_recipient).await;++ let handle = match setup_result {Ok(result) => {let SetupCameraResult {handle,@@ -342,15 +352,22 @@ fn spawn_camera_setup(}};- trace!("Waiting for camera to be done");+ info!(+ "Camera capture thread: waiting for done signal for {:?}",+ &id+ );- let _ = done_rx_thread.recv();+ drop(done_tx_thread);+ let recv_result = done_rx_thread.recv();- trace!("Stoppping capture of {:?}", &id);+ warn!(+ "Camera capture thread: done signal received for {:?}, result={:?}",+ &id, recv_result+ );let _ = handle.stop_capturing();- info!("Stopped capture of {:?}", &id);+ warn!("Camera capture thread: stopped capture of {:?}", &id);})});@@ -394,11 +411,11 @@ struct SetupCameraResult {video_info: VideoInfo,}-async fn setup_camera(- id: &DeviceOrModelID,- recipient: Recipient<NewFrame>,-) -> Result<SetupCameraResult, SetInputError> {- let camera = find_camera(id).ok_or(SetInputError::DeviceNotFound)?;+static CAMERA_CALLBACK_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);++fn select_camera_format(+ camera: &cap_camera::CameraInfo,+) -> Result<cap_camera::Format, SetInputError> {let formats = camera.formats().ok_or(SetInputError::InvalidFormat)?;if formats.is_empty() {return Err(SetInputError::InvalidFormat);@@ -433,8 +450,17 @@ async fn setup_camera(.then(fr_cmp.unwrap_or(Ordering::Equal).reverse())});- let format = ideal_formats.swap_remove(0);+ Ok(ideal_formats.swap_remove(0))+}+#[cfg(target_os = "macos")]+async fn setup_camera(+ id: &DeviceOrModelID,+ recipient: Recipient<NewFrame>,+ native_recipient: Recipient<NewNativeFrame>,+) -> Result<SetupCameraResult, SetInputError> {+ let camera = find_camera(id).ok_or(SetInputError::DeviceNotFound)?;+ let format = select_camera_format(&camera)?;let frame_rate = format.frame_rate() as u32;let (ready_tx, ready_rx) = oneshot::channel();@@ -442,6 +468,20 @@ async fn setup_camera(let capture_handle = camera.start_capturing(format.clone(), move |frame| {+ let callback_num =+ CAMERA_CALLBACK_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);++ let timestamp = Timestamp::MachAbsoluteTime(cap_timestamp::MachAbsoluteTimestamp::new(+ cidre::cm::Clock::convert_host_time_to_sys_units(frame.native().sample_buf().pts()),+ ));++ let _ = native_recipient+ .tell(NewNativeFrame(NativeCameraFrame {+ sample_buf: frame.native().sample_buf().retained(),+ timestamp,+ }))+ .try_send();+let Ok(mut ff_frame) = frame.as_ffmpeg() else {return;};@@ -459,25 +499,129 @@ async fn setup_camera(let _ = signal.send(video_info);}- let _ = recipient+ let send_result = recipient.tell(NewFrame(FFmpegVideoFrame {inner: ff_frame,- #[cfg(windows)]- timestamp: Timestamp::PerformanceCounter(- cap_timestamp::PerformanceCounterTimestamp::new(- frame.native().perf_counter,- ),- ),- #[cfg(target_os = "macos")]- timestamp: Timestamp::MachAbsoluteTime(- cap_timestamp::MachAbsoluteTimestamp::new(- cidre::cm::Clock::convert_host_time_to_sys_units(- frame.native().sample_buf().pts(),- ),- ),- ),+ timestamp,})).try_send();++ if callback_num % 30 == 0 {+ tracing::debug!(+ "Camera callback: sent frame {} to actor, result={:?}",+ callback_num,+ send_result.is_ok()+ );+ }++ if send_result.is_err() && callback_num % 30 == 0 {+ tracing::warn!(+ "Camera callback: failed to send frame {} to actor (mailbox full?)",+ callback_num+ );+ }+ })+ .map_err(|e| SetInputError::StartCapturing(e.to_string()))?;++ let video_info = tokio::time::timeout(CAMERA_INIT_TIMEOUT, ready_rx)+ .await+ .map_err(|e| SetInputError::Timeout(e.to_string()))?+ .map_err(|_| SetInputError::Initialisation)?;++ Ok(SetupCameraResult {+ handle: capture_handle,+ camera_info: camera,+ video_info,+ })+}++#[cfg(not(target_os = "macos"))]+async fn setup_camera(+ id: &DeviceOrModelID,+ recipient: Recipient<NewFrame>,+ native_recipient: Recipient<NewNativeFrame>,+) -> Result<SetupCameraResult, SetInputError> {+ let camera = find_camera(id).ok_or(SetInputError::DeviceNotFound)?;+ let format = select_camera_format(&camera)?;+ let frame_rate = format.frame_rate() as u32;++ let (ready_tx, ready_rx) = oneshot::channel();+ let mut ready_signal = Some(ready_tx);++ let capture_handle = camera+ .start_capturing(format.clone(), move |frame| {+ let callback_num =+ CAMERA_CALLBACK_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);++ let timestamp = Timestamp::PerformanceCounter(+ cap_timestamp::PerformanceCounterTimestamp::new(frame.native().perf_counter),+ );++ if let Ok(bytes) = frame.native().bytes() {+ use cap_mediafoundation_utils::IMFMediaBufferExt;+ use windows::Win32::Media::MediaFoundation::{+ IMFMediaBuffer, MFCreateMemoryBuffer,+ };+ use windows::core::Interface;++ let data_len = bytes.len();+ if let Ok(buffer) = (unsafe { MFCreateMemoryBuffer(data_len as u32) }) {+ if let Ok(mut lock) = buffer.lock_mut() {+ lock.copy_from_slice(&*bytes);+ drop(lock);+ let _ = unsafe { buffer.SetCurrentLength(data_len as u32) };++ let _ = native_recipient+ .tell(NewNativeFrame(NativeCameraFrame {+ buffer,+ pixel_format: frame.native().pixel_format,+ width: frame.native().width as u32,+ height: frame.native().height as u32,+ timestamp,+ }))+ .try_send();+ }+ }+ }++ let Ok(mut ff_frame) = frame.as_ffmpeg() else {+ return;+ };++ ff_frame.set_pts(Some(frame.timestamp.as_micros() as i64));++ if let Some(signal) = ready_signal.take() {+ let video_info = VideoInfo::from_raw_ffmpeg(+ ff_frame.format(),+ ff_frame.width(),+ ff_frame.height(),+ frame_rate,+ );++ let _ = signal.send(video_info);+ }++ let send_result = recipient+ .tell(NewFrame(FFmpegVideoFrame {+ inner: ff_frame,+ timestamp,+ }))+ .try_send();++ if callback_num % 30 == 0 {+ tracing::debug!(+ "Camera callback: sent frame {} to actor, result={:?}",+ callback_num,+ send_result.is_ok()+ );+ }++ if send_result.is_err() && callback_num % 30 == 0 {+ tracing::warn!(+ "Camera callback: failed to send frame {} to actor (mailbox full?)",+ callback_num+ );+ }}).map_err(|e| SetInputError::StartCapturing(e.to_string()))?;@@ -509,12 +653,14 @@ impl Message<SetInput> for CameraFeed {State::Open(state) => {let actor_ref = ctx.actor_ref();let new_frame_recipient = actor_ref.clone().recipient();+ let native_frame_recipient = actor_ref.clone().recipient();let id = msg.id.clone();let (ready, _done_tx) = spawn_camera_setup(id.clone(),actor_ref,new_frame_recipient,+ native_frame_recipient,CameraSetupFlow::Open,);@@ -534,11 +680,13 @@ impl Message<SetInput> for CameraFeed {let actor_ref = ctx.actor_ref();let new_frame_recipient = actor_ref.clone().recipient();+ let native_frame_recipient = actor_ref.clone().recipient();let (ready, _done_tx) = spawn_camera_setup(msg.id.clone(),actor_ref,new_frame_recipient,+ native_frame_recipient,CameraSetupFlow::Locked,);@@ -582,6 +730,19 @@ impl Message<AddSender> for CameraFeed {}}+impl Message<AddNativeSender> for CameraFeed {+ type Reply = ();++ async fn handle(+ &mut self,+ msg: AddNativeSender,+ _: &mut Context<Self, Self::Reply>,+ ) -> Self::Reply {+ debug!("CameraFeed: Adding new native sender");+ self.native_senders.push(msg.0);+ }+}+impl Message<ListenForReady> for CameraFeed {type Reply = ();@@ -616,21 +777,43 @@ impl Message<OnFeedDisconnect> for CameraFeed {}}+static CAMERA_FRAME_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);+impl Message<NewFrame> for CameraFeed {type Reply = ();async fn handle(&mut self, msg: NewFrame, _: &mut Context<Self, Self::Reply>) -> Self::Reply {+ let frame_num = CAMERA_FRAME_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);++ if frame_num % 30 == 0 {+ debug!(+ "CameraFeed: received frame {}, broadcasting to {} senders",+ frame_num,+ self.senders.len()+ );+ }+let mut to_remove = vec![];for (i, sender) in self.senders.iter().enumerate() {- if let Err(flume::TrySendError::Disconnected(_)) = sender.try_send(msg.0.clone()) {- warn!("Camera sender {} disconnected, will be removed", i);- info!(- "Camera sender {} disconnected (rx dropped), removing from list",- i- );- to_remove.push(i);- };+ match sender.try_send(msg.0.clone()) {+ Ok(()) => {}+ Err(flume::TrySendError::Full(_)) => {+ if frame_num % 30 == 0 {+ warn!(+ "Camera sender {} channel full at frame {}, dropping frame",+ i, frame_num+ );+ }+ }+ Err(flume::TrySendError::Disconnected(_)) => {+ warn!(+ "Camera sender {} disconnected at frame {}, will be removed",+ i, frame_num+ );+ to_remove.push(i);+ }+ }}if !to_remove.is_empty() {@@ -642,6 +825,63 @@ impl Message<NewFrame> for CameraFeed {}}+static NATIVE_CAMERA_FRAME_COUNTER: std::sync::atomic::AtomicU64 =+ std::sync::atomic::AtomicU64::new(0);++impl Message<NewNativeFrame> for CameraFeed {+ type Reply = ();++ async fn handle(+ &mut self,+ msg: NewNativeFrame,+ _: &mut Context<Self, Self::Reply>,+ ) -> Self::Reply {+ let frame_num =+ NATIVE_CAMERA_FRAME_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);++ if frame_num % 30 == 0 {+ debug!(+ "CameraFeed: received native frame {}, broadcasting to {} native senders",+ frame_num,+ self.native_senders.len()+ );+ }++ let mut to_remove = vec![];++ for (i, sender) in self.native_senders.iter().enumerate() {+ match sender.try_send(msg.0.clone()) {+ Ok(()) => {}+ Err(flume::TrySendError::Full(_)) => {+ if frame_num % 30 == 0 {+ warn!(+ "Native camera sender {} channel full at frame {}, dropping frame",+ i, frame_num+ );+ }+ }+ Err(flume::TrySendError::Disconnected(_)) => {+ warn!(+ "Native camera sender {} disconnected at frame {}, will be removed",+ i, frame_num+ );+ to_remove.push(i);+ }+ }+ }++ if !to_remove.is_empty() {+ debug!(+ "Removing {} disconnected native camera senders",+ to_remove.len()+ );+ for i in to_remove.into_iter().rev() {+ self.native_senders.swap_remove(i);+ }+ }+ }+}+#[derive(Clone, Debug, thiserror::Error)]pub enum LockFeedError {#[error(transparent)]diff --git a/crates/recording/src/output_pipeline/async_camera.rs b/crates/recording/src/output_pipeline/async_camera.rsnew file mode 100644index 000000000..c62021f87--- /dev/null+++ b/crates/recording/src/output_pipeline/async_camera.rs@@ -0,0 +1,293 @@+use crate::{+ TaskPool,+ output_pipeline::{AudioFrame, AudioMuxer, Muxer, VideoMuxer},+};+use anyhow::{Context, anyhow};+use cap_enc_ffmpeg::{aac::AACEncoder, h264::*};+use cap_frame_converter::{+ AsyncConverterPool, ConversionConfig, ConvertError, ConverterPoolConfig, DropStrategy,+};+use cap_media_info::{AudioInfo, VideoInfo};+use std::{+ path::PathBuf,+ sync::{+ Arc,+ atomic::{AtomicBool, AtomicU64, Ordering},+ },+ time::Duration,+};+use tracing::{debug, info, trace, warn};++use super::FFmpegVideoFrame;++pub struct AsyncCameraMp4Muxer {+ output: ffmpeg::format::context::Output,+ video_encoder: Option<H264Encoder>,+ audio_encoder: Option<AACEncoder>,+ converter_pool: Option<AsyncConverterPool>,+ frame_sequence: AtomicU64,+ use_preconverted: bool,+ last_pts: Option<i64>,+ frames_submitted: u64,+ frames_encoded: u64,+}++pub struct AsyncCameraMuxerConfig {+ pub worker_count: usize,+ pub input_capacity: usize,+ pub output_capacity: usize,+}++impl Default for AsyncCameraMuxerConfig {+ fn default() -> Self {+ Self {+ worker_count: 4,+ input_capacity: 120,+ output_capacity: 90,+ }+ }+}++impl Muxer for AsyncCameraMp4Muxer {+ type Config = AsyncCameraMuxerConfig;++ async fn setup(+ config: Self::Config,+ output_path: PathBuf,+ video_config: Option<VideoInfo>,+ audio_config: Option<AudioInfo>,+ _: Arc<AtomicBool>,+ _: &mut TaskPool,+ ) -> anyhow::Result<Self>+ where+ Self: Sized,+ {+ let mut output = ffmpeg::format::output(&output_path)?;++ let (video_encoder, converter_pool, use_preconverted) =+ if let Some(video_config) = video_config {+ let encoder = H264Encoder::builder(video_config)+ .with_external_conversion()+ .build(&mut output)+ .context("video encoder")?;++ let requirements = encoder.conversion_requirements();++ let pool = if requirements.needs_conversion {+ let conversion_config = ConversionConfig::new(+ requirements.input_format,+ requirements.input_width,+ requirements.input_height,+ requirements.output_format,+ requirements.output_width,+ requirements.output_height,+ );++ let pool_config = ConverterPoolConfig {+ worker_count: config.worker_count,+ input_capacity: config.input_capacity,+ output_capacity: config.output_capacity,+ drop_strategy: DropStrategy::DropOldest,+ };++ let pool = AsyncConverterPool::from_config(conversion_config, pool_config)+ .map_err(|e| anyhow!("Failed to create converter pool: {e}"))?;++ info!(+ "Created async converter pool with {} workers for camera encoding",+ config.worker_count+ );++ Some(pool)+ } else {+ debug!("No conversion needed for camera encoding");+ None+ };++ (Some(encoder), pool, requirements.needs_conversion)+ } else {+ (None, None, false)+ };++ let audio_encoder = audio_config+ .map(|config| AACEncoder::init(config, &mut output))+ .transpose()+ .context("audio encoder")?;++ output.write_header()?;++ Ok(Self {+ output,+ video_encoder,+ audio_encoder,+ converter_pool,+ frame_sequence: AtomicU64::new(0),+ use_preconverted,+ last_pts: None,+ frames_submitted: 0,+ frames_encoded: 0,+ })+ }++ fn finish(&mut self, _: Duration) -> anyhow::Result<anyhow::Result<()>> {+ if let Some(mut pool) = self.converter_pool.take() {+ let initial_stats = pool.stats();+ info!(+ "Converter pool finishing: {} received, {} converted, {} dropped so far (muxer: submitted={}, encoded={})",+ initial_stats.frames_received,+ initial_stats.frames_converted,+ initial_stats.frames_dropped,+ self.frames_submitted,+ self.frames_encoded+ );++ let mut frames_encoded_in_drain = 0u64;+ let drain_timeout = Duration::from_secs(5);++ if let Some(encoder) = &mut self.video_encoder {+ let encoder_ref = encoder;+ let output_ref = &mut self.output;+ let last_pts = &mut self.last_pts;++ pool.drain_with_timeout(+ |converted| {+ let pts = converted.frame.pts().unwrap_or(0);+ if last_pts.map_or(true, |last| pts > last) {+ let timestamp = Duration::from_micros(pts as u64);+ if let Err(e) = encoder_ref.queue_preconverted_frame(+ converted.frame,+ timestamp,+ output_ref,+ ) {+ warn!("Failed to encode drained frame: {e}");+ } else {+ frames_encoded_in_drain += 1;+ }+ *last_pts = Some(pts);+ }+ },+ drain_timeout,+ );+ } else {+ pool.drain_with_timeout(|_| {}, drain_timeout);+ }++ info!(+ "Converter pool drain complete: {} frames encoded during drain",+ frames_encoded_in_drain+ );+ }++ let video_result = self+ .video_encoder+ .as_mut()+ .map(|enc| enc.flush(&mut self.output))+ .unwrap_or(Ok(()));++ let audio_result = self+ .audio_encoder+ .as_mut()+ .map(|enc| enc.flush(&mut self.output))+ .unwrap_or(Ok(()));++ self.output.write_trailer().context("write_trailer")?;++ if video_result.is_ok() && audio_result.is_ok() {+ return Ok(Ok(()));+ }++ Ok(Err(anyhow!(+ "Video: {video_result:#?}, Audio: {audio_result:#?}"+ )))+ }+}++impl VideoMuxer for AsyncCameraMp4Muxer {+ type VideoFrame = FFmpegVideoFrame;++ fn send_video_frame(+ &mut self,+ frame: Self::VideoFrame,+ timestamp: Duration,+ ) -> anyhow::Result<()> {+ let Some(encoder) = self.video_encoder.as_mut() else {+ return Ok(());+ };++ if let Some(pool) = &self.converter_pool {+ let sequence = self.frame_sequence.fetch_add(1, Ordering::Relaxed);++ let mut input_frame = frame.inner;+ input_frame.set_pts(Some(timestamp.as_micros() as i64));++ match pool.submit(input_frame, sequence) {+ Ok(()) => {+ self.frames_submitted += 1;+ }+ Err(ConvertError::PoolShutdown) => {+ debug!("Converter pool shutting down, frame will not be encoded");+ return Ok(());+ }+ Err(e) => {+ return Err(anyhow!("Failed to submit frame to converter: {e}"));+ }+ }++ let mut encoded_this_call = 0u64;+ while let Some(converted) = pool.try_recv() {+ let pts = converted.frame.pts().unwrap_or(0);+ if self.last_pts.map_or(true, |last| pts > last) {+ let frame_timestamp = Duration::from_micros(pts as u64);+ encoder.queue_preconverted_frame(+ converted.frame,+ frame_timestamp,+ &mut self.output,+ )?;+ self.last_pts = Some(pts);+ encoded_this_call += 1;+ self.frames_encoded += 1;+ }+ }++ let backlog = self.frames_submitted.saturating_sub(self.frames_encoded);+ if encoded_this_call == 0 && backlog > 10 {+ if let Some(converted) = pool.recv_timeout(Duration::from_millis(5)) {+ let pts = converted.frame.pts().unwrap_or(0);+ if self.last_pts.map_or(true, |last| pts > last) {+ let frame_timestamp = Duration::from_micros(pts as u64);+ encoder.queue_preconverted_frame(+ converted.frame,+ frame_timestamp,+ &mut self.output,+ )?;+ self.last_pts = Some(pts);+ self.frames_encoded += 1;+ }+ }+ }++ if self.frames_submitted % 60 == 0 {+ trace!(+ "Camera encoder progress: submitted={}, encoded={}, backlog={}",+ self.frames_submitted, self.frames_encoded, backlog+ );+ }+ } else if self.use_preconverted {+ encoder.queue_preconverted_frame(frame.inner, timestamp, &mut self.output)?;+ } else {+ encoder.queue_frame(frame.inner, timestamp, &mut self.output)?;+ }++ Ok(())+ }+}++impl AudioMuxer for AsyncCameraMp4Muxer {+ fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> {+ if let Some(audio_encoder) = self.audio_encoder.as_mut() {+ audio_encoder.send_frame(frame.inner, timestamp, &mut self.output)?;+ }++ Ok(())+ }+}diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rsindex a3d79c8a6..44148ec89 100644--- a/crates/recording/src/output_pipeline/core.rs+++ b/crates/recording/src/output_pipeline/core.rs@@ -397,7 +397,7 @@ async fn setup_video_source<TVideo: VideoSource>(video_config: TVideo::Config,setup_ctx: &mut SetupCtx,) -> anyhow::Result<(TVideo, mpsc::Receiver<TVideo::Frame>)> {- let (video_tx, video_rx) = mpsc::channel(8);+ let (video_tx, video_rx) = mpsc::channel(128);let video_source = TVideo::setup(video_config, video_tx, setup_ctx).await?;Ok((video_source, video_rx))@@ -454,10 +454,13 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: Vuse futures::StreamExt;let mut first_tx = Some(first_tx);+ let mut frame_count = 0u64;let res = stop_token.run_until_cancelled(async {while let Some(frame) = video_rx.next().await {+ frame_count += 1;+let timestamp = frame.timestamp();if let Some(first_tx) = first_tx.take() {@@ -480,14 +483,52 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V}).await;+ let was_cancelled = res.is_none();++ if was_cancelled {+ info!("mux-video cancelled, draining remaining frames from channel");+ let mut drained = 0u64;+ while let Some(frame) = video_rx.next().await {+ frame_count += 1;+ drained += 1;++ let timestamp = frame.timestamp();++ if let Some(first_tx) = first_tx.take() {+ let _ = first_tx.send(timestamp);+ }++ let duration = timestamp+ .checked_duration_since(timestamps)+ .unwrap_or(Duration::ZERO);++ match muxer.lock().await.send_video_frame(frame, duration) {+ Ok(()) => {}+ Err(e) => {+ warn!("Error processing drained frame: {e}");+ break;+ }+ }+ }+ if drained > 0 {+ info!(+ "mux-video drained {} additional frames after cancellation",+ drained+ );+ }+ }+muxer.lock().await.stop();if let Some(Err(e)) = res {return Err(e);}- if res.is_none() {- info!("mux-video cancelled");+ if was_cancelled {+ info!(+ "mux-video finished after cancellation, total {} frames",+ frame_count+ );}Ok(())diff --git a/crates/recording/src/output_pipeline/macos.rs b/crates/recording/src/output_pipeline/macos.rsindex 6c67459db..936b73009 100644--- a/crates/recording/src/output_pipeline/macos.rs+++ b/crates/recording/src/output_pipeline/macos.rs@@ -1,16 +1,33 @@use crate::{- output_pipeline::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer},+ output_pipeline::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoFrame, VideoMuxer},sources::screen_capture,};use anyhow::anyhow;use cap_enc_avfoundation::QueueFrameError;use cap_media_info::{AudioInfo, VideoInfo};+use cap_timestamp::Timestamp;+use cidre::arc;use std::{path::PathBuf,sync::{Arc, Mutex, atomic::AtomicBool},time::Duration,};+#[derive(Clone)]+pub struct NativeCameraFrame {+ pub sample_buf: arc::R<cidre::cm::SampleBuf>,+ pub timestamp: Timestamp,+}++unsafe impl Send for NativeCameraFrame {}+unsafe impl Sync for NativeCameraFrame {}++impl VideoFrame for NativeCameraFrame {+ fn timestamp(&self) -> Timestamp {+ self.timestamp+ }+}+#[derive(Clone)]pub struct AVFoundationMp4Muxer(Arc<Mutex<cap_enc_avfoundation::MP4Encoder>>,@@ -121,3 +138,114 @@ impl AudioMuxer for AVFoundationMp4Muxer {Ok(())}}++#[derive(Clone)]+pub struct AVFoundationCameraMuxer(+ Arc<Mutex<cap_enc_avfoundation::MP4Encoder>>,+ Arc<AtomicBool>,+);++impl AVFoundationCameraMuxer {+ const MAX_QUEUE_RETRIES: u32 = 500;+}++#[derive(Default)]+pub struct AVFoundationCameraMuxerConfig {+ pub output_height: Option<u32>,+}++impl Muxer for AVFoundationCameraMuxer {+ type Config = AVFoundationCameraMuxerConfig;++ async fn setup(+ config: Self::Config,+ output_path: PathBuf,+ video_config: Option<VideoInfo>,+ audio_config: Option<AudioInfo>,+ pause_flag: Arc<AtomicBool>,+ _tasks: &mut TaskPool,+ ) -> anyhow::Result<Self> {+ let video_config =+ video_config.ok_or_else(|| anyhow!("Invariant: No video source provided"))?;++ Ok(Self(+ Arc::new(Mutex::new(+ cap_enc_avfoundation::MP4Encoder::init(+ output_path,+ video_config,+ audio_config,+ config.output_height,+ )+ .map_err(|e| anyhow!("{e}"))?,+ )),+ pause_flag,+ ))+ }++ fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {+ Ok(self+ .0+ .lock()+ .map_err(|e| anyhow!("{e}"))?+ .finish(Some(timestamp))+ .map(Ok)?)+ }+}++impl VideoMuxer for AVFoundationCameraMuxer {+ type VideoFrame = NativeCameraFrame;++ fn send_video_frame(+ &mut self,+ frame: Self::VideoFrame,+ timestamp: Duration,+ ) -> anyhow::Result<()> {+ let mut mp4 = self.0.lock().map_err(|e| anyhow!("MuxerLock/{e}"))?;++ if self.1.load(std::sync::atomic::Ordering::Relaxed) {+ mp4.pause();+ } else {+ mp4.resume();+ }++ let mut retry_count = 0;+ loop {+ match mp4.queue_video_frame(frame.sample_buf.clone(), timestamp) {+ Ok(()) => break,+ Err(QueueFrameError::NotReadyForMore) => {+ retry_count += 1;+ if retry_count >= Self::MAX_QUEUE_RETRIES {+ return Err(anyhow!(+ "send_video_frame/timeout after {} retries",+ Self::MAX_QUEUE_RETRIES+ ));+ }+ std::thread::sleep(Duration::from_millis(2));+ continue;+ }+ Err(e) => return Err(anyhow!("send_video_frame/{e}")),+ }+ }++ Ok(())+ }+}++impl AudioMuxer for AVFoundationCameraMuxer {+ fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> {+ let mut mp4 = self.0.lock().map_err(|e| anyhow!("{e}"))?;++ loop {+ match mp4.queue_audio_frame(&frame.inner, timestamp) {+ Ok(()) => break,+ Err(QueueFrameError::NotReadyForMore) => {+ std::thread::sleep(Duration::from_millis(2));+ continue;+ }+ Err(e) => return Err(anyhow!("send_audio_frame/{e}")),+ }+ }++ Ok(())+ }+}diff --git a/crates/recording/src/output_pipeline/mod.rs b/crates/recording/src/output_pipeline/mod.rsindex 21687aca1..dece16d9a 100644--- a/crates/recording/src/output_pipeline/mod.rs+++ b/crates/recording/src/output_pipeline/mod.rs@@ -1,6 +1,8 @@+mod async_camera;mod core;pub mod ffmpeg;+pub use async_camera::*;pub use core::*;pub use ffmpeg::*;diff --git a/crates/recording/src/output_pipeline/win.rs b/crates/recording/src/output_pipeline/win.rsindex 77edf9bd8..d1779f212 100644--- a/crates/recording/src/output_pipeline/win.rs+++ b/crates/recording/src/output_pipeline/win.rs@@ -1,7 +1,8 @@-use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoMuxer, screen_capture};+use crate::{AudioFrame, AudioMuxer, Muxer, TaskPool, VideoFrame, VideoMuxer, screen_capture};use anyhow::{Context, anyhow};use cap_enc_ffmpeg::aac::AACEncoder;use cap_media_info::{AudioInfo, VideoInfo};+use cap_timestamp::Timestamp;use futures::channel::oneshot;use std::{path::PathBuf,@@ -16,7 +17,10 @@ use tracing::*;use windows::{Foundation::TimeSpan,Graphics::SizeInt32,- Win32::Graphics::{Direct3D11::ID3D11Device, Dxgi::Common::DXGI_FORMAT},+ Win32::Graphics::{+ Direct3D11::ID3D11Device,+ Dxgi::Common::{DXGI_FORMAT, DXGI_FORMAT_NV12, DXGI_FORMAT_UYVY, DXGI_FORMAT_YUY2},+ },};struct PauseTracker {@@ -379,3 +383,361 @@ fn duration_to_timespan(duration: Duration) -> TimeSpan {Duration: clamped as i64,}}++#[derive(Clone)]+pub struct NativeCameraFrame {+ pub buffer: windows::Win32::Media::MediaFoundation::IMFMediaBuffer,+ pub pixel_format: cap_camera_windows::PixelFormat,+ pub width: u32,+ pub height: u32,+ pub timestamp: Timestamp,+}++unsafe impl Send for NativeCameraFrame {}+unsafe impl Sync for NativeCameraFrame {}++impl VideoFrame for NativeCameraFrame {+ fn timestamp(&self) -> Timestamp {+ self.timestamp+ }+}++impl NativeCameraFrame {+ pub fn dxgi_format(&self) -> DXGI_FORMAT {+ match self.pixel_format {+ cap_camera_windows::PixelFormat::NV12 => DXGI_FORMAT_NV12,+ cap_camera_windows::PixelFormat::YUYV422 => DXGI_FORMAT_YUY2,+ cap_camera_windows::PixelFormat::UYVY422 => DXGI_FORMAT_UYVY,+ _ => DXGI_FORMAT_NV12,+ }+ }+}++pub struct WindowsCameraMuxer {+ video_tx: SyncSender<Option<(NativeCameraFrame, Duration)>>,+ output: Arc<Mutex<ffmpeg::format::context::Output>>,+ audio_encoder: Option<AACEncoder>,+ pause: PauseTracker,+}++#[derive(Default)]+pub struct WindowsCameraMuxerConfig {+ pub output_height: Option<u32>,+}++impl Muxer for WindowsCameraMuxer {+ type Config = WindowsCameraMuxerConfig;++ async fn setup(+ config: Self::Config,+ output_path: PathBuf,+ video_config: Option<VideoInfo>,+ audio_config: Option<AudioInfo>,+ pause_flag: Arc<AtomicBool>,+ tasks: &mut TaskPool,+ ) -> anyhow::Result<Self>+ where+ Self: Sized,+ {+ let video_config =+ video_config.ok_or_else(|| anyhow!("invariant: video config expected"))?;++ let input_size = SizeInt32 {+ Width: video_config.width as i32,+ Height: video_config.height as i32,+ };++ let output_height = config.output_height.unwrap_or(video_config.height);+ let output_width = (video_config.width * output_height) / video_config.height;+ let output_width = output_width & !1;+ let output_height = output_height & !1;++ let output_size = SizeInt32 {+ Width: output_width as i32,+ Height: output_height as i32,+ };++ let frame_rate = video_config.fps();+ let bitrate_multiplier = 0.2;++ let (video_tx, video_rx) = sync_channel::<Option<(NativeCameraFrame, Duration)>>(30);++ let mut output = ffmpeg::format::output(&output_path)?;+ let audio_encoder = audio_config+ .map(|config| AACEncoder::init(config, &mut output))+ .transpose()?;++ let output = Arc::new(Mutex::new(output));+ let (ready_tx, ready_rx) = oneshot::channel::<anyhow::Result<()>>();++ {+ let output = output.clone();++ tasks.spawn_thread("windows-camera-encoder", move || {+ cap_mediafoundation_utils::thread_init();++ let d3d_device = match crate::capture_pipeline::create_d3d_device() {+ Ok(device) => device,+ Err(e) => {+ let _ = ready_tx.send(Err(anyhow!("Failed to create D3D device: {e}")));+ return Err(anyhow!("Failed to create D3D device: {e}"));+ }+ };++ let first_frame = match video_rx.recv() {+ Ok(Some(frame)) => frame,+ Ok(None) => {+ let _ = ready_tx.send(Ok(()));+ return Ok(());+ }+ Err(e) => {+ let _ = ready_tx.send(Err(anyhow!("No frames received: {e}")));+ return Err(anyhow!("No frames received: {e}"));+ }+ };++ let input_format = first_frame.0.dxgi_format();++ let encoder_result = cap_enc_mediafoundation::H264Encoder::new_with_scaled_output(+ &d3d_device,+ input_format,+ input_size,+ output_size,+ frame_rate,+ bitrate_multiplier,+ );++ let (mut encoder, mut muxer) = match encoder_result {+ Ok(encoder) => {+ let muxer = {+ let mut output_guard = match output.lock() {+ Ok(guard) => guard,+ Err(poisoned) => {+ let err = anyhow!("Failed to lock output mutex: {}", poisoned);+ let _ = ready_tx.send(Err(err.clone().into()));+ return Err(err);+ }+ };++ cap_mediafoundation_ffmpeg::H264StreamMuxer::new(+ &mut *output_guard,+ cap_mediafoundation_ffmpeg::MuxerConfig {+ width: output_width,+ height: output_height,+ fps: frame_rate,+ bitrate: encoder.bitrate(),+ },+ )+ };++ match muxer {+ Ok(muxer) => (encoder, muxer),+ Err(err) => {+ let err = anyhow!("Failed to create muxer: {err}");+ let _ = ready_tx.send(Err(err.clone().into()));+ return Err(err);+ }+ }+ }+ Err(err) => {+ let err = anyhow!("Failed to create H264 encoder: {err}");+ let _ = ready_tx.send(Err(err.clone().into()));+ return Err(err);+ }+ };++ if ready_tx.send(Ok(())).is_err() {+ error!("Failed to send ready signal - receiver dropped");+ return Ok(());+ }++ info!(+ "Windows camera encoder started: {:?} {}x{} -> NV12 {}x{} @ {}fps",+ input_format,+ input_size.Width,+ input_size.Height,+ output_size.Width,+ output_size.Height,+ frame_rate+ );++ let mut first_timestamp: Option<Duration> = None;+ let mut frame_count = 0u64;++ let process_frame = |frame: NativeCameraFrame,+ timestamp: Duration|+ -> windows::core::Result<+ Option<(+ windows::Win32::Graphics::Direct3D11::ID3D11Texture2D,+ TimeSpan,+ )>,+ > {+ let relative = if let Some(first) = first_timestamp {+ timestamp.checked_sub(first).unwrap_or(Duration::ZERO)+ } else {+ first_timestamp = Some(timestamp);+ Duration::ZERO+ };++ let texture = upload_mf_buffer_to_texture(&d3d_device, &frame)?;+ Ok(Some((texture, duration_to_timespan(relative))))+ };++ if let Ok(Some((texture, frame_time))) = process_frame(first_frame.0, first_frame.1)+ {+ encoder+ .run(+ Arc::new(AtomicBool::default()),+ || {+ if frame_count > 0 {+ let Ok(Some((frame, timestamp))) = video_rx.recv() else {+ trace!("No more camera frames available");+ return Ok(None);+ };+ frame_count += 1;+ if frame_count % 30 == 0 {+ debug!(+ "Windows camera encoder: processed {} frames",+ frame_count+ );+ }+ return process_frame(frame, timestamp);+ }+ frame_count += 1;+ Ok(Some((texture.clone(), frame_time)))+ },+ |output_sample| {+ let mut output = output.lock().unwrap();+ let _ = muxer+ .write_sample(&output_sample, &mut *output)+ .map_err(|e| format!("WriteSample: {e}"));+ Ok(())+ },+ )+ .context("run camera encoder")?;+ }++ info!(+ "Windows camera encoder finished: {} frames encoded",+ frame_count+ );+ Ok(())+ });+ }++ ready_rx+ .await+ .map_err(|_| anyhow!("Camera encoder thread ended unexpectedly"))??;++ output.lock().unwrap().write_header()?;++ Ok(Self {+ video_tx,+ output,+ audio_encoder,+ pause: PauseTracker::new(pause_flag),+ })+ }++ fn stop(&mut self) {+ let _ = self.video_tx.send(None);+ }++ fn finish(&mut self, _: Duration) -> anyhow::Result<anyhow::Result<()>> {+ let mut output = self+ .output+ .lock()+ .map_err(|_| anyhow!("Failed to lock output"))?;+ let audio_result = self+ .audio_encoder+ .as_mut()+ .map(|enc| enc.flush(&mut output))+ .unwrap_or(Ok(()));++ output.write_trailer()?;++ Ok(audio_result.map_err(Into::into))+ }+}++impl VideoMuxer for WindowsCameraMuxer {+ type VideoFrame = NativeCameraFrame;++ fn send_video_frame(+ &mut self,+ frame: Self::VideoFrame,+ timestamp: Duration,+ ) -> anyhow::Result<()> {+ if let Some(timestamp) = self.pause.adjust(timestamp)? {+ self.video_tx.send(Some((frame, timestamp)))?;+ }++ Ok(())+ }+}++impl AudioMuxer for WindowsCameraMuxer {+ fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> {+ if let Some(timestamp) = self.pause.adjust(timestamp)? {+ if let Some(encoder) = self.audio_encoder.as_mut()+ && let Ok(mut output) = self.output.lock()+ {+ encoder.send_frame(frame.inner, timestamp, &mut output)?;+ }+ }++ Ok(())+ }+}++fn upload_mf_buffer_to_texture(+ device: &ID3D11Device,+ frame: &NativeCameraFrame,+) -> windows::core::Result<windows::Win32::Graphics::Direct3D11::ID3D11Texture2D> {+ use cap_mediafoundation_utils::IMFMediaBufferExt;+ use windows::Win32::Graphics::Direct3D11::{+ D3D11_BIND_SHADER_RESOURCE, D3D11_SUBRESOURCE_DATA, D3D11_TEXTURE2D_DESC,+ D3D11_USAGE_DEFAULT,+ };+ use windows::Win32::Graphics::Dxgi::Common::DXGI_SAMPLE_DESC;++ let dxgi_format = frame.dxgi_format();+ let bytes_per_pixel: u32 = match frame.pixel_format {+ cap_camera_windows::PixelFormat::NV12 => 1,+ cap_camera_windows::PixelFormat::YUYV422 | cap_camera_windows::PixelFormat::UYVY422 => 2,+ _ => 2,+ };++ let lock = frame.buffer.lock()?;+ let data = &*lock;++ let row_pitch = frame.width * bytes_per_pixel;++ let texture_desc = D3D11_TEXTURE2D_DESC {+ Width: frame.width,+ Height: frame.height,+ MipLevels: 1,+ ArraySize: 1,+ Format: dxgi_format,+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ Usage: D3D11_USAGE_DEFAULT,+ BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,+ CPUAccessFlags: 0,+ MiscFlags: 0,+ };++ let subresource_data = D3D11_SUBRESOURCE_DATA {+ pSysMem: data.as_ptr() as *const _,+ SysMemPitch: row_pitch,+ SysMemSlicePitch: 0,+ };++ unsafe {+ let mut texture = None;+ device.CreateTexture2D(&texture_desc, Some(&subresource_data), Some(&mut texture))?;+ Ok(texture.unwrap())+ }+}diff --git a/crates/recording/src/sources/camera.rs b/crates/recording/src/sources/camera.rsindex 42c305f5f..be2de19f2 100644--- a/crates/recording/src/sources/camera.rs+++ b/crates/recording/src/sources/camera.rs@@ -5,27 +5,17 @@ use crate::{};use anyhow::anyhow;use cap_media_info::VideoInfo;-use futures::{SinkExt, channel::mpsc};-use std::sync::Arc;--pub struct Camera(Arc<CameraFeedLock>);+use futures::{FutureExt, channel::mpsc, future::BoxFuture};+use std::sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+};+use tokio::sync::oneshot;-struct LogDrop<T>(T, &'static str);-impl<T> Drop for LogDrop<T> {- fn drop(&mut self) {- tracing::debug!("Dropping {}", self.1);- }-}-impl<T> std::ops::Deref for LogDrop<T> {- type Target = T;- fn deref(&self) -> &Self::Target {- &self.0- }-}-impl<T> std::ops::DerefMut for LogDrop<T> {- fn deref_mut(&mut self) -> &mut Self::Target {- &mut self.0- }+pub struct Camera {+ feed_lock: Arc<CameraFeedLock>,+ stop_tx: Option<oneshot::Sender<()>>,+ stopped: Arc<AtomicBool>,}impl VideoSource for Camera {@@ -40,44 +30,118 @@ impl VideoSource for Camera {whereSelf: Sized,{- let (tx, rx) = flume::bounded(32);+ let (tx, rx) = flume::bounded(256);feed_lock.ask(camera::AddSender(tx)).await.map_err(|e| anyhow!("Failed to add camera sender: {e}"))?;- let mut video_tx = LogDrop(video_tx, "camera_video_tx");+ let (stop_tx, stop_rx) = oneshot::channel();+ let stopped = Arc::new(AtomicBool::new(false));+ let stopped_clone = stopped.clone();tokio::spawn(async move {tracing::debug!("Camera source task started");+ let mut frame_count: u64 = 0;+ let mut sent_count: u64 = 0;+ let mut dropped_count: u64 = 0;+ let start = std::time::Instant::now();+ let mut video_tx = video_tx;+ let mut stop_rx = stop_rx.fuse();+loop {- match rx.recv_async().await {- Ok(frame) => {- // tracing::trace!("Sending camera frame");- if let Err(e) = video_tx.send(frame).await {- tracing::warn!("Failed to send to video pipeline: {e}");- // If pipeline is closed, we should stop?- // But lets continue to keep rx alive for now to see if it helps,- // or maybe break?- // If we break, we disconnect from CameraFeed.- // If pipeline is closed, we SHOULD disconnect.- break;- }- }- Err(e) => {- tracing::debug!("Camera feed disconnected (rx closed): {e}");+ if stopped_clone.load(Ordering::Relaxed) {+ tracing::debug!("Camera source: stop flag set, exiting");+ break;+ }++ tokio::select! {+ biased;+ _ = &mut stop_rx => {+ tracing::debug!("Camera source: received stop signal");break;}+ result = rx.recv_async() => {+ match result {+ Ok(frame) => {+ frame_count += 1;+ match video_tx.try_send(frame) {+ Ok(()) => {+ sent_count += 1;+ if sent_count % 30 == 0 {+ tracing::debug!(+ "Camera source: sent {} frames, dropped {} in {:?}",+ sent_count,+ dropped_count,+ start.elapsed()+ );+ }+ }+ Err(e) => {+ if e.is_full() {+ dropped_count += 1;+ if dropped_count % 30 == 0 {+ tracing::warn!(+ "Camera source: encoder can't keep up, dropped {} frames so far",+ dropped_count+ );+ }+ } else if e.is_disconnected() {+ tracing::debug!(+ "Camera source: pipeline closed after {} sent, {} dropped",+ sent_count,+ dropped_count+ );+ break;+ }+ }+ }+ }+ Err(e) => {+ tracing::debug!(+ "Camera feed disconnected (rx closed) after {} frames in {:?}: {e}",+ frame_count,+ start.elapsed()+ );+ break;+ }+ }+ }}}- tracing::debug!("Camera source task finished");++ drop(video_tx);++ tracing::info!(+ "Camera source finished: {} received, {} sent, {} dropped in {:?}",+ frame_count,+ sent_count,+ dropped_count,+ start.elapsed()+ );});- Ok(Self(feed_lock))+ Ok(Self {+ feed_lock,+ stop_tx: Some(stop_tx),+ stopped,+ })}fn video_info(&self) -> VideoInfo {- *self.0.video_info()+ *self.feed_lock.video_info()+ }++ fn stop(&mut self) -> BoxFuture<'_, anyhow::Result<()>> {+ async move {+ tracing::debug!("Camera source: stopping");+ self.stopped.store(true, Ordering::SeqCst);+ if let Some(stop_tx) = self.stop_tx.take() {+ let _ = stop_tx.send(());+ }+ Ok(())+ }+ .boxed()}}diff --git a/crates/recording/src/sources/mod.rs b/crates/recording/src/sources/mod.rsindex 1c5cff932..e86649ec5 100644--- a/crates/recording/src/sources/mod.rs+++ b/crates/recording/src/sources/mod.rs@@ -1,8 +1,9 @@pub mod audio_mixer;pub mod camera;pub mod microphone;+pub mod native_camera;pub mod screen_capture;pub use camera::*;pub use microphone::*;-// pub use screen_capture::*;+pub use native_camera::*;diff --git a/crates/recording/src/sources/native_camera.rs b/crates/recording/src/sources/native_camera.rsnew file mode 100644index 000000000..e2e95ab27--- /dev/null+++ b/crates/recording/src/sources/native_camera.rs@@ -0,0 +1,146 @@+use crate::{+ feeds::camera::{self, CameraFeedLock},+ output_pipeline::{NativeCameraFrame, SetupCtx, VideoSource},+};+use anyhow::anyhow;+use cap_media_info::VideoInfo;+use futures::{FutureExt, channel::mpsc, future::BoxFuture};+use std::sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+};+use tokio::sync::oneshot;++pub struct NativeCamera {+ feed_lock: Arc<CameraFeedLock>,+ stop_tx: Option<oneshot::Sender<()>>,+ stopped: Arc<AtomicBool>,+}++impl VideoSource for NativeCamera {+ type Config = Arc<CameraFeedLock>;+ type Frame = NativeCameraFrame;++ async fn setup(+ feed_lock: Self::Config,+ video_tx: mpsc::Sender<Self::Frame>,+ _: &mut SetupCtx,+ ) -> anyhow::Result<Self>+ where+ Self: Sized,+ {+ let (tx, rx) = flume::bounded(256);++ feed_lock+ .ask(camera::AddNativeSender(tx))+ .await+ .map_err(|e| anyhow!("Failed to add native camera sender: {e}"))?;++ let (stop_tx, stop_rx) = oneshot::channel();+ let stopped = Arc::new(AtomicBool::new(false));+ let stopped_clone = stopped.clone();++ tokio::spawn(async move {+ tracing::debug!("Native camera source task started");+ let mut frame_count: u64 = 0;+ let mut sent_count: u64 = 0;+ let mut dropped_count: u64 = 0;+ let start = std::time::Instant::now();+ let mut video_tx = video_tx;+ let mut stop_rx = stop_rx.fuse();++ loop {+ if stopped_clone.load(Ordering::Relaxed) {+ tracing::debug!("Native camera source: stop flag set, exiting");+ break;+ }++ tokio::select! {+ biased;+ _ = &mut stop_rx => {+ tracing::debug!("Native camera source: received stop signal");+ break;+ }+ result = rx.recv_async() => {+ match result {+ Ok(frame) => {+ frame_count += 1;+ match video_tx.try_send(frame) {+ Ok(()) => {+ sent_count += 1;+ if sent_count % 30 == 0 {+ tracing::debug!(+ "Native camera source: sent {} frames, dropped {} in {:?}",+ sent_count,+ dropped_count,+ start.elapsed()+ );+ }+ }+ Err(e) => {+ if e.is_full() {+ dropped_count += 1;+ if dropped_count % 30 == 0 {+ tracing::warn!(+ "Native camera source: encoder can't keep up, dropped {} frames so far",+ dropped_count+ );+ }+ } else if e.is_disconnected() {+ tracing::debug!(+ "Native camera source: pipeline closed after {} sent, {} dropped",+ sent_count,+ dropped_count+ );+ break;+ }+ }+ }+ }+ Err(e) => {+ tracing::debug!(+ "Native camera feed disconnected (rx closed) after {} frames in {:?}: {e}",+ frame_count,+ start.elapsed()+ );+ break;+ }+ }+ }+ }+ }++ drop(video_tx);++ tracing::info!(+ "Native camera source finished: {} received, {} sent, {} dropped in {:?}",+ frame_count,+ sent_count,+ dropped_count,+ start.elapsed()+ );+ });++ Ok(Self {+ feed_lock,+ stop_tx: Some(stop_tx),+ stopped,+ })+ }++ fn video_info(&self) -> VideoInfo {+ *self.feed_lock.video_info()+ }++ fn stop(&mut self) -> BoxFuture<'_, anyhow::Result<()>> {+ async move {+ tracing::debug!("Native camera source: stopping");+ self.stopped.store(true, Ordering::SeqCst);+ if let Some(stop_tx) = self.stop_tx.take() {+ let _ = stop_tx.send(());+ }+ Ok(())+ }+ .boxed()+ }+}diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex 79a7b19c2..19e9bcbef 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -5,11 +5,17 @@ use crate::{},cursor::{CursorActor, Cursors, spawn_cursor_recorder},feeds::{camera::CameraFeedLock, microphone::MicrophoneFeedLock},- ffmpeg::{Mp4Muxer, OggMuxer},+ ffmpeg::OggMuxer,output_pipeline::{DoneFut, FinishedOutputPipeline, OutputPipeline, PipelineDoneError},screen_capture::ScreenCaptureConfig,sources::{self, screen_capture},};++#[cfg(target_os = "macos")]+use crate::output_pipeline::{AVFoundationCameraMuxer, AVFoundationCameraMuxerConfig};++#[cfg(windows)]+use crate::output_pipeline::{WindowsCameraMuxer, WindowsCameraMuxerConfig};use anyhow::{Context as _, anyhow, bail};use cap_media_info::VideoInfo;use cap_project::{CursorEvents, StudioRecordingMeta};@@ -824,11 +830,24 @@ async fn create_segment_pipeline(.await.context("screen pipeline setup")?;+ #[cfg(target_os = "macos")]+ let camera = OptionFuture::from(base_inputs.camera_feed.map(|camera_feed| {+ OutputPipeline::builder(dir.join("camera.mp4"))+ .with_video::<sources::NativeCamera>(camera_feed)+ .with_timestamps(start_time)+ .build::<AVFoundationCameraMuxer>(AVFoundationCameraMuxerConfig::default())+ .instrument(error_span!("camera-out"))+ }))+ .await+ .transpose()+ .context("camera pipeline setup")?;++ #[cfg(windows)]let camera = OptionFuture::from(base_inputs.camera_feed.map(|camera_feed| {OutputPipeline::builder(dir.join("camera.mp4"))- .with_video::<sources::Camera>(camera_feed)+ .with_video::<sources::NativeCamera>(camera_feed).with_timestamps(start_time)- .build::<Mp4Muxer>(())+ .build::<WindowsCameraMuxer>(WindowsCameraMuxerConfig::default()).instrument(error_span!("camera-out"))})).awaitdiff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rsindex 67831ae2c..c82e3c745 100644--- a/crates/rendering/src/layers/captions.rs+++ b/crates/rendering/src/layers/captions.rs@@ -113,7 +113,7 @@ fn wrap_text_by_words(text: &str, max_words: usize) -> String {if words.is_empty() {return String::new();}-+let mut result = String::new();for (i, word) in words.iter().enumerate() {if i > 0 {@@ -128,14 +128,19 @@ fn wrap_text_by_words(text: &str, max_words: usize) -> String {result}-fn calculate_bounce_offset(_fade_opacity: f32, time_from_start: f32, time_to_end: f32, fade_duration: f32) -> f32 {+fn calculate_bounce_offset(+ _fade_opacity: f32,+ time_from_start: f32,+ time_to_end: f32,+ fade_duration: f32,+) -> f32 {if fade_duration <= 0.0 {return 0.0;}-+let fade_in_progress = (time_from_start / fade_duration).clamp(0.0, 1.0);let fade_out_progress = (time_to_end / fade_duration).clamp(0.0, 1.0);-+if fade_in_progress < 1.0 {let ease = 1.0 - fade_in_progress;let bounce = ease * ease;@@ -305,7 +310,7 @@ impl CaptionsLayer {fn calculate_fade_opacity(&self, current_time: f32, fade_duration: f32) -> (f32, f32, f32) {let time_from_start = current_time - self.current_segment_start;let time_to_end = self.current_segment_end - current_time;-+if fade_duration <= 0.0 {return (1.0, time_from_start, time_to_end);}@@ -356,13 +361,15 @@ impl CaptionsLayer {let raw_caption_text = self.current_text.clone().unwrap_or_default();let caption_text = wrap_text_by_words(&raw_caption_text, MAX_WORDS_PER_LINE);let caption_words = current_caption.words.clone();- let (fade_opacity, time_from_start, time_to_end) = self.calculate_fade_opacity(current_time, fade_duration);+ let (fade_opacity, time_from_start, time_to_end) =+ self.calculate_fade_opacity(current_time, fade_duration);if fade_opacity <= 0.0 {self.current_text = None;return;}-- let bounce_offset = calculate_bounce_offset(fade_opacity, time_from_start, time_to_end, fade_duration);++ let bounce_offset =+ calculate_bounce_offset(fade_opacity, time_from_start, time_to_end, fade_duration);let (width, height) = (output_size.x, output_size.y);let device = &constants.device;@@ -550,7 +557,8 @@ impl CaptionsLayer {let center_y = height as f32 * position.y_factor();let base_background_top =(center_y - box_height / 2.0).clamp(0.0, (height as f32 - box_height).max(0.0));- let background_top = (base_background_top + bounce_offset).clamp(0.0, (height as f32 - box_height).max(0.0));+ let background_top =+ (base_background_top + bounce_offset).clamp(0.0, (height as f32 - box_height).max(0.0));let text_left = background_left + padding;let text_top = background_top + padding;