Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
recording tracing
Brendan Allan2d1d3cefb881
diff --git a/Cargo.lock b/Cargo.lockindex 146cca135..83b87857e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -840,10 +840,13 @@ dependencies = ["clap 4.5.23","core-graphics 0.24.0","editor",+ "ffmpeg-next","scap","serde","serde_json","tokio",+ "tracing",+ "tracing-subscriber","uuid",]@@ -914,6 +917,7 @@ dependencies = ["tempfile","tokio","tracing",+ "tracing-subscriber","uuid","windows 0.58.0","windows-sys 0.59.0",@@ -1026,6 +1030,7 @@ dependencies = ["cap-flags","cap-media","cap-project",+ "cap-utils","chrono","cocoa 0.26.0","device_query",@@ -1039,6 +1044,7 @@ dependencies = ["thiserror 1.0.63","tokio","tracing",+ "tracing-subscriber","windows 0.58.0",]@@ -1079,6 +1085,7 @@ dependencies = ["serde","serde_json","tokio",+ "tracing","uuid","windows 0.58.0","windows-sys 0.52.0",@@ -3938,6 +3945,15 @@ dependencies = ["tendril",]+[[package]]+name = "matchers"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558"+dependencies = [+ "regex-automata 0.1.10",+]+[[package]]name = "matches"version = "0.1.10"@@ -4391,6 +4407,16 @@ dependencies = ["winapi",]+[[package]]+name = "nu-ansi-term"+version = "0.46.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77a8165726e8236064dbb45459242600304b42a5ea24ee2948e18e023bf7ba84"+dependencies = [+ "overload",+ "winapi",+]+[[package]]name = "num-bigint"version = "0.4.6"@@ -4886,6 +4912,12 @@ dependencies = ["windows-sys 0.59.0",]+[[package]]+name = "overload"+version = "0.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"+[[package]]name = "pango"version = "0.18.3"@@ -5663,8 +5695,17 @@ checksum = "4219d74c6b67a3654a9fbebc4b419e22126d13d2f3c4a07ee0cb61ff79a79619"dependencies = ["aho-corasick","memchr",- "regex-automata",- "regex-syntax",+ "regex-automata 0.4.7",+ "regex-syntax 0.8.4",+]++[[package]]+name = "regex-automata"+version = "0.1.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6c230d73fb8d8c1b9c0b3135c5142a8acee3a0558fb8db5cf1cb65f8d7862132"+dependencies = [+ "regex-syntax 0.6.29",][[package]]@@ -5675,9 +5716,15 @@ checksum = "38caf58cc5ef2fed281f89292ef23f6365465ed9a41b7a7754eb4e26496c92df"dependencies = ["aho-corasick","memchr",- "regex-syntax",+ "regex-syntax 0.8.4",]+[[package]]+name = "regex-syntax"+version = "0.6.29"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1"+[[package]]name = "regex-syntax"version = "0.8.4"@@ -6370,6 +6417,15 @@ dependencies = ["digest",]+[[package]]+name = "sharded-slab"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6"+dependencies = [+ "lazy_static",+]+[[package]]name = "shared_child"version = "1.0.1"@@ -7517,6 +7573,16 @@ dependencies = ["syn 2.0.90",]+[[package]]+name = "thread_local"+version = "1.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8b9ef9bad013ada3808854ceac7b46812a6465ba368859a37e2100283d2d719c"+dependencies = [+ "cfg-if 1.0.0",+ "once_cell",+]+[[package]]name = "tiff"version = "0.9.1"@@ -7804,13 +7870,33 @@ dependencies = ["valuable",]+[[package]]+name = "tracing-log"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3"+dependencies = [+ "log",+ "once_cell",+ "tracing-core",+]+[[package]]name = "tracing-subscriber"-version = "0.3.18"+version = "0.3.19"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ad0f048c97dbd9faa9b7df56362b8ebcaa52adb06b498c050d2f4e32f90a7a8b"+checksum = "e8189decb5ac0fa7bc8b96b7cb9b2701d60d48805aca84a238004d665fcc4008"dependencies = [+ "matchers",+ "nu-ansi-term",+ "once_cell",+ "regex",+ "sharded-slab",+ "smallvec",+ "thread_local",+ "tracing","tracing-core",+ "tracing-log",][[package]]diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.tomlindex 83d068d74..a81c4bc52 100644--- a/apps/cli/Cargo.toml+++ b/apps/cli/Cargo.toml@@ -20,3 +20,6 @@ editor = "0.1.1"scap.workspace = truecore-graphics = "0.24.0"uuid = { version = "1.11.1", features = ["v4"] }+ffmpeg = { workspace = true }+tracing = "0.1.41"+tracing-subscriber = "0.3.19"diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rsindex 6ae15b3ca..c78de39f1 100644--- a/apps/cli/src/main.rs+++ b/apps/cli/src/main.rs@@ -6,7 +6,9 @@ use cap_project::{RecordingMeta, XY};use cap_recording::RecordingOptions;use cap_rendering::RenderVideoConstants;use clap::{Args, Parser, Subcommand};+use instrument::WithSubscriber;use tokio::io::AsyncBufReadExt;+use tracing::*;use uuid::Uuid;#[derive(Parser)]@@ -194,8 +196,6 @@ window {}:}).ok_or("No target specified".to_string())??;- dbg!(&target_info);-let id = Uuid::new_v4().to_string();let path = args.path@@ -217,14 +217,14 @@ window {}:.await.map_err(|e| e.to_string())?;- println!("Recording starting, press Enter to stop");+ info!("Recording starting, press Enter to stop");tokio::io::BufReader::new(tokio::io::stdin()).read_line(&mut String::new()).await.unwrap();- println!("Recording stopped");+ info!("Recording stopped");actor.stop().await.unwrap();}@@ -234,3 +234,35 @@ window {}:Ok(())}++// fn ffmpeg_callback_experiment() {+// unsafe {+// unsafe extern "C" fn ffmpeg_log_callback(+// arg1: *mut std::ffi::c_void,+// arg2: std::ffi::c_int,+// arg3: *const std::ffi::c_char,+// arg4: *mut std::ffi::c_char,+// ) {+// // ffmpeg::sys::AVClass;++// if !arg1.is_null() {+// let arg1_ptr = arg1;+// let arg1 = **(arg1 as *mut *mut AVClass);+// dbg!(CStr::from_ptr(arg1.class_name));+// if let Some(item_name_fn) = arg1.item_name {+// dbg!(CStr::from_ptr(item_name_fn(arg1_ptr)));+// }+// }++// // let class_name = if !arg1.is_null() {+// // CStr::from_ptr((*arg1).class_name)+// // } else {+// // "unknown".to_string()+// // };++// // println!("[{class_name}] {arg2} {s:?}",);+// }++// ffmpeg::sys::av_log_set_callback(Some(ffmpeg_log_callback));+// }+// }diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 7243897a8..cf2428031 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -80,6 +80,7 @@ cap-recording = { path = "../../../crates/recording" }cap-export = { path = "../../../crates/export" }flume.workspace = truetauri-plugin-deep-link = "2.2.0"+tracing-subscriber = "0.3.19"[target.'cfg(target_os = "macos")'.dependencies]core-graphics = "0.24.0"diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex 57f256684..2412202c2 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -24,6 +24,7 @@ use cap_rendering::ProjectRecordings;use clipboard_rs::{Clipboard, ClipboardContext};use tauri::{AppHandle, Manager};use tauri_specta::Event;+use tracing::{instrument::WithSubscriber, Level};#[tauri::command(async)]#[specta::specta]@@ -99,7 +100,6 @@ pub async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Re}}}-let actor = cap_recording::spawn_recording_actor(id,recording_dir,diff --git a/crates/media/src/encoders/h264.rs b/crates/media/src/encoders/h264.rsindex 2b09ebb64..4506daba1 100644--- a/crates/media/src/encoders/h264.rs+++ b/crates/media/src/encoders/h264.rs@@ -10,6 +10,7 @@ use ffmpeg::{Dictionary, Rescale,};use ffmpeg_sys_next as sys;+use tracing::{debug, info, trace};use super::Output;@@ -121,7 +122,7 @@ impl PipelineSinkTask for H264Encoder {ready_signal: crate::pipeline::task::PipelineReadySignal,input: flume::Receiver<Self::Input>,) {- println!("Starting {} video encoding thread", self.tag);+ trace!("Starting {} video encoding thread", self.tag);ready_signal.send(Ok(())).unwrap();while let Ok(frame) = input.recv() {@@ -129,10 +130,10 @@ impl PipelineSinkTask for H264Encoder {self.process_frame();}- println!("Received last {} frame. Finishing up encoding.", self.tag);+ trace!("Received last {} frame. Finishing up encoding.", self.tag);self.finish();- println!("Shutting down {} video encoding thread", self.tag);+ info!("Shut down {} video encoding thread", self.tag);}}diff --git a/crates/media/src/encoders/h264_avassetwriter.rs b/crates/media/src/encoders/h264_avassetwriter.rsindex dc75cdaa6..9d2d39e1b 100644--- a/crates/media/src/encoders/h264_avassetwriter.rs+++ b/crates/media/src/encoders/h264_avassetwriter.rs@@ -3,6 +3,7 @@ use crate::{data::VideoInfo, pipeline::task::PipelineSinkTask, MediaError};use super::Output;use arc::Retained;use cidre::{objc::Obj, *};+use tracing::{info, trace};pub struct H264AVAssetWriterEncoder {tag: &'static str,@@ -48,8 +49,8 @@ impl H264AVAssetWriterEncoder {ns::Number::with_u32(config.height).as_id_ref(),);- let bitrate = config.width as f32 * config.height as f32 / (1920.0 * 1080.0) * 10_000_000.0- + fps / 30.0 * 4_000_000.0;+ let bitrate = config.width as f32 * config.height as f32 / (1920.0 * 1080.0) * 14_000_000.0+ + fps / 30.0 * 6_000_000.0;output_settings.insert(av::video_settings_keys::compression_props(),@@ -62,7 +63,7 @@ impl H264AVAssetWriterEncoder {let mut video_input = av::AssetWriterInput::with_media_type_and_output_settings(av::MediaType::video(),- Some(dbg!(output_settings.as_ref())),+ Some(output_settings.as_ref()),).map_err(|_| MediaError::Any("Failed to create AVAssetWriterInput"))?;video_input.set_expects_media_data_in_real_time(true);@@ -124,7 +125,7 @@ impl PipelineSinkTask for H264AVAssetWriterEncoder {ready_signal: crate::pipeline::task::PipelineReadySignal,input: flume::Receiver<Self::Input>,) {- println!("Starting {} video encoding thread", self.tag);+ trace!("Starting {} video encoding thread", self.tag);ready_signal.send(Ok(())).ok();while let Ok(frame) = input.recv() {@@ -132,10 +133,10 @@ impl PipelineSinkTask for H264AVAssetWriterEncoder {self.process_frame();}- println!("Received last {} frame. Finishing up encoding.", self.tag);+ trace!("Received last {} frame. Finishing up encoding.", self.tag);self.finish();- println!("Shutting down {} video encoding thread", self.tag);+ info!("Shut down {} video encoding thread", self.tag);}}diff --git a/crates/media/src/encoders/mp3.rs b/crates/media/src/encoders/mp3.rsindex a7d0cefe8..e10cab3dd 100644--- a/crates/media/src/encoders/mp3.rs+++ b/crates/media/src/encoders/mp3.rs@@ -4,6 +4,7 @@ use ffmpeg::{threading::Config,};use std::collections::VecDeque;+use tracing::{debug, info, trace};use crate::{data::{AudioInfo, FFAudio, FFPacket, FFRational, PlanarData},@@ -106,16 +107,16 @@ impl PipelineSinkTask for MP3Encoder {ready_signal: crate::pipeline::task::PipelineReadySignal,input: flume::Receiver<Self::Input>,) {- println!("Starting {} audio encoding thread", self.tag);+ trace!("Starting {} audio encoding thread", self.tag);ready_signal.send(Ok(())).unwrap();while let Ok(frame) = input.recv() {self.queue_frame(frame);}- println!("Received last {} sample. Finishing up encoding.", self.tag);+ trace!("Received last {} sample. Finishing up encoding.", self.tag);self.finish();- println!("Shutting down {} audio encoding thread", self.tag);+ info!("Shut down {} audio encoding thread", self.tag);}}diff --git a/crates/media/src/encoders/mp4.rs b/crates/media/src/encoders/mp4.rsindex aac98f187..aaccfb9c2 100644--- a/crates/media/src/encoders/mp4.rs+++ b/crates/media/src/encoders/mp4.rs@@ -12,7 +12,7 @@ use ffmpeg::{threading::Config,Dictionary, Rescale,};-use ffmpeg_sys_next as sys;+use tracing::{debug, info, trace};use super::Output;@@ -374,7 +374,7 @@ impl PipelineSinkTask for MP4Encoder {ready_signal: crate::pipeline::task::PipelineReadySignal,input: flume::Receiver<Self::Input>,) {- println!("Starting {} MP4 encoding thread", self.tag);+ trace!("Starting {} MP4 encoding thread", self.tag);ready_signal.send(Ok(())).unwrap();while let Ok(frame) = input.recv() {@@ -384,10 +384,10 @@ impl PipelineSinkTask for MP4Encoder {}}- println!("Received last {} frame. Finishing up encoding.", self.tag);+ trace!("Received last {} frame. Finishing up encoding.", self.tag);self.finish();- println!("Shutting down {} MP4 encoding thread", self.tag);+ info!("Shut down {} MP4 encoding thread", self.tag);}}diff --git a/crates/media/src/feeds/audio_input.rs b/crates/media/src/feeds/audio_input.rsindex 83fb834a6..c0f204364 100644--- a/crates/media/src/feeds/audio_input.rs+++ b/crates/media/src/feeds/audio_input.rs@@ -2,7 +2,7 @@ use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};use cpal::{Device, InputCallbackInfo, SampleFormat, StreamConfig, SupportedStreamConfig};use flume::{Receiver, Sender, TrySendError};use indexmap::IndexMap;-use tracing::{warn, error, info, debug};+use tracing::{debug, error, info, trace, warn};use crate::{data::{ffmpeg_sample_format_for, AudioInfo},@@ -55,12 +55,16 @@ impl AudioInputFeed {}pub async fn init(selected_input: &str) -> Result<Self, MediaError> {- info!("Initializing audio input feed with device: {}", selected_input);-+ trace!("Initializing audio input feed with device");+ debug!(selected_input);+let (device, config) = Self::list_devices().swap_remove_entry(selected_input).map(|(device_name, (device, config))| {- info!("Using audio device: {} with config: {:?}", device_name, config);+ info!(+ "Using audio device: {} with config: {:?}",+ device_name, config+ );(device, config)}).ok_or_else(|| {@@ -72,7 +76,7 @@ impl AudioInputFeed {error!("Failed to create audio info from stream config: {}", e);e})?;-+debug!("Created audio info: {:?}", audio_info);let (control_tx, control_rx) = flume::bounded(1);@@ -94,7 +98,10 @@ impl AudioInputFeed {device.supported_input_configs().map_err(|error| {- error!("Error getting supported input configs for device: {}", error);+ error!(+ "Error getting supported input configs for device: {}",+ error+ );error}).ok()@@ -122,7 +129,9 @@ impl AudioInputFeed {})};- if let Some((name, device, config)) = host.default_input_device().and_then(get_usable_device) {+ if let Some((name, device, config)) =+ host.default_input_device().and_then(get_usable_device)+ {info!("Found default input device: {}", name);device_map.insert(name, (device, config));} else {@@ -196,7 +205,11 @@ fn start_capturing(mut config: SupportedStreamConfig,control: Receiver<AudioInputControl>,) {- info!("Starting audio capture with device: {:?}, config: {:?}", device.name(), config);+ info!(+ "Starting audio capture with device: {:?}, config: {:?}",+ device.name(),+ config+ );let mut senders: Vec<AudioInputSamplesSender> = vec![];loop {@@ -204,35 +217,34 @@ fn start_capturing(info!("Building input stream with config: {:?}", config);let stream_config: StreamConfig = config.clone().into();- let stream = match device- .build_input_stream_raw(- &stream_config,- config.sample_format(),- move |data, info| {- if let Err(e) = tx.send(AudioInputSamples {- data: data.bytes().to_vec(),- format: data.sample_format(),- info: info.clone(),- }) {- error!("Failed to send audio samples: {}", e);- }- },- |e| {- error!("Error in audio input stream: {}", e);- },- None,- ) {- Ok(stream) => {- info!("Successfully built audio input stream");- stream- }- Err(err) => {- error!("Failed to build audio input stream: {}", err);- // Sleep briefly to avoid tight error loop- std::thread::sleep(std::time::Duration::from_secs(1));- continue;+ let stream = match device.build_input_stream_raw(+ &stream_config,+ config.sample_format(),+ move |data, info| {+ if let Err(e) = tx.send(AudioInputSamples {+ data: data.bytes().to_vec(),+ format: data.sample_format(),+ info: info.clone(),+ }) {+ error!("Failed to send audio samples: {}", e);}- };+ },+ |e| {+ error!("Error in audio input stream: {}", e);+ },+ None,+ ) {+ Ok(stream) => {+ info!("Successfully built audio input stream");+ stream+ }+ Err(err) => {+ error!("Failed to build audio input stream: {}", err);+ // Sleep briefly to avoid tight error loop+ std::thread::sleep(std::time::Duration::from_secs(1));+ continue;+ }+ };// Try to play the streamif let Err(e) = stream.play() {@@ -249,7 +261,10 @@ fn start_capturing(drop(stream);let Some(items) = AudioInputFeed::list_devices().swap_remove_entry(&name).map(|(device_name, (device, config))| {- info!("Switching to audio device: {} with config: {:?}", device_name, config);+ info!(+ "Switching to audio device: {} with config: {:?}",+ device_name, config+ );(device, config)},) else {diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rsindex dff46e90d..1a7f162a2 100644--- a/crates/media/src/feeds/camera.rs+++ b/crates/media/src/feeds/camera.rs@@ -88,6 +88,10 @@ impl CameraFeed {}}+ pub fn camera_info(&self) -> CameraInfo {+ self.camera_info.clone()+ }+pub fn video_info(&self) -> VideoInfo {self.video_info}diff --git a/crates/media/src/filters/video.rs b/crates/media/src/filters/video.rsindex 104878c62..47353c935 100644--- a/crates/media/src/filters/video.rs+++ b/crates/media/src/filters/video.rs@@ -31,8 +31,6 @@ impl VideoFilter {filter_graph.add(&filter::find("buffer").unwrap(), "in", &input_args)?;filter_graph.add(&filter::find("buffersink").unwrap(), "out", "")?;- dbg!(input_config.pixel_format, output_config.pixel_format);-let mut input = filter_graph.get("in").unwrap();input.set_pixel_format(input_config.pixel_format);diff --git a/crates/media/src/pipeline/builder.rs b/crates/media/src/pipeline/builder.rsindex 1a962a4d4..c1b2a45f3 100644--- a/crates/media/src/pipeline/builder.rs+++ b/crates/media/src/pipeline/builder.rs@@ -1,6 +1,7 @@use flume::Receiver;use indexmap::IndexMap;use std::thread::{self, JoinHandle};+use tracing::Instrument;use crate::pipeline::{clock::CloneFrom,@@ -60,8 +61,14 @@ impl<T> PipelineBuilder<T> {let (ready_sender, ready_signal) = flume::bounded(1);+ let dispatcher = tracing::dispatcher::get_default(|d| d.clone());+ let span = tracing::error_span!("pipeline", task = &name);let join_handle = thread::spawn(move || {- launch(ready_sender);+ tracing::dispatcher::with_default(&dispatcher, || {+ span.in_scope(|| {+ launch(ready_sender);+ })+ })});self.tasks.insert(name,diff --git a/crates/media/src/pipeline/control.rs b/crates/media/src/pipeline/control.rsindex 67917f1a3..109cc0616 100644--- a/crates/media/src/pipeline/control.rs+++ b/crates/media/src/pipeline/control.rs@@ -1,5 +1,6 @@use flume::{Receiver, Sender, TryRecvError};use indexmap::IndexMap;+use tracing::debug;use crate::pipeline::MediaError;@@ -30,7 +31,7 @@ impl PipelineControlSignal {// Only peek for a new signal, else relinquish control to the callermatch self.receiver.try_recv() {Ok(control) => {- println!("Received new signal: {control:?}");+ debug!("Received new signal: {control:?}");self.last_value = Some(control)}Err(TryRecvError::Empty) => {}@@ -42,7 +43,6 @@ impl PipelineControlSignal {_ => {// For all else, block until a signal is sent.// TODO: Maybe also spin down until the signal is different from the last value we have?- println!("Waiting for play signal...");self.last_value = self.receiver.recv().ok();self.last_value@@ -76,7 +76,6 @@ impl ControlBroadcast {}for (name, listener) in self.listeners.iter() {- println!("Sending signal {value:?} to {name}");if let Err(_) = listener.send_async(value).await {eprintln!("{name} is unreachable!");any_dropped = true;diff --git a/crates/media/src/pipeline/mod.rs b/crates/media/src/pipeline/mod.rsindex d3a94da58..403a801bd 100644--- a/crates/media/src/pipeline/mod.rs+++ b/crates/media/src/pipeline/mod.rs@@ -1,5 +1,6 @@use indexmap::IndexMap;use std::thread::JoinHandle;+use tracing::{info, trace};pub mod audio_buffer;pub mod builder;@@ -30,7 +31,6 @@ impl<T: PipelineClock> Pipeline<T> {return Err(MediaError::ShutdownPipeline);};- println!("Starting pipeline execution");self.clock.start();self.control.broadcast(Control::Play).await}@@ -40,7 +40,6 @@ impl<T: PipelineClock> Pipeline<T> {return Err(MediaError::ShutdownPipeline);};- println!("Pausing pipeline execution");self.clock.stop();self.control.broadcast(Control::Pause).await}@@ -50,12 +49,12 @@ impl<T: PipelineClock> Pipeline<T> {return Err(MediaError::ShutdownPipeline);};- println!("Shutting down pipeline execution");+ trace!("Shutting down pipeline execution");let _ = self.control.broadcast(Control::Shutdown).await;for (_name, task) in self.task_handles.drain(..) {let _ = task.join();}- println!("Pipeline has been stopped.");+ info!("Pipeline has been stopped.");// TODO: Collect shutdown errors?Ok(())}diff --git a/crates/media/src/sources/audio_input.rs b/crates/media/src/sources/audio_input.rsindex 203cb19c0..3ac30b38b 100644--- a/crates/media/src/sources/audio_input.rs+++ b/crates/media/src/sources/audio_input.rs@@ -1,6 +1,7 @@use cpal::{Device, StreamInstant, SupportedStreamConfig};use flume::{Receiver, Sender};use indexmap::IndexMap;+use tracing::{error, info};use crate::feeds::{AudioInputConnection, AudioInputFeed, AudioInputSamples};use crate::{@@ -82,7 +83,6 @@ impl PipelineSourceTask for AudioInputSource {type Clock = RealTimeClock<StreamInstant>;- // #[tracing::instrument(skip_all)]fn run(&mut self,mut clock: Self::Clock,@@ -90,7 +90,7 @@ impl PipelineSourceTask for AudioInputSource {mut control_signal: crate::pipeline::control::PipelineControlSignal,output: Sender<Self::Output>,) {- println!("Preparing audio input source thread...");+ info!("Preparing audio input source thread...");let mut samples_rx: Option<Receiver<AudioInputSamples>> = None;ready_signal.send(Ok(())).unwrap();@@ -103,12 +103,12 @@ impl PipelineSourceTask for AudioInputSource {match samples.recv() {Ok(samples) => {if let Err(error) = self.process_frame(&mut clock, &output, samples) {- eprintln!("{error}");+ error!("{error}");break;}}Err(_) => {- eprintln!("Lost connection with the camera feed");+ error!("Lost connection with the camera feed");break;}}@@ -129,6 +129,6 @@ impl PipelineSourceTask for AudioInputSource {}}- println!("Shutting down audio input source thread.");+ info!("Shutting down audio input source thread.");}}diff --git a/crates/media/src/sources/camera.rs b/crates/media/src/sources/camera.rsindex 1ca33e643..aed59134f 100644--- a/crates/media/src/sources/camera.rs+++ b/crates/media/src/sources/camera.rs@@ -1,5 +1,6 @@use flume::{Receiver, Sender};use std::time::Instant;+use tracing::info;use crate::{data::{FFVideo, VideoInfo},@@ -81,7 +82,7 @@ impl PipelineSourceTask for CameraSource {mut control_signal: crate::pipeline::control::PipelineControlSignal,output: Sender<Self::Output>,) {- println!("Preparing camera source thread...");+ info!("Preparing camera source thread...");let mut frames_rx: Option<Receiver<RawCameraFrame>> = None;ready_signal.send(Ok(())).unwrap();@@ -120,6 +121,6 @@ impl PipelineSourceTask for CameraSource {}}- println!("Shutting down camera source thread.");+ info!("Shutting down camera source thread.");}}diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rsindex 24769d6ed..bba862350 100644--- a/crates/media/src/sources/screen_capture.rs+++ b/crates/media/src/sources/screen_capture.rs@@ -9,7 +9,8 @@ use scap::{};use serde::{Deserialize, Serialize};use specta::Type;-use std::collections::HashMap;+use std::{collections::HashMap, ops::ControlFlow};+use tracing::{error, info, instrument, trace, warn};use crate::{data::{FFVideo, RawVideoFormat, VideoInfo},@@ -130,8 +131,7 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {let options = this.create_options();- let [frame_width, frame_height] = get_output_frame_size(&dbg!(options));- dbg!(frame_width, frame_height);+ let [frame_width, frame_height] = get_output_frame_size(&options);this.video_info =VideoInfo::from_raw(RawVideoFormat::Bgra, frame_width, frame_height, MAX_FPS);@@ -224,150 +224,176 @@ impl<TCaptureFormat> ScreenCaptureSource<TCaptureFormat> {}}+#[derive(Debug)]pub struct AVFrameCapture;impl PipelineSourceTask for ScreenCaptureSource<AVFrameCapture> {type Clock = RealTimeClock<RawNanoseconds>;type Output = FFVideo;+ // #[instrument(skip_all)]fn run(&mut self,mut clock: Self::Clock,ready_signal: crate::pipeline::task::PipelineReadySignal,- mut control_signal: crate::pipeline::control::PipelineControlSignal,+ control_signal: crate::pipeline::control::PipelineControlSignal,output: Sender<Self::Output>,) {- println!("Preparing screen capture source thread...");-- let options = self.create_options();+ let video_info = self.video_info;+ inner(+ self,+ ready_signal,+ control_signal,+ |capturer| match capturer.get_next_frame() {+ Ok(Frame::BGRA(frame)) => {+ if frame.height == 0 || frame.width == 0 {+ return Some(ControlFlow::Continue(()));+ }- let maybe_capture_window_id = match &self.target {- ScreenCaptureTarget::Window(window) => Some(window.id),- _ => None,- };- let mut capturer = match Capturer::build(dbg!(options)) {- Ok(capturer) => capturer,- Err(e) => {- let error = format!("Failed to build capturer: {e}");- eprintln!("{}", error);- ready_signal- .send(Err(MediaError::Any("Failed to build capturer")))- .unwrap();- return;- }- };- let mut capturing = false;- ready_signal.send(Ok(())).unwrap();-- loop {- match control_signal.last() {- Some(Control::Play) => {- if !capturing {- if let Some(window_id) = maybe_capture_window_id {- crate::platform::bring_window_to_focus(window_id);+ let raw_timestamp = RawNanoseconds(frame.display_time);+ match clock.timestamp_for(raw_timestamp) {+ None => {+ warn!("Clock is currently stopped. Dropping frames.");+ None}- capturer.start_capture();- capturing = true;+ Some(timestamp) => {+ let mut buffer = FFVideo::new(+ video_info.pixel_format,+ video_info.width,+ video_info.height,+ );+ buffer.set_pts(Some(timestamp));++ let bytes_per_pixel = 4;+ let width_in_bytes = frame.width as usize * bytes_per_pixel;+ let height = frame.height as usize;++ let src_data = &frame.data;++ let src_stride = src_data.len() / height;+ let dst_stride = buffer.stride(0);++ if src_data.len() < src_stride * height {+ warn!("Frame data size mismatch.");+ return Some(ControlFlow::Continue(()));+ }- println!("Screen recording started.");- }+ if src_stride < width_in_bytes {+ warn!("Source stride is less than expected width in bytes.");+ return Some(ControlFlow::Continue(()));+ }- match capturer.get_next_frame() {- Ok(Frame::BGRA(frame)) => {- if frame.height == 0 || frame.width == 0 {- continue;+ if buffer.data(0).len() < dst_stride * height {+ warn!("Destination data size mismatch.");+ return Some(ControlFlow::Continue(()));}- let raw_timestamp = RawNanoseconds(frame.display_time);- match clock.timestamp_for(raw_timestamp) {- None => {- eprintln!("Clock is currently stopped. Dropping frames.");- }- Some(timestamp) => {- let mut buffer = FFVideo::new(- self.video_info.pixel_format,- self.video_info.width,- self.video_info.height,- );- buffer.set_pts(Some(timestamp));-- let bytes_per_pixel = 4;- let width_in_bytes = frame.width as usize * bytes_per_pixel;- let height = frame.height as usize;-- let src_data = &frame.data;-- let src_stride = src_data.len() / height;- let dst_stride = buffer.stride(0);-- if src_data.len() < src_stride * height {- eprintln!("Frame data size mismatch.");- continue;- }-- if src_stride < width_in_bytes {- eprintln!(- "Source stride is less than expected width in bytes."- );- continue;- }-- if buffer.data(0).len() < dst_stride * height {- eprintln!("Destination data size mismatch.");- continue;- }-- {- let dst_data = buffer.data_mut(0);-- for y in 0..height {- let src_offset = y * src_stride;- let dst_offset = y * dst_stride;- dst_data[dst_offset..dst_offset + width_in_bytes]- .copy_from_slice(- &src_data- [src_offset..src_offset + width_in_bytes],- );- }- }-- if let Err(_) = output.send(buffer) {- eprintln!(- "Pipeline is unreachable. Shutting down recording."+ {+ let dst_data = buffer.data_mut(0);++ for y in 0..height {+ let src_offset = y * src_stride;+ let dst_offset = y * dst_stride;+ dst_data[dst_offset..dst_offset + width_in_bytes]+ .copy_from_slice(+ &src_data[src_offset..src_offset + width_in_bytes],);- break;- }}- };- }- Ok(_) => unreachable!(),- Err(error) => {- eprintln!("Capture error: {error}");- break;+ }++ if let Err(_) = output.send(buffer) {+ error!("Pipeline is unreachable. Shutting down recording.");+ return Some(ControlFlow::Break(()));+ }++ None}}}- Some(Control::Pause) => {- println!("Received pause signal");- if capturing {- capturer.stop_capture();- capturing = false;+ Ok(_) => unreachable!(),+ Err(error) => {+ error!("Capture error: {error}");+ Some(ControlFlow::Break(()))+ }+ },+ )+ }+}++fn inner<T>(+ source: &mut ScreenCaptureSource<T>,+ ready_signal: crate::pipeline::task::PipelineReadySignal,+ mut control_signal: crate::pipeline::control::PipelineControlSignal,+ mut get_frame: impl FnMut(&mut Capturer) -> Option<ControlFlow<()>>,+) {+ trace!("Preparing screen capture source thread...");++ let maybe_capture_window_id = match &source.target {+ ScreenCaptureTarget::Window(window) => Some(window.id),+ _ => None,+ };+ let mut capturer = match Capturer::build(source.create_options()) {+ Ok(capturer) => capturer,+ Err(e) => {+ error!("Failed to build capturer: {e}");+ ready_signal+ .send(Err(MediaError::Any("Failed to build capturer")))+ .unwrap();+ return;+ }+ };++ info!("Capturer built");++ let mut capturing = false;+ ready_signal.send(Ok(())).unwrap();++ loop {+ match control_signal.last() {+ Some(Control::Pause) => {+ trace!("Received pause signal");+ if capturing {+ capturer.stop_capture();+ info!("Capturer stopped");+ capturing = false;+ }+ }+ Some(Control::Shutdown) | None => {+ trace!("Received shutdown signal");+ if capturing {+ capturer.stop_capture();+ info!("Capturer stopped")+ }+ break;+ }+ Some(Control::Play) => {+ if !capturing {+ if let Some(window_id) = maybe_capture_window_id {+ crate::platform::bring_window_to_focus(window_id);}+ capturer.start_capture();+ capturing = true;++ info!("Screen recording started.");}- Some(Control::Shutdown) | None => {- println!("Received shutdown signal");- if capturing {- capturer.stop_capture();++ match get_frame(&mut capturer) {+ Some(ControlFlow::Break(_)) => {+ break;+ }+ Some(ControlFlow::Continue(_)) => {+ continue;}- break;+ None => {}}}}-- println!("Shutting down screen capture source thread.");}++ info!("Shut down screen capture source thread.");}+#[derive(Debug)]pub struct CMSampleBufferCapture;#[cfg(target_os = "macos")]@@ -379,77 +405,32 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {&mut self,_: Self::Clock,ready_signal: crate::pipeline::task::PipelineReadySignal,- mut control_signal: crate::pipeline::control::PipelineControlSignal,+ control_signal: crate::pipeline::control::PipelineControlSignal,output: Sender<Self::Output>,) {- println!("Preparing screen capture source thread...");-- let maybe_capture_window_id = match &self.target {- ScreenCaptureTarget::Window(window) => Some(window.id),- _ => None,- };- let mut capturer = match Capturer::build(dbg!(self.create_options())) {- Ok(capturer) => capturer,- Err(e) => {- let error = format!("Failed to build capturer: {e}");- eprintln!("{}", error);- ready_signal- .send(Err(MediaError::Any("Failed to build capturer")))- .unwrap();- return;- }- };- let mut capturing = false;- ready_signal.send(Ok(())).ok();-- loop {- match control_signal.last() {- Some(Control::Play) => {- if !capturing {- if let Some(window_id) = maybe_capture_window_id {- crate::platform::bring_window_to_focus(window_id);- }- capturer.start_capture();- capturing = true;-- println!("Screen recording started.");+ inner(+ self,+ ready_signal,+ control_signal,+ |capturer| match capturer.raw().get_next_pixel_buffer() {+ Ok(pixel_buffer) => {+ if pixel_buffer.height() == 0 || pixel_buffer.width() == 0 {+ return Some(ControlFlow::Continue(()));}- match capturer.raw().get_next_pixel_buffer() {- Ok(pixel_buffer) => {- if pixel_buffer.height() == 0 || pixel_buffer.width() == 0 {- continue;- }-- if let Err(_) = output.send(pixel_buffer.into()) {- eprintln!("Pipeline is unreachable. Shutting down recording.");- break;- }- }- Err(error) => {- eprintln!("Capture error: {error}");- break;- }- }- }- Some(Control::Pause) => {- println!("Received pause signal");- if capturing {- capturer.stop_capture();- capturing = false;+ if let Err(_) = output.send(pixel_buffer.into()) {+ eprintln!("Pipeline is unreachable. Shutting down recording.");+ return Some(ControlFlow::Continue(()));}++ None}- Some(Control::Shutdown) | None => {- println!("Received shutdown signal");- if capturing {- // capturer.stop_capture();- }- break;+ Err(error) => {+ eprintln!("Capture error: {error}");+ Some(ControlFlow::Break(()))}- }- }-- println!("Shutting down screen capture source thread.");+ },+ )}}diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.tomlindex 71ac98de3..7dd6376fb 100644--- a/crates/recording/Cargo.toml+++ b/crates/recording/Cargo.toml@@ -7,6 +7,7 @@ edition = "2021"cap-project = { path = "../project" }cap-media = { path = "../media" }cap-flags = { path = "../flags" }+cap-utils = { path = "../utils" }specta.workspace = truetokio.workspace = true@@ -20,6 +21,7 @@ tracing = "0.1.40"device_query = "2.1.0"image = "0.25.2"either = "1.13.0"+tracing-subscriber = { version = "0.3.19", features = ["env-filter"] }[target.'cfg(target_os = "macos")'.dependencies]cocoa = "0.26.0"@@ -27,7 +29,7 @@ objc = "0.2.7"[target.'cfg(target_os = "windows")'.dependencies]windows = { workspace = true, features = [- "Win32_Foundation",- "Win32_Graphics_Gdi",- "Win32_UI_WindowsAndMessaging",+ "Win32_Foundation",+ "Win32_Graphics_Gdi",+ "Win32_UI_WindowsAndMessaging",] }diff --git a/crates/recording/src/actor.rs b/crates/recording/src/actor.rsindex 33050ac18..0f6409cb1 100644--- a/crates/recording/src/actor.rs+++ b/crates/recording/src/actor.rs@@ -15,9 +15,16 @@ use cap_media::{MediaError,};use cap_project::{CursorEvents, RecordingMeta};+use cap_utils::spawn_actor;use either::Either;use thiserror::Error;use tokio::sync::{oneshot, Mutex};+use tracing::{+ debug, info,+ instrument::{self, WithSubscriber},+ trace, Instrument, Level, Span,+};+use tracing_subscriber::{layer::SubscriberExt, Layer};use crate::{cursor::{spawn_cursor_recorder, CursorActor, Cursors},@@ -128,181 +135,236 @@ pub async fn spawn_recording_actor(camera_feed: Option<Arc<Mutex<CameraFeed>>>,audio_input_feed: Option<AudioInputFeed>,) -> Result<ActorHandle, RecordingError> {- let recording_dir = recording_dir.into();-- let content_dir = ensure_dir(recording_dir.join("content"))?;-- let segments_dir = ensure_dir(content_dir.join("segments"))?;- let cursors_dir = ensure_dir(content_dir.join("cursors"))?;-- let screen_source = create_screen_capture(&options);-- let index = 0;- let pipeline = create_segment_pipeline(- &segments_dir,- &cursors_dir,- index,- screen_source.clone(),- camera_feed.as_deref(),- audio_input_feed.as_ref(),- Default::default(),- index,- )- .await?;-- let segment_start_time = current_time_f64();-- let (ctrl_tx, ctrl_rx) = flume::bounded(1);-- tokio::spawn({- let options = options.clone();- async move {- let mut actor = Actor {- id,- recording_dir,- options,- segments: Vec::new(),- };-- let mut state = ActorState::Recording {- pipeline,+ let collector = tracing_subscriber::registry().with(+ tracing_subscriber::fmt::layer()+ .with_ansi(true)+ .with_target(false)+ .with_filter(+ tracing_subscriber::filter::EnvFilter::builder()+ .with_default_directive(tracing::level_filters::LevelFilter::DEBUG.into())+ .from_env_lossy(),+ ),+ );+ // let collector = tracing_subscriber::fmt()+ // .with_ansi(true)+ // .with_max_level(tracing::Level::TRACE)+ // .with_target(false)+ // .finish();++ async {+ async {+ trace!("creating recording actor");++ let recording_dir = recording_dir.into();++ let content_dir = ensure_dir(recording_dir.join("content"))?;++ let segments_dir = ensure_dir(content_dir.join("segments"))?;+ let cursors_dir = ensure_dir(content_dir.join("cursors"))?;++ let screen_source = create_screen_capture(&options);++ debug!("screen capture: {screen_source:#?}");++ if let Some(camera_feed) = &camera_feed {+ let camera_feed = camera_feed.lock().await;+ debug!("camera device info: {:#?}", camera_feed.camera_info());+ debug!("camera video info: {:#?}", camera_feed.video_info());+ }++ if let Some(audio_feed) = &audio_input_feed {+ debug!("mic audio info: {:#?}", audio_feed.audio_info())+ }++ let index = 0;+ let pipeline = create_segment_pipeline(+ &segments_dir,+ &cursors_dir,+ index,+ screen_source.clone(),+ camera_feed.as_deref(),+ audio_input_feed.as_ref(),+ Default::default(),index,- segment_start_time,- };+ )+ .await?;- loop {- state = match state {- ActorState::Recording {+ let segment_start_time = current_time_f64();++ let (ctrl_tx, ctrl_rx) = flume::bounded(1);++ trace!("spawning recording actor");++ spawn_actor({+ let options = options.clone();+ async move {+ let mut actor = Actor {+ id,+ recording_dir,+ options,+ segments: Vec::new(),+ };++ let mut state = ActorState::Recording {pipeline,index,segment_start_time,- } => loop {- let Ok(msg) = ctrl_rx.recv_async().await else {- return;- };+ };- async fn shutdown(- mut pipeline: RecordingPipeline,- actor: &mut Actor,- segment_start_time: f64,- ) -> Result<(Cursors, u32), RecordingError> {- pipeline.inner.shutdown().await?;-- let segment_stop_time = current_time_f64();-- let cursors = if let Some(cursor) = pipeline.cursor.take() {- let res = cursor.actor.stop().await;-- std::fs::write(- &cursor.output_path,- serde_json::to_string_pretty(&CursorEvents {- clicks: res.clicks,- moves: res.moves,- })?,- )?;-- (res.cursors, res.next_cursor_id)- } else {- Default::default()- };-- actor.segments.push(RecordingSegment {- start: segment_start_time,- end: segment_stop_time,+ loop {+ state = match state {+ ActorState::Recording {pipeline,- });-- Ok(cursors)- }-- break match msg {- ActorControlMessage::Pause(tx) => {- let (res, cursors, next_cursor_id) = match shutdown(- pipeline,- &mut actor,- segment_start_time,- )- .await- {- Ok((cursors, next_cursor_id)) => {- (Ok(()), cursors, next_cursor_id)+ index,+ segment_start_time,+ } => {+ info!("recording actor recording");+ loop {+ let Ok(msg) = ctrl_rx.recv_async().await else {+ return;+ };++ async fn shutdown(+ mut pipeline: RecordingPipeline,+ actor: &mut Actor,+ segment_start_time: f64,+ ) -> Result<(Cursors, u32), RecordingError>+ {+ pipeline.inner.shutdown().await?;++ let segment_stop_time = current_time_f64();++ let cursors = if let Some(cursor) = pipeline.cursor.take() {+ let res = cursor.actor.stop().await;++ std::fs::write(+ &cursor.output_path,+ serde_json::to_string_pretty(&CursorEvents {+ clicks: res.clicks,+ moves: res.moves,+ })?,+ )?;++ (res.cursors, res.next_cursor_id)+ } else {+ Default::default()+ };++ actor.segments.push(RecordingSegment {+ start: segment_start_time,+ end: segment_stop_time,+ pipeline,+ });++ Ok(cursors)}- Err(e) => (Err(e), Default::default(), 0),- };-- tx.send(res.map_err(Into::into)).ok();- ActorState::Paused {- next_index: index + 1,- cursors,- next_cursor_id,++ break match msg {+ ActorControlMessage::Pause(tx) => {+ let (res, cursors, next_cursor_id) = match shutdown(+ pipeline,+ &mut actor,+ segment_start_time,+ )+ .await+ {+ Ok((cursors, next_cursor_id)) => {+ (Ok(()), cursors, next_cursor_id)+ }+ Err(e) => (Err(e), Default::default(), 0),+ };++ tx.send(res.map_err(Into::into)).ok();+ ActorState::Paused {+ next_index: index + 1,+ cursors,+ next_cursor_id,+ }+ }+ ActorControlMessage::Stop(tx) => {+ let res =+ shutdown(pipeline, &mut actor, segment_start_time)+ .await;+ let res = match res {+ Ok((cursors, _)) => {+ stop_recording(actor, cursors).await+ }+ Err(e) => Err(e),+ };++ tx.send(res).ok();++ return;+ }+ _ => continue,+ };}}- ActorControlMessage::Stop(tx) => {- let res = shutdown(pipeline, &mut actor, segment_start_time).await;- let res = match res {- Ok((cursors, _)) => stop_recording(actor, cursors).await,- Err(e) => Err(e),- };-- tx.send(res).ok();-- return;+ ActorState::Paused {+ next_index,+ cursors,+ next_cursor_id,+ } => {+ info!("recording actor paused");+ loop {+ let Ok(msg) = ctrl_rx.recv_async().await else {+ return;+ };++ break match msg {+ ActorControlMessage::Stop(tx) => {+ tx.send(stop_recording(actor, cursors).await).ok();+ return;+ }+ ActorControlMessage::Resume(tx) => {+ let (state, res) = match create_segment_pipeline(+ &segments_dir,+ &cursors_dir,+ next_index,+ screen_source.clone(),+ camera_feed.as_deref(),+ audio_input_feed.as_ref(),+ cursors,+ next_cursor_id,+ )+ .await+ {+ Ok(pipeline) => (+ ActorState::Recording {+ pipeline,+ index: next_index,+ segment_start_time: current_time_f64(),+ },+ Ok(()),+ ),+ Err(e) => (ActorState::Stopped, Err(e.into())),+ };++ tx.send(res).ok();++ state+ }+ _ => continue,+ };+ }}- _ => continue,- };- },- ActorState::Paused {- next_index,- cursors,- next_cursor_id,- } => loop {- let Ok(msg) = ctrl_rx.recv_async().await else {- return;- };-- break match msg {- ActorControlMessage::Stop(tx) => {- tx.send(stop_recording(actor, cursors).await).ok();+ ActorState::Stopped => {+ info!("recording actor paused");return;}- ActorControlMessage::Resume(tx) => {- let (state, res) = match create_segment_pipeline(- &segments_dir,- &cursors_dir,- next_index,- screen_source.clone(),- camera_feed.as_deref(),- audio_input_feed.as_ref(),- cursors,- next_cursor_id,- )- .await- {- Ok(pipeline) => (- ActorState::Recording {- pipeline,- index: next_index,- segment_start_time: current_time_f64(),- },- Ok(()),- ),- Err(e) => (ActorState::Stopped, Err(e.into())),- };-- tx.send(res).ok();-- state- }- _ => continue,};- },- ActorState::Stopped => return,- };- }- }- });+ }+ }+ .in_current_span()+ });- Ok(ActorHandle { ctrl_tx, options })+ Ok(ActorHandle { ctrl_tx, options })+ }+ .instrument(tracing::info_span!("recording"))+ .await+ }+ .with_subscriber(collector)+ .await}pub struct CompletedRecording {@@ -395,7 +457,7 @@ fn create_screen_capture(#[cfg(target_os = "macos")]{ScreenCaptureSource::<cap_media::sources::CMSampleBufferCapture>::init(- dbg!(&recording_options.capture_target),+ &recording_options.capture_target,recording_options.output_resolution.clone(),None,)@@ -403,13 +465,14 @@ fn create_screen_capture(#[cfg(not(target_os = "macos"))]{ScreenCaptureSource::<cap_media::sources::AVFrameCapture>::init(- dbg!(&recording_options.capture_target),+ &recording_options.capture_target,recording_options.output_resolution.clone(),None,)}}+#[tracing::instrument(skip_all, name = "segment", fields(index = index))]async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(segments_dir: &PathBuf,cursors_dir: &PathBuf,@@ -432,8 +495,8 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(let mut pipeline_builder = Pipeline::builder(clock);let display_output_path = dir.join("display.mp4");- let mut audio_output_path = None;- let mut camera_output_path = None;++ trace!("preparing segment pipeline {index}");let screen_bounds = screen_source.get_bounds();pipeline_builder = TCaptureFormat::make_capture_pipeline(@@ -442,40 +505,53 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(&display_output_path,)?;- if let Some(mic_source) = audio_input_feed.map(AudioInputSource::init) {+ trace!(+ r#"screen pipeline prepared, will output to "{}""#,+ display_output_path.strip_prefix(&dir).unwrap().display()+ );++ let audio_output_path = if let Some(mic_source) = audio_input_feed.map(AudioInputSource::init) {let mic_config = mic_source.info();- audio_output_path = Some(dir.join("audio-input.mp3"));+ let output_path = dir.join("audio-input.mp3");- let mic_encoder = MP3Encoder::init(- "microphone",- mic_config,- Output::File(audio_output_path.clone().unwrap()),- )?;+ let mic_encoder =+ MP3Encoder::init("microphone", mic_config, Output::File(output_path.clone()))?;pipeline_builder = pipeline_builder.source("microphone_capture", mic_source).sink("microphone_encoder", mic_encoder);- }++ debug!(+ "mic pipeline prepared, will output to {}",+ output_path.display()+ );++ Some(output_path)+ } else {+ None+ };let camera = if let Some(camera_source) = camera_feed.map(CameraSource::init) {let camera_config = camera_source.info();let output_config = camera_config.scaled(1280_u32, 30_u32);- camera_output_path = Some(dir.join("camera.mp4"));+ let output_path = dir.join("camera.mp4");let camera_filter = VideoFilter::init("camera", camera_config, output_config)?;- let camera_encoder = H264Encoder::init(- "camera",- output_config,- Output::File(camera_output_path.clone().unwrap()),- )?;+ let camera_encoder =+ H264Encoder::init("camera", output_config, Output::File(output_path.clone()))?;pipeline_builder = pipeline_builder.source("camera_capture", camera_source).pipe("camera_filter", camera_filter).sink("camera_encoder", camera_encoder);+ debug!(+ "mic pipeline prepared, will output to {}",+ output_path.display()+ );+Some(CameraPipelineInfo {- output_path: camera_output_path.clone().unwrap(),+ output_path,fps: (camera_config.frame_rate.0 / camera_config.frame_rate.1) as u32,})} else {@@ -500,6 +576,8 @@ async fn create_segment_pipeline<TCaptureFormat: MakeCapturePipeline>(pipeline.play().await?;+ info!("pipeline playing");+Ok(RecordingPipeline {inner: pipeline,display_output_path,@@ -521,7 +599,7 @@ fn ensure_dir(path: PathBuf) -> Result<PathBuf, MediaError> {type CapturePipelineBuilder = PipelineBuilder<RealTimeClock<()>>;-trait MakeCapturePipeline: 'static {+trait MakeCapturePipeline: std::fmt::Debug + 'static {fn make_capture_pipeline(builder: CapturePipelineBuilder,source: ScreenCaptureSource<Self>,@@ -541,7 +619,7 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {let screen_config = source.info();let screen_encoder = cap_media::encoders::H264AVAssetWriterEncoder::init("screen",- dbg!(screen_config),+ screen_config,Output::File(output_path.into()),)?;diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rsindex e1bae1817..249945651 100644--- a/crates/recording/src/cursor.rs+++ b/crates/recording/src/cursor.rs@@ -8,8 +8,10 @@ use std::{use cap_media::platform::Bounds;use cap_project::{CursorClickEvent, CursorMoveEvent};+use cap_utils::spawn_actor;use device_query::{DeviceQuery, DeviceState};use tokio::sync::oneshot;+use tracing::{debug, error, info};pub type Cursors = HashMap<u64, (String, u32)>;@@ -34,6 +36,7 @@ impl CursorActor {}}+#[tracing::instrument(name = "cursor", skip_all)]pub fn spawn_cursor_recorder(screen_bounds: Bounds,cursors_dir: PathBuf,@@ -43,7 +46,7 @@ pub fn spawn_cursor_recorder(let stop_signal = Arc::new(AtomicBool::new(false));let (tx, rx) = oneshot::channel();- tokio::spawn({+ spawn_actor({let stop_signal = stop_signal.clone();async move {let device_state = DeviceState::new();@@ -80,16 +83,14 @@ pub fn spawn_cursor_recorder(let filename = format!("cursor_{}.png", cursor_id);let cursor_path = cursors_dir.join(&filename);- println!("Saving new cursor image to: {:?}", cursor_path);-if let Ok(image) = image::load_from_memory(&data) {// Convert to RGBAlet rgba_image = image.into_rgba8();if let Err(e) = rgba_image.save(&cursor_path) {- eprintln!("Failed to save cursor image: {}", e);+ error!("Failed to save cursor image: {}", e);} else {- println!("Successfully saved cursor image {}", cursor_id);+ info!("Saved cursor {cursor_id} image to: {:?}", filename);response.cursors.insert(id, (filename.clone(), response.next_cursor_id));diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex 3cd77245b..fcb7d7ca6 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -1026,7 +1026,6 @@ pub async fn produce_frame(let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());- // dbg!(constants.options.screen_size.x, screen_frame.len());constants.queue.write_texture(wgpu::ImageCopyTexture {texture: &texture,diff --git a/crates/utils/Cargo.toml b/crates/utils/Cargo.tomlindex 520963df6..95b40c165 100644--- a/crates/utils/Cargo.toml+++ b/crates/utils/Cargo.toml@@ -26,3 +26,4 @@ uuid = "1.11.0"serde = { version = "1.0", features = ["derive"] }serde_json = "1.0"flume = "0.11.0"+tracing = "0.1.41"diff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rsindex 0e2f7094f..55fe56adb 100644--- a/crates/utils/src/lib.rs+++ b/crates/utils/src/lib.rs@@ -1,6 +1,6 @@-use std::{ffi::OsString, path::PathBuf};-use tokio::io::AsyncWriteExt;-use tokio::sync::mpsc::Receiver;+use std::future::Future;++use tracing::Instrument;#[cfg(windows)]pub fn get_last_win32_error_formatted() -> String {@@ -33,78 +33,12 @@ pub fn format_error_message(error_code: u32) -> String {}}-pub fn create_channel_named_pipe<T, F>(- mut rx: Receiver<T>,- pipe_path: PathBuf,- mut chunk_fn: F,-) -> OsString+/// Wrapper around tokio::spawn that inherits the current tracing subscriber and span.+pub fn spawn_actor<F>(future: F) -> tokio::task::JoinHandle<F::Output>where- T: Send + 'static,- F: FnMut(&T) -> Option<&[u8]> + Send + 'static,+ F: Future + Send + 'static,+ F::Output: Send + 'static,{- #[cfg(windows)]- {- // Build proper Windows named pipe path, e.g. \\.\pipe\my_pipe_name- // Use the final filename from `pipe_path` to avoid conflicts- let filename = pipe_path- .file_name()- .unwrap_or_else(|| std::ffi::OsStr::new("cap-default-pipe"));- let pipe_name = format!(r"\\.\pipe\{}", filename.to_string_lossy());- let os_pipe_name = OsString::from(&pipe_name);-- tokio::spawn(async move {- let mut server = tokio::net::windows::named_pipe::ServerOptions::new()- .first_pipe_instance(true)- .create(&pipe_name)- .expect("Failed to create named pipe");-- // For each message from rx, repeatedly call chunk_fn until None is returned- while let Some(msg) = rx.recv().await {- loop {- if let Some(bytes) = chunk_fn(&msg) {- if let Err(e) = server.write_all(bytes).await {- eprintln!("Error writing to named pipe: {e}");- break;- }- } else {- break;- }- }- }- });-- return os_pipe_name;- }-- #[cfg(unix)]- {- use nix::sys::stat;- let os_pipe_name = pipe_path.clone().into_os_string();-- let _ = std::fs::remove_file(&pipe_path);- // Make FIFO if not existing- nix::unistd::mkfifo(&pipe_path, stat::Mode::S_IRWXU)- .expect("Failed to create a Unix FIFO with mkfifo()");-- tokio::spawn(async move {- let mut file = tokio::fs::File::create(&pipe_path)- .await- .expect("Failed to open FIFO for writing");-- while let Some(msg) = rx.recv().await {- loop {- if let Some(bytes) = chunk_fn(&msg) {- if let Err(e) = file.write_all(bytes).await {- eprintln!("Error writing to FIFO: {e}");- break;- }- } else {- break;- }- }- }- });-- return os_pipe_name;- }+ use tracing::instrument::WithSubscriber;+ tokio::spawn(future.with_current_subscriber().in_current_span())}