Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
feat(recording): refactor instant pipeline to segmented video output
Richie McIlroya0190db3e3f0
diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rsindex 71ed7f6de..8530350aa 100644--- a/crates/recording/src/capture_pipeline.rs+++ b/crates/recording/src/capture_pipeline.rs@@ -1,8 +1,6 @@use crate::{SharedPauseState,- feeds::microphone::MicrophoneFeedLock,output_pipeline::*,- sources,sources::screen_capture::{self, CropBounds, ScreenCaptureFormat, ScreenCaptureTarget},};@@ -13,8 +11,9 @@ use crate::output_pipeline::{WindowsFragmentedM4SMuxer, WindowsFragmentedM4SMuxeuse anyhow::anyhow;#[cfg(windows)]use cap_enc_ffmpeg::h264::H264Preset;+use cap_enc_ffmpeg::segmented_stream::SegmentCompletedEvent;use cap_timestamp::Timestamps;-use std::{path::PathBuf, sync::Arc};+use std::path::PathBuf;#[cfg(windows)]use std::sync::atomic::{AtomicBool, Ordering};@@ -62,14 +61,12 @@ pub trait MakeCapturePipeline: ScreenCaptureFormat + std::fmt::Debug + 'static {whereSelf: Sized;- async fn make_instant_mode_pipeline(+ async fn make_instant_segmented_video_pipeline(screen_capture: screen_capture::VideoSourceConfig,- system_audio: Option<screen_capture::SystemAudioSourceConfig>,- mic_feed: Option<Arc<MicrophoneFeedLock>>,- output_path: PathBuf,- output_resolution: (u32, u32),+ segments_dir: PathBuf,+ output_size: (u32, u32),start_time: Timestamps,- #[cfg(windows)] encoder_preferences: EncoderPreferences,+ segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,) -> anyhow::Result<OutputPipeline>whereSelf: Sized;@@ -114,30 +111,20 @@ impl MakeCapturePipeline for screen_capture::CMSampleBufferCapture {}}- async fn make_instant_mode_pipeline(+ async fn make_instant_segmented_video_pipeline(screen_capture: screen_capture::VideoSourceConfig,- system_audio: Option<screen_capture::SystemAudioSourceConfig>,- mic_feed: Option<Arc<MicrophoneFeedLock>>,- output_path: PathBuf,- output_resolution: (u32, u32),+ segments_dir: PathBuf,+ output_size: (u32, u32),start_time: Timestamps,+ segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,) -> anyhow::Result<OutputPipeline> {- let mut output = OutputPipeline::builder(output_path.clone())+ OutputPipeline::builder(segments_dir).with_video::<screen_capture::VideoSource>(screen_capture)- .with_timestamps(start_time);-- if let Some(system_audio) = system_audio {- output = output.with_audio_source::<screen_capture::SystemAudioSource>(system_audio);- }-- if let Some(mic_feed) = mic_feed {- output = output.with_audio_source::<sources::Microphone>(mic_feed);- }-- output- .build::<AVFoundationMp4Muxer>(AVFoundationMp4MuxerConfig {- output_height: Some(output_resolution.1),- instant_mode: true,+ .with_timestamps(start_time)+ .build::<MacOSFragmentedM4SMuxer>(MacOSFragmentedM4SMuxerConfig {+ output_size: Some(output_size),+ segment_tx,+ ..Default::default()}).await}@@ -193,42 +180,28 @@ impl MakeCapturePipeline for screen_capture::Direct3DCapture {}}- async fn make_instant_mode_pipeline(+ async fn make_instant_segmented_video_pipeline(screen_capture: screen_capture::VideoSourceConfig,- system_audio: Option<screen_capture::SystemAudioSourceConfig>,- mic_feed: Option<Arc<MicrophoneFeedLock>>,- output_path: PathBuf,- output_resolution: (u32, u32),+ segments_dir: PathBuf,+ output_size: (u32, u32),start_time: Timestamps,- encoder_preferences: EncoderPreferences,+ segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,) -> anyhow::Result<OutputPipeline> {- let d3d_device = screen_capture.d3d_device.clone();- let mut output_builder = OutputPipeline::builder(output_path.clone())- .with_video::<screen_capture::VideoSource>(screen_capture)- .with_timestamps(start_time);-- if let Some(mic_feed) = mic_feed {- output_builder = output_builder.with_audio_source::<sources::Microphone>(mic_feed);+ if segment_tx.is_some() {+ tracing::info!(+ "Segment upload channel not yet supported on Windows, using fragmented muxer fallback"+ );}-- if let Some(system_audio) = system_audio {- output_builder =- output_builder.with_audio_source::<screen_capture::SystemAudioSource>(system_audio);- }-- output_builder- .build::<WindowsMuxer>(WindowsMuxerConfig {- pixel_format: screen_capture::Direct3DCapture::PIXEL_FORMAT.as_dxgi(),- bitrate_multiplier: 0.055f32,- frame_rate: 30u32,- d3d_device,- output_size: Some(windows::Graphics::SizeInt32 {- Width: output_resolution.0 as i32,- Height: output_resolution.1 as i32,- }),- encoder_preferences,- fragmented: false,- frag_duration_us: 2_000_000,+ drop(segment_tx);+ OutputPipeline::builder(segments_dir)+ .with_video::<screen_capture::VideoSource>(screen_capture)+ .with_timestamps(start_time)+ .build::<WindowsFragmentedM4SMuxer>(WindowsFragmentedM4SMuxerConfig {+ segment_duration: std::time::Duration::from_secs(3),+ preset: H264Preset::Ultrafast,+ output_size: Some(output_size),+ shared_pause_state: None,+ disk_space_callback: None,}).await}diff --git a/crates/recording/src/feeds/camera.rs b/crates/recording/src/feeds/camera.rsindex 32e30bf42..b266035d8 100644--- a/crates/recording/src/feeds/camera.rs+++ b/crates/recording/src/feeds/camera.rs@@ -12,7 +12,10 @@ use replace_with::replace_with_or_abort;use std::{cmp::Ordering,ops::Deref,- sync::mpsc::{self, SyncSender},+ sync::{+ Arc, Weak,+ mpsc::{self, SyncSender},+ },time::Duration,};use tokio::{runtime::Runtime, sync::oneshot, task::LocalSet};@@ -25,6 +28,7 @@ const CAMERA_INIT_TIMEOUT: Duration = Duration::from_secs(4);#[derive(Actor)]pub struct CameraFeed {+ lock_generation: u64,state: State,senders: Vec<flume::Sender<FFmpegVideoFrame>>,native_senders: Vec<flume::Sender<NativeCameraFrame>>,@@ -34,11 +38,30 @@ pub struct CameraFeed {enum State {Open(OpenState),- Locked { inner: AttachedState },+ Locked {+ inner: AttachedState,+ token: Weak<()>,+ },}impl State {fn try_as_open(&mut self) -> Result<&mut OpenState, FeedLockedError> {+ let is_stale = matches!(self, Self::Locked { token, .. } if token.strong_count() == 0);++ if is_stale {+ warn!("Detected stale camera feed lock, auto-recovering");+ replace_with_or_abort(self, |state| {+ if let Self::Locked { inner, .. } = state {+ Self::Open(OpenState {+ connecting: None,+ attached: Some(inner),+ })+ } else {+ state+ }+ });+ }+if let Self::Open(open_state) = self {Ok(open_state)} else {@@ -136,6 +159,7 @@ impl AttachedState {impl Default for CameraFeed {fn default() -> Self {Self {+ lock_generation: 0,state: State::Open(OpenState {connecting: None,attached: None,@@ -154,6 +178,7 @@ pub struct CameraFeedLock {camera_info: cap_camera::CameraInfo,video_info: VideoInfo,drop_tx: Option<oneshot::Sender<()>>,+ _token: Arc<()>,}impl CameraFeedLock {@@ -246,7 +271,9 @@ struct NewFrame(FFmpegVideoFrame);struct NewNativeFrame(NativeCameraFrame);-struct Unlock;+struct Unlock {+ generation: u64,+}struct FinalizePendingRelease {id: DeviceOrModelID,@@ -664,7 +691,7 @@ impl Message<SetInput> for CameraFeed {.map(|v| v.map(|v| (v.camera_info, v.video_info))).boxed())}- State::Locked { inner } => {+ State::Locked { inner, .. } => {if inner.id != msg.id {return Err(SetInputError::Locked(FeedLockedError));}@@ -933,14 +960,22 @@ impl Message<Lock> for CameraFeed {let camera_info = attached.camera_info.clone();let video_info = attached.video_info;- self.state = State::Locked { inner: attached };+ self.lock_generation += 1;+ let generation = self.lock_generation;+ let token = Arc::new(());+ let token_weak = Arc::downgrade(&token);++ self.state = State::Locked {+ inner: attached,+ token: token_weak,+ };let (drop_tx, drop_rx) = oneshot::channel();let actor_ref = ctx.actor_ref();tokio::spawn(async move {let _ = drop_rx.await;- let _ = actor_ref.tell(Unlock).await;+ let _ = actor_ref.tell(Unlock { generation }).await;});Ok(CameraFeedLock {@@ -948,6 +983,7 @@ impl Message<Lock> for CameraFeed {video_info,actor: ctx.actor_ref(),drop_tx: Some(drop_tx),+ _token: token,})}}@@ -1019,7 +1055,7 @@ impl Message<LockedCameraInputReconnected> for CameraFeed {msg: LockedCameraInputReconnected,_: &mut Context<Self, Self::Reply>,) -> Self::Reply {- if let State::Locked { inner } = &mut self.state+ if let State::Locked { inner, .. } = &mut self.state&& inner.id == msg.id{inner.stage_pending_release();@@ -1054,7 +1090,7 @@ impl Message<FinalizePendingRelease> for CameraFeed {attached.finalize_pending_release();}}- State::Locked { inner } => {+ State::Locked { inner, .. } => {if inner.id == msg.id {inner.finalize_pending_release();}@@ -1066,11 +1102,19 @@ impl Message<FinalizePendingRelease> for CameraFeed {impl Message<Unlock> for CameraFeed {type Reply = ();- async fn handle(&mut self, _: Unlock, _: &mut Context<Self, Self::Reply>) -> Self::Reply {- trace!("CameraFeed.Unlock");+ async fn handle(&mut self, msg: Unlock, _: &mut Context<Self, Self::Reply>) -> Self::Reply {+ trace!("CameraFeed.Unlock(gen={})", msg.generation);++ if msg.generation != self.lock_generation {+ trace!(+ "Ignoring stale camera unlock (msg gen {} != current {})",+ msg.generation, self.lock_generation+ );+ return;+ }replace_with_or_abort(&mut self.state, |state| {- if let State::Locked { inner } = state {+ if let State::Locked { inner, .. } = state {State::Open(OpenState {connecting: None,attached: Some(inner),diff --git a/crates/recording/src/feeds/microphone.rs b/crates/recording/src/feeds/microphone.rsindex 0a16bb106..29a823090 100644--- a/crates/recording/src/feeds/microphone.rs+++ b/crates/recording/src/feeds/microphone.rs@@ -13,7 +13,10 @@ use kameo::prelude::*;use replace_with::replace_with_or_abort;use std::{ops::Deref,- sync::mpsc::{self, SyncSender},+ sync::{+ Arc, Weak,+ mpsc::{self, SyncSender},+ },};use tracing::{debug, error, info, trace, warn};@@ -34,6 +37,7 @@ pub struct MicrophoneSamples {#[derive(Actor)]pub struct MicrophoneFeed {input_id_counter: u32,+ lock_generation: u64,state: State,senders: Vec<flume::Sender<MicrophoneSamples>>,error_sender: flume::Sender<StreamError>,@@ -41,11 +45,30 @@ pub struct MicrophoneFeed {enum State {Open(OpenState),- Locked { inner: AttachedState },+ Locked {+ inner: AttachedState,+ token: Weak<()>,+ },}impl State {fn try_as_open(&mut self) -> Result<&mut OpenState, FeedLockedError> {+ let is_stale = matches!(self, Self::Locked { token, .. } if token.strong_count() == 0);++ if is_stale {+ warn!("Detected stale microphone feed lock, auto-recovering");+ replace_with_or_abort(self, |state| {+ if let Self::Locked { inner, .. } = state {+ Self::Open(OpenState {+ connecting: None,+ attached: Some(inner),+ })+ } else {+ state+ }+ });+ }+if let Self::Open(open_state) = self {Ok(open_state)} else {@@ -93,6 +116,7 @@ impl MicrophoneFeed {pub fn new(error_sender: flume::Sender<StreamError>) -> Self {Self {input_id_counter: 0,+ lock_generation: 0,state: State::Open(OpenState {connecting: None,attached: None,@@ -400,6 +424,7 @@ pub struct MicrophoneFeedLock {buffer_size_frames: Option<u32>,drop_tx: Option<oneshot::Sender<()>>,device_name: String,+ _token: Arc<()>,}impl MicrophoneFeedLock {@@ -470,7 +495,9 @@ struct InputConnectFailed {id: u32,}-struct Unlock;+struct Unlock {+ generation: u64,+}#[derive(Clone, Copy)]enum StreamLogAction {@@ -612,7 +639,7 @@ impl Message<SetInput> for MicrophoneFeed {Ok(ready_for_return)}- State::Locked { inner } => {+ State::Locked { inner, .. } => {if inner.label != msg.label {return Err(SetInputError::Locked(FeedLockedError));}@@ -759,14 +786,22 @@ impl Message<Lock> for MicrophoneFeed {let buffer_size_frames = attached.buffer_size_frames;let device_name = attached.label.clone();- self.state = State::Locked { inner: attached };+ self.lock_generation += 1;+ let generation = self.lock_generation;+ let token = Arc::new(());+ let token_weak = Arc::downgrade(&token);++ self.state = State::Locked {+ inner: attached,+ token: token_weak,+ };let (drop_tx, drop_rx) = oneshot::channel();let actor_ref = ctx.actor_ref();tokio::spawn(async move {let _ = drop_rx.await;- let _ = actor_ref.tell(Unlock).await;+ let _ = actor_ref.tell(Unlock { generation }).await;});let latency_info = estimate_input_latency(@@ -784,6 +819,7 @@ impl Message<Lock> for MicrophoneFeed {buffer_size_frames,drop_tx: Some(drop_tx),device_name,+ _token: token,})}}@@ -836,7 +872,7 @@ impl Message<LockedInputReconnected> for MicrophoneFeed {msg: LockedInputReconnected,_: &mut Context<Self, Self::Reply>,) -> Self::Reply {- if let State::Locked { inner } = &mut self.state+ if let State::Locked { inner, .. } = &mut self.state&& inner.label == msg.label{inner.id = msg.id;@@ -850,11 +886,19 @@ impl Message<LockedInputReconnected> for MicrophoneFeed {impl Message<Unlock> for MicrophoneFeed {type Reply = ();- async fn handle(&mut self, _: Unlock, _: &mut Context<Self, Self::Reply>) -> Self::Reply {- trace!("MicrophoneFeed.Unlock");+ async fn handle(&mut self, msg: Unlock, _: &mut Context<Self, Self::Reply>) -> Self::Reply {+ trace!("MicrophoneFeed.Unlock(gen={})", msg.generation);++ if msg.generation != self.lock_generation {+ trace!(+ "Ignoring stale microphone unlock (msg gen {} != current {})",+ msg.generation, self.lock_generation+ );+ return;+ }replace_with_or_abort(&mut self.state, |state| {- if let State::Locked { inner } = state {+ if let State::Locked { inner, .. } = state {State::Open(OpenState {connecting: None,attached: Some(inner),diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rsindex 10de143ff..3ed2fe206 100644--- a/crates/recording/src/instant_recording.rs+++ b/crates/recording/src/instant_recording.rs@@ -11,7 +11,7 @@ use crate::{sources::screen_capture::{ScreenCaptureConfig, ScreenCaptureTarget},};use anyhow::Context as _;-use cap_media_info::{AudioInfo, VideoInfo};+use cap_media_info::VideoInfo;use cap_project::InstantRecordingMeta;use cap_timestamp::Timestamps;use cap_utils::ensure_dir;@@ -24,8 +24,13 @@ use std::{use tracing::*;struct Pipeline {- output: OutputPipeline,+ video: OutputPipeline,+ audio: Option<OutputPipeline>,video_info: VideoInfo,+ segments_dir: PathBuf,+ audio_path: Option<PathBuf>,+ segment_rx:+ Option<std::sync::mpsc::Receiver<cap_enc_ffmpeg::segmented_stream::SegmentCompletedEvent>>,}enum ActorState {@@ -47,6 +52,13 @@ pub struct ActorHandle {pub capture_target: ScreenCaptureTarget,done_fut: output_pipeline::DoneFut,health_rx: Option<output_pipeline::HealthReceiver>,+ segment_rx: Option<+ std::sync::Mutex<+ Option<+ std::sync::mpsc::Receiver<cap_enc_ffmpeg::segmented_stream::SegmentCompletedEvent>,+ >,+ >,+ >,}impl ActorHandle {@@ -77,6 +89,15 @@ impl ActorHandle {pub async fn is_paused(&self) -> anyhow::Result<bool> {Ok(self.actor_ref.ask(IsPaused).await?)}++ pub fn take_segment_rx(+ &self,+ ) -> Option<std::sync::mpsc::Receiver<cap_enc_ffmpeg::segmented_stream::SegmentCompletedEvent>>+ {+ self.segment_rx+ .as_ref()+ .and_then(|m| m.lock().ok().and_then(|mut guard| guard.take()))+ }}impl Drop for ActorHandle {@@ -94,6 +115,8 @@ pub struct Actor {capture_target: ScreenCaptureTarget,video_info: VideoInfo,state: ActorState,+ total_pause_duration: std::time::Duration,+ pause_started_at: Option<f64>,}impl Actor {@@ -110,7 +133,12 @@ impl Actor {});if let Some(pipeline) = pipeline {- pipeline.output.stop().await?;+ if let Some(audio) = pipeline.audio+ && let Err(e) = audio.stop().await+ {+ warn!("Audio pipeline stop failed (video continues): {e:#}");+ }+ pipeline.video.stop().await?;}Ok(())@@ -121,8 +149,87 @@ impl Message<Stop> for Actor {type Reply = anyhow::Result<CompletedRecording>;async fn handle(&mut self, _: Stop, _: &mut Context<Self, Self::Reply>) -> Self::Reply {+ if matches!(self.state, ActorState::Stopped) {+ return Err(anyhow::anyhow!("Recording already stopped"));+ }++ if let Some(pause_start) = self.pause_started_at.take() {+ let pause_elapsed = current_time_f64() - pause_start;+ if pause_elapsed > 0.0 {+ self.total_pause_duration += std::time::Duration::from_secs_f64(pause_elapsed);+ }+ }++ let (wall_clock_duration, segments_dir, audio_path) =+ replace_with::replace_with_or_abort_and_return(&mut self.state, |state| {+ let result = match &state {+ ActorState::Recording {+ pipeline,+ segment_start_time,+ ..+ }+ | ActorState::Paused {+ pipeline,+ segment_start_time,+ ..+ } => {+ let dur = std::time::Duration::from_secs_f64(+ current_time_f64() - segment_start_time,+ );+ (+ dur,+ pipeline.segments_dir.clone(),+ pipeline.audio_path.clone(),+ )+ }+ ActorState::Stopped => (+ std::time::Duration::ZERO,+ self.recording_dir.join("content").join("display"),+ None,+ ),+ };+ (result, state)+ });+ let wall_clock_duration = wall_clock_duration.saturating_sub(self.total_pause_duration);+self.stop().await?;+ let output_path = self.recording_dir.join("content").join("output.mp4");++ let health = tokio::task::spawn_blocking(move || {+ let assembly_result =+ assemble_canonical_mp4(&segments_dir, audio_path.as_deref(), &output_path);++ match assembly_result {+ Ok(()) => {+ let validation = crate::output_validation::validate_instant_recording(+ &output_path,+ wall_clock_duration,+ );+ match &validation.health {+ crate::RecordingHealth::Healthy => {+ debug!("Instant recording output validated as healthy");+ }+ crate::RecordingHealth::Degraded { issues } => {+ warn!(?issues, "Instant recording output has quality issues");+ }+ _ => {}+ }+ validation.health+ }+ Err(e) => {+ error!("Failed to assemble canonical MP4: {e:#}");+ crate::RecordingHealth::Damaged {+ reason: format!("Segment assembly failed: {e}"),+ }+ }+ }+ })+ .await+ .unwrap_or_else(|e| crate::RecordingHealth::Damaged {+ reason: format!("Assembly task panicked: {e}"),+ });+Ok(CompletedRecording {project_path: self.recording_dir.clone(),meta: InstantRecordingMeta::Complete {@@ -130,6 +237,7 @@ impl Message<Stop> for Actor {sample_rate: None,},display_source: self.capture_target.clone(),+ health,})}}@@ -140,13 +248,17 @@ impl Message<Pause> for Actor {type Reply = ();async fn handle(&mut self, _: Pause, _: &mut Context<Self, Self::Reply>) -> Self::Reply {+ self.pause_started_at = Some(current_time_f64());replace_with::replace_with_or_abort(&mut self.state, |state| {if let ActorState::Recording {pipeline,segment_start_time,} = state{- pipeline.output.pause();+ pipeline.video.pause();+ if let Some(ref audio) = pipeline.audio {+ audio.pause();+ }return ActorState::Paused {pipeline,segment_start_time,@@ -164,13 +276,22 @@ impl Message<Resume> for Actor {type Reply = ();async fn handle(&mut self, _: Resume, _: &mut Context<Self, Self::Reply>) -> Self::Reply {+ if let Some(pause_start) = self.pause_started_at.take() {+ let pause_elapsed = current_time_f64() - pause_start;+ if pause_elapsed > 0.0 {+ self.total_pause_duration += std::time::Duration::from_secs_f64(pause_elapsed);+ }+ }replace_with::replace_with_or_abort(&mut self.state, |state| {if let ActorState::Paused {pipeline,segment_start_time,} = state{- pipeline.output.resume();+ pipeline.video.resume();+ if let Some(ref audio) = pipeline.audio {+ audio.resume();+ }return ActorState::Recording {pipeline,segment_start_time,@@ -209,24 +330,176 @@ pub struct CompletedRecording {pub project_path: PathBuf,pub display_source: ScreenCaptureTarget,pub meta: InstantRecordingMeta,+ pub health: crate::RecordingHealth,+}++fn assemble_canonical_mp4(+ segments_dir: &std::path::Path,+ audio_path: Option<&std::path::Path>,+ output_path: &std::path::Path,+) -> anyhow::Result<()> {+ use cap_enc_ffmpeg::remux::{+ concatenate_m4s_segments_with_init, merge_video_audio, probe_media_valid,+ };++ let init_path = segments_dir.join("init.mp4");+ if !init_path.exists() {+ return Err(anyhow::anyhow!(+ "Video init segment not found at {}",+ init_path.display()+ ));+ }++ let manifest_path = segments_dir.join("manifest.json");+ let segment_paths = if manifest_path.exists() {+ read_segment_paths_from_manifest(&manifest_path, segments_dir)?+ } else {+ discover_segment_files(segments_dir)?+ };++ if segment_paths.is_empty() {+ return Err(anyhow::anyhow!(+ "No video segments found in {}",+ segments_dir.display()+ ));+ }++ info!(+ segment_count = segment_paths.len(),+ segments_dir = %segments_dir.display(),+ has_audio = audio_path.is_some(),+ "Assembling canonical MP4 from segments"+ );++ let video_only_path = if audio_path.is_some() {+ output_path.with_extension("video_only.mp4")+ } else {+ output_path.to_path_buf()+ };++ concatenate_m4s_segments_with_init(&init_path, &segment_paths, &video_only_path)+ .map_err(|e| anyhow::anyhow!("Video segment concatenation failed: {e}"))?;++ let resolved_audio = audio_path.and_then(|audio| {+ if audio.is_file() && probe_media_valid(audio) {+ return Some(audio.to_path_buf());+ }++ if audio.is_dir() {+ let audio_init = audio.join("init.mp4");+ if !audio_init.exists() {+ warn!(+ "Audio init segment not found at {}, skipping audio",+ audio_init.display()+ );+ return None;+ }++ let audio_manifest = audio.join("manifest.json");+ let audio_segments = if audio_manifest.exists() {+ read_segment_paths_from_manifest(&audio_manifest, audio).ok()+ } else {+ discover_segment_files(audio).ok()+ };++ if let Some(segments) = audio_segments+ && !segments.is_empty()+ {+ let assembled_audio = output_path.with_extension("audio_assembled.m4a");+ match concatenate_m4s_segments_with_init(&audio_init, &segments, &assembled_audio) {+ Ok(()) => {+ if probe_media_valid(&assembled_audio) {+ return Some(assembled_audio);+ }+ warn!("Assembled audio file is not valid, skipping audio");+ let _ = std::fs::remove_file(&assembled_audio);+ }+ Err(e) => {+ warn!("Failed to assemble audio segments: {e}");+ }+ }+ }+ }++ None+ });++ if let Some(ref audio_file) = resolved_audio {+ let merge_result = merge_video_audio(&video_only_path, audio_file, output_path);+ let _ = std::fs::remove_file(&video_only_path);+ if audio_file != audio_path.unwrap_or(audio_file.as_path()) {+ let _ = std::fs::remove_file(audio_file);+ }+ merge_result.map_err(|e| anyhow::anyhow!("Audio/video merge failed: {e}"))?;+ } else if audio_path.is_some() {+ if video_only_path != output_path {+ std::fs::rename(&video_only_path, output_path)?;+ }+ warn!("Audio file missing or invalid, output will be video-only");+ }++ info!(output = %output_path.display(), "Canonical MP4 assembled");+ Ok(())+}++fn read_segment_paths_from_manifest(+ manifest_path: &std::path::Path,+ base_dir: &std::path::Path,+) -> anyhow::Result<Vec<PathBuf>> {+ let manifest_text = std::fs::read_to_string(manifest_path)?;+ let manifest: serde_json::Value = serde_json::from_str(&manifest_text)?;++ let segments = manifest+ .get("segments")+ .and_then(|v| v.as_array())+ .ok_or_else(|| anyhow::anyhow!("Invalid manifest: no segments array"))?;++ let mut paths = Vec::new();+ for seg in segments {+ let is_complete = seg+ .get("is_complete")+ .and_then(|v| v.as_bool())+ .unwrap_or(false);+ if !is_complete {+ continue;+ }+ if let Some(path_str) = seg.get("path").and_then(|v| v.as_str()) {+ let full_path = base_dir.join(path_str);+ if full_path.exists() {+ paths.push(full_path);+ }+ }+ }++ Ok(paths)+}++fn discover_segment_files(segments_dir: &std::path::Path) -> anyhow::Result<Vec<PathBuf>> {+ let mut segments: Vec<PathBuf> = std::fs::read_dir(segments_dir)?+ .filter_map(|entry| {+ let entry = entry.ok()?;+ let path = entry.path();+ if path.extension().is_some_and(|ext| ext == "m4s") {+ Some(path)+ } else {+ None+ }+ })+ .collect();++ segments.sort();+ Ok(segments)}async fn create_pipeline(- output_path: PathBuf,- screen_source: ScreenCaptureConfig<ScreenCaptureMethod>,+ content_dir: PathBuf,+ screen_capture: crate::sources::screen_capture::VideoSourceConfig,+ screen_info: cap_media_info::VideoInfo,mic_feed: Option<Arc<MicrophoneFeedLock>>,+ system_audio_source: Option<crate::sources::screen_capture::SystemAudioSourceConfig>,max_output_size: Option<u32>,start_time: Timestamps,) -> anyhow::Result<Pipeline> {- if let Some(mic_feed) = &mic_feed {- debug!(- "mic audio info: {:#?}",- AudioInfo::from_stream_config(mic_feed.config())- );- };-- let screen_info = screen_source.info();-let output_resolution = max_output_size.map(|max_output_size| {clamp_size(@@ -244,28 +517,78 @@ async fn create_pipeline()});- let (screen_capture, system_audio) = screen_source.to_sources().await?;+ let segments_dir = content_dir.join("display");++ #[cfg(target_os = "macos")]+ let segment_channel = {+ let (tx, rx) =+ std::sync::mpsc::channel::<cap_enc_ffmpeg::segmented_stream::SegmentCompletedEvent>();+ Some((tx, rx))+ };+ #[cfg(not(target_os = "macos"))]+ let segment_channel: Option<(+ std::sync::mpsc::Sender<cap_enc_ffmpeg::segmented_stream::SegmentCompletedEvent>,+ std::sync::mpsc::Receiver<cap_enc_ffmpeg::segmented_stream::SegmentCompletedEvent>,+ )> = None;++ let segment_tx_for_video = segment_channel.as_ref().map(|(tx, _)| tx.clone());- let output = ScreenCaptureMethod::make_instant_mode_pipeline(+ let video = ScreenCaptureMethod::make_instant_segmented_video_pipeline(screen_capture,- system_audio,- mic_feed,- output_path.clone(),+ segments_dir.clone(),output_resolution,start_time,- #[cfg(windows)]- crate::capture_pipeline::EncoderPreferences::new(),+ segment_tx_for_video,).await?;+ let has_audio = mic_feed.is_some() || system_audio_source.is_some();+ let (audio, audio_path) = if has_audio {+ let audio_dir = content_dir.join("audio");+ let mut builder =+ output_pipeline::OutputPipeline::builder(audio_dir.clone()).with_timestamps(start_time);++ if let Some(sys_audio) = system_audio_source {+ builder = builder+ .with_audio_source::<crate::sources::screen_capture::SystemAudioSource>(sys_audio);+ }++ if let Some(mic) = mic_feed {+ builder = builder.with_audio_source::<crate::sources::Microphone>(mic);+ }++ let segment_tx_for_audio = segment_channel.as_ref().map(|(tx, _)| tx.clone());++ let audio_pipeline = builder+ .build::<output_pipeline::DashSegmentedAudioMuxer>(+ output_pipeline::DashSegmentedAudioMuxerConfig {+ shared_pause_state: None,+ segment_tx: segment_tx_for_audio,+ ..Default::default()+ },+ )+ .await+ .context("audio pipeline setup")?;++ (Some(audio_pipeline), Some(audio_dir))+ } else {+ (None, None)+ };++ let segment_rx = segment_channel.map(|(_, rx)| rx);+Ok(Pipeline {- output,+ video,+ audio,video_info: VideoInfo::from_raw_ffmpeg(screen_info.pixel_format,output_resolution.0,output_resolution.1,screen_info.fps(),),+ segments_dir,+ audio_path,+ segment_rx,})}@@ -390,7 +713,7 @@ pub async fn spawn_instant_recording_actor(}#[cfg(target_os = "macos")]- let pipeline = builder+ let cam_pipeline = builder.build::<output_pipeline::AVFoundationCameraMuxer>(output_pipeline::AVFoundationCameraMuxerConfig::default(),)@@ -398,7 +721,7 @@ pub async fn spawn_instant_recording_actor(.context("camera-only pipeline setup")?;#[cfg(windows)]- let pipeline = builder+ let cam_pipeline = builder.build::<output_pipeline::WindowsCameraMuxer>(output_pipeline::WindowsCameraMuxerConfig {encoder_preferences: crate::capture_pipeline::EncoderPreferences::default(),@@ -411,8 +734,12 @@ pub async fn spawn_instant_recording_actor(let video_info = *camera_feed.video_info();(Pipeline {- output: pipeline,+ video: cam_pipeline,+ audio: None,video_info,+ segments_dir: content_dir.clone(),+ audio_path: None,+ segment_rx: None,},video_info,)@@ -446,10 +773,15 @@ pub async fn spawn_instant_recording_actor(debug!("screen capture: {screen_source:#?}");+ let screen_info = screen_source.info();+ let (screen_capture, system_audio_source) = screen_source.to_sources().await?;+let pipeline = create_pipeline(- content_dir.join("output.mp4"),- screen_source.clone(),+ content_dir.clone(),+ screen_capture,+ screen_info,inputs.mic_feed.clone(),+ system_audio_source,max_output_size,timestamps,)@@ -465,8 +797,9 @@ pub async fn spawn_instant_recording_actor(trace!("spawning recording actor");- let done_fut = pipeline.output.done_fut();- let health_rx = pipeline.output.take_health_rx();+ let segment_rx = pipeline.segment_rx.take();+ let done_fut = pipeline.video.done_fut();+ let health_rx = pipeline.video.take_health_rx();let actor_ref = Actor::spawn(Actor {recording_dir,capture_target: inputs.capture_target.clone(),@@ -475,6 +808,8 @@ pub async fn spawn_instant_recording_actor(pipeline,segment_start_time,},+ total_pause_duration: std::time::Duration::ZERO,+ pause_started_at: None,});let actor_handle = ActorHandle {@@ -482,6 +817,7 @@ pub async fn spawn_instant_recording_actor(capture_target: inputs.capture_target,done_fut: done_fut.clone(),health_rx,+ segment_rx: segment_rx.map(|rx| std::sync::Mutex::new(Some(rx))),};tokio::spawn(async move {diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rsindex 38a9deda2..aab227022 100644--- a/crates/recording/src/lib.rs+++ b/crates/recording/src/lib.rs@@ -6,6 +6,7 @@ pub mod feeds;pub mod fragmentation;pub mod instant_recording;mod output_pipeline;+pub mod output_validation;pub mod recovery;mod resolution_limits;pub mod screenshot;@@ -132,3 +133,21 @@ pub enum RecordingError {#[error("IO/{0}")]Io(#[from] std::io::Error),}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(tag = "status", rename_all = "camelCase")]+pub enum RecordingHealth {+ Healthy,+ Repaired { original_issue: String },+ Degraded { issues: Vec<String> },+ Damaged { reason: String },+}++impl RecordingHealth {+ pub fn is_uploadable(&self) -> bool {+ matches!(+ self,+ Self::Healthy | Self::Repaired { .. } | Self::Degraded { .. }+ )+ }+}diff --git a/crates/recording/src/output_pipeline/core.rs b/crates/recording/src/output_pipeline/core.rsindex db8c5aea5..83e1b2120 100644--- a/crates/recording/src/output_pipeline/core.rs+++ b/crates/recording/src/output_pipeline/core.rs@@ -73,6 +73,7 @@ pub(crate) fn spawn_blocking_thread_timeout_cleanup(pub enum PipelineHealthEvent {FrameDropRateHigh { rate_pct: f64 },AudioGapDetected { gap_ms: u64 },+ AudioDegradedToVideoOnly { reason: String },SourceRestarting,SourceRestarted,}@@ -122,21 +123,8 @@ pub(crate) fn combine_finish_errors(anyhow!("{primary:#}; {secondary:#}")}-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-enum MuxStreamKind {- Video,- Audio,-}--fn mux_send_error(kind: MuxStreamKind, frame_count: u64, error: anyhow::Error) -> anyhow::Error {- match kind {- MuxStreamKind::Video => {- anyhow!("Video muxer stopped accepting frames at frame {frame_count}: {error}")- }- MuxStreamKind::Audio => {- anyhow!("Audio muxer stopped accepting frames at frame {frame_count}: {error}")- }- }+fn video_mux_send_error(frame_count: u64, error: anyhow::Error) -> anyhow::Error {+ anyhow!("Video muxer stopped accepting frames at frame {frame_count}: {error}")}struct AudioTimestampGenerator {@@ -956,6 +944,7 @@ impl<TVideo: VideoSource> OutputPipelineBuilder<HasVideo<TVideo>> {None,&path,shared_pause,+ true,).await?;@@ -1025,6 +1014,7 @@ impl OutputPipelineBuilder<NoVideo> {Some(first_tx),&path,shared_pause,+ false,).await?;@@ -1087,6 +1077,7 @@ async fn finish_build(first_tx: Option<oneshot::Sender<Timestamp>>,path: &Path,shared_pause: SharedWallClockPause,+ has_video: bool,) -> anyhow::Result<()> {if let Some(audio) = audio {audio.configure(@@ -1096,6 +1087,7 @@ async fn finish_build(timestamps,first_tx,shared_pause,+ has_video,);}@@ -1167,19 +1159,19 @@ async fn setup_muxer<TMuxer: Muxer>(pause_flag: &Arc<AtomicBool>,setup_ctx: &mut SetupCtx,) -> Result<Arc<Mutex<TMuxer>>, anyhow::Error> {- let muxer = Arc::new(Mutex::new(- TMuxer::setup(- muxer_config,- path.to_path_buf(),- video_info,- audio_info,- pause_flag.clone(),- &mut setup_ctx.tasks,- )- .await?,- ));+ let mut muxer = TMuxer::setup(+ muxer_config,+ path.to_path_buf(),+ video_info,+ audio_info,+ pause_flag.clone(),+ &mut setup_ctx.tasks,+ )+ .await?;- Ok(muxer)+ muxer.set_health_sender(setup_ctx.health_tx().clone());++ Ok(Arc::new(Mutex::new(muxer)))}#[allow(clippy::too_many_arguments)]@@ -1277,7 +1269,7 @@ fn spawn_video_encoder<TMutex: VideoMuxer<VideoFrame = TVideo::Frame>, TVideo: V}if let Err(e) = muxer.lock().await.send_video_frame(frame, duration) {- return Err(mux_send_error(MuxStreamKind::Video, frame_count, e));+ return Err(video_mux_send_error(frame_count, e));}}@@ -1395,6 +1387,7 @@ struct PreparedAudioSources {}impl PreparedAudioSources {+ #[allow(clippy::too_many_arguments)]pub fn configure<TMutex: AudioMuxer>(mut self,setup_ctx: &mut SetupCtx,@@ -1403,6 +1396,7 @@ impl PreparedAudioSources {_timestamps: Timestamps,mut first_tx: Option<oneshot::Sender<Timestamp>>,shared_pause: SharedWallClockPause,+ has_video: bool,) {let sample_rate = self.audio_info.sample_rate;let audio_info = self.audio_info;@@ -1470,10 +1464,23 @@ impl PreparedAudioSources {.await.send_audio_frame(silence_frame, sample_based_before){- return Err(mux_send_error(- MuxStreamKind::Audio,- frame_count,- e,+ if has_video {+ warn!(+ frame_count,+ "Audio muxer rejected silence frame, \+ degrading to video-only: {e}"+ );+ emit_health(+ &health_tx,+ PipelineHealthEvent::AudioDegradedToVideoOnly {+ reason: format!("Silence frame rejected at frame {frame_count}: {e}"),+ },+ );+ break;+ }+ return Err(anyhow!(+ "Audio muxer stopped accepting frames \+ at frame {frame_count}: {e}"));}}@@ -1501,7 +1508,24 @@ impl PreparedAudioSources {}if let Err(e) = muxer.lock().await.send_audio_frame(frame, timestamp) {- return Err(mux_send_error(MuxStreamKind::Audio, frame_count, e));+ if has_video {+ warn!(+ frame_count,+ "Audio muxer rejected frame, \+ degrading to video-only: {e}"+ );+ emit_health(+ &health_tx,+ PipelineHealthEvent::AudioDegradedToVideoOnly {+ reason: format!("Frame rejected at frame {frame_count}: {e}"),+ },+ );+ break;+ }+ return Err(anyhow!(+ "Audio muxer stopped accepting frames \+ at frame {frame_count}: {e}"+ ));}}Ok::<(), anyhow::Error>(())@@ -1530,10 +1554,16 @@ impl PreparedAudioSources {let _ = (source.stop_fn)(source.inner.as_mut()).await;}- muxer.lock().await.stop();+ if !has_video {+ muxer.lock().await.stop();+ }if let Some(Err(e)) = res {- return Err(e);+ if has_video {+ error!("Audio stream ended with error (video continues): {e:#}");+ } else {+ return Err(e);+ }}Ok(())@@ -1884,6 +1914,8 @@ pub trait Muxer: Send + 'static {fn stop(&mut self) {}fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>>;++ fn set_health_sender(&mut self, _tx: HealthSender) {}}pub trait AudioMuxer: Muxer {@@ -2442,11 +2474,14 @@ mod tests {#[derive(Clone, Copy)]struct FailingVideoMuxerConfig {fail_after_frame: u64,+ fail_audio_after_frame: u64,}struct FailingVideoMuxer {fail_after_frame: u64,- sent_frames: u64,+ fail_audio_after_frame: u64,+ sent_video_frames: u64,+ sent_audio_frames: u64,}impl Muxer for FailingVideoMuxer {@@ -2465,7 +2500,9 @@ mod tests {{Ok(Self {fail_after_frame: config.fail_after_frame,- sent_frames: 0,+ fail_audio_after_frame: config.fail_audio_after_frame,+ sent_video_frames: 0,+ sent_audio_frames: 0,})}@@ -2480,6 +2517,10 @@ mod tests {_frame: AudioFrame,_timestamp: Duration,) -> anyhow::Result<()> {+ self.sent_audio_frames += 1;+ if self.sent_audio_frames >= self.fail_audio_after_frame {+ return Err(anyhow!("audio mux send failed"));+ }Ok(())}}@@ -2492,8 +2533,8 @@ mod tests {_frame: Self::VideoFrame,_timestamp: Duration,) -> anyhow::Result<()> {- self.sent_frames += 1;- if self.sent_frames >= self.fail_after_frame {+ self.sent_video_frames += 1;+ if self.sent_video_frames >= self.fail_after_frame {return Err(anyhow!("video mux send failed"));}Ok(())@@ -2574,6 +2615,7 @@ mod tests {.with_timestamps(timestamps).build::<FailingVideoMuxer>(FailingVideoMuxerConfig {fail_after_frame: 1,+ fail_audio_after_frame: u64::MAX,}).await.expect("pipeline should build");@@ -2614,7 +2656,7 @@ mod tests {}#[tokio::test]- async fn pipeline_done_future_surfaces_audio_mux_send_failure() {+ async fn audio_only_pipeline_surfaces_audio_mux_failure() {let temp_dir = tempfile::tempdir().expect("temp dir should be created");let timestamps = Timestamps::now();let (mut audio_tx, audio_rx) = mpsc::channel(4);@@ -2641,28 +2683,60 @@ mod tests {let done_error = done_fut.await- .expect_err("done future should fail when mux-audio rejects a frame");- assert!(- done_error.to_string().contains("Task mux-audio failed"),- "done future should surface the mux-audio task failure"- );+ .expect_err("audio-only pipeline should fail when muxer rejects frame");assert!(done_error.to_string()- .contains("Audio muxer stopped accepting frames at frame 1"),- "done future should retain the send-failure context"+ .contains("Audio muxer stopped accepting frames"),+ "error should contain audio failure reason");+ }- let stop_error = match pipeline.stop().await {- Ok(_) => panic!("stop should fail when mux-audio rejects a frame"),- Err(error) => error,- };- assert!(- stop_error- .to_string()- .contains("Audio muxer stopped accepting frames at frame 1"),- "stop should propagate the mux-audio send failure"- );+ #[tokio::test]+ async fn combined_pipeline_survives_audio_mux_failure() {+ let temp_dir = tempfile::tempdir().expect("temp dir should be created");+ let timestamps = Timestamps::now();+ let (video_tx, video_rx) = flume::bounded(4);+ let (mut audio_tx, audio_rx) = mpsc::channel(4);++ let pipeline = OutputPipeline::builder(temp_dir.path().join("combined.mp4"))+ .with_video::<ChannelVideoSource<TestVideoFrame>>(ChannelVideoSourceConfig::new(+ test_video_info(),+ video_rx,+ ))+ .with_audio_source::<ChannelAudioSource>(ChannelAudioSourceConfig::new(+ test_audio_info(),+ audio_rx,+ ))+ .with_timestamps(timestamps)+ .build::<FailingVideoMuxer>(FailingVideoMuxerConfig {+ fail_after_frame: u64::MAX,+ fail_audio_after_frame: 1,+ })+ .await+ .expect("pipeline should build");++ video_tx+ .send_async(TestVideoFrame {+ timestamp: Timestamp::Instant(timestamps.instant() + Duration::from_millis(33)),+ })+ .await+ .expect("video frame should send");++ audio_tx+ .try_send(AudioFrame::new(+ test_audio_info().empty_frame(960),+ Timestamp::Instant(timestamps.instant() + Duration::from_millis(20)),+ ))+ .expect("audio frame should send");++ drop(video_tx);+ drop(audio_tx);++ pipeline+ .stop()+ .await+ .expect("combined pipeline should succeed despite audio muxer failure");}}diff --git a/crates/recording/src/output_pipeline/ffmpeg.rs b/crates/recording/src/output_pipeline/ffmpeg.rsindex e97646ed1..480d3b36f 100644--- a/crates/recording/src/output_pipeline/ffmpeg.rs+++ b/crates/recording/src/output_pipeline/ffmpeg.rs@@ -5,12 +5,13 @@ use crate::{use anyhow::{Context, anyhow};use cap_enc_ffmpeg::{aac::AACEncoder,+ dash_audio::{DashAudioSegmentEncoder, DashAudioSegmentEncoderConfig},fragmented_audio::{FinishError as FragmentedAudioFinishError, FragmentedAudioFile},h264::*,ogg::*,opus::OpusEncoder,segmented_audio::SegmentedAudioEncoder,- segmented_stream::{SegmentedVideoEncoder, SegmentedVideoEncoderConfig},+ segmented_stream::{SegmentCompletedEvent, SegmentedVideoEncoder, SegmentedVideoEncoderConfig},};use cap_media_info::{AudioInfo, VideoInfo};use cap_timestamp::Timestamp;@@ -718,3 +719,85 @@ impl AudioMuxer for SegmentedVideoMuxer {Ok(())}}++pub struct DashSegmentedAudioMuxer {+ encoder: DashAudioSegmentEncoder,+ pause: Option<SharedPauseState>,+}++pub struct DashSegmentedAudioMuxerConfig {+ pub segment_duration: Duration,+ pub shared_pause_state: Option<SharedPauseState>,+ pub segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,+}++impl Default for DashSegmentedAudioMuxerConfig {+ fn default() -> Self {+ Self {+ segment_duration: Duration::from_secs(3),+ shared_pause_state: None,+ segment_tx: None,+ }+ }+}++impl Muxer for DashSegmentedAudioMuxer {+ type Config = DashSegmentedAudioMuxerConfig;++ async fn setup(+ config: Self::Config,+ output_path: PathBuf,+ _: Option<VideoInfo>,+ audio_config: Option<AudioInfo>,+ _: Arc<AtomicBool>,+ _: &mut TaskPool,+ ) -> anyhow::Result<Self>+ where+ Self: Sized,+ {+ let audio_config =+ audio_config.ok_or_else(|| anyhow!("No audio configuration provided"))?;++ let mut encoder = DashAudioSegmentEncoder::init(+ output_path,+ audio_config,+ DashAudioSegmentEncoderConfig {+ segment_duration: config.segment_duration,+ },+ )+ .map_err(|e| anyhow!("Failed to initialize DASH audio segment encoder: {e}"))?;++ if let Some(tx) = config.segment_tx {+ encoder.set_segment_callback(tx);+ }++ Ok(Self {+ encoder,+ pause: config.shared_pause_state,+ })+ }++ fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {+ self.encoder+ .finish_with_timestamp(timestamp)+ .map_err(Into::into)+ .map(|_| Ok(()))+ }+}++impl AudioMuxer for DashSegmentedAudioMuxer {+ fn send_audio_frame(&mut self, frame: AudioFrame, timestamp: Duration) -> anyhow::Result<()> {+ let adjusted_timestamp = if let Some(pause) = &self.pause {+ match pause.adjust(timestamp)? {+ Some(ts) => ts,+ None => return Ok(()),+ }+ } else {+ timestamp+ };++ self.encoder+ .queue_frame(frame.inner, adjusted_timestamp)+ .map_err(|e| anyhow!("Failed to queue audio frame: {e}"))+ }+}diff --git a/crates/recording/src/output_pipeline/macos.rs b/crates/recording/src/output_pipeline/macos.rsindex e18d8c380..2c8c1439a 100644--- a/crates/recording/src/output_pipeline/macos.rs+++ b/crates/recording/src/output_pipeline/macos.rs@@ -1,7 +1,7 @@use crate::{output_pipeline::{- AudioFrame, AudioMuxer, BlockingThreadFinish, Muxer, TaskPool, VideoFrame, VideoMuxer,- wait_for_blocking_thread_finish,+ AudioFrame, AudioMuxer, BlockingThreadFinish, HealthSender, Muxer, PipelineHealthEvent,+ TaskPool, VideoFrame, VideoMuxer, emit_health, wait_for_blocking_thread_finish,},sources::screen_capture,};@@ -135,16 +135,20 @@ struct FrameDropTracker {total_drops: u64,total_frames: u64,last_check: std::time::Instant,+ health_tx: Option<HealthSender>,+ health_emitted: bool,}impl FrameDropTracker {- fn new() -> Self {+ fn new(health_tx: Option<HealthSender>) -> Self {Self {drops_in_window: 0,frames_in_window: 0,total_drops: 0,total_frames: 0,last_check: std::time::Instant::now(),+ health_tx,+ health_emitted: false,}}@@ -174,6 +178,17 @@ impl FrameDropTracker {total_drops = self.total_drops,"MP4 muxer frame drop rate exceeds 5% threshold");+ if !self.health_emitted {+ if let Some(tx) = &self.health_tx {+ emit_health(+ tx,+ PipelineHealthEvent::FrameDropRateHigh {+ rate_pct: drop_rate,+ },+ );+ }+ self.health_emitted = true;+ }} else if self.drops_in_window > 0 {debug!(frames = self.frames_in_window,@@ -588,7 +603,7 @@ impl Muxer for AVFoundationMp4Muxer {instant_mode: is_instant,}),pause_flag,- frame_drops: FrameDropTracker::new(),+ frame_drops: FrameDropTracker::new(None),channel_pressure,audio_channel_pressure,was_paused: false,@@ -609,6 +624,10 @@ impl Muxer for AVFoundationMp4Muxer {}}+ fn set_health_sender(&mut self, tx: HealthSender) {+ self.frame_drops.health_tx = Some(tx);+ }+fn finish(&mut self, timestamp: Duration) -> anyhow::Result<anyhow::Result<()>> {let mut finish_error: Option<anyhow::Error> = None;@@ -1003,7 +1022,7 @@ impl Muxer for AVFoundationCameraMuxer {encoder_handle: Some(encoder_handle),}),pause_flag,- frame_drops: FrameDropTracker::new(),+ frame_drops: FrameDropTracker::new(None),was_paused: false,fatal_error,})diff --git a/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs b/crates/recording/src/output_pipeline/macos_fragmented_m4s.rsindex 5540e694b..d20ba1319 100644--- a/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs+++ b/crates/recording/src/output_pipeline/macos_fragmented_m4s.rs@@ -6,7 +6,7 @@ use crate::{use anyhow::{Context, anyhow};use cap_enc_ffmpeg::h264::{H264EncoderBuilder, H264Preset};use cap_enc_ffmpeg::segmented_stream::{- DiskSpaceCallback, SegmentedVideoEncoder, SegmentedVideoEncoderConfig,+ DiskSpaceCallback, SegmentCompletedEvent, SegmentedVideoEncoder, SegmentedVideoEncoderConfig,};use cap_media_info::{AudioInfo, VideoInfo};use std::{@@ -152,6 +152,7 @@ pub struct MacOSFragmentedM4SMuxer {frame_drops: FrameDropTracker,started: bool,disk_space_callback: Option<DiskSpaceCallback>,+ segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,}pub struct MacOSFragmentedM4SMuxerConfig {@@ -160,6 +161,7 @@ pub struct MacOSFragmentedM4SMuxerConfig {pub output_size: Option<(u32, u32)>,pub shared_pause_state: Option<SharedPauseState>,pub disk_space_callback: Option<DiskSpaceCallback>,+ pub segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,}impl Default for MacOSFragmentedM4SMuxerConfig {@@ -170,6 +172,7 @@ impl Default for MacOSFragmentedM4SMuxerConfig {output_size: None,shared_pause_state: None,disk_space_callback: None,+ segment_tx: None,}}}@@ -209,6 +212,7 @@ impl Muxer for MacOSFragmentedM4SMuxer {frame_drops: FrameDropTracker::new(),started: false,disk_space_callback: config.disk_space_callback,+ segment_tx: config.segment_tx,})}@@ -260,6 +264,9 @@ impl MacOSFragmentedM4SMuxer {if let Some(callback) = &self.disk_space_callback {encoder.set_disk_space_callback(callback.clone());}+ if let Some(tx) = &self.segment_tx {+ encoder.set_segment_callback(tx.clone());+ }let encoder = Arc::new(Mutex::new(encoder));let encoder_clone = encoder.clone();let video_config = self.video_config;@@ -606,6 +613,7 @@ pub struct MacOSFragmentedM4SCameraMuxer {frame_drops: FrameDropTracker,started: bool,disk_space_callback: Option<DiskSpaceCallback>,+ segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,}pub struct MacOSFragmentedM4SCameraMuxerConfig {@@ -614,6 +622,7 @@ pub struct MacOSFragmentedM4SCameraMuxerConfig {pub output_size: Option<(u32, u32)>,pub shared_pause_state: Option<SharedPauseState>,pub disk_space_callback: Option<DiskSpaceCallback>,+ pub segment_tx: Option<std::sync::mpsc::Sender<SegmentCompletedEvent>>,}impl Default for MacOSFragmentedM4SCameraMuxerConfig {@@ -624,6 +633,7 @@ impl Default for MacOSFragmentedM4SCameraMuxerConfig {output_size: None,shared_pause_state: None,disk_space_callback: None,+ segment_tx: None,}}}@@ -664,6 +674,7 @@ impl Muxer for MacOSFragmentedM4SCameraMuxer {frame_drops: FrameDropTracker::new(),started: false,disk_space_callback: config.disk_space_callback,+ segment_tx: config.segment_tx,})}@@ -715,6 +726,9 @@ impl MacOSFragmentedM4SCameraMuxer {if let Some(callback) = &self.disk_space_callback {encoder.set_disk_space_callback(callback.clone());}+ if let Some(tx) = &self.segment_tx {+ encoder.set_segment_callback(tx.clone());+ }let encoder = Arc::new(Mutex::new(encoder));let encoder_clone = encoder.clone();let video_config = self.video_config;diff --git a/crates/recording/src/output_validation.rs b/crates/recording/src/output_validation.rsnew file mode 100644index 000000000..40c1c17f3--- /dev/null+++ b/crates/recording/src/output_validation.rs@@ -0,0 +1,106 @@+use std::{path::Path, time::Duration};++use cap_enc_ffmpeg::remux::{get_media_duration, probe_media_valid, probe_video_can_decode};+use tracing::{debug, info, warn};++use crate::RecordingHealth;++const DURATION_MISMATCH_THRESHOLD: f64 = 0.5;+const MIN_EXPECTED_DURATION: Duration = Duration::from_secs(1);++#[derive(Debug)]+pub struct ValidationResult {+ pub health: RecordingHealth,+ pub output_duration: Option<Duration>,+}++pub fn validate_instant_recording(+ output_path: &Path,+ expected_wall_clock_duration: Duration,+) -> ValidationResult {+ if !output_path.exists() {+ return ValidationResult {+ health: RecordingHealth::Damaged {+ reason: "Output file does not exist".to_string(),+ },+ output_duration: None,+ };+ }++ let file_size = std::fs::metadata(output_path).map(|m| m.len()).unwrap_or(0);++ if file_size == 0 {+ return ValidationResult {+ health: RecordingHealth::Damaged {+ reason: "Output file is empty".to_string(),+ },+ output_duration: None,+ };+ }++ if !probe_media_valid(output_path) {+ return ValidationResult {+ health: RecordingHealth::Damaged {+ reason: "Output file has corrupt container".to_string(),+ },+ output_duration: None,+ };+ }++ let decode_ok = probe_video_can_decode(output_path).unwrap_or(false);++ if !decode_ok {+ return ValidationResult {+ health: RecordingHealth::Damaged {+ reason: "Output video stream cannot be decoded".to_string(),+ },+ output_duration: None,+ };+ }++ let output_duration = get_media_duration(output_path);+ let mut issues = Vec::new();++ if let Some(output_dur) = output_duration+ && expected_wall_clock_duration >= MIN_EXPECTED_DURATION+ {+ let expected_secs = expected_wall_clock_duration.as_secs_f64();+ let actual_secs = output_dur.as_secs_f64();+ let ratio = actual_secs / expected_secs;++ debug!(expected_secs, actual_secs, ratio, "Output duration check");++ if ratio < DURATION_MISMATCH_THRESHOLD {+ let issue = format!(+ "Output duration ({:.1}s) is {:.0}% of expected ({:.1}s)",+ actual_secs,+ ratio * 100.0,+ expected_secs,+ );+ warn!("{issue}");+ issues.push(issue);+ } else if ratio < 0.9 {+ let issue = format!(+ "Output duration ({:.1}s) is shorter than expected ({:.1}s)",+ actual_secs, expected_secs,+ );+ info!("{issue}");+ issues.push(issue);+ }+ }++ if output_duration.is_none() {+ issues.push("Could not determine output duration".to_string());+ }++ let health = if issues.is_empty() {+ RecordingHealth::Healthy+ } else {+ RecordingHealth::Degraded { issues }+ };++ ValidationResult {+ health,+ output_duration,+ }+}diff --git a/crates/recording/src/sources/microphone.rs b/crates/recording/src/sources/microphone.rsindex 4bdd47522..c32d1bc66 100644--- a/crates/recording/src/sources/microphone.rs+++ b/crates/recording/src/sources/microphone.rs@@ -1,6 +1,6 @@use crate::{feeds::microphone::{self, MicrophoneFeedLock},- output_pipeline::{AudioFrame, AudioSource},+ output_pipeline::{AudioFrame, AudioSource, PipelineHealthEvent, emit_health},};use cap_media_info::{AudioInfo, ffmpeg_sample_format_for};use cpal::SampleFormat;@@ -10,11 +10,12 @@ use std::{borrow::Cow,sync::{Arc,- atomic::{AtomicU64, Ordering},+ atomic::{AtomicBool, AtomicU64, Ordering},},time::{Duration, Instant},};use thiserror::Error;+use tokio_util::sync::CancellationToken;use tracing::{debug, info, warn};const MICROPHONE_TARGET_CHANNELS: u16 = 1;@@ -22,10 +23,13 @@ const MICROPHONE_TARGET_CHANNELS: u16 = 1;const SILENCE_TIMEOUT_WIRED: Duration = Duration::from_millis(100);const SILENCE_TIMEOUT_WIRELESS: Duration = Duration::from_millis(200);const SILENCE_CHUNK_DURATION: Duration = Duration::from_millis(20);+const MIC_RECONNECT_AFTER: Duration = Duration::from_secs(2);+const MIC_RECONNECT_BACKOFF_MAX: Duration = Duration::from_secs(30);pub struct Microphone {info: AudioInfo,_lock: Arc<MicrophoneFeedLock>,+ cancel: CancellationToken,}#[derive(Debug, Error)]@@ -116,17 +120,20 @@ impl AudioSource for Microphone {fn setup(feed_lock: Self::Config,mut audio_tx: mpsc::Sender<AudioFrame>,- _: &mut crate::SetupCtx,+ ctx: &mut crate::SetupCtx,) -> impl Future<Output = anyhow::Result<Self>> + 'staticwhereSelf: Sized,{+ let health_tx = ctx.health_tx().clone();async move {let source_info = feed_lock.audio_info();let audio_info = source_info.with_max_channels(MICROPHONE_TARGET_CHANNELS);let source_channels = source_info.channels;let target_channels = audio_info.channels;let is_wireless = source_info.is_wireless_transport;+ let device_name = feed_lock.device_name().to_string();+ let cancel = CancellationToken::new();let (tx, rx) = flume::bounded(128);let send_timeout = if is_wireless {@@ -163,18 +170,41 @@ impl AudioSource for Microphone {let frame_counter = mic_frame_counter.clone();let drop_counter = mic_drop_counter.clone();let silence_counter = mic_silence_counter.clone();+ let feed_lock = feed_lock.clone();+ let device_name = device_name.clone();+ let health_tx = health_tx.clone();+ let cancel = cancel.clone();async move {let mut resampler: Option<MicResampler> = None;let mut silence_mode = false;+ let mut silence_start: Option<Instant> = None;+ let reconnect_in_flight = Arc::new(AtomicBool::new(false));+ let mut reconnect_attempts: u32 = 0;+ let mut next_reconnect_after = MIC_RECONNECT_AFTER;let mut last_timestamp: Option<cap_timestamp::Timestamp> = None;let mut last_frame_duration = SILENCE_CHUNK_DURATION;loop {- match tokio::time::timeout(silence_timeout, rx.recv_async()).await {+ let recv_result = tokio::select! {+ biased;+ _ = cancel.cancelled() => break,+ r = tokio::time::timeout(silence_timeout, rx.recv_async()) => r,+ };+ match recv_result {Ok(Ok(frame)) => {if silence_mode {- info!("Microphone data resumed after silence period");+ let stall_ms =+ silence_start.map(|s| s.elapsed().as_millis()).unwrap_or(0);+ info!(+ stall_ms,+ reconnect_attempts, "Microphone data resumed after silence"+ );silence_mode = false;+ silence_start = None;+ reconnect_in_flight.store(false, Ordering::Relaxed);+ reconnect_attempts = 0;+ next_reconnect_after = MIC_RECONNECT_AFTER;+ emit_health(&health_tx, PipelineHealthEvent::SourceRestarted);}let format_changed = frame.sample_rate != original_rate@@ -270,15 +300,62 @@ impl AudioSource for Microphone {break;}Err(_) => {+ let stall_started = *silence_start.get_or_insert_with(Instant::now);+ let stall_duration = stall_started.elapsed();+if !silence_mode {warn!(- is_wireless = is_wireless,+ is_wireless,timeout_ms = silence_timeout.as_millis(),"Microphone data timeout, generating silence");silence_mode = true;}+ if !reconnect_in_flight.load(Ordering::Relaxed)+ && stall_duration >= next_reconnect_after+ {+ reconnect_attempts += 1;+ warn!(+ attempt = reconnect_attempts,+ backoff_secs = next_reconnect_after.as_secs(),+ stall_secs = stall_duration.as_secs(),+ "Microphone stalled, attempting reconnect"+ );+ emit_health(&health_tx, PipelineHealthEvent::SourceRestarting);+ reconnect_in_flight.store(true, Ordering::Relaxed);++ let feed = feed_lock.clone();+ let name = device_name.clone();+ let in_flight = reconnect_in_flight.clone();+ tokio::spawn(async move {+ let ready = match feed+ .ask(microphone::SetInput { label: name })+ .await+ {+ Ok(r) => r,+ Err(e) => {+ warn!("Microphone reconnect failed: {e}");+ in_flight.store(false, Ordering::Relaxed);+ return;+ }+ };+ match ready.await {+ Ok(_) => {+ info!("Microphone reconnect stream ready")+ }+ Err(e) => {+ warn!("Microphone reconnect stream failed: {e}");+ in_flight.store(false, Ordering::Relaxed);+ }+ }+ });++ next_reconnect_after =+ (next_reconnect_after * 2).min(MIC_RECONNECT_BACKOFF_MAX);+ silence_start = Some(Instant::now());+ }+let timestamp = match last_timestamp {Some(ts) => {let next = ts + last_frame_duration;@@ -310,13 +387,21 @@ impl AudioSource for Microphone {});tokio::spawn({- let frame_counter = mic_frame_counter;- let drop_counter = mic_drop_counter;- let silence_counter = mic_silence_counter;+ let cancel = cancel.clone();async move {+ let frame_counter = mic_frame_counter;+ let drop_counter = mic_drop_counter;+ let silence_counter = mic_silence_counter;let mut last_log = Instant::now();+ let mut prev_captured: u64 = 0;+ let mut prev_dropped: u64 = 0;+ let mut stale_count: u32 = 0;loop {- tokio::time::sleep(Duration::from_secs(5)).await;+ tokio::select! {+ biased;+ _ = cancel.cancelled() => break,+ _ = tokio::time::sleep(Duration::from_secs(5)) => {},+ }let captured = frame_counter.load(Ordering::Relaxed);let dropped = drop_counter.load(Ordering::Relaxed);let silence = silence_counter.load(Ordering::Relaxed);@@ -330,18 +415,40 @@ impl AudioSource for Microphone {} else {0.0};- warn!(- captured = captured,- dropped = dropped,- silence_frames = silence,- drop_pct = format!("{:.1}%", drop_pct),- is_wireless = is_wireless,- send_timeout_ms = send_timeout.as_millis(),- "Microphone audio stats"- );++ let data_changed = captured != prev_captured || dropped != prev_dropped;+ prev_captured = captured;+ prev_dropped = dropped;++ if !data_changed {+ stale_count = stale_count.saturating_add(1);+ } else {+ stale_count = 0;+ }++ if stale_count <= 2 {+ warn!(+ captured,+ dropped,+ silence_frames = silence,+ drop_pct = format!("{:.1}%", drop_pct),+ is_wireless,+ "Microphone audio stats"+ );+ } else if stale_count.is_multiple_of(12) {+ warn!(+ captured,+ dropped,+ silence_frames = silence,+ drop_pct = format!("{:.1}%", drop_pct),+ is_wireless,+ stale_intervals = stale_count,+ "Microphone audio stats (stalled)"+ );+ }last_log = Instant::now();} else if captured > 0 {- debug!(captured = captured, "Microphone audio frames forwarded");+ debug!(captured, "Microphone audio frames forwarded");}}}@@ -350,6 +457,7 @@ impl AudioSource for Microphone {Ok(Self {info: audio_info,_lock: feed_lock,+ cancel,})}}@@ -357,6 +465,11 @@ impl AudioSource for Microphone {fn audio_info(&self) -> AudioInfo {self.info}++ fn stop(&mut self) -> impl Future<Output = anyhow::Result<()>> + Send {+ self.cancel.cancel();+ async { Ok(()) }+ }}fn create_silence_frame(info: &AudioInfo, sample_count: usize) -> ffmpeg::frame::Audio {