Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
Cleanup Rust warnings + edition 2024 & enable lints on all crates (#858)
Oscar Beaumontd04f66a08f08
diff --git a/Cargo.lock b/Cargo.lockindex 295231368..6362f5186 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1,6 +1,6 @@# This file is automatically @generated by Cargo.# It is not intended for manual editing.-version = 3+version = 4[[package]]name = "Inflector"@@ -850,7 +850,6 @@ dependencies = ["cap-rendering","cap-utils","clap",- "editor","ffmpeg-next","flume","scap",@@ -2050,22 +2049,6 @@ dependencies = ["winapi",]-[[package]]-name = "crossterm"-version = "0.27.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f476fe445d41c9e991fd07515a6f463074b782242ccf4a5b7b1d1012e70824df"-dependencies = [- "bitflags 2.9.1",- "crossterm_winapi",- "libc",- "mio 0.8.11",- "parking_lot",- "signal-hook",- "signal-hook-mio",- "winapi",-]-[[package]]name = "crossterm_winapi"version = "0.9.1"@@ -2432,17 +2415,6 @@ version = "1.0.20"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"-[[package]]-name = "editor"-version = "0.1.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3effaacc281d186774006894b787746c6870484cd08834ff42bfa2a6aa60ab6e"-dependencies = [- "crossterm 0.27.0",- "derive_more",- "glam",-]-[[package]]name = "either"version = "1.15.0"@@ -3215,12 +3187,6 @@ dependencies = ["xml-rs",]-[[package]]-name = "glam"-version = "0.28.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "779ae4bf7e8421cf91c0b3b64e7e8b40b862fba4d393f59150042de7c4965a94"-[[package]]name = "glib"version = "0.18.5"@@ -3927,7 +3893,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0fddf93031af70e75410a2511ec04d49e758ed2f26dad3404a934e0fb45cc12a"dependencies = ["bitflags 2.9.1",- "crossterm 0.25.0",+ "crossterm","dyn-clone","fuzzy-matcher","fxhash",diff --git a/Cargo.toml b/Cargo.tomlindex 6e4818c35..477df9c32 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -59,6 +59,11 @@ windows-sys = "0.59.0"windows-capture = "1.5.0"percent-encoding = "2.3.1"+# TODO: Reenable these: https://github.com/CapSoftware/Cap/issues/859+[workspace.lints.rust]+deprecated = "allow"+unexpected_cfgs = "allow"+[workspace.lints.clippy]dbg_macro = "deny"let_underscore_future = "deny"diff --git a/apps/cli/Cargo.toml b/apps/cli/Cargo.tomlindex 00186447c..05105bf0d 100644--- a/apps/cli/Cargo.toml+++ b/apps/cli/Cargo.toml@@ -1,7 +1,7 @@[package]name = "cap"version = "0.1.0"-edition = "2021"+edition = "2024"[dependencies]clap = { version = "4.5.23", features = ["derive"] }@@ -17,10 +17,12 @@ cap-camera = { path = "../../crates/camera" }serde = { workspace = true }serde_json = "1.0.133"tokio.workspace = true-editor = "0.1.1"scap.workspace = trueuuid = { version = "1.11.1", features = ["v4"] }ffmpeg = { workspace = true }tracing.workspace = truetracing-subscriber = "0.3.19"flume.workspace = true++[lints]+workspace = truediff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rsindex 791ddb37a..87285f4d9 100644--- a/apps/cli/src/main.rs+++ b/apps/cli/src/main.rs@@ -1,7 +1,7 @@mod record;use std::{- io::{stdout, Write},+ io::{Write, stdout},path::PathBuf,};@@ -143,7 +143,6 @@ window {}:None => {args.run().await?;}- _ => {}},}@@ -161,7 +160,7 @@ impl Export {let exporter_base = ExporterBase::builder(self.project_path).build().await- .map_err(|v| format!("Exporter build error: {}", v.to_string()))?;+ .map_err(|v| format!("Exporter build error: {v}"))?;let mut stdout = stdout();@@ -170,13 +169,13 @@ impl Export {resolution_base: XY::new(1920, 1080),compression: cap_export::mp4::ExportCompression::Minimal,}- .export(exporter_base, move |f| {+ .export(exporter_base, move |_f| {// print!("\rrendered frame {f}");stdout.flush().unwrap();}).await- .map_err(|v| format!("Exporter error: {}", v.to_string()))?;+ .map_err(|v| format!("Exporter error: {v}"))?;let output_path = if let Some(output_path) = self.output_path {std::fs::copy(&exporter_output_path, &output_path).unwrap();diff --git a/apps/cli/src/record.rs b/apps/cli/src/record.rsindex 2cdad305b..92d9b8bb1 100644--- a/apps/cli/src/record.rs+++ b/apps/cli/src/record.rs@@ -1,7 +1,7 @@use std::{env::current_dir, path::PathBuf, sync::Arc};use cap_camera::ModelID;-use cap_media::{feeds::CameraFeed, sources::ScreenCaptureTarget};+use cap_media::sources::ScreenCaptureTarget;use clap::Args;use tokio::{io::AsyncBufReadExt, sync::Mutex};use uuid::Uuid;@@ -44,7 +44,7 @@ impl RecordStart {}?;let camera = if let Some(model_id) = self.camera {- let model_id: ModelID = model_id+ let _model_id: ModelID = model_id.try_into().map_err(|_| "Invalid model ID".to_string())?;diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex ae5e32521..d6b39d985 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -9,7 +9,7 @@ edition = "2024"workspace = true[lib]-name = "cap_desktop"+name = "cap_desktop_lib"crate-type = ["lib", "cdylib", "staticlib"][build-dependencies]diff --git a/apps/desktop/src-tauri/src/audio_meter.rs b/apps/desktop/src-tauri/src/audio_meter.rsindex 767a7531a..8d69bf020 100644--- a/apps/desktop/src-tauri/src/audio_meter.rs+++ b/apps/desktop/src-tauri/src/audio_meter.rs@@ -53,19 +53,15 @@ impl VolumeMeter {self.maxes.push(time, value);self.times.push_back(time);- loop {- if let Some(time) = self- .times- .back()- .unwrap()- .duration_since(self.times.front().unwrap())- {- if time > self.keep_duration {- self.maxes.remove(self.times.front().unwrap());- self.times.pop_front();- } else {- break;- }+ while let Some(time) = self+ .times+ .back()+ .unwrap()+ .duration_since(self.times.front().unwrap())+ {+ if time > self.keep_duration {+ self.maxes.remove(self.times.front().unwrap());+ self.times.pop_front();} else {break;}@@ -86,6 +82,7 @@ struct MinNonNan(f64);impl Eq for MinNonNan {}+#[allow(clippy::non_canonical_partial_ord_impl)]impl PartialOrd for MinNonNan {fn partial_cmp(&self, other: &Self) -> Option<Ordering> {other.0.partial_cmp(&self.0)diff --git a/apps/desktop/src-tauri/src/auth.rs b/apps/desktop/src-tauri/src/auth.rsindex 406954161..97f999a4b 100644--- a/apps/desktop/src-tauri/src/auth.rs+++ b/apps/desktop/src-tauri/src/auth.rs@@ -57,10 +57,10 @@ impl AuthStore {return Err("User not authenticated".to_string());};- if let Some(plan) = &auth.plan {- if plan.manual {- return Ok(());- }+ if let Some(plan) = &auth.plan+ && plan.manual+ {+ return Ok(());}let mut auth = auth;@@ -72,7 +72,7 @@ impl AuthStore {.authed_api_request("/api/desktop/plan", |client, url| client.get(url)).await.map_err(|e| {- println!("Failed to fetch plan: {}", e);+ println!("Failed to fetch plan: {e}");e.to_string()})?;println!("Plan fetch response status: {}", response.status());@@ -93,7 +93,7 @@ impl AuthStore {auth.plan = Some(Plan {upgraded: plan_response.upgraded,last_checked: chrono::Utc::now().timestamp() as i32,- manual: auth.plan.as_ref().map_or(false, |p| p.manual),+ manual: auth.plan.as_ref().is_some_and(|p| p.manual),});auth.intercom_hash = Some(plan_response.intercom_hash.unwrap_or_default());diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rsindex bf1064e67..e587fa90f 100644--- a/apps/desktop/src-tauri/src/camera.rs+++ b/apps/desktop/src-tauri/src/camera.rs@@ -56,6 +56,7 @@ pub struct CameraWindowState {}pub struct CameraPreview {+ #[allow(clippy::type_complexity)]reconfigure: (broadcast::Sender<Option<(u32, u32)>>,broadcast::Receiver<Option<(u32, u32)>>,@@ -205,13 +206,13 @@ impl CameraPreview {let output_height = (1280.0 / camera_aspect_ratio) as u32;let new_texture_value = if let Some(frame) = frame {- if loading == true {+ if loading {loading_state.store(false, Ordering::Relaxed);loading = false;}let resampler_frame = resampler_frame- .get_or_init((output_width, output_height), || frame::Video::empty());+ .get_or_init((output_width, output_height), frame::Video::empty);scaler.cached(frame.format(),@@ -268,7 +269,7 @@ impl CameraPreview {/// Save the current state of the camera window.pub fn save(&self, state: &CameraWindowState) -> tauri_plugin_store::Result<()> {- self.store.set("state", serde_json::to_value(&state)?);+ self.store.set("state", serde_json::to_value(state)?);self.store.save()?;self.reconfigure.0.send(None).ok();Ok(())@@ -509,11 +510,6 @@ impl Renderer {.contains(&CompositeAlphaMode::PostMultiplied){CompositeAlphaMode::PostMultiplied- } else if surface_capabilities- .alpha_modes- .contains(&CompositeAlphaMode::PostMultiplied)- {- CompositeAlphaMode::PostMultiplied} else {CompositeAlphaMode::Inherit};@@ -598,7 +594,7 @@ impl Renderer {_,) = if let Some(monitor) = self.window.current_monitor()? {let size = monitor.position().to_logical(monitor.scale_factor());- (monitor.size().clone(), size, monitor.scale_factor())+ (*monitor.size(), size, monitor.scale_factor())} else {(PhysicalSize::new(640, 360), LogicalPosition::new(0, 0), 1.0)};@@ -701,8 +697,8 @@ impl Renderer {.texture.create_view(&wgpu::TextureViewDescriptor::default());- let surface_width = surface.texture.width();- let surface_height = surface.texture.height();+ // let surface_width = surface.texture.width();+ // let surface_height = surface.texture.height();let mut encoder = self.device@@ -775,7 +771,7 @@ impl Renderer {origin: wgpu::Origin3d::ZERO,aspect: wgpu::TextureAspect::All,},- &buffer,+ buffer,wgpu::TexelCopyBufferLayout {offset: 0,bytes_per_row: Some(stride),@@ -823,7 +819,7 @@ impl<K, V> Default for Cached<K, V> {}impl<K: PartialEq, V> Cached<K, V> {- pub fn get_or_init<'a>(&'a mut self, key: K, init: impl FnOnce() -> V) -> &'a mut V {+ pub fn get_or_init(&mut self, key: K, init: impl FnOnce() -> V) -> &mut V {if self.value.as_ref().is_none_or(|(k, _)| *k != key) {self.value = Some((key, init()));}diff --git a/apps/desktop/src-tauri/src/captions.rs b/apps/desktop/src-tauri/src/captions.rsindex 10b7f0f23..b00d3a21b 100644--- a/apps/desktop/src-tauri/src/captions.rs+++ b/apps/desktop/src-tauri/src/captions.rs@@ -1,6 +1,5 @@use anyhow::Result;use cap_audio::AudioData;-use cap_project;use ffmpeg::{ChannelLayout, codec as avcodec,format::{self as avformat},@@ -50,19 +49,19 @@ const WHISPER_SAMPLE_RATE: u32 = 16000;#[tauri::command]#[specta::specta]pub async fn create_dir(path: String, _recursive: bool) -> Result<(), String> {- std::fs::create_dir_all(path).map_err(|e| format!("Failed to create directory: {}", e))+ std::fs::create_dir_all(path).map_err(|e| format!("Failed to create directory: {e}"))}/// Function to save the model file#[tauri::command]#[specta::specta]pub async fn save_model_file(path: String, data: Vec<u8>) -> Result<(), String> {- std::fs::write(&path, &data).map_err(|e| format!("Failed to write model file: {}", e))+ std::fs::write(&path, &data).map_err(|e| format!("Failed to write model file: {e}"))}/// Extract audio from a video file and save it as a temporary WAV fileasync fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Result<(), String> {- log::info!("Attempting to extract audio from: {}", video_path);+ log::info!("Attempting to extract audio from: {video_path}");// Check if this is a .cap directoryif video_path.ends_with(".cap") {@@ -71,10 +70,10 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re// Read the recording metadatalet meta_path = std::path::Path::new(video_path).join("recording-meta.json");let meta_content = std::fs::read_to_string(&meta_path)- .map_err(|e| format!("Failed to read recording metadata: {}", e))?;+ .map_err(|e| format!("Failed to read recording metadata: {e}"))?;let meta: serde_json::Value = serde_json::from_str(&meta_content)- .map_err(|e| format!("Failed to parse recording metadata: {}", e))?;+ .map_err(|e| format!("Failed to parse recording metadata: {e}"))?;// Get paths for both audio sourceslet base_path = std::path::Path::new(video_path);@@ -149,7 +148,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re}}Err(e) => {- log::warn!("Failed to process audio source {:?}: {}", source, e);+ log::warn!("Failed to process audio source {source:?}: {e}");continue;}}@@ -157,10 +156,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re// No matter what, ensure we have mono audio for Whisperif channel_count > 1 {- log::info!(- "Converting final mixed audio from {} channels to mono",- channel_count- );+ log::info!("Converting final mixed audio from {channel_count} channels to mono");mixed_samples = convert_to_mono(&mixed_samples, channel_count);channel_count = 1;}@@ -171,7 +167,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re// Convert to WAV format with desired sample ratelet mut output = avformat::output(&output_path)- .map_err(|e| format!("Failed to create output file: {}", e))?;+ .map_err(|e| format!("Failed to create output file: {e}"))?;let codec = avcodec::encoder::find_by_name("pcm_s16le").ok_or_else(|| "PCM encoder not found".to_string())?;@@ -179,7 +175,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Relet mut encoder = avcodec::Context::new().encoder().audio()- .map_err(|e| format!("Failed to create encoder: {}", e))?;+ .map_err(|e| format!("Failed to create encoder: {e}"))?;encoder.set_rate(WHISPER_SAMPLE_RATE as i32);let channel_layout = ChannelLayout::MONO;@@ -188,16 +184,16 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Relet mut encoder = encoder.open_as(codec)- .map_err(|e| format!("Failed to open encoder: {}", e))?;+ .map_err(|e| format!("Failed to open encoder: {e}"))?;let mut stream = output.add_stream(codec)- .map_err(|e| format!("Failed to add stream: {}", e))?;+ .map_err(|e| format!("Failed to add stream: {e}"))?;stream.set_parameters(&encoder);output.write_header()- .map_err(|e| format!("Failed to write header: {}", e))?;+ .map_err(|e| format!("Failed to write header: {e}"))?;// Create resampler for sample rate conversionlet mut resampler = resampling::Context::get(@@ -208,7 +204,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Rechannel_layout,WHISPER_SAMPLE_RATE,)- .map_err(|e| format!("Failed to create resampler: {}", e))?;+ .map_err(|e| format!("Failed to create resampler: {e}"))?;// Process audio in chunkslet frame_size = encoder.frame_size() as usize;@@ -249,7 +245,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Relet bytes = unsafe {std::slice::from_raw_parts(chunk.as_ptr() as *const u8,- chunk.len() * std::mem::size_of::<f32>(),+ std::mem::size_of_val(chunk),)};input_frame.data_mut(0)[0..bytes.len()].copy_from_slice(bytes);@@ -274,13 +270,13 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re}}Err(e) => {- log::error!("Failed to resample chunk {}: {}", chunk_idx, e);+ log::error!("Failed to resample chunk {chunk_idx}: {e}");continue;}}if let Err(e) = encoder.send_frame(&output_frame) {- log::error!("Failed to send frame to encoder: {}", e);+ log::error!("Failed to send frame to encoder: {e}");continue;}@@ -290,7 +286,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Rematch encoder.receive_packet(&mut packet) {Ok(_) => {if let Err(e) = packet.write_interleaved(&mut output) {- log::error!("Failed to write packet: {}", e);+ log::error!("Failed to write packet: {e}");}}Err(_) => break,@@ -302,7 +298,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re// Flush the encoderencoder.send_eof()- .map_err(|e| format!("Failed to send EOF: {}", e))?;+ .map_err(|e| format!("Failed to send EOF: {e}"))?;// Process final packets in a loop with limited borrow scopeloop {@@ -316,20 +312,20 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re// Use a block to limit the scope of the output borrow{if let Err(e) = packet.write_interleaved(&mut output) {- return Err(format!("Failed to write final packet: {}", e));+ return Err(format!("Failed to write final packet: {e}"));}}}output.write_trailer()- .map_err(|e| format!("Failed to write trailer: {}", e))?;+ .map_err(|e| format!("Failed to write trailer: {e}"))?;Ok(())} else {// Handle regular video file- let mut input = avformat::input(&video_path)- .map_err(|e| format!("Failed to open video file: {}", e))?;+ let mut input =+ avformat::input(&video_path).map_err(|e| format!("Failed to open video file: {e}"))?;let stream = input.streams()@@ -340,13 +336,13 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re// Get decoder parameters firstlet decoder_ctx = avcodec::Context::from_parameters(codec_params.clone())- .map_err(|e| format!("Failed to create decoder context: {}", e))?;+ .map_err(|e| format!("Failed to create decoder context: {e}"))?;// Create and open the decoderlet mut decoder = decoder_ctx.decoder().audio()- .map_err(|e| format!("Failed to create decoder: {}", e))?;+ .map_err(|e| format!("Failed to create decoder: {e}"))?;// Now we can access audio-specific methodslet decoder_format = decoder.format();@@ -360,7 +356,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Relet mut encoder_ctx = avcodec::Context::new().encoder().audio()- .map_err(|e| format!("Failed to create encoder: {}", e))?;+ .map_err(|e| format!("Failed to create encoder: {e}"))?;encoder_ctx.set_rate(WHISPER_SAMPLE_RATE as i32);encoder_ctx.set_channel_layout(channel_layout);@@ -371,17 +367,17 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Relet mut encoder = encoder_ctx.open_as(codec)- .map_err(|e| format!("Failed to open encoder: {}", e))?;+ .map_err(|e| format!("Failed to open encoder: {e}"))?;// Create output context separatelylet mut output = avformat::output(&output_path)- .map_err(|e| format!("Failed to create output file: {}", e))?;+ .map_err(|e| format!("Failed to create output file: {e}"))?;// Add stream and get parameters in a block to limit the borrowlet stream_params = {let mut output_stream = output.add_stream(codec)- .map_err(|e| format!("Failed to add stream: {}", e))?;+ .map_err(|e| format!("Failed to add stream: {e}"))?;output_stream.set_parameters(&encoder);@@ -392,7 +388,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re// Write headeroutput.write_header()- .map_err(|e| format!("Failed to write header: {}", e))?;+ .map_err(|e| format!("Failed to write header: {e}"))?;// Create resamplerlet mut resampler = resampling::Context::get(@@ -403,7 +399,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Rechannel_layout,WHISPER_SAMPLE_RATE,)- .map_err(|e| format!("Failed to create resampler: {}", e))?;+ .map_err(|e| format!("Failed to create resampler: {e}"))?;// Create frameslet mut decoded_frame = ffmpeg::frame::Audio::empty();@@ -444,19 +440,19 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re// Then process each cloned packetfor packet_res in packet_queue {if let Err(e) = decoder.send_packet(&packet_res) {- log::warn!("Failed to send packet to decoder: {}", e);+ log::warn!("Failed to send packet to decoder: {e}");continue;}// Process decoded frames- while let Ok(_) = decoder.receive_frame(&mut decoded_frame) {+ while decoder.receive_frame(&mut decoded_frame).is_ok() {if let Err(e) = resampler.run(&decoded_frame, &mut resampled_frame) {- log::warn!("Failed to resample audio: {}", e);+ log::warn!("Failed to resample audio: {e}");continue;}if let Err(e) = encoder.send_frame(&resampled_frame) {- log::warn!("Failed to send frame to encoder: {}", e);+ log::warn!("Failed to send frame to encoder: {e}");continue;}@@ -469,7 +465,7 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Repacket.set_stream(stream_params.0);if let Err(e) = packet.write_interleaved(&mut output) {- log::error!("Failed to write packet: {}", e);+ log::error!("Failed to write packet: {e}");}}Err(_) => break,@@ -481,16 +477,16 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Re// Flush the decoderdecoder.send_eof()- .map_err(|e| format!("Failed to send EOF to decoder: {}", e))?;+ .map_err(|e| format!("Failed to send EOF to decoder: {e}"))?;while decoder.receive_frame(&mut decoded_frame).is_ok() {resampler.run(&decoded_frame, &mut resampled_frame)- .map_err(|e| format!("Failed to resample final audio: {}", e))?;+ .map_err(|e| format!("Failed to resample final audio: {e}"))?;encoder.send_frame(&resampled_frame)- .map_err(|e| format!("Failed to send final frame: {}", e))?;+ .map_err(|e| format!("Failed to send final frame: {e}"))?;// Process final encoded packetsloop {@@ -503,14 +499,14 @@ async fn extract_audio_from_video(video_path: &str, output_path: &PathBuf) -> Repacket.write_interleaved(&mut output)- .map_err(|e| format!("Failed to write final packet: {}", e))?;+ .map_err(|e| format!("Failed to write final packet: {e}"))?;}}// Close the output file with traileroutput.write_trailer()- .map_err(|e| format!("Failed to write trailer: {}", e))?;+ .map_err(|e| format!("Failed to write trailer: {e}"))?;Ok(())}@@ -521,9 +517,9 @@ async fn get_whisper_context(model_path: &str) -> Result<Arc<WhisperContext>, Stlet mut context_guard = WHISPER_CONTEXT.lock().await;// Always create a new context to avoid issues with multiple uses- log::info!("Initializing Whisper context with model: {}", model_path);+ log::info!("Initializing Whisper context with model: {model_path}");let ctx = WhisperContext::new_with_params(model_path, WhisperContextParameters::default())- .map_err(|e| format!("Failed to load Whisper model: {}", e))?;+ .map_err(|e| format!("Failed to load Whisper model: {e}"))?;*context_guard = Some(ctx);@@ -539,7 +535,7 @@ fn process_with_whisper(context: Arc<WhisperContext>,language: &str,) -> Result<CaptionData, String> {- log::info!("Processing audio file: {:?}", audio_path);+ log::info!("Processing audio file: {audio_path:?}");// Set up parameters for Whisperlet mut params = FullParams::new(SamplingStrategy::Greedy { best_of: 1 });@@ -555,11 +551,11 @@ fn process_with_whisper(// Load audio filelet mut audio_file = File::open(audio_path)- .map_err(|e| format!("Failed to open audio file: {} at path: {:?}", e, audio_path))?;+ .map_err(|e| format!("Failed to open audio file: {e} at path: {audio_path:?}"))?;let mut audio_data = Vec::new();audio_file.read_to_end(&mut audio_data)- .map_err(|e| format!("Failed to read audio file: {}", e))?;+ .map_err(|e| format!("Failed to read audio file: {e}"))?;log::info!("Processing audio file of size: {} bytes", audio_data.len());@@ -579,12 +575,7 @@ fn process_with_whisper(let min_sample = audio_data_f32.iter().fold(f32::MAX, |a, &b| a.min(b));let max_sample = audio_data_f32.iter().fold(f32::MIN, |a, &b| a.max(b));let avg_sample = audio_data_f32.iter().sum::<f32>() / audio_data_f32.len() as f32;- log::info!(- "Audio samples - min: {}, max: {}, avg: {}",- min_sample,- max_sample,- avg_sample- );+ log::info!("Audio samples - min: {min_sample}, max: {max_sample}, avg: {avg_sample}");// Sample a few valueslet sample_count = audio_data_f32.len().min(10);@@ -597,33 +588,33 @@ fn process_with_whisper(// Run the transcriptionlet mut state = context.create_state()- .map_err(|e| format!("Failed to create Whisper state: {}", e))?;+ .map_err(|e| format!("Failed to create Whisper state: {e}"))?;state.full(params, &audio_data_f32[..])- .map_err(|e| format!("Failed to run Whisper transcription: {}", e))?;+ .map_err(|e| format!("Failed to run Whisper transcription: {e}"))?;// Process results: convert Whisper segments to CaptionSegmentlet num_segments = state.full_n_segments()- .map_err(|e| format!("Failed to get number of segments: {}", e))?;+ .map_err(|e| format!("Failed to get number of segments: {e}"))?;- log::info!("Found {} segments", num_segments);+ log::info!("Found {num_segments} segments");let mut segments = Vec::new();for i in 0..num_segments {let text = state.full_get_segment_text(i)- .map_err(|e| format!("Failed to get segment text: {}", e))?;+ .map_err(|e| format!("Failed to get segment text: {e}"))?;// Properly unwrap the Result first, then convert i64 to f64let start_i64 = state.full_get_segment_t0(i)- .map_err(|e| format!("Failed to get segment start time: {}", e))?;+ .map_err(|e| format!("Failed to get segment start time: {e}"))?;let end_i64 = state.full_get_segment_t1(i)- .map_err(|e| format!("Failed to get segment end time: {}", e))?;+ .map_err(|e| format!("Failed to get segment end time: {e}"))?;// Convert timestamps from centiseconds to seconds (as f32 for CaptionSegment)let start_time = (start_i64 as f32) / 100.0;@@ -640,7 +631,7 @@ fn process_with_whisper(if !text.trim().is_empty() {segments.push(CaptionSegment {- id: format!("segment-{}", i),+ id: format!("segment-{i}"),start: start_time,end: end_time,text: text.trim().to_string(),@@ -666,23 +657,23 @@ pub async fn transcribe_audio() -> Result<CaptionData, String> {// Check if files exist with detailed error messagesif !std::path::Path::new(&video_path).exists() {- return Err(format!("Video file not found at path: {}", video_path));+ return Err(format!("Video file not found at path: {video_path}"));}if !std::path::Path::new(&model_path).exists() {- return Err(format!("Model file not found at path: {}", model_path));+ return Err(format!("Model file not found at path: {model_path}"));}// Create temp dir with better error handling- let temp_dir = tempdir().map_err(|e| format!("Failed to create temporary directory: {}", e))?;+ let temp_dir = tempdir().map_err(|e| format!("Failed to create temporary directory: {e}"))?;let audio_path = temp_dir.path().join("audio.wav");// First try the ffmpeg implementationmatch extract_audio_from_video(&video_path, &audio_path).await {- Ok(_) => log::info!("Successfully extracted audio to {:?}", audio_path),+ Ok(_) => log::info!("Successfully extracted audio to {audio_path:?}"),Err(e) => {- log::error!("Failed to extract audio: {}", e);- return Err(format!("Failed to extract audio from video: {}", e));+ log::error!("Failed to extract audio: {e}");+ return Err(format!("Failed to extract audio from video: {e}"));}}@@ -691,14 +682,14 @@ pub async fn transcribe_audio(return Err("Failed to create audio file for transcription".to_string());}- log::info!("Audio file created at: {:?}", audio_path);+ log::info!("Audio file created at: {audio_path:?}");// Get or initialize Whisper context with detailed error handlinglet context = match get_whisper_context(&model_path).await {Ok(ctx) => ctx,Err(e) => {- log::error!("Failed to initialize Whisper context: {}", e);- return Err(format!("Failed to initialize transcription model: {}", e));+ log::error!("Failed to initialize Whisper context: {e}");+ return Err(format!("Failed to initialize transcription model: {e}"));}};@@ -712,8 +703,8 @@ pub async fn transcribe_audio(Ok(captions)}Err(e) => {- log::error!("Failed to process audio with Whisper: {}", e);- Err(format!("Failed to transcribe audio: {}", e))+ log::error!("Failed to process audio with Whisper: {e}");+ Err(format!("Failed to transcribe audio: {e}"))}}}@@ -734,7 +725,7 @@ pub async fn save_captions(tracing::info!("Creating captions directory: {:?}", captions_dir);std::fs::create_dir_all(&captions_dir).map_err(|e| {tracing::error!("Failed to create captions directory: {}", e);- format!("Failed to create captions directory: {}", e)+ format!("Failed to create captions directory: {e}")})?;}@@ -778,7 +769,7 @@ pub async fn save_captions().map_err(|e| {tracing::error!("Failed to serialize captions segments: {}", e);- format!("Failed to serialize captions: {}", e)+ format!("Failed to serialize captions: {e}")})?;json_obj.insert("segments".to_string(), segments_array);@@ -839,12 +830,12 @@ pub async fn save_captions(// Convert to pretty JSON stringlet json = serde_json::to_string_pretty(&json_obj).map_err(|e| {tracing::error!("Failed to serialize captions: {}", e);- format!("Failed to serialize captions: {}", e)+ format!("Failed to serialize captions: {e}")})?;std::fs::write(captions_path, json).map_err(|e| {tracing::error!("Failed to write captions file: {}", e);- format!("Failed to write captions file: {}", e)+ format!("Failed to write captions file: {e}")})?;tracing::info!("Successfully saved captions");@@ -968,7 +959,7 @@ pub fn parse_captions_json(json: &str) -> Result<cap_project::CaptionsData, StriErr("Missing or invalid segments array in captions file".to_string())}}- Err(e) => Err(format!("Failed to parse captions JSON: {}", e)),+ Err(e) => Err(format!("Failed to parse captions JSON: {e}")),}}@@ -992,7 +983,7 @@ pub async fn load_captions(Ok(j) => j,Err(e) => {tracing::error!("Failed to read captions file: {}", e);- return Err(format!("Failed to read captions file: {}", e));+ return Err(format!("Failed to read captions file: {e}"));}};@@ -1014,7 +1005,7 @@ pub async fn load_captions(}Err(e) => {tracing::error!("Failed to parse captions: {}", e);- Err(format!("Failed to parse captions: {}", e))+ Err(format!("Failed to parse captions: {e}"))}}}@@ -1074,7 +1065,7 @@ pub async fn download_whisper_model(.get(model_url).send().await- .map_err(|e| format!("Failed to download model: {}", e))?;+ .map_err(|e| format!("Failed to download model: {e}"))?;if !response.status().is_success() {return Err(format!(@@ -1089,18 +1080,18 @@ pub async fn download_whisper_model(// Create a file to write toif let Some(parent) = std::path::Path::new(&output_path).parent() {std::fs::create_dir_all(parent)- .map_err(|e| format!("Failed to create parent directories: {}", e))?;+ .map_err(|e| format!("Failed to create parent directories: {e}"))?;}let mut file = tokio::fs::File::create(&output_path).await- .map_err(|e| format!("Failed to create file: {}", e))?;+ .map_err(|e| format!("Failed to create file: {e}"))?;// Download and write in chunkslet mut downloaded = 0;let mut bytes = response.bytes().await- .map_err(|e| format!("Failed to get response bytes: {}", e))?;+ .map_err(|e| format!("Failed to get response bytes: {e}"))?;// Write the bytes in chunks to show progressconst CHUNK_SIZE: usize = 1024 * 1024; // 1MB chunks@@ -1110,7 +1101,7 @@ pub async fn download_whisper_model(file.write_all(&chunk).await- .map_err(|e| format!("Error while writing to file: {}", e))?;+ .map_err(|e| format!("Error while writing to file: {e}"))?;downloaded += chunk_size as u64;@@ -1125,17 +1116,17 @@ pub async fn download_whisper_model(.emit(DownloadProgress::EVENT_NAME,DownloadProgress {- message: format!("Downloading model: {:.1}%", progress),+ message: format!("Downloading model: {progress:.1}%"),progress,},)- .map_err(|e| format!("Failed to emit progress: {}", e))?;+ .map_err(|e| format!("Failed to emit progress: {e}"))?;}// Ensure file is properly writtenfile.flush().await- .map_err(|e| format!("Failed to flush file: {}", e))?;+ .map_err(|e| format!("Failed to flush file: {e}"))?;Ok(())}@@ -1152,12 +1143,12 @@ pub async fn check_model_exists(model_path: String) -> Result<bool, String> {#[specta::specta]pub async fn delete_whisper_model(model_path: String) -> Result<(), String> {if !std::path::Path::new(&model_path).exists() {- return Err(format!("Model file not found: {}", model_path));+ return Err(format!("Model file not found: {model_path}"));}tokio::fs::remove_file(&model_path).await- .map_err(|e| format!("Failed to delete model file: {}", e))?;+ .map_err(|e| format!("Failed to delete model file: {e}"))?;Ok(())}@@ -1188,7 +1179,7 @@ fn format_srt_time(seconds: f64) -> String {let minutes = ((seconds % 3600.0) / 60.0) as i32;let secs = (seconds % 60.0) as i32;let millis = ((seconds % 1.0) * 1000.0) as i32;- format!("{:02}:{:02}:{:02},{:03}", hours, minutes, secs, millis)+ format!("{hours:02}:{minutes:02}:{secs:02},{millis:03}")}/// Export captions to an SRT file@@ -1238,7 +1229,7 @@ pub async fn export_captions_srt(}Err(e) => {tracing::error!("Failed to write SRT file: {}", e);- Err(format!("Failed to write SRT file: {}", e))+ Err(format!("Failed to write SRT file: {e}"))}}}@@ -1264,7 +1255,7 @@ fn convert_to_mono(samples: &[f32], channels: usize) -> Vec<f32> {}// Helper function to mix two sample arrays together-fn mix_samples(dest: &mut Vec<f32>, source: &[f32]) -> usize {+fn mix_samples(dest: &mut [f32], source: &[f32]) -> usize {let length = dest.len().min(source.len());for i in 0..length {// Simple mix with equal weight (0.5) to prevent clippingdiff --git a/apps/desktop/src-tauri/src/deeplink_actions.rs b/apps/desktop/src-tauri/src/deeplink_actions.rsindex 3c50f6d2c..fb0762053 100644--- a/apps/desktop/src-tauri/src/deeplink_actions.rs+++ b/apps/desktop/src-tauri/src/deeplink_actions.rs@@ -1,3 +1,5 @@+use std::path::Path;+use cap_recording::RecordingMode;use serde::{Deserialize, Serialize};use tauri::{AppHandle, Manager, Url};@@ -63,7 +65,7 @@ pub fn handle(app_handle: &AppHandle, urls: Vec<Url>) {tauri::async_runtime::spawn(async move {for action in actions {if let Err(e) = action.execute(&app_handle).await {- eprintln!("Failed to handle deep link action: {}", e);+ eprintln!("Failed to handle deep link action: {e}");}}});@@ -138,7 +140,7 @@ impl DeepLinkAction {crate::recording::stop_recording(app.clone(), app.state()).await}DeepLinkAction::OpenEditor { project_path } => {- crate::open_project_from_path(&project_path.into(), app.clone())+ crate::open_project_from_path(Path::new(&project_path), app.clone())}DeepLinkAction::OpenSettings { page } => {crate::show_window(app.clone(), ShowCapWindow::Settings { page }).awaitdiff --git a/apps/desktop/src-tauri/src/general_settings.rs b/apps/desktop/src-tauri/src/general_settings.rsindex 1616d6790..c70eef6dc 100644--- a/apps/desktop/src-tauri/src/general_settings.rs+++ b/apps/desktop/src-tauri/src/general_settings.rs@@ -81,10 +81,6 @@ pub struct GeneralSettingsStore {pub auto_zoom_on_clicks: bool,}-fn yes(_: &bool) -> bool {- true-}-fn default_server_url() -> String {std::option_env!("VITE_SERVER_URL").unwrap_or("https://cap.so")diff --git a/apps/desktop/src-tauri/src/hotkeys.rs b/apps/desktop/src-tauri/src/hotkeys.rsindex fde775035..d4f5a99ac 100644--- a/apps/desktop/src-tauri/src/hotkeys.rs+++ b/apps/desktop/src-tauri/src/hotkeys.rs@@ -19,29 +19,30 @@ pub struct Hotkey {shift: bool,}-impl Hotkey {- fn to_shortcut(&self) -> Shortcut {+impl From<Hotkey> for Shortcut {+ fn from(hotkey: Hotkey) -> Self {let mut modifiers = Modifiers::empty();- if self.meta {+ if hotkey.meta {modifiers |= Modifiers::META;}- if self.ctrl {+ if hotkey.ctrl {modifiers |= Modifiers::CONTROL;}- if self.alt {+ if hotkey.alt {modifiers |= Modifiers::ALT;}- if self.shift {+ if hotkey.shift {modifiers |= Modifiers::SHIFT;}- Shortcut::new(Some(modifiers), self.code)+ Shortcut::new(Some(modifiers), hotkey.code)}}#[derive(Serialize, Deserialize, Type, PartialEq, Eq, Hash, Clone, Copy)]#[serde(rename_all = "camelCase")]+#[allow(clippy::enum_variant_names)]pub enum HotkeyAction {StartRecording,StopRecording,@@ -77,7 +78,7 @@ pub fn init(app: &AppHandle) {let store = state.lock().unwrap();for (action, hotkey) in &store.hotkeys {- if &hotkey.to_shortcut() == shortcut {+ if &Shortcut::from(*hotkey) == shortcut {tokio::spawn(handle_hotkey(app.clone(), *action));}}@@ -91,7 +92,7 @@ pub fn init(app: &AppHandle) {let global_shortcut = app.global_shortcut();for hotkey in store.hotkeys.values() {- global_shortcut.register(hotkey.to_shortcut()).ok();+ global_shortcut.register(Shortcut::from(*hotkey)).ok();}app.manage(Mutex::new(store));@@ -125,14 +126,14 @@ pub fn set_hotkey(app: AppHandle, action: HotkeyAction, hotkey: Option<Hotkey>)store.hotkeys.remove(&action);}- if let Some(prev) = prev {- if !store.hotkeys.values().any(|h| h == &prev) {- global_shortcut.unregister(prev.to_shortcut()).ok();- }+ if let Some(prev) = prev+ && !store.hotkeys.values().any(|h| h == &prev)+ {+ global_shortcut.unregister(Shortcut::from(prev)).ok();}if let Some(hotkey) = hotkey {- global_shortcut.register(hotkey.to_shortcut()).ok();+ global_shortcut.register(Shortcut::from(hotkey)).ok();}Ok(())diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 27127e400..fb38f62dd 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -44,17 +44,17 @@ use general_settings::GeneralSettingsStore;use mp4::Mp4Reader;use notifications::NotificationType;use png::{ColorType, Encoder};-use recording::{InProgressRecording, StartRecordingInputs};+use recording::InProgressRecording;use relative_path::RelativePathBuf;use scap::capturer::Capturer;use scap::frame::Frame;use scap::frame::VideoFrame;use serde::{Deserialize, Serialize};-use serde_json::Value;use serde_json::json;use specta::Type;use std::collections::BTreeMap;+use std::path::Path;use std::{fs::File,future::Future,@@ -72,21 +72,18 @@ use tauri_plugin_dialog::DialogExt;use tauri_plugin_notification::{NotificationExt, PermissionState};use tauri_plugin_opener::OpenerExt;use tauri_plugin_shell::ShellExt;-use tauri_plugin_store::StoreExt;use tauri_specta::Event;use tokio::sync::mpsc;use tokio::sync::{Mutex, RwLock};use tracing::debug;use tracing::error;-use tracing_subscriber::Layer;-use tracing_subscriber::layer::SubscriberExt;-use tracing_subscriber::util::SubscriberInitExt;use upload::{S3UploadMeta, create_or_get_video, upload_image, upload_video};use web_api::ManagerExt as WebManagerExt;use windows::EditorWindowIds;use windows::set_window_transparent;use windows::{CapWindowId, ShowCapWindow};+#[allow(clippy::large_enum_variant)]pub enum RecordingState {None,Pending,@@ -316,13 +313,13 @@ async fn set_camera_input(feed.attach(legacy_camera_tx);}app.camera_feed = Some(Arc::new(Mutex::new(feed)));- return Ok(true);+ Ok(true)} else {- return Ok(false);+ Ok(false)}}_ = shutdown_rx.recv() => {- return Ok(false);+ Ok(false)}}}@@ -439,11 +436,11 @@ async fn get_current_recording(ScreenCaptureTarget::Screen { id } => CurrentRecordingTarget::Screen { id: *id },ScreenCaptureTarget::Window { id } => CurrentRecordingTarget::Window {id: *id,- bounds: bounds.clone(),+ bounds: *bounds,},ScreenCaptureTarget::Area { screen, bounds } => CurrentRecordingTarget::Area {screen: *screen,- bounds: bounds.clone(),+ bounds: *bounds,},};@@ -465,19 +462,16 @@ async fn create_screenshot(output: PathBuf,size: Option<(u32, u32)>,) -> Result<(), String> {- println!(- "Creating screenshot: input={:?}, output={:?}, size={:?}",- input, output, size- );+ println!("Creating screenshot: input={input:?}, output={output:?}, size={size:?}");let result: Result<(), String> = tokio::task::spawn_blocking(move || -> Result<(), String> {ffmpeg::init().map_err(|e| {- eprintln!("Failed to initialize ffmpeg: {}", e);+ eprintln!("Failed to initialize ffmpeg: {e}");e.to_string()})?;let mut ictx = ffmpeg::format::input(&input).map_err(|e| {- eprintln!("Failed to create input context: {}", e);+ eprintln!("Failed to create input context: {e}");e.to_string()})?;let input_stream = ictx@@ -485,18 +479,18 @@ async fn create_screenshot(.best(ffmpeg::media::Type::Video).ok_or("No video stream found")?;let video_stream_index = input_stream.index();- println!("Found video stream at index {}", video_stream_index);+ println!("Found video stream at index {video_stream_index}");let mut decoder =ffmpeg::codec::context::Context::from_parameters(input_stream.parameters()).map_err(|e| {- eprintln!("Failed to create decoder context: {}", e);+ eprintln!("Failed to create decoder context: {e}");e.to_string()})?.decoder().video().map_err(|e| {- eprintln!("Failed to create video decoder: {}", e);+ eprintln!("Failed to create video decoder: {e}");e.to_string()})?;@@ -510,7 +504,7 @@ async fn create_screenshot(ffmpeg::software::scaling::flag::Flags::BILINEAR,).map_err(|e| {- eprintln!("Failed to create scaler: {}", e);+ eprintln!("Failed to create scaler: {e}");e.to_string()})?;@@ -520,14 +514,14 @@ async fn create_screenshot(for (stream, packet) in ictx.packets() {if stream.index() == video_stream_index {decoder.send_packet(&packet).map_err(|e| {- eprintln!("Failed to send packet to decoder: {}", e);+ eprintln!("Failed to send packet to decoder: {e}");e.to_string()})?;if decoder.receive_frame(&mut frame).is_ok() {println!("Frame received, scaling...");let mut rgb_frame = ffmpeg::frame::Video::empty();scaler.run(&frame, &mut rgb_frame).map_err(|e| {- eprintln!("Failed to scale frame: {}", e);+ eprintln!("Failed to scale frame: {e}");e.to_string()})?;@@ -548,11 +542,11 @@ async fn create_screenshot(let img = image::RgbImage::from_raw(width as u32, height as u32, img_buffer).ok_or("Failed to create image from frame data")?;- println!("Saving image to {:?}", output);+ println!("Saving image to {output:?}");img.save_with_format(&output, image::ImageFormat::Jpeg).map_err(|e| {- eprintln!("Failed to save image: {}", e);+ eprintln!("Failed to save image: {e}");e.to_string()})?;@@ -566,97 +560,92 @@ async fn create_screenshot(Err("Failed to create screenshot".to_string())}).await- .map_err(|e| format!("Task join error: {}", e))?;+ .map_err(|e| format!("Task join error: {e}"))?;result}-async fn create_thumbnail(input: PathBuf, output: PathBuf, size: (u32, u32)) -> Result<(), String> {- println!(- "Creating thumbnail: input={:?}, output={:?}, size={:?}",- input, output, size- );-- tokio::task::spawn_blocking(move || -> Result<(), String> {- let img = image::open(&input).map_err(|e| {- eprintln!("Failed to open image: {}", e);- e.to_string()- })?;-- let width = img.width() as usize;- let height = img.height() as usize;- let bytes_per_pixel = 3;- let src_stride = width * bytes_per_pixel;-- let rgb_img = img.to_rgb8();- let img_buffer = rgb_img.as_raw();-- let mut corrected_buffer = vec![0u8; height * src_stride];-- for y in 0..height {- let src_slice = &img_buffer[y * src_stride..(y + 1) * src_stride];- let dst_slice = &mut corrected_buffer[y * src_stride..(y + 1) * src_stride];- dst_slice.copy_from_slice(src_slice);- }-- let corrected_img =- image::RgbImage::from_raw(width as u32, height as u32, corrected_buffer)- .ok_or("Failed to create corrected image")?;-- let thumbnail = image::imageops::resize(- &corrected_img,- size.0,- size.1,- image::imageops::FilterType::Lanczos3,- );-- thumbnail- .save_with_format(&output, image::ImageFormat::Png)- .map_err(|e| {- eprintln!("Failed to save thumbnail: {}", e);- e.to_string()- })?;-- println!("Thumbnail created successfully");- Ok(())- })- .await- .map_err(|e| format!("Task join error: {}", e))?-}+// async fn create_thumbnail(input: PathBuf, output: PathBuf, size: (u32, u32)) -> Result<(), String> {+// println!("Creating thumbnail: input={input:?}, output={output:?}, size={size:?}");++// tokio::task::spawn_blocking(move || -> Result<(), String> {+// let img = image::open(&input).map_err(|e| {+// eprintln!("Failed to open image: {e}");+// e.to_string()+// })?;++// let width = img.width() as usize;+// let height = img.height() as usize;+// let bytes_per_pixel = 3;+// let src_stride = width * bytes_per_pixel;++// let rgb_img = img.to_rgb8();+// let img_buffer = rgb_img.as_raw();++// let mut corrected_buffer = vec![0u8; height * src_stride];++// for y in 0..height {+// let src_slice = &img_buffer[y * src_stride..(y + 1) * src_stride];+// let dst_slice = &mut corrected_buffer[y * src_stride..(y + 1) * src_stride];+// dst_slice.copy_from_slice(src_slice);+// }++// let corrected_img =+// image::RgbImage::from_raw(width as u32, height as u32, corrected_buffer)+// .ok_or("Failed to create corrected image")?;++// let thumbnail = image::imageops::resize(+// &corrected_img,+// size.0,+// size.1,+// image::imageops::FilterType::Lanczos3,+// );++// thumbnail+// .save_with_format(&output, image::ImageFormat::Png)+// .map_err(|e| {+// eprintln!("Failed to save thumbnail: {e}");+// e.to_string()+// })?;++// println!("Thumbnail created successfully");+// Ok(())+// })+// .await+// .map_err(|e| format!("Task join error: {e}"))?+// }#[tauri::command]#[specta::specta]async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(), String> {- println!("Attempting to copy file from {} to {}", src, dst);+ println!("Attempting to copy file from {src} to {dst}");let is_screenshot = src.contains("screenshots/");let is_gif = src.ends_with(".gif") || dst.ends_with(".gif");let src_path = std::path::Path::new(&src);if !src_path.exists() {- return Err(format!("Source file {} does not exist", src));+ return Err(format!("Source file {src} does not exist"));}- if !is_screenshot && !is_gif {- if !is_valid_mp4(src_path) {- let mut attempts = 0;- while attempts < 10 {- std::thread::sleep(std::time::Duration::from_secs(1));- if is_valid_mp4(src_path) {- break;- }- attempts += 1;- }- if attempts == 10 {- return Err("Source video file is not a valid MP4".to_string());+ if !is_screenshot && !is_gif && !is_valid_mp4(src_path) {+ let mut attempts = 0;+ while attempts < 10 {+ std::thread::sleep(std::time::Duration::from_secs(1));+ if is_valid_mp4(src_path) {+ break;}+ attempts += 1;+ }+ if attempts == 10 {+ return Err("Source video file is not a valid MP4".to_string());}}if let Some(parent) = std::path::Path::new(&dst).parent() {tokio::fs::create_dir_all(parent).await- .map_err(|e| format!("Failed to create target directory: {}", e))?;+ .map_err(|e| format!("Failed to create target directory: {e}"))?;}let mut attempts = 0;@@ -669,7 +658,7 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(let src_size = match tokio::fs::metadata(&src).await {Ok(metadata) => metadata.len(),Err(e) => {- last_error = Some(format!("Failed to get source file metadata: {}", e));+ last_error = Some(format!("Failed to get source file metadata: {e}"));attempts += 1;tokio::time::sleep(tokio::time::Duration::from_secs(1)).await;continue;@@ -678,8 +667,7 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(if bytes != src_size {last_error = Some(format!(- "File copy verification failed: copied {} bytes but source is {} bytes",- bytes, src_size+ "File copy verification failed: copied {bytes} bytes but source is {src_size} bytes"));let _ = tokio::fs::remove_file(&dst).await;attempts += 1;@@ -695,10 +683,7 @@ async fn copy_file_to_path(app: AppHandle, src: String, dst: String) -> Result<(continue;}- println!(- "Successfully copied {} bytes from {} to {}",- bytes, src, dst- );+ println!("Successfully copied {bytes} bytes from {src} to {dst}");notifications::send_notification(&app,@@ -760,11 +745,15 @@ async fn copy_screenshot_to_clipboard(clipboard: MutableState<'_, ClipboardContext>,path: String,) -> Result<(), String> {- println!("Copying screenshot to clipboard: {:?}", path);+ println!("Copying screenshot to clipboard: {path:?}");let img_data = clipboard_rs::RustImageData::from_path(&path)- .map_err(|e| format!("Failed to copy screenshot to clipboard: {}", e))?;- clipboard.write().await.set_image(img_data);+ .map_err(|e| format!("Failed to copy screenshot to clipboard: {e}"))?;+ clipboard+ .write()+ .await+ .set_image(img_data)+ .map_err(|err| format!("Failed to copy screenshot to clipboard: {err}"))?;Ok(())}@@ -787,7 +776,7 @@ async fn open_file_path(_app: AppHandle, path: PathBuf) -> Result<(), String> {.arg("-R").arg(path_str).spawn()- .map_err(|e| format!("Failed to open folder: {}", e))?;+ .map_err(|e| format!("Failed to open folder: {e}"))?;}#[cfg(target_os = "linux")]@@ -933,20 +922,17 @@ async fn get_video_metadata(path: PathBuf) -> Result<VideoRecordingMetadata, Strfn get_duration_for_path(path: PathBuf) -> Result<f64, String> {let reader = BufReader::new(- File::open(&path).map_err(|e| format!("Failed to open video file: {}", e))?,+ File::open(&path).map_err(|e| format!("Failed to open video file: {e}"))?,);let file_size = path.metadata()- .map_err(|e| format!("Failed to get file metadata: {}", e))?+ .map_err(|e| format!("Failed to get file metadata: {e}"))?.len();let current_duration = match Mp4Reader::read_header(reader, file_size) {Ok(mp4) => mp4.duration().as_secs_f64(),Err(e) => {- println!(- "Failed to read MP4 header: {}. Falling back to default duration.",- e- );+ println!("Failed to read MP4 header: {e}. Falling back to default duration.");0.0_f64}};@@ -1012,20 +998,20 @@ fn close_recordings_overlay_window(app: AppHandle) {}}- if !cfg!(target_os = "macos") {- if let Some(window) = CapWindowId::RecordingsOverlay.get(&app) {- let _ = window.close();- }+ if !cfg!(target_os = "macos")+ && let Some(window) = CapWindowId::RecordingsOverlay.get(&app)+ {+ let _ = window.close();}}#[tauri::command(async)]#[specta::specta]-fn focus_captures_panel(app: AppHandle) {+fn focus_captures_panel(_app: AppHandle) {#[cfg(target_os = "macos")]{use tauri_nspanel::ManagerExt;- if let Ok(panel) = app.get_webview_panel(&CapWindowId::RecordingsOverlay.label()) {+ if let Ok(panel) = _app.get_webview_panel(&CapWindowId::RecordingsOverlay.label()) {panel.make_key_window();}}@@ -1119,7 +1105,7 @@ async fn upload_exported_video(let screen_metadata = get_video_metadata(path.clone()).await.map_err(|e| {sentry::capture_message(- &format!("Failed to get video metadata: {}", e),+ &format!("Failed to get video metadata: {e}"),sentry::Level::Error,);@@ -1223,7 +1209,7 @@ async fn upload_screenshot(clipboard: MutableState<'_, ClipboardContext>,screenshot_path: PathBuf,) -> Result<UploadResult, String> {- let Ok(Some(mut auth)) = AuthStore::get(&app) else {+ let Ok(Some(auth)) = AuthStore::get(&app) else {AuthStore::set(&app, None).map_err(|e| e.to_string())?;return Ok(UploadResult::NotAuthenticated);};@@ -1233,7 +1219,7 @@ async fn upload_screenshot(return Ok(UploadResult::UpgradeRequired);}- println!("Uploading screenshot: {:?}", screenshot_path);+ println!("Uploading screenshot: {screenshot_path:?}");let screenshot_dir = screenshot_path.parent().unwrap().to_path_buf();let mut meta = RecordingMeta::load_for_project(&screenshot_dir).unwrap();@@ -1250,12 +1236,13 @@ async fn upload_screenshot(link: uploaded.link.clone(),id: uploaded.id.clone(),});- meta.save_for_project();+ meta.save_for_project()+ .map_err(|err| format!("Error saving project: {err}"))?;uploaded.link};- println!("Copying to clipboard: {:?}", share_link);+ println!("Copying to clipboard: {share_link:?}");let _ = clipboard.write().await.set_text(share_link.clone());@@ -1295,7 +1282,7 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resulcapturer.start_capture();let frame = capturer.get_next_frame()- .map_err(|e| format!("Failed to get frame: {}", e))?;+ .map_err(|e| format!("Failed to get frame: {e}"))?;capturer.stop_capture();if let Some(window) = CapWindowId::Main.get(&app) {@@ -1362,7 +1349,7 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> Resulsegment: cap_project::SingleSegment {display: VideoMeta {path: RelativePathBuf::from_path(- &screenshot_path.strip_prefix(&recording_dir).unwrap(),+ screenshot_path.strip_prefix(&recording_dir).unwrap(),).unwrap(),fps: 0,@@ -1386,7 +1373,7 @@ async fn take_screenshot(app: AppHandle, _state: MutableState<'_, App>) -> ResulOk(())}).await- .map_err(|e| format!("Task join error: {}", e))??;+ .map_err(|e| format!("Task join error: {e}"))??;Ok(())}@@ -1400,16 +1387,13 @@ async fn save_file_dialog() -> Result<Option<String>, String> {use tauri_plugin_dialog::DialogExt;- println!(- "save_file_dialog called with file_name: {}, file_type: {}",- file_name, file_type- );+ println!("save_file_dialog called with file_name: {file_name}, file_type: {file_type}");let file_name = file_name.strip_suffix(".cap").unwrap_or(&file_name).to_string();- println!("File name after removing .cap suffix: {}", file_name);+ println!("File name after removing .cap suffix: {file_name}");let (name, extension) = match file_type.as_str() {"recording" => {@@ -1421,15 +1405,12 @@ async fn save_file_dialog(("PNG Image", "png")}_ => {- println!("Invalid file type: {}", file_type);+ println!("Invalid file type: {file_type}");return Err("Invalid file type".to_string());}};- println!(- "Showing save dialog with name: {}, extension: {}",- name, extension- );+ println!("Showing save dialog with name: {name}, extension: {extension}");let (tx, rx) = std::sync::mpsc::channel();println!("Created channel for communication");@@ -1451,11 +1432,11 @@ async fn save_file_dialog(println!("Waiting for user selection");match rx.recv() {Ok(result) => {- println!("Save dialog result: {:?}", result);+ println!("Save dialog result: {result:?}");Ok(result)}Err(e) => {- println!("Error receiving result: {}", e);+ println!("Error receiving result: {e}");notifications::send_notification(&app,notifications::NotificationType::VideoSaveFailed,@@ -1491,16 +1472,22 @@ pub enum RecordingType {Instant,}+#[derive(Debug, Clone, Serialize, Deserialize, Type, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub enum FileType {+ Recording,+ Screenshot,+}+#[tauri::command(async)]#[specta::specta]fn get_recording_meta(- app: AppHandle,path: PathBuf,- file_type: String,+ _file_type: FileType,) -> Result<RecordingMetaWithType, String> {RecordingMeta::load_for_project(&path).map(RecordingMetaWithType::new)- .map_err(|e| format!("Failed to load recording meta: {}", e))+ .map_err(|e| format!("Failed to load recording meta: {e}"))}#[tauri::command]@@ -1513,7 +1500,7 @@ fn list_recordings(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMetaWithType}let mut result = std::fs::read_dir(&recordings_dir)- .map_err(|e| format!("Failed to read recordings directory: {}", e))?+ .map_err(|e| format!("Failed to read recordings directory: {e}"))?.filter_map(|entry| {let entry = match entry {Ok(e) => e,@@ -1526,7 +1513,7 @@ fn list_recordings(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMetaWithTypereturn None;}- get_recording_meta(app.clone(), path.clone(), "recording".to_string())+ get_recording_meta(path.clone(), FileType::Recording).ok().map(|meta| (path, meta))})@@ -1555,16 +1542,15 @@ fn list_screenshots(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMeta)>, Strlet screenshots_dir = screenshots_path(&app);let mut result = std::fs::read_dir(&screenshots_dir)- .map_err(|e| format!("Failed to read screenshots directory: {}", e))?+ .map_err(|e| format!("Failed to read screenshots directory: {e}"))?.filter_map(|entry| {let entry = entry.ok()?;let path = entry.path();if path.is_dir() && path.extension().and_then(|s| s.to_str()) == Some("cap") {- let meta =- match get_recording_meta(app.clone(), path.clone(), "screenshot".to_string()) {- Ok(meta) => meta.inner,- Err(_) => return None,- };+ let meta = match get_recording_meta(path.clone(), FileType::Screenshot) {+ Ok(meta) => meta.inner,+ Err(_) => return None,+ };let png_path = std::fs::read_dir(&path).ok()?@@ -1598,10 +1584,10 @@ fn list_screenshots(app: AppHandle) -> Result<Vec<(PathBuf, RecordingMeta)>, Strasync fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {println!("Checking upgraded status and updating...");- if let Ok(Some(settings)) = GeneralSettingsStore::get(&app) {- if settings.commercial_license.is_some() {- return Ok(true);- }+ if let Ok(Some(settings)) = GeneralSettingsStore::get(&app)+ && settings.commercial_license.is_some()+ {+ return Ok(true);}let Ok(Some(auth)) = AuthStore::get(&app) else {@@ -1610,10 +1596,10 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {return Ok(false);};- if let Some(ref plan) = auth.plan {- if plan.manual {- return Ok(true);- }+ if let Some(ref plan) = auth.plan+ && plan.manual+ {+ return Ok(true);}println!(@@ -1624,8 +1610,8 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {.authed_api_request("/api/desktop/plan", |client, url| client.get(url)).await.map_err(|e| {- println!("Failed to fetch plan: {}", e);- format!("Failed to fetch plan: {}", e)+ println!("Failed to fetch plan: {e}");+ format!("Failed to fetch plan: {e}")})?;println!("Plan fetch response status: {}", response.status());@@ -1636,15 +1622,15 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {}let plan_data = response.json::<serde_json::Value>().await.map_err(|e| {- println!("Failed to parse plan response: {}", e);- format!("Failed to parse plan response: {}", e)+ println!("Failed to parse plan response: {e}");+ format!("Failed to parse plan response: {e}")})?;let is_pro = plan_data.get("upgraded").and_then(|v| v.as_bool()).unwrap_or(false);- println!("Pro status: {}", is_pro);+ println!("Pro status: {is_pro}");let updated_auth = AuthStore {secret: auth.secret,user_id: auth.user_id,@@ -1664,15 +1650,15 @@ async fn check_upgraded_and_update(app: AppHandle) -> Result<bool, String> {#[tauri::command]#[specta::specta]fn open_external_link(app: tauri::AppHandle, url: String) -> Result<(), String> {- if let Ok(Some(settings)) = GeneralSettingsStore::get(&app) {- if settings.disable_auto_open_links {- return Ok(());- }+ if let Ok(Some(settings)) = GeneralSettingsStore::get(&app)+ && settings.disable_auto_open_links+ {+ return Ok(());}app.shell().open(&url, None)- .map_err(|e| format!("Failed to open URL: {}", e))?;+ .map_err(|e| format!("Failed to open URL: {e}"))?;Ok(())}@@ -1816,35 +1802,35 @@ async fn check_notification_permissions(app: AppHandle) {println!("Notification permission already granted");}Err(e) => {- eprintln!("Error checking notification permission state: {}", e);+ eprintln!("Error checking notification permission state: {e}");}}}-fn configure_logging(folder: &PathBuf) -> tracing_appender::non_blocking::WorkerGuard {- let file_appender = tracing_appender::rolling::daily(folder, "cap-logs.log");- let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);+// fn configure_logging(folder: &PathBuf) -> tracing_appender::non_blocking::WorkerGuard {+// let file_appender = tracing_appender::rolling::daily(folder, "cap-logs.log");+// let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);- let filter = || tracing_subscriber::filter::EnvFilter::builder().parse_lossy("cap-*=TRACE");+// let filter = || tracing_subscriber::filter::EnvFilter::builder().parse_lossy("cap-*=TRACE");- tracing_subscriber::registry()- .with(- tracing_subscriber::fmt::layer()- .with_ansi(false)- .with_target(false)- .with_writer(non_blocking)- .with_filter(filter()),- )- .with(- tracing_subscriber::fmt::layer()- .with_ansi(true)- .with_target(false)- .with_filter(filter()),- )- .init();+// tracing_subscriber::registry()+// .with(+// tracing_subscriber::fmt::layer()+// .with_ansi(false)+// .with_target(false)+// .with_writer(non_blocking)+// .with_filter(filter()),+// )+// .with(+// tracing_subscriber::fmt::layer()+// .with_ansi(true)+// .with_target(false)+// .with_filter(filter()),+// )+// .init();- _guard-}+// _guard+// }#[tauri::command]#[specta::specta]@@ -1861,7 +1847,6 @@ async fn set_camera_preview_state() -> Result<(), ()> {store.save(&state).map_err(|err| {error!("Error saving camera window state: {err}");- ()})?;Ok(())@@ -2127,7 +2112,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) {println!("Checking startup completion and permissions...");let permissions = permissions::do_permissions_check(false);- println!("Permissions check result: {:?}", permissions);+ println!("Permissions check result: {permissions:?}");tokio::spawn({let app = app.clone();@@ -2155,7 +2140,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) {RequestNewScreenshot::listen_any_spawn(&app, |_, app| async move {if let Err(e) = take_screenshot(app.clone(), app.state()).await {- eprintln!("Failed to take screenshot: {}", e);+ eprintln!("Failed to take screenshot: {e}");}});@@ -2207,7 +2192,7 @@ pub async fn run(recording_logging_handle: LoggingHandle) {CapWindowId::Settings| CapWindowId::Upgrade| CapWindowId::ModeSelect => {- if let Some(window) = CapWindowId::Main.get(&app) {+ if let Some(window) = CapWindowId::Main.get(app) {let _ = window.show();}return;@@ -2216,32 +2201,30 @@ pub async fn run(recording_logging_handle: LoggingHandle) {};}- if let Some(settings) = GeneralSettingsStore::get(app).unwrap_or(None) {- if settings.hide_dock_icon- && app.webview_windows().keys().all(|label| {- !CapWindowId::from_str(label).unwrap().activates_dock()- })- {- #[cfg(target_os = "macos")]- app.set_activation_policy(tauri::ActivationPolicy::Accessory)- .ok();- }+ if let Some(settings) = GeneralSettingsStore::get(app).unwrap_or(None)+ && settings.hide_dock_icon+ && app+ .webview_windows()+ .keys()+ .all(|label| !CapWindowId::from_str(label).unwrap().activates_dock())+ {+ #[cfg(target_os = "macos")]+ app.set_activation_policy(tauri::ActivationPolicy::Accessory)+ .ok();}}#[cfg(target_os = "macos")]WindowEvent::Focused(focused) if *focused => {- if let Ok(window_id) = CapWindowId::from_str(label) {- if window_id.activates_dock() {- app.set_activation_policy(tauri::ActivationPolicy::Regular)- .ok();- }+ if let Ok(window_id) = CapWindowId::from_str(label)+ && window_id.activates_dock()+ {+ app.set_activation_policy(tauri::ActivationPolicy::Regular)+ .ok();}}- WindowEvent::DragDrop(event) => {- if let tauri::DragDropEvent::Drop { paths, .. } = event {- for path in paths {- let _ = open_project_from_path(path, app.clone());- }+ WindowEvent::DragDrop(tauri::DragDropEvent::Drop { paths, .. }) => {+ for path in paths {+ let _ = open_project_from_path(path, app.clone());}}_ => {}@@ -2333,9 +2316,9 @@ fn recordings_path(app: &AppHandle) -> PathBuf {path}-fn recording_path(app: &AppHandle, recording_id: &str) -> PathBuf {- recordings_path(app).join(format!("{}.cap", recording_id))-}+// fn recording_path(app: &AppHandle, recording_id: &str) -> PathBuf {+// recordings_path(app).join(format!("{recording_id}.cap"))+// }fn screenshots_path(app: &AppHandle) -> PathBuf {let path = app.path().app_data_dir().unwrap().join("screenshots");@@ -2343,9 +2326,9 @@ fn screenshots_path(app: &AppHandle) -> PathBuf {path}-fn screenshot_path(app: &AppHandle, screenshot_id: &str) -> PathBuf {- screenshots_path(app).join(format!("{}.cap", screenshot_id))-}+// fn screenshot_path(app: &AppHandle, screenshot_id: &str) -> PathBuf {+// screenshots_path(app).join(format!("{screenshot_id}.cap"))+// }#[tauri::command]#[specta::specta]@@ -2400,25 +2383,23 @@ trait TransposeAsync {impl<F: Future<Output = T>, T, E> TransposeAsync for Result<F, E> {type Output = Result<T, E>;- fn transpose_async(self) -> impl Future<Output = Self::Output>+ async fn transpose_async(self) -> Self::OutputwhereSelf: Sized,{- async {- match self {- Ok(f) => Ok(f.await),- Err(e) => Err(e),- }+ match self {+ Ok(f) => Ok(f.await),+ Err(e) => Err(e),}}}-fn open_project_from_path(path: &PathBuf, app: AppHandle) -> Result<(), String> {+fn open_project_from_path(path: &Path, app: AppHandle) -> Result<(), String> {let meta = RecordingMeta::load_for_project(path).map_err(|v| v.to_string())?;match &meta.inner {RecordingMetaInner::Studio(_) => {- let project_path = path.clone();+ let project_path = path.to_path_buf();tokio::spawn(async move { ShowCapWindow::Editor { project_path }.show(&app).await });}diff --git a/apps/desktop/src-tauri/src/main.rs b/apps/desktop/src-tauri/src/main.rsindex d94118d76..fded2c590 100644--- a/apps/desktop/src-tauri/src/main.rs+++ b/apps/desktop/src-tauri/src/main.rs@@ -3,7 +3,7 @@use std::sync::Arc;-use cap_desktop::DynLoggingLayer;+use cap_desktop_lib::DynLoggingLayer;use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};fn main() {@@ -69,5 +69,5 @@ fn main() {.enable_all().build().expect("Failed to build multi threaded tokio runtime")- .block_on(cap_desktop::run(handle));+ .block_on(cap_desktop_lib::run(handle));}diff --git a/apps/desktop/src-tauri/src/notifications.rs b/apps/desktop/src-tauri/src/notifications.rsindex 76fa4619c..c61e24b97 100644--- a/apps/desktop/src-tauri/src/notifications.rs+++ b/apps/desktop/src-tauri/src/notifications.rs@@ -1,6 +1,7 @@use crate::{AppSounds, general_settings::GeneralSettingsStore};use tauri_plugin_notification::NotificationExt;+#[allow(unused)]pub enum NotificationType {VideoSaved,VideoCopiedToClipboard,@@ -64,6 +65,7 @@ impl NotificationType {}}+ #[allow(unused)]pub fn message(&self) -> &'static str {match self {NotificationType::UploadFailed => {@@ -73,6 +75,7 @@ impl NotificationType {}}+ #[allow(unused)]pub fn title(&self) -> &'static str {match self {NotificationType::UploadFailed => "Upload Failed",@@ -88,14 +91,14 @@ impl NotificationType {pub fn send_notification(app: &tauri::AppHandle, notification_type: NotificationType) {// Check if notifications are enabled in settingslet enable_notifications = GeneralSettingsStore::get(app)- .map(|settings| settings.map_or(false, |s| s.enable_notifications))+ .map(|settings| settings.is_some_and(|s| s.enable_notifications)).unwrap_or(false);if !enable_notifications {return;}- let (title, body, is_error) = notification_type.details();+ let (title, body, _is_error) = notification_type.details();app.notification().builder()diff --git a/apps/desktop/src-tauri/src/permissions.rs b/apps/desktop/src-tauri/src/permissions.rsindex 36287bf04..73dc886d7 100644--- a/apps/desktop/src-tauri/src/permissions.rs+++ b/apps/desktop/src-tauri/src/permissions.rs@@ -22,66 +22,88 @@ pub enum OSPermission {#[tauri::command(async)]#[specta::specta]-pub fn open_permission_settings(permission: OSPermission) {+pub fn open_permission_settings(_permission: OSPermission) {#[cfg(target_os = "macos")]{use std::process::Command;- match permission {- OSPermission::ScreenRecording => {- Command::new("open")- .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture")- .spawn()- .expect("Failed to open Screen Recording settings");- }- OSPermission::Camera => {- Command::new("open")- .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Camera")- .spawn()- .expect("Failed to open Camera settings");- }- OSPermission::Microphone => {- Command::new("open")- .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")- .spawn()- .expect("Failed to open Microphone settings");- }- OSPermission::Accessibility => {- Command::new("open")- .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility")- .spawn()- .expect("Failed to open Accessibility settings");- }- }+ let mut process = match _permission {+ OSPermission::ScreenRecording => Command::new("open")+ .arg(+ "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture",+ )+ .spawn()+ .expect("Failed to open Screen Recording settings"),+ OSPermission::Camera => Command::new("open")+ .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Camera")+ .spawn()+ .expect("Failed to open Camera settings"),+ OSPermission::Microphone => Command::new("open")+ .arg("x-apple.systempreferences:com.apple.preference.security?Privacy_Microphone")+ .spawn()+ .expect("Failed to open Microphone settings"),+ OSPermission::Accessibility => Command::new("open")+ .arg(+ "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",+ )+ .spawn()+ .expect("Failed to open Accessibility settings"),+ };++ // https://doc.rust-lang.org/stable/std/process/struct.Child.html#warning+ tokio::spawn(async move {+ let _ = process.wait().map_err(|err| {+ tracing::error!("Error waiting for accessibility child process: {err}")+ });+ });}}#[tauri::command]#[specta::specta]-pub async fn request_permission(permission: OSPermission) {+pub async fn request_permission(_permission: OSPermission) {#[cfg(target_os = "macos")]{use futures::executor::block_on;+ use std::thread;- match permission {+ match _permission {OSPermission::ScreenRecording => {scap::request_permission();}OSPermission::Camera => {- std::thread::spawn(|| {- let _ = block_on(av::CaptureDevice::request_access_for_media_type(+ thread::spawn(|| {+ block_on(av::CaptureDevice::request_access_for_media_type(av::MediaType::video(),- ));+ ))+ .ok();});}OSPermission::Microphone => {- std::thread::spawn(|| {- let _ = block_on(av::CaptureDevice::request_access_for_media_type(+ thread::spawn(|| {+ block_on(av::CaptureDevice::request_access_for_media_type(av::MediaType::audio(),- ));+ ))+ .ok();});}- OSPermission::Accessibility => request_accessibility_permission(),+ OSPermission::Accessibility => {+ use core_foundation::base::TCFType;+ use core_foundation::dictionary::CFDictionary; // Import CFDictionaryRef+ use core_foundation::string::CFString;++ let prompt_key = CFString::new("AXTrustedCheckOptionPrompt");+ let prompt_value = core_foundation::boolean::CFBoolean::true_value();++ let options = CFDictionary::from_CFType_pairs(&[(+ prompt_key.as_CFType(),+ prompt_value.as_CFType(),+ )]);++ unsafe {+ AXIsProcessTrustedWithOptions(options.as_concrete_TypeRef());+ }+ }}}}@@ -101,10 +123,7 @@ pub enum OSPermissionStatus {impl OSPermissionStatus {pub fn permitted(&self) -> bool {- match self {- Self::NotNeeded | Self::Granted => true,- _ => false,- }+ matches!(self, Self::NotNeeded | Self::Granted)}}@@ -125,7 +144,7 @@ impl OSPermissionsCheck {#[tauri::command(async)]#[specta::specta]-pub fn do_permissions_check(initial_check: bool) -> OSPermissionsCheck {+pub fn do_permissions_check(_initial_check: bool) -> OSPermissionsCheck {#[cfg(target_os = "macos")]{use cidre::av::{AuthorizationStatus, CaptureDevice, MediaType};@@ -143,7 +162,7 @@ pub fn do_permissions_check(initial_check: bool) -> OSPermissionsCheck {OSPermissionsCheck {screen_recording: {let result = scap::has_permission();- match (result, initial_check) {+ match (result, _initial_check) {(true, _) => OSPermissionStatus::Granted,(false, true) => OSPermissionStatus::Empty,(false, false) => OSPermissionStatus::Denied,@@ -151,7 +170,11 @@ pub fn do_permissions_check(initial_check: bool) -> OSPermissionsCheck {},microphone: check_av_permission(MediaType::audio()),camera: check_av_permission(MediaType::video()),- accessibility: { check_accessibility_permission() },+ accessibility: if unsafe { AXIsProcessTrusted() } {+ OSPermissionStatus::Granted+ } else {+ OSPermissionStatus::Denied+ },}}@@ -165,38 +188,3 @@ pub fn do_permissions_check(initial_check: bool) -> OSPermissionsCheck {}}}--pub fn check_accessibility_permission() -> OSPermissionStatus {- #[cfg(target_os = "macos")]- {- if unsafe { AXIsProcessTrusted() } {- OSPermissionStatus::Granted- } else {- OSPermissionStatus::Denied- }- }- #[cfg(not(target_os = "macos"))]- {- // For non-macOS platforms, assume permission is granted- OSPermissionStatus::NotNeeded- }-}--pub fn request_accessibility_permission() {- #[cfg(target_os = "macos")]- {- use core_foundation::base::TCFType;- use core_foundation::dictionary::CFDictionary; // Import CFDictionaryRef- use core_foundation::string::CFString;-- let prompt_key = CFString::new("AXTrustedCheckOptionPrompt");- let prompt_value = core_foundation::boolean::CFBoolean::true_value();-- let options =- CFDictionary::from_CFType_pairs(&[(prompt_key.as_CFType(), prompt_value.as_CFType())]);-- unsafe {- AXIsProcessTrustedWithOptions(options.as_concrete_TypeRef());- }- }-}diff --git a/apps/desktop/src-tauri/src/platform/macos/delegates.rs b/apps/desktop/src-tauri/src/platform/macos/delegates.rsindex a4959ee23..7c9c97f02 100644--- a/apps/desktop/src-tauri/src/platform/macos/delegates.rs+++ b/apps/desktop/src-tauri/src/platform/macos/delegates.rs@@ -326,33 +326,33 @@ pub fn setup<R: Runtime>(window: Window<R>, controls_inset: LogicalPosition<f64>// We need to ensure we have a unique delegate name, otherwise we will panic while trying to create a duplicate// delegate with the same name.- let delegate_name = format!("windowDelegate_cap_{}_{}", window_label, random_str);+ let delegate_name = format!("windowDelegate_cap_{window_label}_{random_str}");ns_win_id.setDelegate_(cocoa::delegate!(&delegate_name, {window: id = ns_win_id,app_box: *mut c_void = app_box,toolbar: id = cocoa::base::nil,super_delegate: id = current_delegate,- (windowShouldClose:) => on_window_should_close as extern fn(&Object, Sel, id) -> BOOL,- (windowWillClose:) => on_window_will_close as extern fn(&Object, Sel, id),- (windowDidResize:) => on_window_did_resize::<R> as extern fn(&Object, Sel, id),- (windowDidMove:) => on_window_did_move as extern fn(&Object, Sel, id),- (windowDidChangeBackingProperties:) => on_window_did_change_backing_properties as extern fn(&Object, Sel, id),- (windowDidBecomeKey:) => on_window_did_become_key as extern fn(&Object, Sel, id),- (windowDidResignKey:) => on_window_did_resign_key as extern fn(&Object, Sel, id),- (draggingEntered:) => on_dragging_entered as extern fn(&Object, Sel, id) -> BOOL,- (prepareForDragOperation:) => on_prepare_for_drag_operation as extern fn(&Object, Sel, id) -> BOOL,- (performDragOperation:) => on_perform_drag_operation as extern fn(&Object, Sel, id) -> BOOL,- (concludeDragOperation:) => on_conclude_drag_operation as extern fn(&Object, Sel, id),- (draggingExited:) => on_dragging_exited as extern fn(&Object, Sel, id),- (window:willUseFullScreenPresentationOptions:) => on_window_will_use_full_screen_presentation_options as extern fn(&Object, Sel, id, NSUInteger) -> NSUInteger,- (windowDidEnterFullScreen:) => on_window_did_enter_full_screen::<R> as extern fn(&Object, Sel, id),- (windowWillEnterFullScreen:) => on_window_will_enter_full_screen::<R> as extern fn(&Object, Sel, id),- (windowDidExitFullScreen:) => on_window_did_exit_full_screen::<R> as extern fn(&Object, Sel, id),- (windowWillExitFullScreen:) => on_window_will_exit_full_screen::<R> as extern fn(&Object, Sel, id),- (windowDidFailToEnterFullScreen:) => on_window_did_fail_to_enter_full_screen as extern fn(&Object, Sel, id),- (effectiveAppearanceDidChange:) => on_effective_appearance_did_change as extern fn(&Object, Sel, id),- (effectiveAppearanceDidChangedOnMainThread:) => on_effective_appearance_did_changed_on_main_thread as extern fn(&Object, Sel, id)+ (windowShouldClose:) => on_window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,+ (windowWillClose:) => on_window_will_close as extern "C" fn(&Object, Sel, id),+ (windowDidResize:) => on_window_did_resize::<R> as extern "C" fn(&Object, Sel, id),+ (windowDidMove:) => on_window_did_move as extern "C" fn(&Object, Sel, id),+ (windowDidChangeBackingProperties:) => on_window_did_change_backing_properties as extern "C" fn(&Object, Sel, id),+ (windowDidBecomeKey:) => on_window_did_become_key as extern "C" fn(&Object, Sel, id),+ (windowDidResignKey:) => on_window_did_resign_key as extern "C" fn(&Object, Sel, id),+ (draggingEntered:) => on_dragging_entered as extern "C" fn(&Object, Sel, id) -> BOOL,+ (prepareForDragOperation:) => on_prepare_for_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,+ (performDragOperation:) => on_perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,+ (concludeDragOperation:) => on_conclude_drag_operation as extern "C" fn(&Object, Sel, id),+ (draggingExited:) => on_dragging_exited as extern "C" fn(&Object, Sel, id),+ (window:willUseFullScreenPresentationOptions:) => on_window_will_use_full_screen_presentation_options as extern "C" fn(&Object, Sel, id, NSUInteger) -> NSUInteger,+ (windowDidEnterFullScreen:) => on_window_did_enter_full_screen::<R> as extern "C" fn(&Object, Sel, id),+ (windowWillEnterFullScreen:) => on_window_will_enter_full_screen::<R> as extern "C" fn(&Object, Sel, id),+ (windowDidExitFullScreen:) => on_window_did_exit_full_screen::<R> as extern "C" fn(&Object, Sel, id),+ (windowWillExitFullScreen:) => on_window_will_exit_full_screen::<R> as extern "C" fn(&Object, Sel, id),+ (windowDidFailToEnterFullScreen:) => on_window_did_fail_to_enter_full_screen as extern "C" fn(&Object, Sel, id),+ (effectiveAppearanceDidChange:) => on_effective_appearance_did_change as extern "C" fn(&Object, Sel, id),+ (effectiveAppearanceDidChangedOnMainThread:) => on_effective_appearance_did_changed_on_main_thread as extern "C" fn(&Object, Sel, id)}))}}diff --git a/apps/desktop/src-tauri/src/platform/macos/mod.rs b/apps/desktop/src-tauri/src/platform/macos/mod.rsindex fd771803c..540744b2f 100644--- a/apps/desktop/src-tauri/src/platform/macos/mod.rs+++ b/apps/desktop/src-tauri/src/platform/macos/mod.rs@@ -1,14 +1,14 @@-use std::ffi::c_void;+// use std::ffi::c_void;-use cocoa::{- base::{id, nil},- foundation::NSString,-};-use core_graphics::{- base::boolean_t,- display::{CFDictionaryRef, CGRect},-};-use objc::{class, msg_send, sel, sel_impl};+// use cocoa::{+// base::{id, nil},+// foundation::NSString,+// };+// use core_graphics::{+// base::boolean_t,+// display::{CFDictionaryRef, CGRect},+// };+// use objc::{class, msg_send, sel, sel_impl};pub mod delegates;@@ -23,28 +23,28 @@ pub fn set_window_level(window: tauri::Window, level: objc2_app_kit::NSWindowLev});}-pub fn get_ns_window_number(ns_window: *mut c_void) -> isize {- let ns_window = ns_window as *const objc2_app_kit::NSWindow;+// pub fn get_ns_window_number(ns_window: *mut c_void) -> isize {+// let ns_window = ns_window as *const objc2_app_kit::NSWindow;- unsafe { (*ns_window).windowNumber() }-}+// unsafe { (*ns_window).windowNumber() }+// }-#[link(name = "CoreGraphics", kind = "framework")]-unsafe extern "C" {- pub fn CGRectMakeWithDictionaryRepresentation(- dict: CFDictionaryRef,- rect: *mut CGRect,- ) -> boolean_t;-}+// #[link(name = "CoreGraphics", kind = "framework")]+// unsafe extern "C" {+// pub fn CGRectMakeWithDictionaryRepresentation(+// dict: CFDictionaryRef,+// rect: *mut CGRect,+// ) -> boolean_t;+// }-/// Makes the background of the WKWebView layer transparent.-/// This differs from Tauri's implementation as it does not change the window background which causes performance performance issues and artifacts when shadows are enabled on the window.-/// Use Tauri's implementation to make the window itself transparent.-pub fn make_webview_transparent(target: &tauri::WebviewWindow) -> tauri::Result<()> {- target.with_webview(|webview| unsafe {- let wkwebview = webview.inner() as id;- let no: id = msg_send![class!(NSNumber), numberWithBool:0];- // [https://developer.apple.com/documentation/webkit/webview/1408486-drawsbackground]- let _: id = msg_send![wkwebview, setValue:no forKey: NSString::alloc(nil).init_str("drawsBackground")];- })-}+// /// Makes the background of the WKWebView layer transparent.+// /// This differs from Tauri's implementation as it does not change the window background which causes performance performance issues and artifacts when shadows are enabled on the window.+// /// Use Tauri's implementation to make the window itself transparent.+// pub fn make_webview_transparent(target: &tauri::WebviewWindow) -> tauri::Result<()> {+// target.with_webview(|webview| unsafe {+// let wkwebview = webview.inner() as id;+// let no: id = msg_send![class!(NSNumber), numberWithBool:0];+// // [https://developer.apple.com/documentation/webkit/webview/1408486-drawsbackground]+// let _: id = msg_send![wkwebview, setValue:no forKey: NSString::alloc(nil).init_str("drawsBackground")];+// })+// }diff --git a/apps/desktop/src-tauri/src/platform/mod.rs b/apps/desktop/src-tauri/src/platform/mod.rsindex 3fee95932..5a03c820c 100644--- a/apps/desktop/src-tauri/src/platform/mod.rs+++ b/apps/desktop/src-tauri/src/platform/mod.rs@@ -3,9 +3,6 @@ use specta::Type;#[cfg(target_os = "windows")]pub mod win;-#[cfg(target_os = "windows")]-pub use win::*;-#[cfg(target_os = "macos")]pub mod macos;@@ -33,8 +30,8 @@ pub enum HapticPerformanceTime {#[tauri::command]#[specta::specta]pub fn perform_haptic_feedback(- pattern: Option<HapticPattern>,- time: Option<HapticPerformanceTime>,+ _pattern: Option<HapticPattern>,+ _time: Option<HapticPerformanceTime>,) -> Result<(), String> {#[cfg(target_os = "macos")]unsafe {@@ -44,8 +41,8 @@ pub fn perform_haptic_feedback(};NSHapticFeedbackManager::defaultPerformer().performFeedbackPattern_performanceTime(- NSHapticFeedbackPattern(pattern.unwrap_or_default() as isize),- NSHapticFeedbackPerformanceTime(time.unwrap_or_default() as usize),+ NSHapticFeedbackPattern(_pattern.unwrap_or_default() as isize),+ NSHapticFeedbackPerformanceTime(_time.unwrap_or_default() as usize),);Ok(())}diff --git a/apps/desktop/src-tauri/src/presets.rs b/apps/desktop/src-tauri/src/presets.rsindex 56ba8db4d..bc2130bfe 100644--- a/apps/desktop/src-tauri/src/presets.rs+++ b/apps/desktop/src-tauri/src/presets.rs@@ -49,6 +49,7 @@ impl PresetsStore {Ok(this.presets.get(default_i as usize).cloned())}+ #[allow(unused)]pub fn update(app: &AppHandle, update: impl FnOnce(&mut Self)) -> Result<(), String> {let Ok(store) = app.store("store") else {return Err("Store not found".to_string());@@ -62,6 +63,7 @@ impl PresetsStore {}impl Preset {+ #[allow(unused)]fn resolve(&self, timeline: TimelineConfiguration) -> ProjectConfiguration {let mut ret = self.config.clone();ret.timeline = Some(timeline);diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rsindex ff4989b1b..170cb3026 100644--- a/apps/desktop/src-tauri/src/recording.rs+++ b/apps/desktop/src-tauri/src/recording.rs@@ -1,8 +1,8 @@use std::{collections::HashMap, path::PathBuf, sync::Arc, time::Duration};use crate::{- App, CurrentRecordingChanged, DynLoggingLayer, MutableState, NewStudioRecordingAdded,- RecordingStarted, RecordingStopped, VideoUploadInfo,+ App, CurrentRecordingChanged, MutableState, NewStudioRecordingAdded, RecordingStarted,+ RecordingStopped, VideoUploadInfo,audio::AppSounds,auth::AuthStore,create_screenshot,@@ -301,9 +301,9 @@ pub async fn start_recording(};match &inputs.capture_target {- ScreenCaptureTarget::Window { id } => {+ ScreenCaptureTarget::Window { id: _id } => {#[cfg(target_os = "macos")]- let display = display_for_window(*id).unwrap().id;+ let display = display_for_window(*_id).unwrap().id;#[cfg(windows)]let display = {@@ -450,7 +450,7 @@ pub async fn start_recording(}}).await- .map_err(|e| format!("Failed to spawn recording actor: {}", e))??;+ .map_err(|e| format!("Failed to spawn recording actor: {e}"))??;let _ = RecordingEvent::Started.emit(&app);@@ -463,7 +463,6 @@ pub async fn start_recording(Ok(Ok(_)) => {let _ = finish_upload_tx.send(());let _ = RecordingEvent::Stopped.emit(&app);- return;}Ok(Err(e)) => {let mut state = state_mtx.write().await;@@ -472,7 +471,7 @@ pub async fn start_recording(let mut dialog = MessageDialogBuilder::new(app.dialog().clone(),- format!("An error occurred"),+ "An error occurred".to_string(),e,).kind(tauri_plugin_dialog::MessageDialogKind::Error);@@ -585,7 +584,7 @@ pub async fn delete_recording(app: AppHandle, state: MutableState<'_, App>) -> Rif let Some(id) = video_id {let _ = app.authed_api_request(- format!("/api/desktop/video/delete?videoId={}", id),+ format!("/api/desktop/video/delete?videoId={id}"),|c, url| c.delete(url),).await;@@ -622,9 +621,9 @@ async fn handle_recording_end(if let Some(window) = CapWindowId::Main.get(&handle) {window.unminimize().ok();} else {- CapWindowId::Camera.get(&handle).map(|v| {+ if let Some(v) = CapWindowId::Camera.get(&handle) {let _ = v.close();- });+ }app.camera_feed.take();app.mic_feed.take();}@@ -676,10 +675,10 @@ async fn handle_recording_finish(let recordings = ProjectRecordingsMeta::new(&recording_dir, &recording.meta)?;let config = project_config_from_recording(- &app,+ app,&recording,&recordings,- PresetsStore::get_default_preset(&app)?.map(|p| p.config),+ PresetsStore::get_default_preset(app)?.map(|p| p.config),);config.write(&recording_dir).map_err(|e| e.to_string())?;@@ -800,7 +799,7 @@ async fn handle_recording_finish(.map_err(|e| format!("Failed to save recording meta: {e}"))?;if let RecordingMetaInner::Studio(_) = meta.inner {- match GeneralSettingsStore::get(&app)+ match GeneralSettingsStore::get(app).ok().flatten().map(|v| v.post_studio_recording_behaviour)@@ -810,11 +809,11 @@ async fn handle_recording_finish(let _ = ShowCapWindow::Editor {project_path: recording_dir,}- .show(&app)+ .show(app).await;}PostStudioRecordingBehaviour::ShowOverlay => {- let _ = ShowCapWindow::RecordingsOverlay.show(&app).await;+ let _ = ShowCapWindow::RecordingsOverlay.show(app).await;let app = AppHandle::clone(app);tokio::spawn(async move {@@ -964,7 +963,7 @@ fn project_config_from_recording(}).collect(),zoom_segments: if settings.auto_zoom_on_clicks {- generate_zoom_segments_from_clicks(&completed_recording, &recordings)+ generate_zoom_segments_from_clicks(completed_recording, recordings)} else {Vec::new()},diff --git a/apps/desktop/src-tauri/src/upload.rs b/apps/desktop/src-tauri/src/upload.rsindex 87c966f96..303461d61 100644--- a/apps/desktop/src-tauri/src/upload.rs+++ b/apps/desktop/src-tauri/src/upload.rs@@ -2,15 +2,13 @@use crate::web_api::ManagerExt;use crate::{UploadProgress, VideoUploadInfo};-use axum::http::{HeaderMap, HeaderName, HeaderValue};use cap_utils::spawn_actor;use flume::Receiver;-use futures::{StreamExt, stream};+use futures::StreamExt;use image::ImageReader;use image::codecs::jpeg::JpegEncoder;use reqwest::StatusCode;use reqwest::header::CONTENT_LENGTH;-use serde::de::{self, Deserializer};use serde::{Deserialize, Serialize};use serde_json::json;use specta::Type;@@ -29,53 +27,53 @@ pub struct S3UploadMeta {id: String,}-fn deserialize_empty_object_as_string<'de, D>(deserializer: D) -> Result<String, D::Error>-where- D: Deserializer<'de>,-{- struct StringOrObject;-- impl<'de> de::Visitor<'de> for StringOrObject {- type Value = String;-- fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {- formatter.write_str("string or empty object")- }-- fn visit_str<E>(self, value: &str) -> Result<String, E>- where- E: de::Error,- {- Ok(value.to_string())- }-- fn visit_string<E>(self, value: String) -> Result<String, E>- where- E: de::Error,- {- Ok(value)- }-- fn visit_map<M>(self, _map: M) -> Result<String, M::Error>- where- M: de::MapAccess<'de>,- {- // Return empty string for empty objects- Ok(String::new())- }- }-- deserializer.deserialize_any(StringOrObject)-}+// fn deserialize_empty_object_as_string<'de, D>(deserializer: D) -> Result<String, D::Error>+// where+// D: Deserializer<'de>,+// {+// struct StringOrObject;++// impl<'de> de::Visitor<'de> for StringOrObject {+// type Value = String;++// fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {+// formatter.write_str("string or empty object")+// }++// fn visit_str<E>(self, value: &str) -> Result<String, E>+// where+// E: de::Error,+// {+// Ok(value.to_string())+// }++// fn visit_string<E>(self, value: String) -> Result<String, E>+// where+// E: de::Error,+// {+// Ok(value)+// }++// fn visit_map<M>(self, _map: M) -> Result<String, M::Error>+// where+// M: de::MapAccess<'de>,+// {+// // Return empty string for empty objects+// Ok(String::new())+// }+// }++// deserializer.deserialize_any(StringOrObject)+// }impl S3UploadMeta {pub fn id(&self) -> &str {&self.id}- pub fn new(id: String) -> Self {- Self { id }- }+ // pub fn new(id: String) -> Self {+ // Self { id }+ // }}#[derive(serde::Serialize)]@@ -112,19 +110,20 @@ struct S3ImageUploadBody {base: S3UploadBody,}-#[derive(serde::Serialize)]-#[serde(rename_all = "camelCase")]-struct S3AudioUploadBody {- #[serde(flatten)]- base: S3UploadBody,- duration: String,- audio_codec: String,- is_mp3: bool,-}+// #[derive(serde::Serialize)]+// #[serde(rename_all = "camelCase")]+// struct S3AudioUploadBody {+// #[serde(flatten)]+// base: S3UploadBody,+// duration: String,+// audio_codec: String,+// is_mp3: bool,+// }pub struct UploadedVideo {pub link: String,pub id: String,+ #[allow(unused)]pub config: S3UploadMeta,}@@ -133,11 +132,11 @@ pub struct UploadedImage {pub id: String,}-pub struct UploadedAudio {- pub link: String,- pub id: String,- pub config: S3UploadMeta,-}+// pub struct UploadedAudio {+// pub link: String,+// pub id: String,+// pub config: S3UploadMeta,+// }pub async fn upload_video(app: &AppHandle,@@ -167,12 +166,12 @@ pub async fn upload_video(let file = tokio::fs::File::open(&file_path).await- .map_err(|e| format!("Failed to open file: {}", e))?;+ .map_err(|e| format!("Failed to open file: {e}"))?;let metadata = file.metadata().await- .map_err(|e| format!("Failed to get file metadata: {}", e))?;+ .map_err(|e| format!("Failed to get file metadata: {e}"))?;let total_size = metadata.len();@@ -218,8 +217,7 @@ pub async fn upload_video(}});- let response =- video_upload.map_err(|e| format!("Failed to send upload file request: {}", e))?;+ let response = video_upload.map_err(|e| format!("Failed to send upload file request: {e}"))?;if response.status().is_success() {println!("Video uploaded successfully");@@ -253,8 +251,7 @@ pub async fn upload_video(error_body);Err(format!(- "Failed to upload file. Status: {}. Body: {}",- status, error_body+ "Failed to upload file. Status: {status}. Body: {error_body}"))}@@ -279,7 +276,7 @@ pub async fn upload_image(app: &AppHandle, file_path: PathBuf) -> Result<Uploadelet file_content = tokio::fs::read(&file_path).await- .map_err(|e| format!("Failed to read file: {}", e))?;+ .map_err(|e| format!("Failed to read file: {e}"))?;let response = client.put(presigned_put)@@ -287,7 +284,7 @@ pub async fn upload_image(app: &AppHandle, file_path: PathBuf) -> Result<Uploade.body(file_content).send().await- .map_err(|e| format!("Failed to send upload file request: {}", e))?;+ .map_err(|e| format!("Failed to send upload file request: {e}"))?;if response.status().is_success() {println!("File uploaded successfully");@@ -308,8 +305,7 @@ pub async fn upload_image(app: &AppHandle, file_path: PathBuf) -> Result<Uploadeerror_body);Err(format!(- "Failed to upload file. Status: {}. Body: {}",- status, error_body+ "Failed to upload file. Status: {status}. Body: {error_body}"))}@@ -329,17 +325,17 @@ pub async fn create_or_get_video(};if let Some(name) = name {- s3_config_url.push_str(&format!("&name={}", name));+ s3_config_url.push_str(&format!("&name={name}"));}if let Some(duration) = duration {- s3_config_url.push_str(&format!("&duration={}", duration));+ s3_config_url.push_str(&format!("&duration={duration}"));}let response = app.authed_api_request(s3_config_url, |client, url| client.get(url)).await- .map_err(|e| format!("Failed to send request to Next.js handler: {}", e))?;+ .map_err(|e| format!("Failed to send request to Next.js handler: {e}"))?;if response.status() == StatusCode::UNAUTHORIZED {return Err("Failed to authenticate request; please log in again".into());@@ -348,13 +344,10 @@ pub async fn create_or_get_video(let response_text = response.text().await- .map_err(|e| format!("Failed to read response body: {}", e))?;+ .map_err(|e| format!("Failed to read response body: {e}"))?;- let mut config = serde_json::from_str::<S3UploadMeta>(&response_text).map_err(|e| {- format!(- "Failed to deserialize response: {}. Response body: {}",- e, response_text- )+ let config = serde_json::from_str::<S3UploadMeta>(&response_text).map_err(|e| {+ format!("Failed to deserialize response: {e}. Response body: {response_text}")})?;Ok(config)@@ -380,7 +373,7 @@ async fn presigned_s3_put(app: &AppHandle, body: impl Serialize) -> Result<Strinclient.post(url).json(&json!(body_json))}).await- .map_err(|e| format!("Failed to send request to Next.js handler: {}", e))?;+ .map_err(|e| format!("Failed to send request to Next.js handler: {e}"))?;if response.status() == StatusCode::UNAUTHORIZED {return Err("Failed to authenticate request; please log in again".into());@@ -389,7 +382,7 @@ async fn presigned_s3_put(app: &AppHandle, body: impl Serialize) -> Result<Strinlet Wrapper { presigned_put_data } = response.json::<Wrapper>().await- .map_err(|e| format!("Failed to deserialize server response: {}", e))?;+ .map_err(|e| format!("Failed to deserialize server response: {e}"))?;Ok(presigned_put_data.url)}@@ -428,7 +421,7 @@ pub fn build_video_meta(path: &PathBuf) -> Result<S3VideoMeta, String> {Ok(S3VideoMeta {duration: duration_millis.to_string(),- resolution: format!("{}x{}", width, height),+ resolution: format!("{width}x{height}"),framerate: frame_rate,bandwidth: bit_rate.to_string(),video_codec: format!("{video_codec_name:?}")@@ -440,32 +433,32 @@ pub fn build_video_meta(path: &PathBuf) -> Result<S3VideoMeta, String> {})}-fn build_audio_upload_body(- path: &PathBuf,- base: S3UploadBody,-) -> Result<S3AudioUploadBody, String> {- let input =- ffmpeg::format::input(path).map_err(|e| format!("Failed to read input file: {e}"))?;- let stream = input- .streams()- .best(ffmpeg::media::Type::Audio)- .ok_or_else(|| "Failed to find appropriate audio stream in file".to_string())?;-- let duration_millis = input.duration() as f64 / 1000.;-- let codec = ffmpeg::codec::context::Context::from_parameters(stream.parameters())- .map_err(|e| format!("Unable to read audio codec information: {e}"))?;- let codec_name = codec.id();-- let is_mp3 = path.extension().map_or(false, |ext| ext == "mp3");-- Ok(S3AudioUploadBody {- base,- duration: duration_millis.to_string(),- audio_codec: format!("{codec_name:?}").replace("Id::", "").to_lowercase(),- is_mp3,- })-}+// fn build_audio_upload_body(+// path: &PathBuf,+// base: S3UploadBody,+// ) -> Result<S3AudioUploadBody, String> {+// let input =+// ffmpeg::format::input(path).map_err(|e| format!("Failed to read input file: {e}"))?;+// let stream = input+// .streams()+// .best(ffmpeg::media::Type::Audio)+// .ok_or_else(|| "Failed to find appropriate audio stream in file".to_string())?;++// let duration_millis = input.duration() as f64 / 1000.;++// let codec = ffmpeg::codec::context::Context::from_parameters(stream.parameters())+// .map_err(|e| format!("Unable to read audio codec information: {e}"))?;+// let codec_name = codec.id();++// let is_mp3 = path.extension().is_some_and(|ext| ext == "mp3");++// Ok(S3AudioUploadBody {+// base,+// duration: duration_millis.to_string(),+// audio_codec: format!("{codec_name:?}").replace("Id::", "").to_lowercase(),+// is_mp3,+// })+// }pub async fn prepare_screenshot_upload(app: &AppHandle,@@ -489,15 +482,15 @@ pub async fn prepare_screenshot_upload(.body(compressed_image).send().await- .map_err(|e| format!("Error uploading screenshot: {}", e))+ .map_err(|e| format!("Error uploading screenshot: {e}"))}async fn compress_image(path: PathBuf) -> Result<Vec<u8>, String> {task::spawn_blocking(move || {let img = ImageReader::open(&path)- .map_err(|e| format!("Failed to open image: {}", e))?+ .map_err(|e| format!("Failed to open image: {e}"))?.decode()- .map_err(|e| format!("Failed to decode image: {}", e))?;+ .map_err(|e| format!("Failed to decode image: {e}"))?;let new_width = img.width() / 2;let new_height = img.height() / 2;@@ -513,17 +506,17 @@ async fn compress_image(path: PathBuf) -> Result<Vec<u8>, String> {new_height,resized_img.color().into(),)- .map_err(|e| format!("Failed to compress image: {}", e))?;+ .map_err(|e| format!("Failed to compress image: {e}"))?;Ok(buffer)}).await- .map_err(|e| format!("Failed to compress image: {}", e))?+ .map_err(|e| format!("Failed to compress image: {e}"))?}// a typical recommended chunk size is 5MB (AWS min part size).const CHUNK_SIZE: u64 = 5 * 1024 * 1024; // 5MB-const MIN_PART_SIZE: u64 = 5 * 1024 * 1024; // For non-final parts+// const MIN_PART_SIZE: u64 = 5 * 1024 * 1024; // For non-final partspub struct InstantMultipartUpload {pub handle: tokio::task::JoinHandle<Result<(), String>>,@@ -558,7 +551,7 @@ impl InstantMultipartUpload {realtime_video_done: Option<Receiver<()>>,) -> Result<(), String> {use std::time::Duration;- use tokio::sync::mpsc;+use tokio::time::sleep;// --------------------------------------------@@ -590,7 +583,7 @@ impl InstantMultipartUpload {{Ok(r) => r,Err(e) => {- return Err(format!("Failed to initiate multipart upload: {}", e));+ return Err(format!("Failed to initiate multipart upload: {e}"));}};@@ -601,15 +594,14 @@ impl InstantMultipartUpload {.await.unwrap_or_else(|_| "<no response body>".to_string());return Err(format!(- "Failed to initiate multipart upload. Status: {}. Body: {}",- status, error_body+ "Failed to initiate multipart upload. Status: {status}. Body: {error_body}"));}let initiate_data = match initiate_response.json::<serde_json::Value>().await {Ok(d) => d,Err(e) => {- return Err(format!("Failed to parse initiate response: {}", e));+ return Err(format!("Failed to parse initiate response: {e}"));}};@@ -624,7 +616,7 @@ impl InstantMultipartUpload {return Err("Empty uploadId returned from initiate endpoint".to_string());}- println!("Multipart upload initiated with ID: {}", upload_id);+ println!("Multipart upload initiated with ID: {upload_id}");let mut realtime_is_done = realtime_video_done.as_ref().map(|_| false);@@ -635,19 +627,17 @@ impl InstantMultipartUpload {// - If recording stopped, do leftover final(s).// --------------------------------------------loop {- if !realtime_is_done.unwrap_or(true) {- if let Some(realtime_video_done) = &realtime_video_done {- match realtime_video_done.try_recv() {- Ok(_) => {- realtime_is_done = Some(true);- }- Err(flume::TryRecvError::Empty) => {}- _ => {- warn!("cancelling upload as realtime generation failed");- return Err(- "cancelling upload as realtime generation failed".to_string()- );- }+ if !realtime_is_done.unwrap_or(true)+ && let Some(realtime_video_done) = &realtime_video_done+ {+ match realtime_video_done.try_recv() {+ Ok(_) => {+ realtime_is_done = Some(true);+ }+ Err(flume::TryRecvError::Empty) => {}+ _ => {+ warn!("cancelling upload as realtime generation failed");+ return Err("cancelling upload as realtime generation failed".to_string());}}}@@ -661,7 +651,7 @@ impl InstantMultipartUpload {let file_size = match tokio::fs::metadata(&file_path).await {Ok(md) => md.len(),Err(e) => {- println!("Failed to get file metadata: {}", e);+ println!("Failed to get file metadata: {e}");sleep(Duration::from_millis(500)).await;continue;}@@ -691,8 +681,7 @@ impl InstantMultipartUpload {}Err(e) => {println!(- "Error uploading chunk (part {}): {}. Retrying in 1s...",- part_number, e+ "Error uploading chunk (part {part_number}): {e}. Retrying in 1s...");sleep(Duration::from_secs(1)).await;}@@ -701,7 +690,7 @@ impl InstantMultipartUpload {if realtime_is_done.unwrap_or(false) {info!("realtime video done, uploading header chunk");- match Self::upload_chunk(+ let part = Self::upload_chunk(&app,&client,&file_path,@@ -712,15 +701,10 @@ impl InstantMultipartUpload {uploaded_parts[0].size as u64,).await- {- Ok(part) => {- uploaded_parts[0] = part;- println!("Successfully re-uploaded first chunk",);- }- Err(e) => {- return Err(format!("Failed to re-upload first chunk"));- }- }+ .map_err(|err| format!("Failed to re-upload first chunk: {err}"))?;++ uploaded_parts[0] = part;+ println!("Successfully re-uploaded first chunk",);}// All leftover chunks are now uploaded. We finalize.@@ -731,7 +715,7 @@ impl InstantMultipartUpload {Self::finalize_upload(&app,&file_path,- &s3_config.id(),+ s3_config.id(),&upload_id,&uploaded_parts,)@@ -751,6 +735,7 @@ impl InstantMultipartUpload {/// Upload a single chunk from the file at `last_uploaded_position` for `chunk_size` bytes./// Advances `last_uploaded_position` accordingly. Returns JSON { PartNumber, ETag, Size }.+ #[allow(clippy::too_many_arguments)]async fn upload_chunk(app: &AppHandle,client: &reqwest::Client,@@ -763,7 +748,7 @@ impl InstantMultipartUpload {) -> Result<UploadedPart, String> {let file_size = match tokio::fs::metadata(file_path).await {Ok(metadata) => metadata.len(),- Err(e) => return Err(format!("Failed to get file metadata: {}", e)),+ Err(e) => return Err(format!("Failed to get file metadata: {e}")),};// Check if we're at the end of the file@@ -777,7 +762,7 @@ impl InstantMultipartUpload {let mut file = tokio::fs::File::open(file_path).await- .map_err(|e| format!("Failed to open file: {}", e))?;+ .map_err(|e| format!("Failed to open file: {e}"))?;// Log before seekingprintln!(@@ -790,7 +775,7 @@ impl InstantMultipartUpload {.seek(std::io::SeekFrom::Start(*last_uploaded_position)).await{- return Err(format!("Failed to seek in file: {}", e));+ return Err(format!("Failed to seek in file: {e}"));}// Read exactly bytes_to_read@@ -802,12 +787,9 @@ impl InstantMultipartUpload {Ok(0) => break, // EOFOk(n) => {total_read += n;- println!(- "Read {} bytes, total so far: {}/{}",- n, total_read, bytes_to_read- );+ println!("Read {n} bytes, total so far: {total_read}/{bytes_to_read}");}- Err(e) => return Err(format!("Failed to read chunk from file: {}", e)),+ Err(e) => return Err(format!("Failed to read chunk from file: {e}")),}}@@ -828,13 +810,12 @@ impl InstantMultipartUpload {let pos_after_read = file.seek(std::io::SeekFrom::Current(0)).await- .map_err(|e| format!("Failed to get current file position: {}", e))?;+ .map_err(|e| format!("Failed to get current file position: {e}"))?;let expected_pos = *last_uploaded_position + total_read as u64;if pos_after_read != expected_pos {println!(- "WARNING: File position after read ({}) doesn't match expected position ({})",- pos_after_read, expected_pos+ "WARNING: File position after read ({pos_after_read}) doesn't match expected position ({expected_pos})");}@@ -890,7 +871,7 @@ impl InstantMultipartUpload {let presign_data = match presign_response.json::<serde_json::Value>().await {Ok(d) => d,- Err(e) => return Err(format!("Failed to parse presigned URL response: {}", e)),+ Err(e) => return Err(format!("Failed to parse presigned URL response: {e}")),};let presigned_url = presign_data@@ -947,7 +928,7 @@ impl InstantMultipartUpload {upload_response.status());if let Ok(body) = upload_response.text().await {- println!("Error response: {}", body);+ println!("Error response: {body}");}retry_count += 1;sleep(Duration::from_secs(2)).await;@@ -1018,7 +999,7 @@ impl InstantMultipartUpload {let size = part.size;let etag = &part.etag;total_bytes_in_parts += part.size;- println!("Part {}: {} bytes (ETag: {})", pn, size, etag);+ println!("Part {pn}: {size} bytes (ETag: {etag})");}let file_final_size = tokio::fs::metadata(file_path)@@ -1026,8 +1007,8 @@ impl InstantMultipartUpload {.map(|md| md.len()).unwrap_or(0);- println!("Sum of all parts: {} bytes", total_bytes_in_parts);- println!("File size on disk: {} bytes", file_final_size);+ println!("Sum of all parts: {total_bytes_in_parts} bytes");+ println!("File size on disk: {file_final_size} bytes");println!("Proceeding with multipart upload completion...");let metadata = build_video_meta(file_path)@@ -1054,7 +1035,7 @@ impl InstantMultipartUpload {{Ok(response) => response,Err(e) => {- return Err(format!("Failed to complete multipart upload: {}", e));+ return Err(format!("Failed to complete multipart upload: {e}"));}};@@ -1065,15 +1046,14 @@ impl InstantMultipartUpload {.await.unwrap_or_else(|_| "<no response body>".to_string());return Err(format!(- "Failed to complete multipart upload. Status: {}. Body: {}",- status, error_body+ "Failed to complete multipart upload. Status: {status}. Body: {error_body}"));}let complete_data = match complete_response.json::<serde_json::Value>().await {Ok(d) => d,Err(e) => {- return Err(format!("Failed to parse completion response: {}", e));+ return Err(format!("Failed to parse completion response: {e}"));}};diff --git a/apps/desktop/src-tauri/src/windows.rs b/apps/desktop/src-tauri/src/windows.rsindex e03fed367..f9d47b996 100644--- a/apps/desktop/src-tauri/src/windows.rs+++ b/apps/desktop/src-tauri/src/windows.rs@@ -67,7 +67,7 @@ impl FromStr for CapWindowId {.parse::<u32>().map_err(|e| e.to_string())?,},- _ => return Err(format!("unknown window label: {}", s)),+ _ => return Err(format!("unknown window label: {s}")),})}}@@ -177,7 +177,7 @@ impl ShowCapWindow {if let Self::Editor { project_path } = self {let state = app.state::<EditorWindowIds>();let mut s = state.ids.lock().unwrap();- if s.iter().find(|(path, _)| path == project_path).is_none() {+ if !s.iter().any(|(path, _)| path == project_path) {s.push((project_path.clone(),state@@ -192,7 +192,7 @@ impl ShowCapWindow {return Ok(window);}- let id = self.id(app);+ let _id = self.id(app);let monitor = app.primary_monitor()?.unwrap();let window = match self {@@ -239,14 +239,11 @@ impl ShowCapWindow {let _ = main.close();};- let window = self- .window_builder(app, "/editor")+ self.window_builder(app, "/editor").maximizable(true).inner_size(1240.0, 800.0).center()- .build()?;-- window+ .build()?}Self::Upgrade => {// Hide main window when upgrade window opens@@ -303,7 +300,7 @@ impl ShowCapWindow {- WINDOW_SIZE- 100.0,)- .initialization_script(&format!(+ .initialization_script(format!("window.__CAP__ = window.__CAP__ ?? {{}};window.__CAP__.cameraWsPort = {port};@@ -398,15 +395,13 @@ impl ShowCapWindow {);// Hide the main window if the target monitor is the same- if let Some(main_window) = CapWindowId::Main.get(&app) {- if let (Ok(outer_pos), Ok(outer_size)) =+ if let Some(main_window) = CapWindowId::Main.get(app)+ && let (Ok(outer_pos), Ok(outer_size)) =(main_window.outer_position(), main_window.outer_size())- {- if target_monitor.intersects(outer_pos, outer_size) {- let _ = main_window.minimize();- }- };- }+ && target_monitor.intersects(outer_pos, outer_size)+ {+ let _ = main_window.minimize();+ };window}@@ -502,7 +497,7 @@ impl ShowCapWindow {// window.hide().ok();#[cfg(target_os = "macos")]- if let Some(position) = id.traffic_lights_position() {+ if let Some(position) = _id.traffic_lights_position() {add_traffic_lights(&window, position);}@@ -565,7 +560,7 @@ impl ShowCapWindow {}}ShowCapWindow::CaptureArea { .. } => CapWindowId::CaptureArea,- ShowCapWindow::Camera { .. } => CapWindowId::Camera,+ ShowCapWindow::Camera => CapWindowId::Camera,ShowCapWindow::InProgressRecording { .. } => CapWindowId::InProgressRecording,ShowCapWindow::Upgrade => CapWindowId::Upgrade,ShowCapWindow::ModeSelect => CapWindowId::ModeSelect,@@ -588,10 +583,7 @@ fn add_traffic_lights(window: &WebviewWindow<Wry>, controls_inset: Option<Logicalet c_win = target_window.clone();target_window.on_window_event(move |event| match event {tauri::WindowEvent::ThemeChanged(..) | tauri::WindowEvent::Focused(..) => {- position_traffic_lights_impl(- &c_win.as_ref().window(),- controls_inset.map(LogicalPosition::from),- );+ position_traffic_lights_impl(&c_win.as_ref().window(), controls_inset);}_ => {}});@@ -617,13 +609,13 @@ pub fn set_theme(window: tauri::Window, theme: AppTheme) {#[tauri::command]#[specta::specta]-pub fn position_traffic_lights(window: tauri::Window, controls_inset: Option<(f64, f64)>) {+pub fn position_traffic_lights(_window: tauri::Window, _controls_inset: Option<(f64, f64)>) {#[cfg(target_os = "macos")]position_traffic_lights_impl(- &window,- controls_inset.map(LogicalPosition::from).or_else(|| {+ &_window,+ _controls_inset.map(LogicalPosition::from).or_else(|| {// Attempt to get the default inset from the window's traffic lights position- CapWindowId::from_str(window.label())+ CapWindowId::from_str(_window.label()).ok().and_then(|id| id.traffic_lights_position().flatten())}),@@ -682,16 +674,16 @@ impl MonitorExt for Monitor {#[specta::specta]#[tauri::command(async)]-pub fn set_window_transparent(window: tauri::Window, value: bool) {+pub fn set_window_transparent(_window: tauri::Window, _value: bool) {#[cfg(target_os = "macos")]{- let ns_win = window+ let ns_win = _window.ns_window().expect("Failed to get native window handle")as *const objc2_app_kit::NSWindow;unsafe {- (*ns_win).setOpaque(!value);+ (*ns_win).setOpaque(!_value);}}}diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex c19dd3b32..2e27bc137 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -119,7 +119,7 @@ async uploadExportedVideo(path: string, mode: UploadMode) : Promise<UploadResultasync uploadScreenshot(screenshotPath: string) : Promise<UploadResult> {return await TAURI_INVOKE("upload_screenshot", { screenshotPath });},-async getRecordingMeta(path: string, fileType: string) : Promise<RecordingMetaWithType> {+async getRecordingMeta(path: string, fileType: FileType) : Promise<RecordingMetaWithType> {return await TAURI_INVOKE("get_recording_meta", { path, fileType });},async saveFileDialog(fileName: string, fileType: string) : Promise<string | null> {@@ -349,6 +349,7 @@ export type EditorStateChanged = { playhead_position: number }export type ExportCompression = "Minimal" | "Social" | "Web" | "Potato"export type ExportEstimates = { duration_seconds: number; estimated_time_seconds: number; estimated_size_mb: number }export type ExportSettings = ({ format: "Mp4" } & Mp4ExportSettings) | ({ format: "Gif" } & GifExportSettings)+export type FileType = "recording" | "screenshot"export type Flags = { captions: boolean }export type FramesRendered = { renderedCount: number; totalFrames: number; type: "FramesRendered" }export type GeneralSettingsStore = { instanceId?: string; uploadIndividualFiles?: boolean; hideDockIcon?: boolean; hapticsEnabled?: boolean; autoCreateShareableLink?: boolean; enableNotifications?: boolean; disableAutoOpenLinks?: boolean; hasCompletedStartup?: boolean; theme?: AppTheme; commercialLicense?: CommercialLicense | null; lastVersion?: string | null; windowTransparency?: boolean; postStudioRecordingBehaviour?: PostStudioRecordingBehaviour; mainWindowRecordingStartBehaviour?: MainWindowRecordingStartBehaviour; customCursorCapture?: boolean; serverUrl?: string; recordingCountdown?: number | null;diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.tomlindex 825981272..322ceee1f 100644--- a/crates/audio/Cargo.toml+++ b/crates/audio/Cargo.toml@@ -1,7 +1,7 @@[package]name = "cap-audio"version = "0.1.0"-edition = "2021"+edition = "2024"[dependencies]@@ -11,3 +11,6 @@ tokio.workspace = true[target.'cfg(target_os = "macos")'.dependencies]cidre = { workspace = true }++[lints]+workspace = truediff --git a/crates/audio/src/audio_data.rs b/crates/audio/src/audio_data.rsindex b2c3bc98b..fc2a013ff 100644--- a/crates/audio/src/audio_data.rs+++ b/crates/audio/src/audio_data.rs@@ -1,7 +1,6 @@use ffmpeg::{- codec as avcodec,+ ChannelLayout, codec as avcodec,format::{self as avformat},- ChannelLayout,};use std::path::Path;@@ -23,7 +22,7 @@ impl AudioData {let input_stream = input_ctx.streams().best(ffmpeg::media::Type::Audio)- .ok_or_else(|| format!("No Stream"))?;+ .ok_or_else(|| "No Stream".to_string())?;let decoder_ctx = avcodec::Context::from_parameters(input_stream.parameters()).map_err(|e| format!("AudioData Parameters / {e}"))?;@@ -64,7 +63,7 @@ impl AudioData {.send_packet(&packet).map_err(|e| format!("Send Packet / {e}"))?;- while let Ok(_) = decoder.receive_frame(&mut decoded_frame) {+ while decoder.receive_frame(&mut decoded_frame).is_ok() {let resample_delay = resampler.run(&decoded_frame, &mut resampled_frame).map_err(|e| format!("Run Resampler / {e:?}"))?;@@ -108,7 +107,7 @@ impl AudioData {decoder.send_eof().unwrap();- while let Ok(_) = decoder.receive_frame(&mut decoded_frame) {+ while decoder.receive_frame(&mut decoded_frame).is_ok() {let resample_delay = resampler.run(&decoded_frame, &mut resampled_frame).map_err(|e| format!("Run Resampler / {e}"))?;@@ -171,6 +170,8 @@ impl AudioData {}}+/// # Safety+/// This function assumes that the input slice is aligned to a 4-byte boundary.pub unsafe fn cast_bytes_to_f32_slice(slice: &[u8]) -> &[f32] {- std::slice::from_raw_parts(slice.as_ptr() as *const f32, slice.len() / 4)+ unsafe { std::slice::from_raw_parts(slice.as_ptr() as *const f32, slice.len() / 4) }}diff --git a/crates/audio/src/bin/analyze.rs b/crates/audio/src/bin/analyze.rsindex f32ba2b6d..990e55d38 100644--- a/crates/audio/src/bin/analyze.rs+++ b/crates/audio/src/bin/analyze.rs@@ -7,8 +7,9 @@ pub fn main() {let data = AudioData::from_file(&path).unwrap();- dbg!(data.channels());- dbg!(data.sample_count());- dbg!(data.samples().len());- dbg!(data.samples().len() as f32 / AudioData::SAMPLE_RATE as f32 / data.channels() as f32);+ println!("Channels: {}", data.channels());+ println!("Sample count: {}", data.sample_count());+ println!("Samples len: {}", data.samples().len());+ println!("Sample Rate: {}", AudioData::SAMPLE_RATE as f32);+ println!("Channels: {}", data.channels());}diff --git a/crates/audio/src/bin/macos-audio-capture.rs b/crates/audio/src/bin/macos-audio-capture.rsindex 2b1b0fc8d..2ba94cc29 100644--- a/crates/audio/src/bin/macos-audio-capture.rs+++ b/crates/audio/src/bin/macos-audio-capture.rs@@ -1,90 +1,99 @@-use std::{f64::consts::PI, sync::mpsc::Sender, time::Duration};--use cidre::{- cat, cm, define_obj_type, ns, objc,- sc::{- self,- stream::{Output, OutputImpl},- },-};-use cpal::traits::{DeviceTrait, HostTrait};-use ffmpeg::frame as avframe;-use ffmpeg::ChannelLayout;--#[repr(C)]-struct DelegateInner {- tx: Sender<avframe::Audio>,+#[tokio::main]+pub async fn main() {+ #[cfg(target_os = "macos")]+ macos::main().await;+ #[cfg(not(target_os = "macos"))]+ panic!("This example is only supported on macOS");}-define_obj_type!(Delegate + OutputImpl, DelegateInner, FRAME_COUNTER);--impl Output for Delegate {}--#[objc::add_methods]-impl OutputImpl for Delegate {- extern "C" fn impl_stream_did_output_sample_buf(- &mut self,- _cmd: Option<&cidre::objc::Sel>,- _stream: &sc::Stream,- sample_buf: &mut cm::SampleBuf,- kind: sc::OutputType,- ) {- match kind {- sc::OutputType::Screen => {}- sc::OutputType::Audio => {- let buf_list = sample_buf.audio_buf_list::<2>().unwrap();- let slice = buf_list.block().as_slice().unwrap();- dbg!(&buf_list);-- let mut frame = ffmpeg::frame::Audio::new(- ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Planar),- sample_buf.num_samples() as usize,- ChannelLayout::STEREO,- );- assert!(!frame.is_planar());- let asdb = sample_buf.format_desc().unwrap();- frame.set_rate(asdb.stream_basic_desc().unwrap().sample_rate as u32);- frame.data_mut(0).copy_from_slice(slice);- self.inner_mut().tx.send(frame);+#[cfg(target_os = "macos")]+mod macos {++ use std::{sync::mpsc::Sender, time::Duration};++ use cidre::{+ cm, define_obj_type, ns, objc,+ sc::{+ self,+ stream::{Output, OutputImpl},+ },+ };+ use ffmpeg::ChannelLayout;+ use ffmpeg::frame as avframe;++ #[repr(C)]+ struct DelegateInner {+ tx: Sender<avframe::Audio>,+ }++ define_obj_type!(Delegate + OutputImpl, DelegateInner, FRAME_COUNTER);++ impl Output for Delegate {}++ #[objc::add_methods]+ impl OutputImpl for Delegate {+ extern "C" fn impl_stream_did_output_sample_buf(+ &mut self,+ _cmd: Option<&cidre::objc::Sel>,+ _stream: &sc::Stream,+ sample_buf: &mut cm::SampleBuf,+ kind: sc::OutputType,+ ) {+ match kind {+ sc::OutputType::Screen => {}+ sc::OutputType::Audio => {+ let buf_list = sample_buf.audio_buf_list::<2>().unwrap();+ let slice = buf_list.block().as_slice().unwrap();++ let mut frame = ffmpeg::frame::Audio::new(+ ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Planar),+ sample_buf.num_samples() as usize,+ ChannelLayout::STEREO,+ );+ assert!(!frame.is_planar());+ let asdb = sample_buf.format_desc().unwrap();+ frame.set_rate(asdb.stream_basic_desc().unwrap().sample_rate as u32);+ frame.data_mut(0).copy_from_slice(slice);+ self.inner_mut().tx.send(frame).unwrap();+ }+ sc::OutputType::Mic => {}}- sc::OutputType::Mic => {}}}-}-#[tokio::main]-pub async fn main() {- let mut cfg = sc::StreamCfg::new();- cfg.set_captures_audio(true);- cfg.set_excludes_current_process_audio(false);+ pub async fn main() {+ let mut cfg = sc::StreamCfg::new();+ cfg.set_captures_audio(true);+ cfg.set_excludes_current_process_audio(false);- let content = sc::ShareableContent::current().await.expect("content");- let display = &content.displays().get(0).unwrap();- let filter = sc::ContentFilter::with_display_excluding_windows(display, &ns::Array::new());- let stream = sc::Stream::new(&filter, &cfg);+ let content = sc::ShareableContent::current().await.expect("content");+ let display = &content.displays().get(0).unwrap();+ let filter = sc::ContentFilter::with_display_excluding_windows(display, &ns::Array::new());+ let stream = sc::Stream::new(&filter, &cfg);- let (tx, rx) = std::sync::mpsc::channel();- let delegate = Delegate::with(DelegateInner { tx });+ let (tx, rx) = std::sync::mpsc::channel();+ let delegate = Delegate::with(DelegateInner { tx });- stream- .add_stream_output(delegate.as_ref(), sc::OutputType::Audio, None)- .unwrap();+ stream+ .add_stream_output(delegate.as_ref(), sc::OutputType::Audio, None)+ .unwrap();- stream.start().await.unwrap();+ stream.start().await.unwrap();- tokio::time::sleep(Duration::from_secs(5)).await;+ tokio::time::sleep(Duration::from_secs(5)).await;- let _ = stream.stop().await;+ let _ = stream.stop().await;- let mut samples = vec![];- while let Ok(s) = rx.try_recv() {- samples.push(s)- }+ let mut samples = vec![];+ while let Ok(s) = rx.try_recv() {+ samples.push(s)+ }- let bytes = samples- .iter()- .flat_map(|s| s.data(0).to_vec())- .collect::<Vec<_>>();+ let bytes = samples+ .iter()+ .flat_map(|s| s.data(0).to_vec())+ .collect::<Vec<_>>();- std::fs::write("./bruh.raw", &bytes);+ std::fs::write("./bruh.raw", &bytes).unwrap();+ }}diff --git a/crates/audio/src/main.rs b/crates/audio/src/main.rsindex 47d9fc5e1..a9b7966d6 100644--- a/crates/audio/src/main.rs+++ b/crates/audio/src/main.rs@@ -1,18 +1,20 @@use cap_audio::AudioData;-use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};use ffmpeg::{codec as avcodec,format::{self as avformat},- software::resampling::Delay,};-use std::{collections::VecDeque, path::Path};+use std::path::Path;+/// # Safety+/// This function assumes that the input slice contains valid f32 values and that the length of the slice is a multiple of 4.pub unsafe fn cast_f32_slice_to_bytes(slice: &[f32]) -> &[u8] {- std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * 4)+ unsafe { std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * 4) }}+/// # Safety+/// This function assumes that the input slice contains valid f32 values and that the length of the slice is a multiple of 4.pub unsafe fn cast_bytes_to_f32_slice(slice: &[u8]) -> &[f32] {- std::slice::from_raw_parts(slice.as_ptr() as *const f32, slice.len() / 4)+ unsafe { std::slice::from_raw_parts(slice.as_ptr() as *const f32, slice.len() / 4) }}pub fn opus_encode_audio(path: impl AsRef<Path>, samples: &AudioData) {diff --git a/crates/camera-avfoundation/examples/cli.rs b/crates/camera-avfoundation/examples/cli.rsindex db2b83f24..4d9aab2af 100644--- a/crates/camera-avfoundation/examples/cli.rs+++ b/crates/camera-avfoundation/examples/cli.rs@@ -31,10 +31,7 @@ pub fn main() {let selected = Select::new("Select a device", devices).prompt().unwrap();let mut selected_device = _devices.get(selected.1).unwrap();- println!(- "Info for device '{}'",- selected_device.localized_name().to_string()- );+ println!("Info for device '{}'", selected_device.localized_name());let formats = selected_device.formats();@@ -154,6 +151,7 @@ struct Format {width: i32,height: i32,fourcc: FourCharCode,+ #[allow(unused)]color_space: Option<YCbCrMatrix>,max_frame_rate: (i64, i32),}@@ -177,18 +175,13 @@ struct CaptureDeviceSelectOption<'a>(&'a av::CaptureDevice, usize);impl<'a> Display for CaptureDeviceSelectOption<'a> {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- write!(- f,- "{} ({})",- self.0.localized_name().to_string(),- self.0.unique_id().to_string()- )+ write!(f, "{} ({})", self.0.localized_name(), self.0.unique_id())}}impl AsRef<av::CaptureDevice> for CaptureDeviceSelectOption<'_> {fn as_ref(&self) -> &av::CaptureDevice {- &self.0+ self.0}}@@ -196,6 +189,6 @@ impl Deref for CaptureDeviceSelectOption<'_> {type Target = av::CaptureDevice;fn deref(&self) -> &Self::Target {- &self.0+ self.0}}diff --git a/crates/camera-avfoundation/src/lib.rs b/crates/camera-avfoundation/src/lib.rsindex 6a6e40d84..3b0fa130f 100644--- a/crates/camera-avfoundation/src/lib.rs+++ b/crates/camera-avfoundation/src/lib.rs@@ -60,7 +60,7 @@ impl TryFrom<&cf::String> for YCbCrMatrix {s if s == cv::image_buf_attachment::ycbcr_matrix::itu_r_601_4() => Self::Rec601,s if s == cv::image_buf_attachment::ycbcr_matrix::itu_r_709_2() => Self::Rec709,s if s == cv::image_buf_attachment::ycbcr_matrix::itu_r_2020() => Self::Rec2020,- s => return Err(()),+ _ => return Err(()),})}}diff --git a/crates/camera-directshow/examples/cli.rs b/crates/camera-directshow/examples/cli.rsindex dd76ecf64..0cb8658d1 100644--- a/crates/camera-directshow/examples/cli.rs+++ b/crates/camera-directshow/examples/cli.rs@@ -1,152 +1,163 @@-use cap_camera_directshow::*;-use std::{fmt::Display, time::Duration};-use tracing::error;-use windows::{- Win32::{- Foundation::SIZE,- Media::{DirectShow::*, MediaFoundation::*},- System::Com::*,- },- core::Interface,-};-fn main() {- tracing_subscriber::fmt::init();+ #[cfg(windows)]+ windows::run();+ #[cfg(not(windows))]+ panic!("This example is only available on Windows");+}- unsafe {- CoInitialize(None).unwrap();+#[cfg(windows)]+mod windows {- let devices = VideoInputDeviceIterator::new().unwrap().collect::<Vec<_>>();+ use cap_camera_directshow::*;+ use std::{fmt::Display, time::Duration};+ use tracing::error;+ use windows::{+ Win32::{+ Foundation::SIZE,+ Media::{DirectShow::*, MediaFoundation::*},+ System::Com::*,+ },+ core::Interface,+ };- let mut devices = devices- .into_iter()- .map(VideoDeviceSelectOption)- .collect::<Vec<_>>();+ fn main() {+ tracing_subscriber::fmt::init();- let selected = if devices.len() > 1 {- inquire::Select::new("Select a device", devices)- .prompt()+ unsafe {+ CoInitialize(None).unwrap();++ let devices = VideoInputDeviceIterator::new().unwrap().collect::<Vec<_>>();++ let mut devices = devices+ .into_iter()+ .map(VideoDeviceSelectOption)+ .collect::<Vec<_>>();++ let selected = if devices.len() > 1 {+ inquire::Select::new("Select a device", devices)+ .prompt()+ .unwrap()+ } else {+ devices.remove(0)+ };++ let device = selected.0;++ let video_control = device.output_pin().cast::<IAMVideoControl>().ok();++ let formats = device+ .media_types().unwrap()- } else {- devices.remove(0)- };-- let device = selected.0;-- let video_control = device.output_pin().cast::<IAMVideoControl>().ok();-- let formats = device- .media_types()- .unwrap()- .enumerate()- .filter_map(|(i, media_type)| {- let is_video = media_type.majortype == MEDIATYPE_Video- && media_type.formattype == FORMAT_VideoInfo;-- if !is_video {- return None;- }-- let video_info = &*media_type.video_info();-- let width = video_info.bmiHeader.biWidth;- let height = video_info.bmiHeader.biHeight;-- let mut frame_rates = vec![];-- if let Some(video_control) = &video_control {- let time_per_frame_list = video_control.time_per_frame_list(- device.output_pin(),- i as i32,- SIZE {- cx: width,- cy: height,- },- );-- for time_per_frame in time_per_frame_list {- if *time_per_frame <= 0 {- return None;+ .enumerate()+ .filter_map(|(i, media_type)| {+ let is_video = media_type.majortype == MEDIATYPE_Video+ && media_type.formattype == FORMAT_VideoInfo;++ if !is_video {+ return None;+ }++ let video_info = &*media_type.video_info();++ let width = video_info.bmiHeader.biWidth;+ let height = video_info.bmiHeader.biHeight;++ let mut frame_rates = vec![];++ if let Some(video_control) = &video_control {+ let time_per_frame_list = video_control.time_per_frame_list(+ device.output_pin(),+ i as i32,+ SIZE {+ cx: width,+ cy: height,+ },+ );++ for time_per_frame in time_per_frame_list {+ if *time_per_frame <= 0 {+ return None;+ }+ frame_rates.push(10_000_000.0 / *time_per_frame as f64)}- frame_rates.push(10_000_000.0 / *time_per_frame as f64)}- }- if frame_rates.is_empty() {- let frame_rate = 10_000_000.0 / video_info.AvgTimePerFrame as f64;- frame_rates.push(frame_rate);- }+ if frame_rates.is_empty() {+ let frame_rate = 10_000_000.0 / video_info.AvgTimePerFrame as f64;+ frame_rates.push(frame_rate);+ }- frame_rates- .iter_mut()- .for_each(|v| *v = (*v * 100.0).round() / 100.0);+ frame_rates+ .iter_mut()+ .for_each(|v| *v = (*v * 100.0).round() / 100.0);- // println!(" Frame Rates: {:?}", frame_rates);+ // println!(" Frame Rates: {:?}", frame_rates);- Some(Format {- width,- height,- media_type,- frame_rates,+ Some(Format {+ width,+ height,+ media_type,+ frame_rates,+ })})- })- .collect::<Vec<_>>();+ .collect::<Vec<_>>();- if formats.is_empty() {- error!("No formats found");- return;- }+ if formats.is_empty() {+ error!("No formats found");+ return;+ }- let selected_format = inquire::Select::new("Select a format", formats)- .prompt()- .unwrap();-- device- .start_capturing(- &selected_format.media_type,- Box::new(|frame| {- unsafe { dbg!(frame.sample.GetActualDataLength()) };- dbg!(frame.media_type.subtype_str());- dbg!(frame.reference_time);- dbg!(frame.timestamp);- }),- )- .unwrap();-- std::thread::sleep(Duration::from_secs(10));+ let selected_format = inquire::Select::new("Select a format", formats)+ .prompt()+ .unwrap();++ device+ .start_capturing(+ &selected_format.media_type,+ Box::new(|frame| {+ unsafe { dbg!(frame.sample.GetActualDataLength()) };+ dbg!(frame.media_type.subtype_str());+ dbg!(frame.reference_time);+ dbg!(frame.timestamp);+ }),+ )+ .unwrap();++ std::thread::sleep(Duration::from_secs(10));+ }}-}-#[derive(Debug)]-struct Format {- width: i32,- height: i32,- media_type: AMMediaType,- frame_rates: Vec<f64>,-}+ #[derive(Debug)]+ struct Format {+ width: i32,+ height: i32,+ media_type: AMMediaType,+ frame_rates: Vec<f64>,+ }-impl Display for Format {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- write!(- f,- "{}x{} {} ({:?})",- self.width,- self.height,- unsafe {- self.media_type- .subtype_str()- .map(|v| v.to_string())- .unwrap_or(format!("unknown ({:?})", self.media_type.subtype))- },- &self.frame_rates- )+ impl Display for Format {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ f,+ "{}x{} {} ({:?})",+ self.width,+ self.height,+ unsafe {+ self.media_type+ .subtype_str()+ .map(|v| v.to_string())+ .unwrap_or(format!("unknown ({:?})", self.media_type.subtype))+ },+ &self.frame_rates+ )+ }}-}-struct VideoDeviceSelectOption(VideoInputDevice);+ struct VideoDeviceSelectOption(VideoInputDevice);-impl Display for VideoDeviceSelectOption {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- write!(f, "{:?}", self.0.name().unwrap())+ impl Display for VideoDeviceSelectOption {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{:?}", self.0.name().unwrap())+ }}}diff --git a/crates/camera-directshow/src/lib.rs b/crates/camera-directshow/src/lib.rsindex b12fae314..bfb468667 100644--- a/crates/camera-directshow/src/lib.rs+++ b/crates/camera-directshow/src/lib.rs@@ -16,9 +16,7 @@ use windows::{Foundation::*,Media::{DirectShow::*,- KernelStreaming::{- IKsPropertySet, KS_BITMAPINFOHEADER, KS_VIDEOINFO, KS_VIDEOINFOHEADER,- },+ KernelStreaming::{IKsPropertySet, KS_VIDEOINFOHEADER},MediaFoundation::*,},System::{@@ -35,40 +33,52 @@ pub fn initialize_directshow() -> windows_core::Result<()> {}pub trait IPinExt {+ /// # Safety+ /// Do it correctlyunsafe fn matches_category(&self, category: GUID) -> bool;++ /// # Safety+ /// Do it correctlyunsafe fn matches_major_type(&self, major_type: GUID) -> bool;}impl IPinExt for IPin {unsafe fn matches_category(&self, category: GUID) -> bool {- let ks_property = self.cast::<IKsPropertySet>().unwrap();- let mut return_value_size = 0;- let mut pin_category = GUID::zeroed();- ks_property- .Get(- &ROPSETID_Pin,- AMPROPERTY_PIN_CATEGORY.0 as u32,- null(),- 0,- (&mut pin_category) as *mut _ as *mut c_void,- std::mem::size_of_val(&pin_category) as u32,- &mut return_value_size,- )- .unwrap();+ unsafe {+ let ks_property = self.cast::<IKsPropertySet>().unwrap();+ let mut return_value_size = 0;+ let mut pin_category = GUID::zeroed();+ ks_property+ .Get(+ &ROPSETID_Pin,+ AMPROPERTY_PIN_CATEGORY.0 as u32,+ null(),+ 0,+ (&mut pin_category) as *mut _ as *mut c_void,+ std::mem::size_of_val(&pin_category) as u32,+ &mut return_value_size,+ )+ .unwrap();- return_value_size as usize == std::mem::size_of_val(&category) && pin_category == category+ return_value_size as usize == std::mem::size_of_val(&category)+ && pin_category == category+ }}unsafe fn matches_major_type(&self, major_type: GUID) -> bool {- let mut connection_media_type = AM_MEDIA_TYPE::default();- self.ConnectionMediaType(&mut connection_media_type)- .map(|_| connection_media_type.majortype == major_type)- .unwrap_or(false)+ unsafe {+ let mut connection_media_type = AM_MEDIA_TYPE::default();+ self.ConnectionMediaType(&mut connection_media_type)+ .map(|_| connection_media_type.majortype == major_type)+ .unwrap_or(false)+ }}}pub trait IBaseFilterExt {fn get_pin(&self, direction: PIN_DIRECTION, category: GUID, major_type: GUID) -> Option<IPin>;+ /// # Safety+ /// Don't mess it upunsafe fn get_pin_by_name(&self,direction: PIN_DIRECTION,@@ -93,12 +103,11 @@ impl IBaseFilterExt for IBaseFilter {continue;};- if pin_dir == direction {- if (category == GUID::zeroed() || pin.matches_category(category))- && (major_type == GUID::zeroed() || pin.matches_major_type(major_type))- {- return Some(pin);- }+ if pin_dir == direction+ && (category == GUID::zeroed() || pin.matches_category(category))+ && (major_type == GUID::zeroed() || pin.matches_major_type(major_type))+ {+ return Some(pin);}}}@@ -111,24 +120,26 @@ impl IBaseFilterExt for IBaseFilter {direction: PIN_DIRECTION,_name: Option<&PWSTR>,) -> windows_core::Result<Option<IPin>> {- let pin_enum = self.EnumPins()?;+ unsafe {+ let pin_enum = self.EnumPins()?;- let _ = pin_enum.Reset();+ let _ = pin_enum.Reset();- let mut pin = [None];- while pin_enum.Next(&mut pin, None) == S_OK {- let Some(pin) = pin[0].take() else {- break;- };+ let mut pin = [None];+ while pin_enum.Next(&mut pin, None) == S_OK {+ let Some(pin) = pin[0].take() else {+ break;+ };- let pin_dir = pin.QueryDirection().unwrap();+ let pin_dir = pin.QueryDirection().unwrap();- if pin_dir == direction {- return Ok(Some(pin));+ if pin_dir == direction {+ return Ok(Some(pin));+ }}- }- Ok(None)+ Ok(None)+ }}}@@ -152,8 +163,10 @@ pub struct IAMStreamConfigMediaTypes<'a> {i: i32,}-impl<'a> IAMStreamConfigMediaTypes<'a> {- pub fn next(&mut self) -> Option<(&'a AM_MEDIA_TYPEVideo, i32)> {+impl<'a> Iterator for IAMStreamConfigMediaTypes<'a> {+ type Item = (&'a AM_MEDIA_TYPEVideo, i32);++ fn next(&mut self) -> Option<Self::Item> {let i = self.i;if i >= self.count as i32 {@@ -176,23 +189,25 @@ impl<'a> IAMStreamConfigMediaTypes<'a> {Some((&*media_type, i))}}+}+impl<'a> IAMStreamConfigMediaTypes<'a> {pub fn count(&self) -> u32 {self.count}}pub trait IAMStreamConfigExt {- fn media_types(&self) -> windows_core::Result<IAMStreamConfigMediaTypes>;+ fn media_types(&self) -> windows_core::Result<IAMStreamConfigMediaTypes<'_>>;}impl IAMStreamConfigExt for IAMStreamConfig {- fn media_types(&self) -> windows_core::Result<IAMStreamConfigMediaTypes> {+ fn media_types(&self) -> windows_core::Result<IAMStreamConfigMediaTypes<'_>> {let mut count = 0;unsafe { self.GetNumberOfCapabilities(&mut count, &mut 0) }?;Ok(IAMStreamConfigMediaTypes {- stream_config: &self,+ stream_config: self,count: count as u32,caps: VIDEO_STREAM_CONFIG_CAPS::default(),i: 0,@@ -205,17 +220,21 @@ type AM_MEDIA_TYPEVideo = AM_MEDIA_TYPE;#[allow(non_camel_case_types)]pub trait AM_MEDIA_TYPEVideoExt {+ /// # Safety+ /// Just don't do it wrongunsafe fn video_info(&self) -> &KS_VIDEOINFOHEADER;}impl AM_MEDIA_TYPEVideoExt for AM_MEDIA_TYPEVideo {unsafe fn video_info(&self) -> &KS_VIDEOINFOHEADER {- &*self.pbFormat.cast::<KS_VIDEOINFOHEADER>()+ unsafe { &*self.pbFormat.cast::<KS_VIDEOINFOHEADER>() }}}#[allow(non_camel_case_types)]pub trait AM_MEDIA_TYPEExt {+ /// # Safety+ /// Just don't do it wrongunsafe fn subtype_str(&self) -> Option<&'static str>;}@@ -238,39 +257,49 @@ impl AM_MEDIA_TYPEExt for AM_MEDIA_TYPE {}pub trait IAMVideoControlExt {+ /// # Safety+ /// Just don't do it wrongunsafe fn time_per_frame_list<'a>(&self, pin: &'a IPin, i: i32, dimensions: SIZE) -> &'a [i64];}impl IAMVideoControlExt for IAMVideoControl {unsafe fn time_per_frame_list<'a>(&self, pin: &'a IPin, i: i32, dimensions: SIZE) -> &'a [i64] {- let mut time_per_frame_list = null_mut();- let mut list_size = 0;+ unsafe {+ let mut time_per_frame_list = null_mut();+ let mut list_size = 0;++ self.GetFrameRateList(pin, i, dimensions, &mut list_size, &mut time_per_frame_list)+ .unwrap();- self.GetFrameRateList(pin, i, dimensions, &mut list_size, &mut time_per_frame_list)- .unwrap();+ if list_size > 0 && !time_per_frame_list.is_null() {+ return std::slice::from_raw_parts(time_per_frame_list, list_size as usize);+ }- if list_size > 0 && !time_per_frame_list.is_null() {- return std::slice::from_raw_parts(time_per_frame_list, list_size as usize);+ &[]}-- &[]}}pub trait IPropertyBagExt {+ /// # Safety+ /// Do it correctlyunsafe fn read<P0>(&self, pszpropname: P0) -> windows_core::Result<VARIANT>whereP0: windows_core::Param<windows_core::PCWSTR>;}impl IPropertyBagExt for IPropertyBag {+ /// # Safety+ /// Do it correctlyunsafe fn read<P0>(&self, pszpropname: P0) -> windows_core::Result<VARIANT>whereP0: windows_core::Param<windows_core::PCWSTR>,{- let mut ret = VARIANT::default();- self.Read(pszpropname, &mut ret, None)?;- Ok(ret)+ unsafe {+ let mut ret = VARIANT::default();+ self.Read(pszpropname, &mut ret, None)?;+ Ok(ret)+ }}}@@ -383,7 +412,7 @@ impl VideoInputDevice {.and_then(|v| get_device_model_id(&v.to_string_lossy()))}- pub fn media_types(&self) -> Option<VideoMediaTypesIterator> {+ pub fn media_types(&self) -> Option<VideoMediaTypesIterator<'_>> {self.stream_config.media_types().map(|inner| VideoMediaTypesIterator { inner })@@ -636,6 +665,7 @@ impl IBaseFilter_Impl for SinkFilter_Impl {Err(E_NOTIMPL.into())}+ #[allow(clippy::not_unsafe_ptr_arg_deref)] // This is a public traitfn QueryFilterInfo(&self,pinfo: *mut windows::Win32::Media::DirectShow::FILTER_INFO,@@ -753,8 +783,7 @@ impl<'a> IEnumPins_Impl for PinEnumerator_Impl<'a> {}fn Clone(&self) -> windows_core::Result<IEnumPins> {- let result = unsafe { self.cast() };- result+ unsafe { self.cast() }}}@@ -770,6 +799,7 @@ pub type SinkCallback = Box<dyn FnMut(CallbackData)>;#[implement(IPin, IMemInputPin)]struct SinkInputPin {desired_media_type: AMMediaType,+ #[allow(unused)]current_media_type: RefCell<AMMediaType>,connected_pin: RefCell<Option<IPin>>,owner: RefCell<Option<IBaseFilter>>,@@ -777,32 +807,34 @@ struct SinkInputPin {first_ref_time: RefCell<Option<Instant>>,}-impl SinkInputPin {- unsafe fn get_valid_media_type(&self, index: i32, media_type: &mut AM_MEDIA_TYPE) -> bool {- let video_info_header = &mut *(media_type.pbFormat as *mut KS_VIDEOINFOHEADER);-- video_info_header.bmiHeader.biSize = size_of::<KS_BITMAPINFOHEADER>() as u32;- video_info_header.bmiHeader.biPlanes = 1;- video_info_header.bmiHeader.biClrImportant = 0;- video_info_header.bmiHeader.biClrUsed = 0;-- media_type.majortype = MEDIATYPE_Video;- media_type.formattype = FORMAT_VideoInfo;- media_type.bTemporalCompression = false.into();-- if index == 0 {- video_info_header.bmiHeader.biCompression =- u32::from_ne_bytes(*"yuy2".as_bytes().first_chunk::<4>().unwrap());- video_info_header.bmiHeader.biBitCount = 16;- video_info_header.bmiHeader.biWidth = 640;- video_info_header.bmiHeader.biHeight = 480;- media_type.subtype = MEDIASUBTYPE_YUY2;- true- } else {- false- }- }-}+// impl SinkInputPin {+// unsafe fn get_valid_media_type(&self, index: i32, media_type: &mut AM_MEDIA_TYPE) -> bool {+// unsafe {+// let video_info_header = &mut *(media_type.pbFormat as *mut KS_VIDEOINFOHEADER);++// video_info_header.bmiHeader.biSize = size_of::<KS_BITMAPINFOHEADER>() as u32;+// video_info_header.bmiHeader.biPlanes = 1;+// video_info_header.bmiHeader.biClrImportant = 0;+// video_info_header.bmiHeader.biClrUsed = 0;++// media_type.majortype = MEDIATYPE_Video;+// media_type.formattype = FORMAT_VideoInfo;+// media_type.bTemporalCompression = false.into();++// if index == 0 {+// video_info_header.bmiHeader.biCompression =+// u32::from_ne_bytes(*"yuy2".as_bytes().first_chunk::<4>().unwrap());+// video_info_header.bmiHeader.biBitCount = 16;+// video_info_header.bmiHeader.biWidth = 640;+// video_info_header.bmiHeader.biHeight = 480;+// media_type.subtype = MEDIASUBTYPE_YUY2;+// true+// } else {+// false+// }+// }+// }+// }impl IPin_Impl for SinkInputPin_Impl {fn Connect(@@ -844,19 +876,17 @@ impl IPin_Impl for SinkInputPin_Impl {}fn Disconnect(&self) -> windows_core::Result<()> {- let result = match self.connected_pin.borrow_mut().take() {+ match self.connected_pin.borrow_mut().take() {Some(_) => S_OK.ok(),None => VFW_E_NOT_CONNECTED.ok(),- };- result+ }}fn ConnectedTo(&self) -> windows_core::Result<IPin> {- let result = match self.connected_pin.borrow().as_ref() {+ match self.connected_pin.borrow().as_ref() {Some(connected_pin) => Ok(connected_pin.clone()),None => Err(VFW_E_NOT_CONNECTED.into()),- };- result+ }}fn ConnectionMediaType(@@ -880,7 +910,7 @@ impl IPin_Impl for SinkInputPin_Impl {unsafe {(*pinfo).dir = PINDIR_INPUT;(*pinfo).pFilter =- ManuallyDrop::new(self.owner.borrow().as_ref().map(|v| (&*v).clone()));+ ManuallyDrop::new(self.owner.borrow().as_ref().map(|v| (*v).clone()));(*pinfo).achName[0] = '\0' as u16;}@@ -969,11 +999,11 @@ impl IMemInputPin_Impl for SinkInputPin_Impl {};unsafe {- if let Ok(new_media_type) = psample.GetMediaType() {- if !new_media_type.is_null() {- self.current_media_type- .replace(AMMediaType::new(&*new_media_type));- }+ if let Ok(new_media_type) = psample.GetMediaType()+ && !new_media_type.is_null()+ {+ self.current_media_type+ .replace(AMMediaType::new(&*new_media_type));}}@@ -1002,10 +1032,10 @@ impl IMemInputPin_Impl for SinkInputPin_Impl {let timestamp = timestamp.get_or_insert(Instant::now() - *first_ref_time);(self.callback.borrow_mut())(CallbackData {- sample: &psample,+ sample: psample,media_type: &media_type,- reference_time: first_ref_time.clone(),- timestamp: timestamp.clone(),+ reference_time: *first_ref_time,+ timestamp: *timestamp,});Ok(())@@ -1037,16 +1067,16 @@ struct TypeEnumerator<'a> {pin: &'a SinkInputPin,}-impl<'a> TypeEnumerator<'a> {- unsafe fn free_allocated_media_types(allocated: usize, types: *mut *mut AM_MEDIA_TYPE) {- for i in 0..allocated {- unsafe {- CoTaskMemFree(Some((*(*types.add(i))).pbFormat as *const _));- CoTaskMemFree(Some(*types.add(i) as *const _));- }- }- }-}+// impl<'a> TypeEnumerator<'a> {+// unsafe fn free_allocated_media_types(allocated: usize, types: *mut *mut AM_MEDIA_TYPE) {+// for i in 0..allocated {+// unsafe {+// CoTaskMemFree(Some((*(*types.add(i))).pbFormat as *const _));+// CoTaskMemFree(Some(*types.add(i) as *const _));+// }+// }+// }+// }impl<'a> IEnumMediaTypes_Impl for TypeEnumerator_Impl<'a> {fn Next(@@ -1129,7 +1159,7 @@ unsafe fn copy_media_type(src: &AM_MEDIA_TYPE) -> AM_MEDIA_TYPE {}fn get_device_model_id(device_id: &str) -> Option<String> {- const VID_PID_SIZE: usize = 4;+ // const VID_PID_SIZE: usize = 4;let vid_location = device_id.find("vid_")?;let pid_location = device_id.find("pid_")?;diff --git a/crates/camera-ffmpeg/examples/cli.rs b/crates/camera-ffmpeg/examples/cli.rsindex b77db4a35..21183ee09 100644--- a/crates/camera-ffmpeg/examples/cli.rs+++ b/crates/camera-ffmpeg/examples/cli.rs@@ -4,10 +4,7 @@ use cap_camera::{CameraInfo, Format};use cap_camera_ffmpeg::CapturedFrameExt;fn main() {- let cameras = cap_camera::list_cameras()- .into_iter()- .map(CameraSelectOption)- .collect();+ let cameras = cap_camera::list_cameras().map(CameraSelectOption).collect();let selected_camera = inquire::Select::new("Select a device", cameras).prompt()@@ -31,7 +28,9 @@ fn main() {return;};- dbg!(ff_frame.width(), ff_frame.height(), ff_frame.format());+ ff_frame.width();+ ff_frame.height();+ ff_frame.format();}).unwrap();diff --git a/crates/camera-mediafoundation/Cargo.toml b/crates/camera-mediafoundation/Cargo.tomlindex 01ec2e478..2eaa352c0 100644--- a/crates/camera-mediafoundation/Cargo.toml+++ b/crates/camera-mediafoundation/Cargo.toml@@ -6,6 +6,7 @@ edition = "2024"[dependencies]tracing.workspace = truethiserror.workspace = true+windows-core.workspace = true[target.'cfg(windows)'.dependencies]windows-core = { workspace = true }diff --git a/crates/camera-mediafoundation/examples/cli.rs b/crates/camera-mediafoundation/examples/cli.rsindex b73b7abf1..2916d4eb9 100644--- a/crates/camera-mediafoundation/examples/cli.rs+++ b/crates/camera-mediafoundation/examples/cli.rs@@ -1,137 +1,148 @@-use std::{fmt::Display, time::Duration};+fn main() {+ #[cfg(windows)]+ windows::run();+ #[cfg(not(windows))]+ panic!("This example is only available on Windows");+}-use cap_camera_mediafoundation::DeviceSourcesIterator;-use tracing::warn;-use windows::Win32::{Media::MediaFoundation::*, System::Com::CoInitialize};-use windows_core::GUID;+#[cfg(windows)]+mod windows {-pub fn main() {- unsafe {- CoInitialize(None).unwrap();+ use std::{fmt::Display, time::Duration};- let device_sources = DeviceSourcesIterator::new().unwrap();+ use cap_camera_mediafoundation::DeviceSourcesIterator;+ use tracing::warn;+ use windows::Win32::{Media::MediaFoundation::*, System::Com::CoInitialize};+ use windows_core::GUID;- if device_sources.len() == 0 {- warn!("No devices found");- return;- }+ pub fn main() {+ unsafe {+ CoInitialize(None).unwrap();- let mut device_list = device_sources.collect::<Vec<_>>();+ let device_sources = DeviceSourcesIterator::new().unwrap();- let selected = if device_list.len() > 1 {- inquire::Select::new("Select a device", device_list)- .prompt()- .unwrap()- } else {- device_list.remove(0)- };-- let mut formats = selected- .formats()- .unwrap()- .filter_map(|v| VideoFormat::new(v).ok())- .collect::<Vec<_>>();-- let selected_format = if formats.len() > 1 {- inquire::Select::new("Select a format", formats)- .prompt()- .unwrap()- } else {- formats.remove(0)- };-- let _handle = selected- .start_capturing(- &selected_format.inner,- Box::new(|data| {- let pts = data.sample.GetSampleTime().unwrap();- let bytes = data.sample.GetTotalLength().unwrap();- // if stream_flags as i32 & MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED.0- // == MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED.0- // {- // selected_format =- // VideoFormat::new(reader.GetCurrentMediaType(stream_index).unwrap()).unwrap();- // }- println!(- "New frame: {pts}pts, {bytes} bytes",- // selected_format.width,- // selected_format.height,- // media_subtype_str(&selected_format.subtype).unwrap_or("unknown format")- );- }),- )- .unwrap();+ if device_sources.len() == 0 {+ warn!("No devices found");+ return;+ }- std::thread::sleep(Duration::from_secs(10));+ let mut device_list = device_sources.collect::<Vec<_>>();++ let selected = if device_list.len() > 1 {+ inquire::Select::new("Select a device", device_list)+ .prompt()+ .unwrap()+ } else {+ device_list.remove(0)+ };++ let mut formats = selected+ .formats()+ .unwrap()+ .filter_map(|v| VideoFormat::new(v).ok())+ .collect::<Vec<_>>();++ let selected_format = if formats.len() > 1 {+ inquire::Select::new("Select a format", formats)+ .prompt()+ .unwrap()+ } else {+ formats.remove(0)+ };++ let _handle = selected+ .start_capturing(+ &selected_format.inner,+ Box::new(|data| {+ let pts = data.sample.GetSampleTime().unwrap();+ let bytes = data.sample.GetTotalLength().unwrap();+ // if stream_flags as i32 & MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED.0+ // == MF_SOURCE_READERF_CURRENTMEDIATYPECHANGED.0+ // {+ // selected_format =+ // VideoFormat::new(reader.GetCurrentMediaType(stream_index).unwrap()).unwrap();+ // }+ println!(+ "New frame: {pts}pts, {bytes} bytes",+ // selected_format.width,+ // selected_format.height,+ // media_subtype_str(&selected_format.subtype).unwrap_or("unknown format")+ );+ }),+ )+ .unwrap();++ std::thread::sleep(Duration::from_secs(10));+ }}-}-struct VideoFormat {- inner: IMFMediaType,- width: u32,- height: u32,- frame_rate_ratio: (u32, u32),- frame_rate: f32,- subtype: GUID,-}+ struct VideoFormat {+ inner: IMFMediaType,+ width: u32,+ height: u32,+ frame_rate_ratio: (u32, u32),+ frame_rate: f32,+ subtype: GUID,+ }-impl VideoFormat {- fn new(inner: IMFMediaType) -> windows_core::Result<Self> {- let size = unsafe { inner.GetUINT64(&MF_MT_FRAME_SIZE)? };- let width = (size >> 32) as u32;- let height = (size & 0xFFFFFFFF) as u32;-- let frame_rate_ratio = {- let frame_rate = unsafe { inner.GetUINT64(&MF_MT_FRAME_RATE)? };- let numerator = (frame_rate >> 32) as u32;- let denominator = frame_rate as u32;- (numerator, denominator)- };- let frame_rate = frame_rate_ratio.0 as f32 / frame_rate_ratio.1 as f32;-- let subtype = unsafe { inner.GetGUID(&MF_MT_SUBTYPE)? };-- Ok(Self {- inner,- width,- height,- frame_rate_ratio,- frame_rate,- subtype,- })+ impl VideoFormat {+ fn new(inner: IMFMediaType) -> windows_core::Result<Self> {+ let size = unsafe { inner.GetUINT64(&MF_MT_FRAME_SIZE)? };+ let width = (size >> 32) as u32;+ let height = (size & 0xFFFFFFFF) as u32;++ let frame_rate_ratio = {+ let frame_rate = unsafe { inner.GetUINT64(&MF_MT_FRAME_RATE)? };+ let numerator = (frame_rate >> 32) as u32;+ let denominator = frame_rate as u32;+ (numerator, denominator)+ };+ let frame_rate = frame_rate_ratio.0 as f32 / frame_rate_ratio.1 as f32;++ let subtype = unsafe { inner.GetGUID(&MF_MT_SUBTYPE)? };++ Ok(Self {+ inner,+ width,+ height,+ frame_rate_ratio,+ frame_rate,+ subtype,+ })+ }}-}-impl Display for VideoFormat {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- write!(f, "{}x{} {}fps", self.width, self.height, self.frame_rate)?;- if self.frame_rate_ratio.1 != 1 {+ impl Display for VideoFormat {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}x{} {}fps", self.width, self.height, self.frame_rate)?;+ if self.frame_rate_ratio.1 != 1 {+ write!(+ f,+ " ({}/{})",+ self.frame_rate_ratio.0, self.frame_rate_ratio.1+ )?+ }write!(f,- " ({}/{})",- self.frame_rate_ratio.0, self.frame_rate_ratio.1- )?+ " {}",+ media_subtype_str(&self.subtype).unwrap_or("unknown format")+ )}- write!(- f,- " {}",- media_subtype_str(&self.subtype).unwrap_or("unknown format")- )}-}-fn media_subtype_str(subtype: &GUID) -> Option<&'static str> {- Some(match *subtype {- t if t == MFVideoFormat_I420 => "i420",- t if t == MFVideoFormat_IYUV => "iyuv",- t if t == MFVideoFormat_RGB24 => "rgb24",- t if t == MFVideoFormat_RGB32 => "rgb32",- t if t == MFVideoFormat_YUY2 => "yuy2",- t if t == MFVideoFormat_MJPG => "mjpg",- t if t == MFVideoFormat_UYVY => "uyvy",- t if t == MFVideoFormat_ARGB32 => "argb32",- t if t == MFVideoFormat_NV12 => "nv12",- t if t == MFVideoFormat_H264 => "h264",- _ => return None,- })+ fn media_subtype_str(subtype: &GUID) -> Option<&'static str> {+ Some(match *subtype {+ t if t == MFVideoFormat_I420 => "i420",+ t if t == MFVideoFormat_IYUV => "iyuv",+ t if t == MFVideoFormat_RGB24 => "rgb24",+ t if t == MFVideoFormat_RGB32 => "rgb32",+ t if t == MFVideoFormat_YUY2 => "yuy2",+ t if t == MFVideoFormat_MJPG => "mjpg",+ t if t == MFVideoFormat_UYVY => "uyvy",+ t if t == MFVideoFormat_ARGB32 => "argb32",+ t if t == MFVideoFormat_NV12 => "nv12",+ t if t == MFVideoFormat_H264 => "h264",+ _ => return None,+ })+ }}diff --git a/crates/camera-mediafoundation/src/lib.rs b/crates/camera-mediafoundation/src/lib.rsindex a5f40692e..349df5061 100644--- a/crates/camera-mediafoundation/src/lib.rs+++ b/crates/camera-mediafoundation/src/lib.rs@@ -7,9 +7,12 @@ use std::{mem::MaybeUninit,ops::{Deref, DerefMut},os::windows::ffi::OsStringExt,- ptr::{null, null_mut},+ ptr::null_mut,slice::from_raw_parts,- sync::{Mutex, mpsc::*},+ sync::{+ Mutex,+ mpsc::{Receiver, Sender, channel},+ },time::{Duration, Instant},};@@ -19,7 +22,7 @@ use windows::Win32::{Media::MediaFoundation::*,System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance, CoInitialize},};-use windows_core::{ComObjectInner, GUID, Interface, PWSTR, implement};+use windows_core::{ComObjectInner, Interface, PWSTR, implement};pub fn initialize_mediafoundation() -> windows_core::Result<()> {unsafe { CoInitialize(None) }.ok()?;@@ -64,6 +67,10 @@ impl DeviceSourcesIterator {pub fn len(&self) -> u32 {self.count}++ pub fn is_empty(&self) -> bool {+ self.count == 0+ }}impl Iterator for DeviceSourcesIterator {@@ -152,7 +159,7 @@ impl Device {pub fn model_id(&self) -> Option<String> {self.id().ok()- .and_then(|v| get_device_model_id(&*v.to_string_lossy()))+ .and_then(|v| get_device_model_id(&v.to_string_lossy()))}// Returns an iterator of IMFMediaTypes available for this device.@@ -263,13 +270,15 @@ impl Device {loop {let mut media_type = None;- if let Err(_) = retry_on_invalid_request(|| {+ if retry_on_invalid_request(|| {source.GetAvailableDeviceMediaType(stream_index,media_type_index,Some(&mut media_type),)- }) {+ })+ .is_err()+ {break;}@@ -388,7 +397,7 @@ impl Display for Device {"{}",self.name().map(|v| v.to_string_lossy().to_string())- .unwrap_or_else(|_| format!("Unknown device name"))+ .unwrap_or_else(|_| "Unknown device name".to_string()))}}@@ -402,7 +411,7 @@ impl SourceReader {pub fn native_media_types(&self,stream_index: u32,- ) -> windows_core::Result<NativeMediaTypesIterator> {+ ) -> windows_core::Result<NativeMediaTypesIterator<'_>> {NativeMediaTypesIterator::new(&self.inner, stream_index)}@@ -494,13 +503,8 @@ impl Iterator for NativeMediaTypesIterator<'_> {type Item = IMFMediaType;fn next(&mut self) -> Option<Self::Item> {- let Some(ret) = unsafe { self.reader.GetNativeMediaType(self.stream_index, self.i) }.ok()- else {- return None;- };-+ let ret = unsafe { self.reader.GetNativeMediaType(self.stream_index, self.i) }.ok()?;self.i += 1;-Some(ret)}}@@ -520,7 +524,7 @@ impl DerefMut for SourceReader {}fn get_device_model_id(device_id: &str) -> Option<String> {- const VID_PID_SIZE: usize = 4;+ // const VID_PID_SIZE: usize = 4;let vid_location = device_id.find("vid_")?;let pid_location = device_id.find("pid_")?;@@ -538,11 +542,11 @@ fn get_device_model_id(device_id: &str) -> Option<String> {}pub trait IMFMediaBufferExt {- fn lock(&self) -> windows_core::Result<IMFMediaBufferLock>;+ fn lock(&self) -> windows_core::Result<IMFMediaBufferLock<'_>>;}impl IMFMediaBufferExt for IMFMediaBuffer {- fn lock(&self) -> windows_core::Result<IMFMediaBufferLock> {+ fn lock(&self) -> windows_core::Result<IMFMediaBufferLock<'_>> {let mut bytes_ptr = null_mut();let mut size = 0;@@ -552,7 +556,7 @@ impl IMFMediaBufferExt for IMFMediaBuffer {Ok(IMFMediaBufferLock {source: self,- bytes: unsafe { std::slice::from_raw_parts_mut(bytes_ptr as *mut u8, size as usize) },+ bytes: unsafe { std::slice::from_raw_parts_mut(bytes_ptr, size as usize) },})}}@@ -572,13 +576,13 @@ impl<'a> Deref for IMFMediaBufferLock<'a> {type Target = [u8];fn deref(&self) -> &Self::Target {- &self.bytes+ self.bytes}}impl<'a> DerefMut for IMFMediaBufferLock<'a> {fn deref_mut(&mut self) -> &mut Self::Target {- &mut self.bytes+ self.bytes}}@@ -611,7 +615,7 @@ impl IMFCaptureEngineOnSampleCallback_Impl for VideoCallback_Impl {let raw_time_stamp = unsafe { sample.GetSampleTime() }.unwrap_or(0);let timestamp = Duration::from_micros((raw_time_stamp / 10) as u64);- let mut raw_capture_begin_time =+ let raw_capture_begin_time =unsafe { sample.GetUINT64(&MFSampleExtension_DeviceReferenceSystemTime) }.or_else(// retry, it's what chromium does /shrugdiff --git a/crates/camera-windows/examples/cli.rs b/crates/camera-windows/examples/cli.rsindex 801dc3f12..7c4c598a4 100644--- a/crates/camera-windows/examples/cli.rs+++ b/crates/camera-windows/examples/cli.rs@@ -1,57 +1,67 @@-use std::{ops::Deref, time::Duration};--use cap_camera_windows::*;-fn main() {- let devices = get_devices()- .unwrap()- .into_iter()- .map(DeviceSelection)- .collect::<Vec<_>>();-- let selected_device = inquire::Select::new("Select a device", devices)- .prompt()- .unwrap();-- let format = inquire::Select::new("Select a format", selected_device.formats().clone())- .prompt()- .unwrap();-- let _handle = selected_device- .0- .start_capturing(&format.inner, |frame| {- let Ok(bytes) = frame.bytes() else {- return;- };- dbg!(bytes.len(), frame.pixel_format);- })- .unwrap();-- std::thread::sleep(Duration::from_secs(10));+ #[cfg(windows)]+ windows::run();+ #[cfg(not(windows))]+ panic!("This example is only available on Windows");}-pub struct DeviceSelection(pub VideoDeviceInfo);+#[cfg(windows)]+mod windows {+ use std::{ops::Deref, time::Duration};++ use cap_camera_windows::*;++ fn run() {+ let devices = get_devices()+ .unwrap()+ .into_iter()+ .map(DeviceSelection)+ .collect::<Vec<_>>();-impl Deref for DeviceSelection {- type Target = VideoDeviceInfo;+ let selected_device = inquire::Select::new("Select a device", devices)+ .prompt()+ .unwrap();- fn deref(&self) -> &Self::Target {- &self.0+ let format = inquire::Select::new("Select a format", selected_device.formats().clone())+ .prompt()+ .unwrap();++ let _handle = selected_device+ .0+ .start_capturing(&format.inner, |frame| {+ let Ok(bytes) = frame.bytes() else {+ return;+ };+ dbg!(bytes.len(), frame.pixel_format);+ })+ .unwrap();++ std::thread::sleep(Duration::from_secs(10));}-}-impl std::fmt::Display for DeviceSelection {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- write!(- f,- "{:?} ({})",- self.0.name(),- &match self.0.is_mf() {- true => "Media Foundation",- false => "DirectShow",- },- )+ pub struct DeviceSelection(pub VideoDeviceInfo);++ impl Deref for DeviceSelection {+ type Target = VideoDeviceInfo;++ fn deref(&self) -> &Self::Target {+ &self.0+ }}-}-pub struct FormatSelection(VideoFormat);+ impl std::fmt::Display for DeviceSelection {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(+ f,+ "{:?} ({})",+ self.0.name(),+ &match self.0.is_mf() {+ true => "Media Foundation",+ false => "DirectShow",+ },+ )+ }+ }++ pub struct FormatSelection(VideoFormat);+}diff --git a/crates/camera-windows/src/lib.rs b/crates/camera-windows/src/lib.rsindex 73a683224..773555ac9 100644--- a/crates/camera-windows/src/lib.rs+++ b/crates/camera-windows/src/lib.rs@@ -55,7 +55,7 @@ impl VideoDeviceInfo {}pub fn model_id(&self) -> Option<&str> {- self.model_id.as_ref().map(|s| s.as_str())+ self.model_id.as_deref()}pub fn is_mf(&self) -> bool {@@ -83,7 +83,7 @@ impl VideoDeviceInfo {let format = VideoFormat::new_mf(mf_format.clone())?;let handle = device.start_capturing(- &mf_format,+ mf_format,Box::new(move |data| {let sample = &data.sample;let len = unsafe { sample.GetBufferCount() }.unwrap();@@ -118,7 +118,7 @@ impl VideoDeviceInfo {&*(media_type.pbFormat as *const _ as *const KS_VIDEOINFOHEADER)};- let Some(format) = DSPixelFormat::new(&media_type).map(|v| v.format) else {+ let Some(format) = DSPixelFormat::new(media_type).map(|v| v.format) else {return;};@@ -325,7 +325,7 @@ pub fn get_devices() -> Result<Vec<VideoDeviceInfo>, GetDevicesError> {match mf_device {Some((i, mf_device)) => {- if mf_device.formats().len() == 0 {+ if mf_device.formats().is_empty() {devices.push(mf_device.clone());devices.swap_remove(i);}@@ -372,7 +372,7 @@ pub enum VideoFormatInner {impl Debug for VideoFormatInner {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.write_str(&match self {+ f.write_str(match self {VideoFormatInner::MediaFoundation(_) => "MediaFoundation",VideoFormatInner::DirectShow(_) => "DirectShow",})@@ -449,6 +449,7 @@ impl Display for VideoFormat {struct MFPixelFormat {format: PixelFormat,+ #[allow(unused)]mf: GUID,}@@ -484,6 +485,7 @@ impl Deref for MFPixelFormat {struct DSPixelFormat {format: PixelFormat,+ #[allow(unused)]ds: GUID,}diff --git a/crates/camera/examples/cli.rs b/crates/camera/examples/cli.rsindex 02622afea..8e7bc1385 100644--- a/crates/camera/examples/cli.rs+++ b/crates/camera/examples/cli.rs@@ -3,12 +3,9 @@ use std::{fmt::Display, ops::Deref, time::Duration};use cap_camera::{CameraInfo, Format};fn main() {- let cameras: Vec<_> = cap_camera::list_cameras()- .into_iter()- .map(CameraSelectOption)- .collect();+ let cameras: Vec<_> = cap_camera::list_cameras().map(CameraSelectOption).collect();- if cameras.len() < 1 {+ if cameras.is_empty() {eprintln!("No cameras found");return;}@@ -30,7 +27,7 @@ fn main() {let _handle = selected_camera.start_capturing(selected_format.0, |frame| {- dbg!(frame);+ drop(frame);}).unwrap();@@ -44,7 +41,7 @@ impl Display for CameraSelectOption {write!(f, "{}", self.0.display_name())?;if let Some(model_id) = self.0.model_id() {- write!(f, " (Model ID: {})", model_id)?;+ write!(f, " (Model ID: {model_id})")?;}Ok(())diff --git a/crates/camera/src/lib.rs b/crates/camera/src/lib.rsindex 3a33dc2bc..a15803521 100644--- a/crates/camera/src/lib.rs+++ b/crates/camera/src/lib.rs@@ -98,7 +98,6 @@ impl Debug for Format {}#[cfg(windows)]{- use crate::windows::NativeFormat;use cap_camera_windows::VideoFormatInner;match &self.native {@@ -122,6 +121,7 @@ pub struct ModelID {#[cfg_attr(feature = "specta", derive(specta::Type))]#[cfg_attr(feature = "specta", specta(remote = ModelID))]+#[allow(dead_code)] // It's never constructed but it's a remote implstruct ModelIDType(String);#[cfg(feature = "serde")]@@ -231,7 +231,7 @@ pub struct RecordingHandle {}impl RecordingHandle {- pub fn stop_capturing(self) {- let _ = self.native.stop_capturing();+ pub fn stop_capturing(self) -> Result<(), String> {+ self.native.stop_capturing()}}diff --git a/crates/camera/src/macos.rs b/crates/camera/src/macos.rsindex f78e95cfe..389c3b02f 100644--- a/crates/camera/src/macos.rs+++ b/crates/camera/src/macos.rs@@ -8,12 +8,10 @@ pub(super) fn list_cameras_impl() -> impl Iterator<Item = CameraInfo> {let devices = cap_camera_avfoundation::list_video_devices();devices.iter()- .filter_map(|d| {- Some(CameraInfo {- device_id: d.unique_id().to_string(),- model_id: ModelID::from_avfoundation(d),- display_name: d.localized_name().to_string(),- })+ .map(|d| CameraInfo {+ device_id: d.unique_id().to_string(),+ model_id: ModelID::from_avfoundation(d),+ display_name: d.localized_name().to_string(),}).collect::<Vec<_>>().into_iter()@@ -79,7 +77,7 @@ fn find_device(info: &CameraInfo) -> Option<arc::R<av::CaptureDevice>> {.find(|d| match (ModelID::from_avfoundation(d).as_ref(), info.model_id()) {(Some(a), Some(b)) => a == b,- (None, None) => &d.unique_id().to_string() == info.device_id(),+ (None, None) => d.unique_id().to_string() == info.device_id(),_ => false,},)@@ -134,7 +132,7 @@ pub(super) fn start_capturing_impl({let mut _lock = device.config_lock().map_err(AVFoundationError::Retained)?;- _lock.set_active_format(&format.native());+ _lock.set_active_format(format.native());session.start_running();}@@ -157,8 +155,9 @@ pub struct AVFoundationRecordingHandle {}impl AVFoundationRecordingHandle {- pub fn stop_capturing(mut self) {+ pub fn stop_capturing(mut self) -> Result<(), String> {self.session.stop_running();+ Ok(())}}@@ -196,8 +195,8 @@ impl Deref for AVFoundationError {impl Debug for AVFoundationError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {match self {- AVFoundationError::Static(err) => write!(f, "{}", err),- AVFoundationError::Retained(err) => write!(f, "{}", err),+ AVFoundationError::Static(err) => write!(f, "{err}"),+ AVFoundationError::Retained(err) => write!(f, "{err}"),}}}diff --git a/crates/camera/src/windows.rs b/crates/camera/src/windows.rsindex 725c460df..4c2a6bdf8 100644--- a/crates/camera/src/windows.rs+++ b/crates/camera/src/windows.rs@@ -3,12 +3,10 @@ use crate::*;pub(super) fn list_cameras_impl() -> impl Iterator<Item = CameraInfo> {let devices = cap_camera_windows::get_devices().unwrap_or_default();- devices.into_iter().filter_map(|d| {- Some(CameraInfo {- device_id: d.id().to_string_lossy().to_string(),- model_id: ModelID::from_windows(&d),- display_name: d.name().to_string_lossy().to_string(),- })+ devices.into_iter().map(|d| CameraInfo {+ device_id: d.id().to_string_lossy().to_string(),+ model_id: ModelID::from_windows(&d),+ display_name: d.name().to_string_lossy().to_string(),})}@@ -60,8 +58,6 @@ impl ModelID {}}-pub type NativeFormat = cap_camera_windows::VideoFormat;-#[derive(Debug)]pub struct NativeCapturedFrame(cap_camera_windows::Frame);@@ -91,8 +87,8 @@ pub struct WindowsCaptureHandle {}impl WindowsCaptureHandle {- pub fn stop_capturing(self) -> windows_core::Result<()> {- self.inner.stop_capturing()+ pub fn stop_capturing(self) -> Result<(), String> {+ self.inner.stop_capturing().map_err(|e| e.to_string())}}diff --git a/crates/cursor-capture/src/position.rs b/crates/cursor-capture/src/position.rsindex 26cab0807..7b071fe38 100644--- a/crates/cursor-capture/src/position.rs+++ b/crates/cursor-capture/src/position.rs@@ -38,15 +38,16 @@ impl RelativeCursorPosition {let raw_display = display.raw_handle().inner();let display_bounds = raw_display.bounds();- return Self {+ Self {x: raw.x - display_bounds.origin.x as i32,y: raw.y - display_bounds.origin.y as i32,display,- };+ }}#[cfg(windows)]{+ let _ = (raw, display);todo!()}}@@ -75,6 +76,7 @@ impl RelativeCursorPosition {};#[cfg(windows)]+ #[allow(unused_variables)]let (x, y) = {todo!();// let display_bounds = self.display().raw_handle().bounds();@@ -85,6 +87,7 @@ impl RelativeCursorPosition {// )};+ #[allow(unreachable_code)]NormalizedCursorPosition {x,y,@@ -165,7 +168,7 @@ mod tests {// Helper function to create a mock Display for testingfn mock_display() -> Display {- Display::list()[0].clone()+ Display::list()[0]}#[test]diff --git a/crates/cursor-info/examples/cli.rs b/crates/cursor-info/examples/cli.rsindex 2d9b3f744..7bb589fab 100644--- a/crates/cursor-info/examples/cli.rs+++ b/crates/cursor-info/examples/cli.rs@@ -1,12 +1,12 @@use std::collections::HashMap;-use cap_cursor_info::{CursorShape, CursorShapeMacOS, CursorShapeWindows};+use cap_cursor_info::{CursorShape, CursorShapeMacOS};use sha2::{Digest, Sha256};+#[allow(unreachable_code)]fn main() {#[cfg(any(target_os = "macos", target_os = "windows"))]return run();- #[allow(unreachable_code)]panic!("Unsupported platform!");}@@ -45,13 +45,13 @@ fn run() {for (name, cursor) in cursors {let hash = hex::encode(Sha256::digest(- &cursor+ cursor.image().TIFFRepresentation().expect("Failed to get TIFF representation of built-in cursor").as_bytes_unchecked(),));- println!("{name}: {}", hash);+ println!("{name}: {hash}");cursor_lookup.insert(hash, name);}@@ -61,7 +61,7 @@ fn run() {#[allow(deprecated)]let cursor = NSCursor::currentSystemCursor().unwrap_or(NSCursor::currentCursor());let hash = hex::encode(Sha256::digest(- &cursor+ cursor.image().TIFFRepresentation().expect("Failed to get TIFF representation of built-in cursor")@@ -71,9 +71,9 @@ fn run() {// Try to resolve to CursorShapeif let Some(cursor_shape_macos) = CursorShapeMacOS::from_hash(&hash) {let cursor_shape = CursorShape::MacOS(cursor_shape_macos);- println!("CursorShape: {} | Hash: {}", cursor_shape, hash);+ println!("CursorShape: {cursor_shape} | Hash: {hash}");} else {- println!("Unknown cursor | Hash: {}", hash);+ println!("Unknown cursor | Hash: {hash}");}std::thread::sleep(std::time::Duration::from_millis(100));diff --git a/crates/cursor-info/src/windows.rs b/crates/cursor-info/src/windows.rsindex 66fa9a07e..d2f2f4665 100644--- a/crates/cursor-info/src/windows.rs+++ b/crates/cursor-info/src/windows.rs@@ -154,7 +154,7 @@ impl CursorShapeWindows {}#[cfg(target_os = "windows")]-mod windows {+mod windows_only {use super::*;use ::windows::{Win32::UI::WindowsAndMessaging::{diff --git a/crates/displays/src/platform/win.rs b/crates/displays/src/platform/win.rsindex ee75c8e02..db78e9959 100644--- a/crates/displays/src/platform/win.rs+++ b/crates/displays/src/platform/win.rs@@ -1,13 +1,9 @@use windows::{Win32::{- Foundation::{CloseHandle, FALSE, HWND, LPARAM, RECT, TRUE},- Graphics::Gdi::{- DEVMODEW, DISPLAY_DEVICEW, EnumDisplayDevicesW, EnumDisplayMonitors,- EnumDisplaySettingsW, GetMonitorInfoW, HDC, HMONITOR, MONITOR_DEFAULTTONULL,- MONITORINFO, MONITORINFOEXW, MonitorFromWindow,- },+ Foundation::{FALSE, LPARAM, RECT},+ Graphics::Gdi::{EnumDisplayMonitors, GetMonitorInfoW, HDC, HMONITOR, MONITORINFOEXW},},- core::{BOOL, PCWSTR, PWSTR},+ core::BOOL,};#[derive(Clone, Copy)]@@ -21,11 +17,13 @@ impl DisplayImpl {_lprc_clip: *mut RECT,lparam: LPARAM,) -> BOOL {- let list = &mut *(lparam.0 as *mut Vec<DisplayImpl>);+ unsafe {+ let list = &mut *(lparam.0 as *mut Vec<DisplayImpl>);- list.push(DisplayImpl(hmonitor));+ list.push(DisplayImpl(hmonitor));- FALSE+ FALSE+ }}let mut list = vec![];@@ -48,7 +46,7 @@ impl DisplayImpl {unsafe {GetMonitorInfoW(self.0, &mut minfo as *mut MONITORINFOEXW as *mut _).as_bool()- .then(|| minfo.monitorInfo.rcMonitor)+ .then_some(minfo.monitorInfo.rcMonitor)}}diff --git a/crates/editor/Cargo.toml b/crates/editor/Cargo.tomlindex bf6b19c7c..a0ad0329c 100644--- a/crates/editor/Cargo.toml+++ b/crates/editor/Cargo.toml@@ -1,7 +1,7 @@[package]name = "cap-editor"version = "0.1.0"-edition = "2021"+edition = "2024"[lints]workspace = truediff --git a/crates/editor/examples/cli.rs b/crates/editor/examples/cli.rsindex 582b64bbe..148804681 100644--- a/crates/editor/examples/cli.rs+++ b/crates/editor/examples/cli.rs@@ -1,12 +1,12 @@use cap_editor::EditorInstance;-use cap_project::{CursorEvents, ProjectConfiguration, RecordingMeta, RecordingMetaInner, XY};+use cap_project::XY;use std::path::PathBuf;#[tokio::main]async fn main() {let path: PathBuf = std::env::args().collect::<Vec<_>>().swap_remove(1).into();- let editor = EditorInstance::new(path, |s| {}).await.unwrap();+ let editor = EditorInstance::new(path, |_s| {}).await.unwrap();editor.start_playback(30, XY::new(1920, 1080)).await;diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rsindex 43229f6d3..4b53f576b 100644--- a/crates/editor/src/editor.rs+++ b/crates/editor/src/editor.rs@@ -1,16 +1,17 @@use std::sync::Arc;use cap_media::frame_ws::WSFrame;-use cap_project::{CursorEvents, RecordingMeta, StudioRecordingMeta, XY};+use cap_project::{CursorEvents, RecordingMeta, StudioRecordingMeta};use cap_rendering::{- decoder::DecodedFrame, DecodedSegmentFrames, FrameRenderer, ProjectRecordingsMeta,- ProjectUniforms, RenderVideoConstants, RendererLayers,+ DecodedSegmentFrames, FrameRenderer, ProjectRecordingsMeta, ProjectUniforms,+ RenderVideoConstants, RendererLayers,};use tokio::{sync::{mpsc, oneshot},task::JoinHandle,};+#[allow(clippy::large_enum_variant)]pub enum RendererMessage {RenderFrame {segment_frames: DecodedSegmentFrames,@@ -27,6 +28,7 @@ pub struct Renderer {rx: mpsc::Receiver<RendererMessage>,frame_tx: flume::Sender<WSFrame>,render_constants: Arc<RenderVideoConstants>,+ #[allow(unused)]total_frames: u32,}@@ -48,12 +50,11 @@ impl Renderer {let mut max_duration = recordings.duration();// Check camera duration if it exists- if let Some(camera_path) = meta.camera_path() {- if let Ok(camera_duration) =+ if let Some(camera_path) = meta.camera_path()+ && let Ok(camera_duration) =recordings.get_source_duration(&recording_meta.path(&camera_path))- {- max_duration = max_duration.max(camera_duration);- }+ {+ max_duration = max_duration.max(camera_duration);}let total_frames = (30_f64 * max_duration).ceil() as u32;@@ -156,7 +157,12 @@ impl RendererHandle {pub async fn stop(&self) {// Send a stop message to the rendererlet (tx, rx) = oneshot::channel();- if let Err(_) = self.tx.send(RendererMessage::Stop { finished: tx }).await {+ if self+ .tx+ .send(RendererMessage::Stop { finished: tx })+ .await+ .is_err()+ {println!("Failed to send stop message to renderer");}// Wait for the renderer to acknowledge the stopdiff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rsindex 14eae6f0a..a80582d46 100644--- a/crates/editor/src/editor_instance.rs+++ b/crates/editor/src/editor_instance.rs@@ -3,16 +3,15 @@ use crate::playback::{self, PlaybackHandle};use cap_audio::AudioData;// use cap_media::feeds::AudioData;use cap_media::frame_ws::create_frame_ws;+use cap_project::StudioRecordingMeta;use cap_project::{CursorEvents, ProjectConfiguration, RecordingMeta, RecordingMetaInner, XY};-use cap_project::{RecordingConfig, StudioRecordingMeta};use cap_rendering::{- get_duration, ProjectRecordingsMeta, ProjectUniforms, RecordingSegmentDecoders, RenderOptions,- RenderVideoConstants, SegmentVideoPaths,+ ProjectRecordingsMeta, ProjectUniforms, RecordingSegmentDecoders, RenderVideoConstants,+ SegmentVideoPaths, get_duration,};use std::ops::Deref;-use std::sync::Mutex as StdMutex;use std::{path::PathBuf, sync::Arc};-use tokio::sync::{mpsc, watch, Mutex};+use tokio::sync::{Mutex, watch};use tokio_util::sync::CancellationToken;use tracing::trace;@@ -249,7 +248,7 @@ impl EditorInstance {fn get_studio_meta(&self) -> &StudioRecordingMeta {match &self.meta.inner {- RecordingMetaInner::Studio(meta) => &meta,+ RecordingMetaInner::Studio(meta) => meta,_ => panic!("Not a studio recording"),}}@@ -310,7 +309,7 @@ pub async fn create_segments(.map(Arc::new);let decoders = RecordingSegmentDecoders::new(- &recording_meta,+ recording_meta,meta,SegmentVideoPaths {display: recording_meta.path(&s.display.path),@@ -352,10 +351,10 @@ pub async fn create_segments(.transpose()?.map(Arc::new);- let cursor = Arc::new(s.cursor_events(&recording_meta));+ let cursor = Arc::new(s.cursor_events(recording_meta));let decoders = RecordingSegmentDecoders::new(- &recording_meta,+ recording_meta,meta,SegmentVideoPaths {display: recording_meta.path(&s.display.path),diff --git a/crates/editor/src/lib.rs b/crates/editor/src/lib.rsindex f57c92b6b..2b9befe8a 100644--- a/crates/editor/src/lib.rs+++ b/crates/editor/src/lib.rs@@ -3,5 +3,5 @@ mod editor_instance;mod playback;mod segments;-pub use editor_instance::{create_segments, EditorInstance, EditorState, Segment};+pub use editor_instance::{EditorInstance, EditorState, Segment, create_segments};pub use segments::get_audio_segments;diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rsindex bd9b8a3d8..1eb526552 100644--- a/crates/editor/src/playback.rs+++ b/crates/editor/src/playback.rs@@ -1,14 +1,14 @@use std::{sync::Arc, time::Duration};+use cap_media::MediaError;use cap_media::data::FromSampleBytes;use cap_media::feeds::{AudioPlaybackBuffer, AudioSegment};-use cap_media::MediaError;use cap_media_info::AudioInfo;use cap_project::{ProjectConfiguration, XY};use cap_rendering::{ProjectUniforms, RenderVideoConstants};use cpal::{- traits::{DeviceTrait, HostTrait, StreamTrait},BufferSize, SampleFormat,+ traits::{DeviceTrait, HostTrait, StreamTrait},};use tokio::{sync::watch, time::Instant};use tracing::{error, info};@@ -260,12 +260,12 @@ impl AudioPlayback {elapsed += buffer.len() / output_info.channels;},- |_err| eprintln!("Audio stream error: {}", _err),+ |_err| eprintln!("Audio stream error: {_err}"),None,);let stream = stream_result.map_err(|e| {- MediaError::TaskLaunch(format!("Failed to build audio output stream: {}", e))+ MediaError::TaskLaunch(format!("Failed to build audio output stream: {e}"))})?;Ok((stop_rx, stream))diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.tomlindex 7f28b26e2..1f5540de1 100644--- a/crates/export/Cargo.toml+++ b/crates/export/Cargo.toml@@ -1,7 +1,7 @@[package]name = "cap-export"version = "0.1.0"-edition = "2021"+edition = "2024"[dependencies]cap-utils = { path = "../utils" }@@ -29,3 +29,6 @@ tracing.workspace = trueclap = { version = "4.5.41", features = ["derive"] }inquire = "0.7.5"tokio.workspace = true++[lints]+workspace = truediff --git a/crates/export/examples/export-cli.rs b/crates/export/examples/export-cli.rsindex 44fa7f46b..f890a87d7 100644--- a/crates/export/examples/export-cli.rs+++ b/crates/export/examples/export-cli.rs@@ -1,6 +1,6 @@use std::{fmt::Display, path::PathBuf};-use cap_export::{gif::GifExportSettings, mp4::Mp4ExportSettings, ExporterBase, ExporterBuilder};+use cap_export::{ExporterBase, gif::GifExportSettings, mp4::Mp4ExportSettings};use clap::{Parser, ValueEnum};#[derive(Parser, Debug)]@@ -12,6 +12,7 @@ struct Cli {}#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, ValueEnum, Debug)]+#[allow(clippy::upper_case_acronyms)]enum ExportFormat {MP4,GIF,@@ -53,7 +54,7 @@ async fn main() {let total_frames = base.total_frames(settings.fps);settings.export(base, move |progress| {- print!("Exporting frame {} of {}\r", progress, total_frames);+ print!("Exporting frame {progress} of {total_frames}\r");}).await.unwrap();@@ -63,7 +64,7 @@ async fn main() {let total_frames = base.total_frames(settings.fps);settings.export(base, move |progress| {- print!("Exporting frame {} of {}\r", progress, total_frames);+ print!("Exporting frame {progress} of {total_frames}\r");}).await.unwrap();diff --git a/crates/export/src/gif.rs b/crates/export/src/gif.rsindex 3e69188f2..bd4f3a066 100644--- a/crates/export/src/gif.rs+++ b/crates/export/src/gif.rs@@ -48,7 +48,7 @@ impl GifExportSettings {);let mut gif_encoder =GifEncoderWrapper::new(&gif_output_path, output_size.0, output_size.1, fps)- .map_err(|e| format!("Failed to create GIF encoder: {}", e))?;+ .map_err(|e| format!("Failed to create GIF encoder: {e}"))?;let encoder_thread = tokio::task::spawn_blocking(move || {let mut frame_count = 0;@@ -60,8 +60,7 @@ impl GifExportSettings {gif_encoder.add_frame(&frame.data, frame.padded_bytes_per_row as usize){return Err(ExportError::Other(format!(- "Failed to add frame to GIF: {}",- e+ "Failed to add frame to GIF: {e}")));}@@ -69,7 +68,7 @@ impl GifExportSettings {}if let Err(e) = gif_encoder.finish() {- return Err(ExportError::Other(format!("Failed to finish GIF: {}", e)));+ return Err(ExportError::Other(format!("Failed to finish GIF: {e}")));}Ok(gif_output_path)diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rsindex ccb4fe953..b94f5302e 100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@ -70,8 +70,8 @@ impl ExporterBuilder {).map_err(|v| Error::ConfigLoad(v.into()))?;- let recording_meta = RecordingMeta::load_for_project(&self.project_path)- .map_err(|v| Error::MetaLoad(v.into()))?;+ let recording_meta =+ RecordingMeta::load_for_project(&self.project_path).map_err(Error::MetaLoad)?;let studio_meta = recording_meta.studio_meta().ok_or(Error::NotStudioRecording)?;diff --git a/crates/export/src/mp4.rs b/crates/export/src/mp4.rsindex e34d2e042..cbd73400e 100644--- a/crates/export/src/mp4.rs+++ b/crates/export/src/mp4.rs@@ -69,7 +69,7 @@ impl Mp4ExportSettings {let audio_segments = get_audio_segments(&base.segments);let mut audio_renderer = audio_segments- .get(0)+ .first().filter(|_| !base.project_config.audio.mute).map(|_| AudioRenderer::new(audio_segments.clone()));let has_audio = audio_renderer.is_some();@@ -155,14 +155,17 @@ impl Mp4ExportSettings {frame});- if let Err(_) = frame_tx.send(MP4Input {- audio: audio_frame,- video: video_info.wrap_frame(- &frame.data,- frame_number as i64,- frame.padded_bytes_per_row as usize,- ),- }) {+ if frame_tx+ .send(MP4Input {+ audio: audio_frame,+ video: video_info.wrap_frame(+ &frame.data,+ frame_number as i64,+ frame.padded_bytes_per_row as usize,+ ),+ })+ .is_err()+ {warn!("Renderer task sender dropped. Exiting");return Ok(());}@@ -188,13 +191,13 @@ impl Mp4ExportSettings {let screenshots_dir = project_path.join("screenshots");std::fs::create_dir_all(&screenshots_dir).unwrap_or_else(|e| {- eprintln!("Failed to create screenshots directory: {:?}", e);+ eprintln!("Failed to create screenshots directory: {e:?}");});// Save full-size screenshotlet screenshot_path = screenshots_dir.join("display.jpg");rgb_img.save(&screenshot_path).unwrap_or_else(|e| {- eprintln!("Failed to save screenshot: {:?}", e);+ eprintln!("Failed to save screenshot: {e:?}");});} else {warn!("No frames were processed, cannot save screenshot or thumbnail");diff --git a/crates/fail/Cargo.toml b/crates/fail/Cargo.tomlindex cd994fb23..73214b96f 100644--- a/crates/fail/Cargo.toml+++ b/crates/fail/Cargo.toml@@ -1,7 +1,10 @@[package]name = "cap-fail"version = "0.1.0"-edition = "2021"+edition = "2024"[dependencies]inventory = "0.3.19"++[lints]+workspace = truediff --git a/crates/ffmpeg-hw-device/Cargo.toml b/crates/ffmpeg-hw-device/Cargo.tomlindex 0a5e2aa00..cbca7b7a6 100644--- a/crates/ffmpeg-hw-device/Cargo.toml+++ b/crates/ffmpeg-hw-device/Cargo.toml@@ -1,8 +1,11 @@[package]name = "ffmpeg-hw-device"version = "0.1.0"-edition = "2021"+edition = "2024"[dependencies]ffmpeg.workspace = trueffmpeg-sys-next.workspace = true++[lints]+workspace = truediff --git a/crates/ffmpeg-hw-device/src/lib.rs b/crates/ffmpeg-hw-device/src/lib.rsindex 8b7bc921e..c9f88ed2a 100644--- a/crates/ffmpeg-hw-device/src/lib.rs+++ b/crates/ffmpeg-hw-device/src/lib.rs@@ -5,13 +5,12 @@ use std::{use ffmpeg::{codec,- format::Pixel,frame::{self, Video},};use ffmpeg_sys_next::{- av_buffer_ref, av_buffer_unref, av_hwdevice_ctx_create, av_hwframe_transfer_data,- avcodec_get_hw_config, AVBufferRef, AVCodecContext, AVCodecHWConfig, AVHWDeviceType,- AVPixelFormat, AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX,+ AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX, AVBufferRef, AVCodecContext, AVCodecHWConfig,+ AVHWDeviceType, AVPixelFormat, av_buffer_ref, av_buffer_unref, av_hwdevice_ctx_create,+ av_hwframe_transfer_data, avcodec_get_hw_config,};thread_local! {@@ -22,21 +21,23 @@ unsafe extern "C" fn get_format(_: *mut AVCodecContext,pix_fmts: *const AVPixelFormat,) -> AVPixelFormat {- let mut fmt = pix_fmts;+ unsafe {+ let mut fmt = pix_fmts;- loop {- if *fmt == AVPixelFormat::AV_PIX_FMT_NONE {- break;- }+ loop {+ if *fmt == AVPixelFormat::AV_PIX_FMT_NONE {+ break;+ }- if *fmt == HW_PIX_FMT.get() {- return *fmt;+ if *fmt == HW_PIX_FMT.get() {+ return *fmt;+ }++ fmt = fmt.offset(1);}- fmt = fmt.offset(1);+ AVPixelFormat::AV_PIX_FMT_NONE}-- AVPixelFormat::AV_PIX_FMT_NONE}pub struct HwDevice {diff --git a/crates/flags/Cargo.toml b/crates/flags/Cargo.tomlindex 3e98a7937..10a4ae7ac 100644--- a/crates/flags/Cargo.toml+++ b/crates/flags/Cargo.toml@@ -1,8 +1,11 @@[package]name = "cap-flags"version = "0.1.0"-edition = "2021"+edition = "2024"[dependencies]serde = { workspace = true }specta.workspace = true++[lints]+workspace = truediff --git a/crates/gpu-converters/Cargo.toml b/crates/gpu-converters/Cargo.tomlindex 7496d8455..ead0b7fc8 100644--- a/crates/gpu-converters/Cargo.toml+++ b/crates/gpu-converters/Cargo.toml@@ -1,7 +1,10 @@[package]name = "cap-gpu-converters"version = "0.1.0"-edition = "2021"+edition = "2024"[dependencies]wgpu.workspace = true++[lints]+workspace = truediff --git a/crates/gpu-converters/src/nv12_rgba/mod.rs b/crates/gpu-converters/src/nv12_rgba/mod.rsindex f7c81c613..1ab46be9e 100644--- a/crates/gpu-converters/src/nv12_rgba/mod.rs+++ b/crates/gpu-converters/src/nv12_rgba/mod.rs@@ -98,7 +98,12 @@ impl NV12ToRGBA {}}- pub fn convert(&self, input: NV12Input, width: u32, height: u32) -> Vec<u8> {+ pub fn convert(+ &self,+ input: NV12Input,+ width: u32,+ height: u32,+ ) -> Result<Vec<u8>, wgpu::PollError> {// Create textures for Y and UV planeslet y_texture = self.device.create_texture_with_data(&self.queue,@@ -196,7 +201,7 @@ impl NV12ToRGBA {});compute_pass.set_pipeline(&self.pipeline);compute_pass.set_bind_group(0, &bind_group, &[]);- compute_pass.dispatch_workgroups((width + 7) / 8, (height + 7) / 8, 1);+ compute_pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);}// Create buffer for reading back the results@@ -239,10 +244,10 @@ impl NV12ToRGBA {buffer_slice.map_async(wgpu::MapMode::Read, move |result| {tx.send(result).unwrap();});- self.device.poll(wgpu::PollType::Wait);+ self.device.poll(wgpu::PollType::Wait)?;rx.recv().unwrap().unwrap();let data = buffer_slice.get_mapped_range();- data.to_vec()+ Ok(data.to_vec())}}diff --git a/crates/gpu-converters/src/util.rs b/crates/gpu-converters/src/util.rsindex 5e3d26f53..07602a34c 100644--- a/crates/gpu-converters/src/util.rs+++ b/crates/gpu-converters/src/util.rs@@ -1,14 +1,17 @@-pub fn read_buffer_to_vec(buffer: &wgpu::Buffer, device: &wgpu::Device) -> Vec<u8> {+pub fn read_buffer_to_vec(+ buffer: &wgpu::Buffer,+ device: &wgpu::Device,+) -> Result<Vec<u8>, wgpu::PollError> {let buffer_slice = buffer.slice(..);let (tx, rx) = std::sync::mpsc::channel();buffer_slice.map_async(wgpu::MapMode::Read, move |result| {tx.send(result).unwrap();});- device.poll(wgpu::PollType::Wait);+ device.poll(wgpu::PollType::Wait)?;rx.recv().unwrap().unwrap();let data = buffer_slice.get_mapped_range();- data.to_vec()+ Ok(data.to_vec())}pub fn copy_texture_to_buffer_command(diff --git a/crates/gpu-converters/src/uyvy_nv12/mod.rs b/crates/gpu-converters/src/uyvy_nv12/mod.rsindex a7f002778..c083ec479 100644--- a/crates/gpu-converters/src/uyvy_nv12/mod.rs+++ b/crates/gpu-converters/src/uyvy_nv12/mod.rs@@ -10,6 +10,7 @@ pub struct UYVYToNV12 {}impl UYVYToNV12 {+ #[allow(unreachable_code)]pub async fn new() -> Self {todo!("implement UV downsampling for UYVYToNV12");@@ -109,7 +110,12 @@ impl UYVYToNV12 {}}- pub fn convert(&self, uyvy_data: &[u8], width: u32, height: u32) -> (Vec<u8>, Vec<u8>) {+ pub fn convert(+ &self,+ uyvy_data: &[u8],+ width: u32,+ height: u32,+ ) -> Result<(Vec<u8>, Vec<u8>), wgpu::PollError> {let uyvy_texture =uyvy::create_input_texture(&self.device, &self.queue, uyvy_data, width, height);@@ -184,7 +190,7 @@ impl UYVYToNV12 {});compute_pass.set_pipeline(&self.pipeline);compute_pass.set_bind_group(0, &bind_group, &[]);- compute_pass.dispatch_workgroups((width + 3) / 4, (height + 7) / 8, 1);+ compute_pass.dispatch_workgroups(width.div_ceil(4), height.div_ceil(8), 1);}let y_read_buffer = self.device.create_buffer(&wgpu::BufferDescriptor {@@ -213,9 +219,9 @@ impl UYVYToNV12 {// Submit commandsself.queue.submit(std::iter::once(encoder.finish()));- (- read_buffer_to_vec(&y_read_buffer, &self.device),- read_buffer_to_vec(&uv_read_buffer, &self.device),- )+ Ok((+ read_buffer_to_vec(&y_read_buffer, &self.device)?,+ read_buffer_to_vec(&uv_read_buffer, &self.device)?,+ ))}}diff --git a/crates/gpu-converters/src/uyvy_rgba/mod.rs b/crates/gpu-converters/src/uyvy_rgba/mod.rsindex cbc3ac809..84fa3e861 100644--- a/crates/gpu-converters/src/uyvy_rgba/mod.rs+++ b/crates/gpu-converters/src/uyvy_rgba/mod.rs@@ -87,7 +87,12 @@ impl UYVYToRGBA {}}- pub fn convert(&self, uyvy_data: &[u8], width: u32, height: u32) -> Vec<u8> {+ pub fn convert(+ &self,+ uyvy_data: &[u8],+ width: u32,+ height: u32,+ ) -> Result<Vec<u8>, wgpu::PollError> {let uyvy_texture =uyvy::create_input_texture(&self.device, &self.queue, uyvy_data, width, height);@@ -141,7 +146,7 @@ impl UYVYToRGBA {});compute_pass.set_pipeline(&self.pipeline);compute_pass.set_bind_group(0, &bind_group, &[]);- compute_pass.dispatch_workgroups((width + 7) / 8, (height + 7) / 8, 1);+ compute_pass.dispatch_workgroups(width.div_ceil(8), height.div_ceil(8), 1);}let output_buffer =diff --git a/crates/media-encoders/src/aac.rs b/crates/media-encoders/src/aac.rsindex c8563985e..bd3e0ae6a 100644--- a/crates/media-encoders/src/aac.rs+++ b/crates/media-encoders/src/aac.rs@@ -20,6 +20,7 @@ pub enum AACEncoderError {}pub struct AACEncoder {+ #[allow(unused)]tag: &'static str,encoder: encoder::Audio,packet: ffmpeg::Packet,@@ -70,7 +71,7 @@ impl AACEncoder {rate};- let mut output_config = input_config.clone();+ let mut output_config = input_config;output_config.sample_format = Self::SAMPLE_FORMAT;output_config.sample_rate = rate as u32;@@ -136,7 +137,7 @@ impl AACEncoder {for i in 0..frame.planes() {self.buffer[i]- .extend(&frame.data(i)[0..frame_size_bytes(&frame) / frame.channels() as usize]);+ .extend(&frame.data(i)[0..frame_size_bytes(frame) / frame.channels() as usize]);}let channel_size_bytes = self.encoder.frame_size() as usize * self.encoder.format().bytes();@@ -218,7 +219,7 @@ impl AACEncoder {}}- while self.buffer[0].len() > 0 {+ while !self.buffer[0].is_empty() {let channel_size_bytes =(frame_size_bytes / self.encoder.channels() as usize).min(self.buffer[0].len());let frame_size = channel_size_bytes / self.encoder.format().bytes();diff --git a/crates/media-encoders/src/h264.rs b/crates/media-encoders/src/h264.rsindex 9981e1ee6..ae4e34364 100644--- a/crates/media-encoders/src/h264.rs+++ b/crates/media-encoders/src/h264.rs@@ -59,7 +59,7 @@ impl H264EncoderBuilder {output: &mut format::context::Output,) -> Result<H264Encoder, H264EncoderError> {let input_config = &self.input_config;- let (codec, encoder_options) = get_codec_and_options(&input_config, self.preset)+ let (codec, encoder_options) = get_codec_and_options(input_config, self.preset).ok_or(H264EncoderError::CodecNotFound)?;let (format, converter) = if !codec@@ -137,6 +137,7 @@ impl H264EncoderBuilder {}pub struct H264Encoder {+ #[allow(unused)]tag: &'static str,encoder: encoder::Video,config: VideoInfo,@@ -203,15 +204,20 @@ impl H264Encoder {}}-fn get_codec_and_options(config: &VideoInfo, preset: H264Preset) -> Option<(Codec, Dictionary)> {+fn get_codec_and_options(+ config: &VideoInfo,+ preset: H264Preset,+) -> Option<(Codec, Dictionary<'_>)> {let encoder_name = {- if cfg!(target_os = "macos") {- "libx264"- // looks terrible rn :(- // "h264_videotoolbox"- } else {- "libx264"- }+ // if cfg!(target_os = "macos") {+ // "libx264"+ // // looks terrible rn :(+ // // "h264_videotoolbox"+ // } else {+ // "libx264"+ // }++ "libx264"};if let Some(codec) = encoder::find_by_name(encoder_name) {diff --git a/crates/media-encoders/src/lib.rs b/crates/media-encoders/src/lib.rsindex c4ff41a94..46107522d 100644--- a/crates/media-encoders/src/lib.rs+++ b/crates/media-encoders/src/lib.rs@@ -11,6 +11,7 @@ mod h264;pub use h264::*;mod mp4;+#[allow(ambiguous_glob_reexports)]pub use mp4::*;mod opus;diff --git a/crates/media-encoders/src/mp4.rs b/crates/media-encoders/src/mp4.rsindex 73e1bcb1e..c2c94ff98 100644--- a/crates/media-encoders/src/mp4.rs+++ b/crates/media-encoders/src/mp4.rs@@ -11,6 +11,7 @@ use crate::H264EncoderError;use super::{AudioEncoder, H264Encoder};pub struct MP4File {+ #[allow(unused)]tag: &'static str,output: format::context::Output,video: H264Encoder,diff --git a/crates/media-encoders/src/mp4_avassetwriter.rs b/crates/media-encoders/src/mp4_avassetwriter.rsindex 5f6ffd525..ecf25c676 100644--- a/crates/media-encoders/src/mp4_avassetwriter.rs+++ b/crates/media-encoders/src/mp4_avassetwriter.rs@@ -6,8 +6,11 @@ use std::path::PathBuf;use tracing::{debug, info};pub struct MP4AVAssetWriterEncoder {+ #[allow(unused)]tag: &'static str,+ #[allow(unused)]last_pts: Option<i64>,+ #[allow(unused)]config: VideoInfo,asset_writer: Retained<av::AssetWriter>,video_input: Retained<av::AssetWriterInput>,@@ -220,7 +223,7 @@ impl MP4AVAssetWriterEncoder {self.video_input.append_sample_buf(&frame).map_err(QueueVideoFrameError::AppendError)- .and_then(|v| v.then(|| ()).ok_or_else(|| QueueVideoFrameError::Failed))?;+ .and_then(|v| v.then_some(()).ok_or(QueueVideoFrameError::Failed))?;self.first_timestamp.get_or_insert(time);self.segment_first_timestamp.get_or_insert(time);@@ -298,7 +301,7 @@ impl MP4AVAssetWriterEncoder {audio_input.append_sample_buf(&buffer).map_err(QueueAudioFrameError::AppendError)- .and_then(|v| v.then(|| ()).ok_or_else(|| QueueAudioFrameError::Failed))?;+ .and_then(|v| v.then_some(()).ok_or(QueueAudioFrameError::Failed))?;self.audio_frames_appended += 1;@@ -339,7 +342,9 @@ impl MP4AVAssetWriterEncoder {self.asset_writer.end_session_at_src_time(self.last_timestamp.unwrap_or(cm::Time::zero()));self.video_input.mark_as_finished();- self.audio_input.as_mut().map(|i| i.mark_as_finished());+ if let Some(i) = self.audio_input.as_mut() {+ i.mark_as_finished()+ }self.asset_writer.finish_writing();diff --git a/crates/media-encoders/src/opus.rs b/crates/media-encoders/src/opus.rsindex 21553e4b4..05a12bb79 100644--- a/crates/media-encoders/src/opus.rs+++ b/crates/media-encoders/src/opus.rs@@ -41,6 +41,7 @@ impl OggFile {}pub struct OpusEncoder {+ #[allow(unused)]tag: &'static str,encoder: encoder::Audio,packet: ffmpeg::Packet,@@ -101,7 +102,7 @@ impl OpusEncoder {rate};- let mut output_config = input_config.clone();+ let mut output_config = input_config;output_config.sample_format = Self::SAMPLE_FORMAT;output_config.sample_rate = rate as u32;@@ -259,7 +260,7 @@ impl OpusEncoder {}}- while self.buffer.len() > 0 {+ while !self.buffer.is_empty() {let frame_size_bytes = frame_size_bytes.min(self.buffer.len());let frame_size = frame_size_bytes/ self.encoder.channels() as usizediff --git a/crates/media-info/src/lib.rs b/crates/media-info/src/lib.rsindex 1e988fd6b..3c48a39de 100644--- a/crates/media-info/src/lib.rs+++ b/crates/media-info/src/lib.rs@@ -113,25 +113,25 @@ impl AudioInfo {frame.set_pts(Some(timestamp));frame.set_rate(self.sample_rate);- match self.channels {- 0 => unreachable!(),- 1 | _ if frame.is_packed() => frame.data_mut(0)[0..data.len()].copy_from_slice(data),+ if self.channels == 0 {+ unreachable!()+ } else if self.channels == 1 || frame.is_packed() {+ frame.data_mut(0)[0..data.len()].copy_from_slice(data)+ } else {// cpal *always* returns interleaved data (i.e. the first sample from every channel, followed// by the second sample from every channel, et cetera). Many audio codecs work better/primarily// with planar data, so we de-interleave it here if there is more than one channel.- channel_count => {- for (chunk_index, interleaved_chunk) in- data.chunks(interleaved_chunk_size).enumerate()- {- let start = chunk_index * sample_size;- let end = start + sample_size;-- for channel in 0..channel_count {- let channel_start = channel * sample_size;- let channel_end = channel_start + sample_size;- frame.plane_data_mut(channel)[start..end]- .copy_from_slice(&interleaved_chunk[channel_start..channel_end]);- }++ for (chunk_index, interleaved_chunk) in data.chunks(interleaved_chunk_size).enumerate()+ {+ let start = chunk_index * sample_size;+ let end = start + sample_size;++ for channel in 0..self.channels {+ let channel_start = channel * sample_size;+ let channel_end = channel_start + sample_size;+ frame.plane_data_mut(channel)[start..end]+ .copy_from_slice(&interleaved_chunk[channel_start..channel_end]);}}}@@ -219,7 +219,7 @@ impl VideoInfo {let mut frame = frame::Video::new(self.pixel_format, self.width, self.height);frame.set_pts(Some(timestamp));- let frame_stride = frame.stride(0) as usize;+ let frame_stride = frame.stride(0);let frame_height = self.height as usize;// Ensure we don't try to copy more data than we havediff --git a/crates/media/Cargo.toml b/crates/media/Cargo.tomlindex 592989b6e..e940e491b 100644--- a/crates/media/Cargo.toml+++ b/crates/media/Cargo.toml@@ -2,8 +2,7 @@name = "cap-media"version = "0.1.0"description = "A modular multimedia processing library"-edition = "2021"-rust-version = "1.80"+edition = "2024"[lints]workspace = truediff --git a/crates/media/examples/camera.rs b/crates/media/examples/camera.rsindex 36e62c1d8..7426d9852 100644--- a/crates/media/examples/camera.rs+++ b/crates/media/examples/camera.rs@@ -2,7 +2,7 @@ use std::fmt::Display;use cap_media::feeds::{CameraFeed, DeviceOrModelID};use ffmpeg::format::Pixel;-use image::{codecs::jpeg, ColorType};+use image::{ColorType, codecs::jpeg};#[tokio::main]async fn main() {@@ -22,7 +22,9 @@ async fn main() {let (tx, rx) = flume::bounded(1);feed.attach(tx);let frame = rx.recv_async().await.unwrap().frame;- dbg!(frame.format(), frame.width(), frame.height());+ frame.format();+ frame.width();+ frame.height();let mut converter = ffmpeg::software::converter((frame.width(), frame.height()),@@ -34,7 +36,10 @@ async fn main() {let mut converted_frame = ffmpeg::frame::Video::empty();converter.run(&frame, &mut converted_frame).unwrap();- dbg!(converted_frame.data(0).len());+ println!(+ "Converted frame data len: {}",+ converted_frame.data(0).len()+ );let mut file = std::fs::File::create("./out.jpeg").unwrap();jpeg::JpegEncoder::new(&mut file).encode(diff --git a/crates/media/src/data.rs b/crates/media/src/data.rsindex 6d7db4f34..304babd73 100644--- a/crates/media/src/data.rs+++ b/crates/media/src/data.rs@@ -1,4 +1,3 @@-use cpal::{SampleFormat, SupportedBufferSize, SupportedStreamConfig};pub use ffmpeg::format::{pixel::Pixel,sample::{Sample, Type},@@ -8,14 +7,20 @@ pub use ffmpeg::util::{frame::{Audio as FFAudio, Frame as FFFrame, Video as FFVideo},rational::Rational as FFRational,};-pub use ffmpeg::{error::EAGAIN, Error as FFError, Packet as FFPacket};+pub use ffmpeg::{Error as FFError, Packet as FFPacket, error::EAGAIN};+/// # Safety+/// The input slice must be aligned to the size of `f32`.pub unsafe fn cast_f32_slice_to_bytes(slice: &[f32]) -> &[u8] {- std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * f32::BYTE_SIZE)+ unsafe { std::slice::from_raw_parts(slice.as_ptr() as *const u8, slice.len() * f32::BYTE_SIZE) }}+/// # Safety+/// The input slice must be aligned to the size of `f32`.pub unsafe fn cast_bytes_to_f32_slice(slice: &[u8]) -> &[f32] {- std::slice::from_raw_parts(slice.as_ptr() as *const f32, slice.len() / f32::BYTE_SIZE)+ unsafe {+ std::slice::from_raw_parts(slice.as_ptr() as *const f32, slice.len() / f32::BYTE_SIZE)+ }}pub trait FromSampleBytes: cpal::SizedSample + std::fmt::Debug + Send + 'static {diff --git a/crates/media/src/feeds/audio.rs b/crates/media/src/feeds/audio.rsindex ac6ade758..d9e9a03da 100644--- a/crates/media/src/feeds/audio.rs+++ b/crates/media/src/feeds/audio.rs@@ -1,122 +1,114 @@use cap_audio::{AudioData, StereoMode};use cap_media_info::AudioInfo;use cap_project::{AudioConfiguration, ProjectConfiguration, TimelineConfiguration};-use ffmpeg::{- codec::decoder,- format::{- self, self as avformat,- sample::{Sample, Type},- },- software::resampling,- ChannelLayout,-};+use ffmpeg::{ChannelLayout, format as avformat, software::resampling};use ringbuf::{- traits::{Consumer, Observer, Producer},HeapRb,+ traits::{Consumer, Observer, Producer},};use std::sync::Arc;use crate::{- data::{cast_bytes_to_f32_slice, cast_f32_slice_to_bytes, FFAudio, FromSampleBytes},MediaError,+ data::{FFAudio, FromSampleBytes, cast_f32_slice_to_bytes},};-fn decode_audio_to_f32(- decoder: &mut decoder::Audio,- input_ctx: &mut format::context::Input,- stream_index: usize,-) -> Vec<f32> {- let mut decoded_frame = ffmpeg::frame::Audio::empty();- let mut resampled_frame = ffmpeg::frame::Audio::empty();-- let mut resampler = ffmpeg::software::resampler(- (decoder.format(), decoder.channel_layout(), decoder.rate()),- (- Sample::F32(Type::Packed),- decoder.channel_layout(),- AudioData::SAMPLE_RATE,- ),- )- .unwrap();-- // let mut resampled_frames = 0;- let mut samples: Vec<f32> = vec![];-- fn process_resampler(- resampler: &mut resampling::Context,- samples: &mut Vec<f32>,- resampled_frame: &mut FFAudio,- ) {- loop {- let resample_delay = resampler.flush(resampled_frame).unwrap();- if resampled_frame.samples() == 0 {- break;- }-- let slice = &resampled_frame.data(0)- [0..resampled_frame.samples() * 4 * resampled_frame.channels() as usize];- samples.extend(unsafe { cast_bytes_to_f32_slice(slice) });-- if resample_delay.is_none() {- break;- }- }- }-- fn process_decoder(- decoder: &mut ffmpeg::decoder::Audio,- decoded_frame: &mut FFAudio,- resampler: &mut resampling::Context,- resampled_frame: &mut FFAudio,- samples: &mut Vec<f32>,- ) {- while let Ok(_) = decoder.receive_frame(decoded_frame) {- let resample_delay = resampler.run(&decoded_frame, resampled_frame).unwrap();-- let slice = &resampled_frame.data(0)- [0..resampled_frame.samples() * 4 * resampled_frame.channels() as usize];- samples.extend(unsafe { cast_bytes_to_f32_slice(slice) });-- if resample_delay.is_some() {- process_resampler(resampler, samples, resampled_frame);- }- }- }-- for (stream, packet) in input_ctx.packets() {- if stream.index() != stream_index {- continue;- }-- decoder.send_packet(&packet).unwrap();-- process_decoder(- decoder,- &mut decoded_frame,- &mut resampler,- &mut resampled_frame,- &mut samples,- );-- if resampler.delay().is_some() {- process_resampler(&mut resampler, &mut samples, &mut resampled_frame);- }- }-- decoder.send_eof().unwrap();-- process_decoder(- decoder,- &mut decoded_frame,- &mut resampler,- &mut resampled_frame,- &mut samples,- );-- process_resampler(&mut resampler, &mut samples, &mut resampled_frame);-- samples-}+// fn decode_audio_to_f32(+// decoder: &mut decoder::Audio,+// input_ctx: &mut format::context::Input,+// stream_index: usize,+// ) -> Vec<f32> {+// let mut decoded_frame = ffmpeg::frame::Audio::empty();+// let mut resampled_frame = ffmpeg::frame::Audio::empty();++// let mut resampler = ffmpeg::software::resampler(+// (decoder.format(), decoder.channel_layout(), decoder.rate()),+// (+// Sample::F32(Type::Packed),+// decoder.channel_layout(),+// AudioData::SAMPLE_RATE,+// ),+// )+// .unwrap();++// // let mut resampled_frames = 0;+// let mut samples: Vec<f32> = vec![];++// fn process_resampler(+// resampler: &mut resampling::Context,+// samples: &mut Vec<f32>,+// resampled_frame: &mut FFAudio,+// ) {+// loop {+// let resample_delay = resampler.flush(resampled_frame).unwrap();+// if resampled_frame.samples() == 0 {+// break;+// }++// let slice = &resampled_frame.data(0)+// [0..resampled_frame.samples() * 4 * resampled_frame.channels() as usize];+// samples.extend(unsafe { cast_bytes_to_f32_slice(slice) });++// if resample_delay.is_none() {+// break;+// }+// }+// }++// fn process_decoder(+// decoder: &mut ffmpeg::decoder::Audio,+// decoded_frame: &mut FFAudio,+// resampler: &mut resampling::Context,+// resampled_frame: &mut FFAudio,+// samples: &mut Vec<f32>,+// ) {+// while decoder.receive_frame(decoded_frame).is_ok() {+// let resample_delay = resampler.run(decoded_frame, resampled_frame).unwrap();++// let slice = &resampled_frame.data(0)+// [0..resampled_frame.samples() * 4 * resampled_frame.channels() as usize];+// samples.extend(unsafe { cast_bytes_to_f32_slice(slice) });++// if resample_delay.is_some() {+// process_resampler(resampler, samples, resampled_frame);+// }+// }+// }++// for (stream, packet) in input_ctx.packets() {+// if stream.index() != stream_index {+// continue;+// }++// decoder.send_packet(&packet).unwrap();++// process_decoder(+// decoder,+// &mut decoded_frame,+// &mut resampler,+// &mut resampled_frame,+// &mut samples,+// );++// if resampler.delay().is_some() {+// process_resampler(&mut resampler, &mut samples, &mut resampled_frame);+// }+// }++// decoder.send_eof().unwrap();++// process_decoder(+// decoder,+// &mut decoded_frame,+// &mut resampler,+// &mut resampled_frame,+// &mut samples,+// );++// process_resampler(&mut resampler, &mut samples, &mut resampled_frame);++// samples+// }pub struct AudioRenderer {data: Vec<AudioSegment>,@@ -245,8 +237,7 @@ impl AudioRenderer {requested_samples: usize,project: &ProjectConfiguration,) -> Option<FFAudio> {- let res = self- .render_frame_raw(requested_samples, project)+ self.render_frame_raw(requested_samples, project).map(move |(samples, data)| {let mut raw_frame =FFAudio::new(AudioData::SAMPLE_FORMAT, samples, ChannelLayout::STEREO);@@ -255,13 +246,11 @@ impl AudioRenderer {.copy_from_slice(unsafe { cast_f32_slice_to_bytes(&data) });raw_frame- });-- res+ })}- pub fn render_frame_raw<'a>(- &'a mut self,+ pub fn render_frame_raw(+ &mut self,samples: usize,project: &ProjectConfiguration,) -> Option<(usize, Vec<f32>)> {@@ -302,11 +291,7 @@ impl AudioRenderer {f32::NEG_INFINITY} else {let g = t.gain(&project.audio);- if g < -30.0 {- f32::NEG_INFINITY- } else {- g- }+ if g < -30.0 { f32::NEG_INFINITY } else { g }},t.stereo_mode(&project.audio),)@@ -339,7 +324,7 @@ impl<T: FromSampleBytes> AudioPlaybackBuffer<T> {pub fn new(data: Vec<AudioSegment>, output_info: AudioInfo) -> Self {// println!("Input info: {:?}", data[0][0].info);- println!("Output info: {:?}", output_info);+ println!("Output info: {output_info:?}");let resampler = AudioResampler::new(output_info).unwrap();diff --git a/crates/media/src/feeds/audio_input.rs b/crates/media/src/feeds/audio_input.rsindex 7690b1e59..d74378b38 100644--- a/crates/media/src/feeds/audio_input.rs+++ b/crates/media/src/feeds/audio_input.rs@@ -1,5 +1,5 @@use cap_fail::fail_err;-use cap_media_info::{ffmpeg_sample_format_for, AudioInfo};+use cap_media_info::{AudioInfo, ffmpeg_sample_format_for};use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};use cpal::{Device, InputCallbackInfo, SampleFormat, StreamConfig, SupportedStreamConfig};use flume::{Receiver, Sender, TrySendError};diff --git a/crates/media/src/feeds/camera.rs b/crates/media/src/feeds/camera.rsindex 1eefca269..4c6411161 100644--- a/crates/media/src/feeds/camera.rs+++ b/crates/media/src/feeds/camera.rs@@ -205,7 +205,7 @@ fn run_camera_feed(Ok(state) => {let _ = ready_tx.send(Ok(CameraFeedInfo {camera: state.camera_info.clone(),- video_info: state.video_info.clone(),+ video_info: state.video_info,reference_time: state.reference_time,}));state@@ -226,7 +226,11 @@ fn run_camera_feed(break 'outer;}Ok(CameraControl::Shutdown) => {- state.handle.stop_capturing();+ state+ .handle+ .stop_capturing()+ .map_err(|err| error!("Error stopping capture: {err:?}"))+ .ok();println!("Deliberate shutdown");break 'outer;}@@ -238,7 +242,7 @@ fn run_camera_feed(Ok(new_state) => {let _ = switch_result.send(Ok(CameraFeedInfo {camera: new_state.camera_info.clone(),- video_info: new_state.video_info.clone(),+ video_info: new_state.video_info,reference_time: new_state.reference_time,}));state = new_state;@@ -357,7 +361,7 @@ fn setup_camera(id: DeviceOrModelID) -> Result<SetupCameraState, SetupCameraErroff_frame.set_pts(Some(frame.timestamp.as_micros() as i64));- ready_signal.take().map(|signal| {+ if let Some(signal) = ready_signal.take() {let video_info = VideoInfo::from_raw_ffmpeg(ff_frame.format(),ff_frame.width(),@@ -366,7 +370,7 @@ fn setup_camera(id: DeviceOrModelID) -> Result<SetupCameraState, SetupCameraErro);let _ = signal.send((video_info, frame.reference_time));- });+ }let _ = frame_tx.send(RawCameraFrame {frame: ff_frame,diff --git a/crates/media/src/frame_ws.rs b/crates/media/src/frame_ws.rsindex 8ceab86e4..1276f2108 100644--- a/crates/media/src/frame_ws.rs+++ b/crates/media/src/frame_ws.rs@@ -1,7 +1,6 @@use std::sync::Arc;use flume::Receiver;-use tokio::sync::mpsc;use tokio_util::sync::CancellationToken;pub struct WSFrame {@@ -14,8 +13,8 @@ pub struct WSFrame {pub async fn create_frame_ws(frame_rx: Receiver<WSFrame>) -> (u16, CancellationToken) {use axum::{extract::{- ws::{Message, WebSocket, WebSocketUpgrade},State,+ ws::{Message, WebSocket, WebSocketUpgrade},},response::IntoResponse,routing::get,diff --git a/crates/media/src/pipeline/builder.rs b/crates/media/src/pipeline/builder.rsindex 2e9ee1890..d878ff96c 100644--- a/crates/media/src/pipeline/builder.rs+++ b/crates/media/src/pipeline/builder.rs@@ -8,10 +8,10 @@ use tokio::sync::oneshot;use tracing::{error, info};use crate::pipeline::{+ MediaError, Pipeline, PipelineClock,clock::CloneFrom,control::ControlBroadcast,task::{PipelineReadySignal, PipelineSourceTask},- MediaError, Pipeline, PipelineClock,};struct Task {@@ -85,7 +85,7 @@ impl<T> PipelineBuilder<T> {} else if let Some(s) = e.downcast_ref::<String>() {format!("Panicked: {s}")} else {- format!("Panicked: Unknown error")+ "Panicked: Unknown error".to_string()}})})@@ -171,7 +171,7 @@ impl<T: PipelineClock> PipelineBuilder<T> {}}-pub struct PipelinePathBuilder<Clock, PreviousOutput: Send> {- pipeline: PipelineBuilder<Clock>,- next_input: Receiver<PreviousOutput>,-}+// pub struct PipelinePathBuilder<Clock, PreviousOutput: Send> {+// pipeline: PipelineBuilder<Clock>,+// next_input: Receiver<PreviousOutput>,+// }diff --git a/crates/media/src/pipeline/clock/real_time.rs b/crates/media/src/pipeline/clock/real_time.rsindex 9192136b7..ac7cd6eb8 100644--- a/crates/media/src/pipeline/clock/real_time.rs+++ b/crates/media/src/pipeline/clock/real_time.rs@@ -1,6 +1,6 @@use std::sync::{- atomic::{AtomicBool, AtomicU64, Ordering},Arc, RwLock,+ atomic::{AtomicBool, AtomicU64, Ordering},};use std::time::{Duration, Instant};diff --git a/crates/media/src/pipeline/clock/recorded.rs b/crates/media/src/pipeline/clock/recorded.rsindex 8c5238f4d..027a6cd76 100644--- a/crates/media/src/pipeline/clock/recorded.rs+++ b/crates/media/src/pipeline/clock/recorded.rs@@ -1,6 +1,6 @@use std::sync::{- atomic::{AtomicBool, AtomicU32, Ordering},Arc,+ atomic::{AtomicBool, AtomicU32, Ordering},};use super::{CloneInto, PipelineClock};diff --git a/crates/media/src/pipeline/control.rs b/crates/media/src/pipeline/control.rsindex 5b84435ca..39aa72ab1 100644--- a/crates/media/src/pipeline/control.rs+++ b/crates/media/src/pipeline/control.rs@@ -1,8 +1,6 @@use flume::{Receiver, Sender, TryRecvError};use indexmap::IndexMap;-use tracing::{debug, error};--use crate::pipeline::MediaError;+use tracing::debug;#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum Control {diff --git a/crates/media/src/platform/macos.rs b/crates/media/src/platform/macos.rsindex e522ff7f2..796cf2eb6 100644--- a/crates/media/src/platform/macos.rs+++ b/crates/media/src/platform/macos.rs@@ -4,16 +4,16 @@ use core_foundation::{array::CFArrayGetCount,base::FromVoid,dictionary::CFDictionaryGetValue,- number::{kCFNumberIntType, CFNumberGetValue, CFNumberRef},+ number::{CFNumberGetValue, CFNumberRef, kCFNumberIntType},string::{CFString, CFStringRef},};use core_graphics::{base::boolean_t,display::{CFArrayGetValueAtIndex, CFDictionaryRef, CGDisplay, CGDisplayBounds, CGRect},window::{- kCGNullWindowID, kCGWindowBounds, kCGWindowLayer, kCGWindowListExcludeDesktopElements,- kCGWindowListOptionOnScreenOnly, kCGWindowName, kCGWindowNumber, kCGWindowOwnerName,- kCGWindowOwnerPID, CGWindowListCopyWindowInfo,+ CGWindowListCopyWindowInfo, kCGNullWindowID, kCGWindowBounds, kCGWindowLayer,+ kCGWindowListExcludeDesktopElements, kCGWindowListOptionOnScreenOnly, kCGWindowName,+ kCGWindowNumber, kCGWindowOwnerName, kCGWindowOwnerPID,},};use std::{collections::HashMap, ffi::c_void};@@ -23,7 +23,7 @@ use crate::platform::{Bounds, LogicalPosition, LogicalSize, Window};use super::LogicalBounds;#[link(name = "CoreGraphics", kind = "framework")]-extern "C" {+unsafe extern "C" {fn CGRectMakeWithDictionaryRepresentation(dict: CFDictionaryRef,rect: *mut CGRect,@@ -100,7 +100,7 @@ unsafe fn get_nullable_value_from_dict(cf_dictionary_ref: CFDictionaryRef,key: CFStringRef,) -> Option<*const c_void> {- let value_ref = CFDictionaryGetValue(cf_dictionary_ref, key as *const c_void);+ let value_ref = unsafe { CFDictionaryGetValue(cf_dictionary_ref, key as *const c_void) };if value_ref.is_null() {return None;}@@ -112,10 +112,10 @@ unsafe fn get_number_value_from_dict(cf_dictionary_ref: CFDictionaryRef,key: CFStringRef,) -> Option<u32> {- get_nullable_value_from_dict(cf_dictionary_ref, key).and_then(|value_ref| {+ unsafe { get_nullable_value_from_dict(cf_dictionary_ref, key) }.and_then(|value_ref| {let mut value: u32 = 0;let value_ptr = &mut value as *mut _ as *mut c_void;- match CFNumberGetValue(value_ref as CFNumberRef, kCFNumberIntType, value_ptr) {+ match unsafe { CFNumberGetValue(value_ref as CFNumberRef, kCFNumberIntType, value_ptr) } {true => Some(value),false => None,}@@ -126,25 +126,27 @@ unsafe fn get_string_value_from_dict(cf_dictionary_ref: CFDictionaryRef,key: CFStringRef,) -> Option<String> {- get_nullable_value_from_dict(cf_dictionary_ref, key)- .map(|value_ref| CFString::from_void(value_ref).to_string())+ unsafe { get_nullable_value_from_dict(cf_dictionary_ref, key) }+ .map(|value_ref| unsafe { CFString::from_void(value_ref).to_string() })}-unsafe fn get_window_bounds(window_cf_dictionary_ref: CFDictionaryRef) -> Option<Bounds> {- get_nullable_value_from_dict(window_cf_dictionary_ref, kCGWindowBounds).map(|value_ref| {- let rect: CGRect = {- let mut rect = std::mem::zeroed();- CGRectMakeWithDictionaryRepresentation(value_ref.cast(), &mut rect);- rect- };+fn get_window_bounds(window_cf_dictionary_ref: CFDictionaryRef) -> Option<Bounds> {+ unsafe { get_nullable_value_from_dict(window_cf_dictionary_ref, kCGWindowBounds) }.map(+ |value_ref| {+ let rect: CGRect = {+ let mut rect = unsafe { std::mem::zeroed() };+ unsafe { CGRectMakeWithDictionaryRepresentation(value_ref.cast(), &mut rect) };+ rect+ };- Bounds {- x: rect.origin.x,- y: rect.origin.y,- width: rect.size.width,- height: rect.size.height,- }- })+ Bounds {+ x: rect.origin.x,+ y: rect.origin.y,+ width: rect.size.width,+ height: rect.size.height,+ }+ },+ )}pub fn bring_window_to_focus(window_id: u32) {@@ -153,7 +155,7 @@ pub fn bring_window_to_focus(window_id: u32) {use std::process::Command;use tempfile::NamedTempFile;- println!("Attempting to bring window {} to focus", window_id);+ println!("Attempting to bring window {window_id} to focus");// Get the window information associated with the window idlet windows = get_on_screen_windows();@@ -241,15 +243,15 @@ pub fn bring_window_to_focus(window_id: u32) {println!("Successfully executed AppleScript");} else {let error_message = String::from_utf8_lossy(&output.stderr);- eprintln!("AppleScript execution failed: {}", error_message);+ eprintln!("AppleScript execution failed: {error_message}");}}- Err(e) => eprintln!("Failed to execute AppleScript: {}", e),+ Err(e) => eprintln!("Failed to execute AppleScript: {e}"),}- println!("Finished attempt to bring window {} to focus", window_id);+ println!("Finished attempt to bring window {window_id} to focus");} else {- eprintln!("Window with id {} not found", window_id);+ eprintln!("Window with id {window_id} not found");}}@@ -340,7 +342,7 @@ pub fn get_display_refresh_rate(let display = CGDisplay::new(display_id);let rate = display.display_mode()- .ok_or_else(|| "no display_mode")?+ .ok_or("no display_mode")?.refresh_rate().round() as u32;@@ -484,16 +486,3 @@ pub fn logical_monitor_bounds(monitor_id: u32) -> Option<LogicalBounds> {None}}--#[cfg(test)]-mod test {- use super::*;-- #[test]- fn bruh() {- dbg!(MonitorHandle::list_all()- .into_iter()- .map(|v| logical_monitor_bounds(v.0))- .collect::<Vec<_>>());- }-}diff --git a/crates/media/src/platform/win.rs b/crates/media/src/platform/win.rsindex 897b4a789..2ae664fde 100644--- a/crates/media/src/platform/win.rs+++ b/crates/media/src/platform/win.rs@@ -1,34 +1,32 @@use std::collections::HashMap;-use std::ffi::{c_void, OsString};+use std::ffi::{OsString, c_void};use std::os::windows::ffi::OsStringExt;use std::path::PathBuf;use super::{Bounds, LogicalBounds, LogicalPosition, LogicalSize, Window};use tracing::debug;-use windows::core::{BOOL, PCWSTR, PWSTR};use windows::Win32::{Foundation::{CloseHandle, FALSE, HWND, LPARAM, RECT, TRUE},Graphics::{- Dwm::{DwmGetWindowAttribute, DWMWA_CLOAKED, DWMWA_EXTENDED_FRAME_BOUNDS},+ Dwm::{DWMWA_CLOAKED, DWMWA_EXTENDED_FRAME_BOUNDS, DwmGetWindowAttribute},Gdi::{- EnumDisplayDevicesW, EnumDisplayMonitors, EnumDisplaySettingsW, GetMonitorInfoW,- MonitorFromWindow, DEVMODEW, DISPLAY_DEVICEW, HDC, HMONITOR, MONITORINFO,- MONITORINFOEXW, MONITOR_DEFAULTTONULL,+ DEVMODEW, DISPLAY_DEVICEW, EnumDisplayDevicesW, EnumDisplayMonitors,+ EnumDisplaySettingsW, GetMonitorInfoW, HDC, HMONITOR, MONITOR_DEFAULTTONULL,+ MONITORINFO, MONITORINFOEXW, MonitorFromWindow,},},System::Threading::{- OpenProcess, QueryFullProcessImageNameW, PROCESS_NAME_FORMAT,- PROCESS_QUERY_LIMITED_INFORMATION,+ OpenProcess, PROCESS_NAME_FORMAT, PROCESS_QUERY_LIMITED_INFORMATION,+ QueryFullProcessImageNameW,},UI::HiDpi::GetDpiForWindow,UI::WindowsAndMessaging::{- EnumWindows, GetCursorInfo, GetWindowTextLengthW, GetWindowTextW, GetWindowThreadProcessId,- IsWindowVisible, LoadCursorW, SetForegroundWindow, CURSORINFO, IDC_APPSTARTING, IDC_ARROW,- IDC_CROSS, IDC_HAND, IDC_HELP, IDC_IBEAM, IDC_NO, IDC_PERSON, IDC_PIN, IDC_SIZEALL,- IDC_SIZENESW, IDC_SIZENS, IDC_SIZENWSE, IDC_SIZEWE, IDC_UPARROW, IDC_WAIT,+ EnumWindows, GetWindowTextLengthW, GetWindowTextW, GetWindowThreadProcessId,+ IsWindowVisible, SetForegroundWindow,},};+use windows::core::{BOOL, PCWSTR, PWSTR};#[inline]pub fn bring_window_to_focus(window_id: u32) {@@ -36,20 +34,22 @@ pub fn bring_window_to_focus(window_id: u32) {}unsafe fn pid_to_exe_path(pid: u32) -> Result<PathBuf, windows::core::Error> {- let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid)?;+ let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid) }?;if handle.is_invalid() {tracing::error!("Invalid PID {}", pid);}let mut lpexename = [0u16; 1024];let mut lpdwsize = lpexename.len() as u32;- let query = QueryFullProcessImageNameW(- handle,- PROCESS_NAME_FORMAT::default(),- windows::core::PWSTR(lpexename.as_mut_ptr()),- &mut lpdwsize,- );- CloseHandle(handle).ok();+ let query = unsafe {+ QueryFullProcessImageNameW(+ handle,+ PROCESS_NAME_FORMAT::default(),+ windows::core::PWSTR(lpexename.as_mut_ptr()),+ &mut lpdwsize,+ )+ };+ unsafe { CloseHandle(handle) }.ok();query?;let os_str = &OsString::from_wide(&lpexename[..lpdwsize as usize]);@@ -63,19 +63,21 @@ pub fn get_on_screen_windows() -> Vec<Window> {if hwnd.is_invalid() {return TRUE;}- let windows = &mut *(lparam.0 as *mut Vec<Window>);+ let windows = unsafe { &mut *(lparam.0 as *mut Vec<Window>) };- if !IsWindowVisible(hwnd).as_bool() {+ if !unsafe { IsWindowVisible(hwnd) }.as_bool() {return TRUE;}let mut pvattribute_cloaked = 0u32;- DwmGetWindowAttribute(- hwnd,- DWMWA_CLOAKED,- &mut pvattribute_cloaked as *mut _ as *mut std::ffi::c_void,- std::mem::size_of::<u32>() as u32,- )+ unsafe {+ DwmGetWindowAttribute(+ hwnd,+ DWMWA_CLOAKED,+ &mut pvattribute_cloaked as *mut _ as *mut std::ffi::c_void,+ std::mem::size_of::<u32>() as u32,+ )+ }.ok();if pvattribute_cloaked != 0 {@@ -83,16 +85,16 @@ pub fn get_on_screen_windows() -> Vec<Window> {}let mut process_id = 0;- let _thrad_id = GetWindowThreadProcessId(hwnd, Some(&mut process_id));+ let _thrad_id = unsafe { GetWindowThreadProcessId(hwnd, Some(&mut process_id)) };- let wnamelen = GetWindowTextLengthW(hwnd);+ let wnamelen = unsafe { GetWindowTextLengthW(hwnd) };if wnamelen == 0 {return TRUE;}let mut wname = [0u16; 512];- let len = GetWindowTextW(hwnd, &mut wname);+ let len = unsafe { GetWindowTextW(hwnd, &mut wname) };- let owner_process_path = match pid_to_exe_path(process_id) {+ let owner_process_path = match unsafe { pid_to_exe_path(process_id) } {Ok(path) => path,Err(_) => return TRUE,};@@ -109,18 +111,20 @@ pub fn get_on_screen_windows() -> Vec<Window> {// Windows 10 build 1607 or later// Credits: TAO src/platform_impl/windows/dpi.rsconst BASE_DPI: u32 = 96;- let dpi = match GetDpiForWindow(hwnd) {+ let _dpi = match unsafe { GetDpiForWindow(hwnd) } {0 => BASE_DPI,dpi => dpi,} as i32;let mut rect = RECT::default();- DwmGetWindowAttribute(- hwnd,- DWMWA_EXTENDED_FRAME_BOUNDS,- &mut rect as *mut _ as *mut std::ffi::c_void,- std::mem::size_of::<RECT>() as u32,- )+ unsafe {+ DwmGetWindowAttribute(+ hwnd,+ DWMWA_EXTENDED_FRAME_BOUNDS,+ &mut rect as *mut _ as *mut std::ffi::c_void,+ std::mem::size_of::<RECT>() as u32,+ )+ }.ok();let rect_left = rect.left as f64;@@ -163,23 +167,30 @@ pub fn monitor_bounds(id: u32) -> Bounds {_lprc_clip: *mut RECT,lparam: LPARAM,) -> BOOL {- let (target_id, bounds) = &mut *(lparam.0 as *mut (u32, Option<Bounds>));+ let (target_id, bounds) = unsafe { &mut *(lparam.0 as *mut (u32, Option<Bounds>)) };let mut minfo = MONITORINFOEXW::default();minfo.monitorInfo.cbSize = std::mem::size_of::<MONITORINFOEXW>() as u32;- if !GetMonitorInfoW(hmonitor, &mut minfo as *mut MONITORINFOEXW as *mut _).as_bool() {+ if !unsafe { GetMonitorInfoW(hmonitor, &mut minfo as *mut MONITORINFOEXW as *mut _) }+ .as_bool()+ {return TRUE;}let mut display_device = DISPLAY_DEVICEW::default();- display_device.cb = std::mem::size_of::<DISPLAY_DEVICEW>() as u32;+ #[allow(clippy::field_reassign_with_default)]+ {+ display_device.cb = std::mem::size_of::<DISPLAY_DEVICEW>() as u32;+ }- if !EnumDisplayDevicesW(- PWSTR(minfo.szDevice.as_ptr() as _),- 0,- &mut display_device,- 0,- )+ if !unsafe {+ EnumDisplayDevicesW(+ PWSTR(minfo.szDevice.as_ptr() as _),+ 0,+ &mut display_device,+ 0,+ )+ }.as_bool(){return TRUE;diff --git a/crates/media/src/sources/audio_input.rs b/crates/media/src/sources/audio_input.rsindex 2aaec7542..9cfec73fd 100644--- a/crates/media/src/sources/audio_input.rs+++ b/crates/media/src/sources/audio_input.rs@@ -10,13 +10,13 @@ use tracing::{error, info};use crate::feeds::{AudioInputConnection, AudioInputFeed, AudioInputSamples};use crate::{+ MediaError,data::FFAudio,pipeline::{clock::{LocalTimestamp, RealTimeClock},control::Control,task::PipelineSourceTask,},- MediaError,};pub type AudioInputDeviceMap = IndexMap<String, (Device, SupportedStreamConfig)>;@@ -81,7 +81,7 @@ impl AudioInputSource {&samples.data,(elapsed.as_secs_f64() * AV_TIME_BASE_Q.den as f64) as i64,);- if let Err(_) = self.tx.send((frame, timestamp)) {+ if self.tx.send((frame, timestamp)).is_err() {return Err(MediaError::Any("Pipeline is unreachable! Stopping capture".into(),));diff --git a/crates/media/src/sources/audio_mixer.rs b/crates/media/src/sources/audio_mixer.rsindex 079f99af5..52d26ecbf 100644--- a/crates/media/src/sources/audio_mixer.rs+++ b/crates/media/src/sources/audio_mixer.rs@@ -5,7 +5,7 @@ use ffmpeg_sys_next::AV_TIME_BASE_Q;use flume::{Receiver, Sender};use tracing::{debug, warn};-use crate::pipeline::{task::PipelineSourceTask, RawNanoseconds, RealTimeClock};+use crate::pipeline::{RawNanoseconds, RealTimeClock, task::PipelineSourceTask};pub struct AudioMixer {sources: Vec<AudioMixerSource>,@@ -45,7 +45,7 @@ impl AudioMixer {.unwrap()}- pub fn run(&mut self, mut get_is_stopped: impl FnMut() -> bool, on_ready: impl FnOnce() -> ()) {+ pub fn run(&mut self, mut get_is_stopped: impl FnMut() -> bool, on_ready: impl FnOnce()) {let mut filter_graph = ffmpeg::filter::Graph::new();let mut abuffers = self@@ -132,7 +132,7 @@ impl AudioMixer {};let frame = &value.0;- abuffers[i].source().add(&frame).unwrap();+ abuffers[i].source().add(frame).unwrap();}}@@ -166,7 +166,7 @@ impl PipelineSourceTask for AudioMixer {fn run(&mut self,- clock: Self::Clock,+ _clock: Self::Clock,ready_signal: crate::pipeline::task::PipelineReadySignal,mut control_signal: crate::pipeline::control::PipelineControlSignal,) -> Result<(), String> {diff --git a/crates/media/src/sources/camera.rs b/crates/media/src/sources/camera.rsindex 0ff1ed852..12c5d404b 100644--- a/crates/media/src/sources/camera.rs+++ b/crates/media/src/sources/camera.rs@@ -5,9 +5,9 @@ use std::time::{Duration, Instant};use tracing::{error, info};use crate::{+ MediaError,feeds::{CameraConnection, CameraFeed, RawCameraFrame},pipeline::{clock::RealTimeClock, control::Control, task::PipelineSourceTask},- MediaError,};pub struct CameraSource {@@ -57,10 +57,14 @@ impl CameraSource {let relative_timestamp = camera_frame.timestamp - first_frame_timestamp;- if let Err(_) = self.output.send((- camera_frame.frame,- (first_frame_instant + relative_timestamp - self.start_instant).as_secs_f64(),- )) {+ if self+ .output+ .send((+ camera_frame.frame,+ (first_frame_instant + relative_timestamp - self.start_instant).as_secs_f64(),+ ))+ .is_err()+ {return Err(MediaError::Any("Pipeline is unreachable! Stopping capture".into(),));diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rsindex aa0a88b4f..b3284906e 100644--- a/crates/media/src/sources/screen_capture.rs+++ b/crates/media/src/sources/screen_capture.rs@@ -4,22 +4,22 @@ use ffmpeg::{format::Sample, frame};use ffmpeg_sys_next::AV_TIME_BASE_Q;use flume::Sender;use scap::{+ Target,capturer::{Area, Capturer, Options, Point, Resolution as ScapResolution, Size},frame::{Frame, FrameType, VideoFrame},- Target,};use serde::{Deserialize, Serialize};use specta::Type;-use std::{collections::HashMap, ops::ControlFlow, sync::Arc, time::SystemTime};+use std::{collections::HashMap, ops::ControlFlow, rc::Rc, time::SystemTime};use tracing::{debug, error, info, trace, warn};#[cfg(target_os = "windows")]use windows::Win32::{Foundation::HWND, Graphics::Gdi::HMONITOR};use crate::{- pipeline::{clock::*, control::Control, task::PipelineSourceTask},- platform::{self, logical_monitor_bounds, Bounds, Window},MediaError,+ pipeline::{clock::*, control::Control, task::PipelineSourceTask},+ platform::{self, Bounds, Window, logical_monitor_bounds},};static EXCLUDED_WINDOWS: &[&str] = &[@@ -110,7 +110,7 @@ pub struct ScreenCaptureSource<TCaptureFormat: ScreenCaptureFormat> {output_type: Option<FrameType>,fps: u32,video_info: VideoInfo,- options: Arc<Options>,+ options: Rc<Options>,show_camera: bool,force_show_cursor: bool,bounds: Bounds,@@ -167,10 +167,10 @@ unsafe impl<T: ScreenCaptureFormat> Sync for ScreenCaptureSource<T> {}impl<TCaptureFormat: ScreenCaptureFormat> Clone for ScreenCaptureSource<TCaptureFormat> {fn clone(&self) -> Self {Self {- target: self.target.clone(),+ target: self.target,output_type: self.output_type,fps: self.fps,- video_info: self.video_info.clone(),+ video_info: self.video_info,options: self.options.clone(),show_camera: self.show_camera,force_show_cursor: self.force_show_cursor,@@ -179,7 +179,7 @@ impl<TCaptureFormat: ScreenCaptureFormat> Clone for ScreenCaptureSource<TCapturevideo_tx: self.video_tx.clone(),audio_tx: self.audio_tx.clone(),_phantom: std::marker::PhantomData,- start_time: self.start_time.clone(),+ start_time: self.start_time,}}}@@ -197,6 +197,7 @@ pub struct CropRatio {}impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {+ #[allow(clippy::too_many_arguments)]pub async fn init(target: &ScreenCaptureTarget,output_type: Option<FrameType>,@@ -214,23 +215,19 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {bounds,crop_area,display_size,- } = Self::get_options_config(&target)?;+ } = Self::get_options_config(target)?;let fps = get_target_fps(&scap_target).map_err(|e| format!("target_fps / {e}"))?;let fps = fps.min(max_fps);- if !(fps > 0) {- return Err("FPS must be greater than 0".to_string());- }-let captures_audio = audio_tx.is_some();let mut this = Self {- target: target.clone(),+ target: *target,output_type,fps,video_info: VideoInfo::from_raw(RawVideoFormat::Bgra, 0, 0, 0),- options: Arc::new(Default::default()),+ options: std::rc::Rc::new(Default::default()),bounds,display_size,show_camera,@@ -243,7 +240,7 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {let options = this.create_options(scap_target, crop_area, captures_audio)?;- this.options = Arc::new(options);+ this.options = std::rc::Rc::new(options);#[cfg(target_os = "macos")]let video_size = {@@ -359,7 +356,7 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {let (screen_info, target) = screens.into_iter()- .find(|(i, t)| i.id == *id)+ .find(|(i, _t)| i.id == *id).ok_or_else(|| "Target for screen capture not found".to_string())?;let bounds = platform::monitor_bounds(screen_info.id);@@ -432,7 +429,7 @@ impl<TCaptureFormat: ScreenCaptureFormat> ScreenCaptureSource<TCaptureFormat> {crop_area,output_type: self.output_type.unwrap_or(FrameType::BGRAFrame),output_resolution: ScapResolution::Captured,- excluded_targets: (!excluded_targets.is_empty()).then(|| excluded_targets),+ excluded_targets: (!excluded_targets.is_empty()).then_some(excluded_targets),captures_audio,exclude_current_process_audio: true,})@@ -456,7 +453,7 @@ impl PipelineSourceTask for ScreenCaptureSource<AVFrameCapture> {// #[instrument(skip_all)]fn run(&mut self,- mut clock: Self::Clock,+ _clock: Self::Clock,ready_signal: crate::pipeline::task::PipelineReadySignal,control_signal: crate::pipeline::control::PipelineControlSignal,) -> Result<(), String> {@@ -743,7 +740,7 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {fn run(&mut self,- clock: Self::Clock,+ _clock: Self::Clock,ready_signal: crate::pipeline::task::PipelineReadySignal,control_signal: crate::pipeline::control::PipelineControlSignal,) -> Result<(), String> {@@ -772,6 +769,7 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {Ok((sample_buffer, typ)) => {use cidre::sc;+ #[allow(clippy::useless_transmute)]let sample_buffer = unsafe {std::mem::transmute::<_, cidre::arc::R<cidre::cm::SampleBuf>>(sample_buffer)};@@ -800,11 +798,11 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {Ok::<(), ()>(())};- if check_skip_send().is_ok() {- if let Err(_) = video_tx.send((sample_buffer, relative_time)) {- error!("Pipeline is unreachable. Shutting down recording.");- return ControlFlow::Continue(());- }+ if check_skip_send().is_ok()+ && video_tx.send((sample_buffer, relative_time)).is_err()+ {+ error!("Pipeline is unreachable. Shutting down recording.");+ return ControlFlow::Continue(());}}sc::stream::OutputType::Audio => {@@ -814,7 +812,7 @@ impl PipelineSourceTask for ScreenCaptureSource<CMSampleBufferCapture> {cap_fail::fail_err!("screen_capture audio skip", ());Ok::<(), ()>(())};- if let Err(_) = res() {+ if res().is_err() {return ControlFlow::Continue(());}diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.tomlindex cc51c6fde..1bca4e93a 100644--- a/crates/project/Cargo.toml+++ b/crates/project/Cargo.toml@@ -1,7 +1,7 @@[package]name = "cap-project"version = "0.1.0"-edition = "2021"+edition = "2024"[lints]workspace = truediff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rsindex b4c93158d..3202b1e5c 100644--- a/crates/project/src/configuration.rs+++ b/crates/project/src/configuration.rs@@ -158,21 +158,18 @@ where}}-impl Into<XY<f64>> for XY<f32> {- fn into(self) -> XY<f64> {+impl From<XY<f32>> for XY<f64> {+ fn from(val: XY<f32>) -> Self {XY {- x: self.x as f64,- y: self.y as f64,+ x: val.x as f64,+ y: val.y as f64,}}}-impl<T> Into<XY<T>> for (T, T) {- fn into(self) -> XY<T> {- XY {- x: self.0,- y: self.1,- }+impl<T> From<(T, T)> for XY<T> {+ fn from(val: (T, T)) -> Self {+ XY { x: val.0, y: val.1 }}}@@ -541,22 +538,15 @@ impl Default for CaptionSettings {#[derive(Type, Serialize, Deserialize, Clone, Debug)]#[serde(rename_all = "camelCase")]+#[derive(Default)]pub struct CaptionsData {pub segments: Vec<CaptionSegment>,pub settings: CaptionSettings,}-impl Default for CaptionsData {- fn default() -> Self {- Self {- segments: Vec::new(),- settings: CaptionSettings::default(),- }- }-}-#[derive(Type, Serialize, Deserialize, Clone, Debug)]#[serde(rename_all = "camelCase")]+#[derive(Default)]pub struct ProjectConfiguration {pub aspect_ratio: Option<AspectRatio>,pub background: BackgroundConfiguration,@@ -589,23 +579,8 @@ impl ProjectConfiguration {pub fn get_segment_time(&self, frame_time: f64) -> Option<(f64, u32)> {self.timeline.as_ref()- .map(|t| t.get_segment_time(frame_time as f64))- .unwrap_or(Some((frame_time as f64, 0)))- }-}--impl Default for ProjectConfiguration {- fn default() -> Self {- ProjectConfiguration {- aspect_ratio: None,- background: BackgroundConfiguration::default(),- camera: Camera::default(),- audio: AudioConfiguration::default(),- cursor: CursorConfiguration::default(),- hotkeys: HotkeysConfiguration::default(),- timeline: None,- captions: None,- }+ .map(|t| t.get_segment_time(frame_time))+ .unwrap_or(Some((frame_time, 0)))}}diff --git a/crates/project/src/cursor.rs b/crates/project/src/cursor.rsindex bc9fa4802..db636b3be 100644--- a/crates/project/src/cursor.rs+++ b/crates/project/src/cursor.rs@@ -55,8 +55,8 @@ pub struct CursorData {impl CursorData {pub fn load_from_file(path: &Path) -> Result<Self, String> {- let file = File::open(path).map_err(|e| format!("Failed to open cursor file: {}", e))?;- serde_json::from_reader(file).map_err(|e| format!("Failed to parse cursor data: {}", e))+ let file = File::open(path).map_err(|e| format!("Failed to open cursor file: {e}"))?;+ serde_json::from_reader(file).map_err(|e| format!("Failed to parse cursor data: {e}"))}}@@ -68,13 +68,13 @@ pub struct CursorEvents {impl CursorEvents {pub fn load_from_file(path: &Path) -> Result<Self, String> {- let file = File::open(path).map_err(|e| format!("Failed to open cursor file: {}", e))?;- serde_json::from_reader(file).map_err(|e| format!("Failed to parse cursor data: {}", e))+ let file = File::open(path).map_err(|e| format!("Failed to open cursor file: {e}"))?;+ serde_json::from_reader(file).map_err(|e| format!("Failed to parse cursor data: {e}"))}pub fn cursor_position_at(&self, time: f64) -> Option<XY<f64>> {// Debug print to understand what we're looking for- println!("Looking for cursor position at time: {}", time);+ println!("Looking for cursor position at time: {time}");println!("Total cursor events: {}", self.moves.len());// Check if we have any move events at alldiff --git a/crates/project/src/meta.rs b/crates/project/src/meta.rsindex 583d41be1..15c08e095 100644--- a/crates/project/src/meta.rs+++ b/crates/project/src/meta.rs@@ -91,10 +91,10 @@ impl RecordingMeta {pub fn path(&self, relative: &RelativePathBuf) -> PathBuf {relative.to_path(&self.project_path)}- pub fn load_for_project(project_path: &PathBuf) -> Result<Self, Box<dyn Error>> {+ pub fn load_for_project(project_path: &Path) -> Result<Self, Box<dyn Error>> {let meta_path = project_path.join("recording-meta.json");let mut meta: Self = serde_json::from_str(&std::fs::read_to_string(&meta_path)?)?;- meta.project_path = project_path.clone();+ meta.project_path = project_path.to_path_buf();Ok(meta)}@@ -140,7 +140,7 @@ impl RecordingMeta {pub fn studio_meta(&self) -> Option<&StudioRecordingMeta> {match &self.inner {- RecordingMetaInner::Studio(meta) => Some(&meta),+ RecordingMetaInner::Studio(meta) => Some(meta),_ => None,}}@@ -296,7 +296,7 @@ impl MultipleSegment {match CursorEvents::load_from_file(&full_path) {Ok(data) => data,Err(e) => {- eprintln!("Failed to load cursor data: {}", e);+ eprintln!("Failed to load cursor data: {e}");CursorEvents::default()}}diff --git a/crates/recording/Cargo.toml b/crates/recording/Cargo.tomlindex 11385c7b1..b28f975ee 100644--- a/crates/recording/Cargo.toml+++ b/crates/recording/Cargo.toml@@ -1,7 +1,7 @@[package]name = "cap-recording"version = "0.1.0"-edition = "2021"+edition = "2024"[lints]workspace = truediff --git a/crates/recording/examples/recording-cli.rs b/crates/recording/examples/recording-cli.rsindex 469812a06..5e0dbae0b 100644--- a/crates/recording/examples/recording-cli.rs+++ b/crates/recording/examples/recording-cli.rs@@ -14,7 +14,7 @@ pub async fn main() {println!("Recording to directory '{}'", dir.path().display());- let (handle, ready_rx) = cap_recording::spawn_studio_recording_actor(+ let (handle, _ready_rx) = cap_recording::spawn_studio_recording_actor("test".to_string(),dir.path().into(),RecordingBaseInputs {diff --git a/crates/recording/src/capture_pipeline.rs b/crates/recording/src/capture_pipeline.rsindex cf8680b23..fc7a31f64 100644--- a/crates/recording/src/capture_pipeline.rs+++ b/crates/recording/src/capture_pipeline.rs@@ -1,25 +1,22 @@use std::{future::Future,path::PathBuf,- sync::{atomic::AtomicBool, Arc},+ sync::{Arc, atomic::AtomicBool},time::SystemTime,};use cap_media::{+ MediaError,feeds::AudioInputFeed,- pipeline::{builder::PipelineBuilder, RealTimeClock},+ pipeline::{RealTimeClock, builder::PipelineBuilder},sources::{- AVFrameCapture, AudioInputSource, AudioMixer, CMSampleBufferCapture, ScreenCaptureFormat,- ScreenCaptureSource, ScreenCaptureTarget,+ AVFrameCapture, AudioInputSource, AudioMixer, ScreenCaptureFormat, ScreenCaptureSource,+ ScreenCaptureTarget,},- MediaError,};use cap_media_encoders::{AACEncoder, AudioEncoder, H264Encoder, MP4File};use cap_media_info::AudioInfo;-use ffmpeg::ffi::AV_TIME_BASE_Q;use flume::{Receiver, Sender};-use tokio::sync::oneshot;-use tracing::error;use crate::RecordingError;@@ -67,7 +64,7 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {"screen",screen_config,None,- output_path.into(),+ output_path,None,).map_err(|e| MediaError::Any(e.to_string().into()))?;@@ -75,8 +72,6 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {let (timestamp_tx, timestamp_rx) = flume::bounded(1);builder.spawn_task("screen_capture_encoder", move |ready| {- use std::time::Duration;-let mut timestamp_tx = Some(timestamp_tx);let _ = ready.send(Ok(()));@@ -89,8 +84,6 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {}let result = loop {- use flume::RecvTimeoutError;-match source.1.recv() {Ok(frame) => {let _ = screen_encoder.queue_video_frame(frame.0.as_ref());@@ -146,15 +139,18 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {"mp4",source.0.info(),has_audio_sources.then_some(AudioMixer::info()),- output_path.into(),+ output_path,Some(1080),).map_err(|e| MediaError::Any(e.to_string().into()))?,));use cidre::cm;+ use ffmpeg::ffi::AV_TIME_BASE_Q;+ use tracing::error;- let (first_frame_tx, mut first_frame_rx) = oneshot::channel::<(cm::Time, f64)>();+ let (first_frame_tx, mut first_frame_rx) =+ tokio::sync::oneshot::channel::<(cm::Time, f64)>();if has_audio_sources {builder.spawn_source("audio_mixer", audio_mixer);@@ -184,11 +180,11 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {frame.set_pts(Some(time.value / (time.scale / AV_TIME_BASE_Q.den) as i64));- if let Ok(mut mp4) = mp4.lock() {- if let Err(e) = mp4.queue_audio_frame(frame) {- error!("{e}");- return Ok(());- }+ if let Ok(mut mp4) = mp4.lock()+ && let Err(e) = mp4.queue_audio_frame(frame)+ {+ error!("{e}");+ return Ok(());}}@@ -211,7 +207,9 @@ impl MakeCapturePipeline for cap_media::sources::CMSampleBufferCapture {let _ = first_frame_tx.send((frame.pts(), unix_time));}- mp4.queue_video_frame(frame.as_ref());+ mp4.queue_video_frame(frame.as_ref())+ .map_err(|err| error!("Error queueing video frame: {err}"))+ .ok();}}if let Ok(mut mp4) = mp4.lock() {@@ -242,7 +240,7 @@ impl MakeCapturePipeline for AVFrameCapture {let screen_config = source.0.info();let mut screen_encoder = MP4File::init("screen",- output_path.into(),+ output_path,|o| H264Encoder::builder("screen", screen_config).build(o),|_| None,)@@ -303,7 +301,7 @@ impl MakeCapturePipeline for AVFrameCapture {let mp4 = Arc::new(std::sync::Mutex::new(MP4File::init("screen",- output_path.into(),+ output_path,|o| H264Encoder::builder("screen", screen_config).build(o),|o| {has_audio_sources.then(|| {@@ -335,7 +333,7 @@ impl MakeCapturePipeline for AVFrameCapture {builder.spawn_task("screen_encoder", move |ready| {let _ = ready.send(Ok(()));- while let Ok((frame, unix_time)) = source.1.recv() {+ while let Ok((frame, _unix_time)) = source.1.recv() {if let Ok(mut mp4) = mp4.lock() {// if pause_flag.load(std::sync::atomic::Ordering::Relaxed) {// mp4.pause();@@ -362,7 +360,7 @@ type ScreenCaptureReturn<T> = ();#[cfg(target_os = "macos")]-pub type ScreenCaptureMethod = CMSampleBufferCapture;+pub type ScreenCaptureMethod = cap_media::sources::CMSampleBufferCapture;#[cfg(not(target_os = "macos"))]pub type ScreenCaptureMethod = AVFrameCapture;diff --git a/crates/recording/src/cursor.rs b/crates/recording/src/cursor.rsindex ab67b39f2..dd2cc7f94 100644--- a/crates/recording/src/cursor.rs+++ b/crates/recording/src/cursor.rs@@ -1,23 +1,10 @@-use std::{- collections::HashMap,- hash::{DefaultHasher, Hash, Hasher},- path::PathBuf,- pin::pin,- time::{Duration, SystemTime},-};--use cap_cursor_capture::RawCursorPosition;+use std::{collections::HashMap, path::PathBuf, time::SystemTime};+use cap_cursor_info::CursorShape;-use cap_displays::Display;-use cap_media::{platform::Bounds, sources::CropRatio};+use cap_media::platform::Bounds;use cap_project::{CursorClickEvent, CursorMoveEvent, XY};-use cap_utils::spawn_actor;-use device_query::{DeviceQuery, DeviceState};-use futures::future::Either;-use sha2::{Digest, Sha256};use tokio::sync::oneshot;use tokio_util::sync::CancellationToken;-use tracing::{error, info};pub struct Cursor {pub file_name: String,@@ -51,13 +38,24 @@ impl CursorActor {#[tracing::instrument(name = "cursor", skip_all)]pub fn spawn_cursor_recorder(#[allow(unused)] screen_bounds: Bounds,- #[cfg(target_os = "macos")] display: Display,- #[cfg(target_os = "macos")] crop_ratio: CropRatio,+ #[cfg(target_os = "macos")] display: cap_displays::Display,+ #[cfg(target_os = "macos")] crop_ratio: cap_media::sources::CropRatio,cursors_dir: PathBuf,prev_cursors: Cursors,next_cursor_id: u32,start_time: SystemTime,) -> CursorActor {+ use std::{+ hash::{DefaultHasher, Hash, Hasher},+ pin::pin,+ time::Duration,+ };++ use cap_utils::spawn_actor;+ use device_query::{DeviceQuery, DeviceState};+ use futures::future::Either;+ use tracing::{error, info};+let stop_token = CancellationToken::new();let (tx, rx) = oneshot::channel();@@ -67,7 +65,7 @@ pub fn spawn_cursor_recorder(let mut last_mouse_state = device_state.get_mouse();#[cfg(target_os = "macos")]- let mut last_position = RawCursorPosition::get();+ let mut last_position = cap_cursor_capture::RawCursorPosition::get();// Create cursors directory if it doesn't existstd::fs::create_dir_all(&cursors_dir).unwrap();@@ -105,7 +103,7 @@ pub fn spawn_cursor_recorder(} else {// New cursor data - save itlet cursor_id = response.next_cursor_id.to_string();- let file_name = format!("cursor_{}.png", cursor_id);+ let file_name = format!("cursor_{cursor_id}.png");let cursor_path = cursors_dir.join(&file_name);if let Ok(image) = image::load_from_memory(&data.image) {@@ -138,7 +136,7 @@ pub fn spawn_cursor_recorder(// TODO: use this on windows too#[cfg(target_os = "macos")]let position = {- let position = RawCursorPosition::get();+ let position = cap_cursor_capture::RawCursorPosition::get();if position != last_position {last_position = position;@@ -251,6 +249,7 @@ struct CursorData {fn get_cursor_data() -> Option<CursorData> {use objc::rc::autoreleasepool;use objc2_app_kit::NSCursor;+ use sha2::{Digest, Sha256};autoreleasepool(|| unsafe {#[allow(deprecated)]@@ -259,9 +258,7 @@ fn get_cursor_data() -> Option<CursorData> {let image = cursor.image();let size = image.size();let hotspot = cursor.hotSpot();- let Some(image_data) = image.TIFFRepresentation() else {- return None;- };+ let image_data = image.TIFFRepresentation()?;let image = image_data.as_bytes_unchecked().to_vec();@@ -280,11 +277,11 @@ fn get_cursor_data() -> Option<CursorData> {fn get_cursor_data() -> Option<CursorData> {use windows::Win32::Foundation::{HWND, POINT};use windows::Win32::Graphics::Gdi::{- CreateCompatibleDC, CreateDIBSection, DeleteDC, DeleteObject, GetDC, GetObjectA, ReleaseDC,- SelectObject, BITMAP, BITMAPINFO, BITMAPINFOHEADER, DIB_RGB_COLORS,+ BITMAP, BITMAPINFO, BITMAPINFOHEADER, CreateCompatibleDC, CreateDIBSection, DIB_RGB_COLORS,+ DeleteDC, DeleteObject, GetDC, GetObjectA, ReleaseDC, SelectObject,};- use windows::Win32::UI::WindowsAndMessaging::{DrawIconEx, GetIconInfo, DI_NORMAL, ICONINFO};- use windows::Win32::UI::WindowsAndMessaging::{GetCursorInfo, CURSORINFO, CURSORINFO_FLAGS};+ use windows::Win32::UI::WindowsAndMessaging::{CURSORINFO, CURSORINFO_FLAGS, GetCursorInfo};+ use windows::Win32::UI::WindowsAndMessaging::{DI_NORMAL, DrawIconEx, GetIconInfo, ICONINFO};unsafe {// Get cursor info@@ -325,10 +322,10 @@ fn get_cursor_data() -> Option<CursorData> {{// Clean up handlesif !icon_info.hbmColor.is_invalid() {- DeleteObject(icon_info.hbmColor.into());+ let _ = DeleteObject(icon_info.hbmColor.into());}if !icon_info.hbmMask.is_invalid() {- DeleteObject(icon_info.hbmMask.into());+ let _ = DeleteObject(icon_info.hbmMask.into());}return None;}@@ -379,13 +376,13 @@ fn get_cursor_data() -> Option<CursorData> {if dib.is_err() {// Clean up- DeleteDC(mem_dc);+ let _ = DeleteDC(mem_dc);ReleaseDC(Some(HWND::default()), screen_dc);if !icon_info.hbmColor.is_invalid() {- DeleteObject(icon_info.hbmColor.into());+ let _ = DeleteObject(icon_info.hbmColor.into());}if !icon_info.hbmMask.is_invalid() {- DeleteObject(icon_info.hbmMask.into());+ let _ = DeleteObject(icon_info.hbmMask.into());}return None;}@@ -411,14 +408,14 @@ fn get_cursor_data() -> Option<CursorData> {{// Clean upSelectObject(mem_dc, old_bitmap);- DeleteObject(dib.into());- DeleteDC(mem_dc);+ let _ = DeleteObject(dib.into());+ let _ = DeleteDC(mem_dc);ReleaseDC(Some(HWND::default()), screen_dc);if !icon_info.hbmColor.is_invalid() {- DeleteObject(icon_info.hbmColor.into());+ let _ = DeleteObject(icon_info.hbmColor.into());}if !icon_info.hbmMask.is_invalid() {- DeleteObject(icon_info.hbmMask.into());+ let _ = DeleteObject(icon_info.hbmMask.into());}return None;}@@ -429,13 +426,13 @@ fn get_cursor_data() -> Option<CursorData> {std::ptr::copy_nonoverlapping(bits, image_data.as_mut_ptr() as *mut _, size);// Calculate hotspot- let mut hotspot_x = if icon_info.fIcon.as_bool() == false {+ let mut hotspot_x = if !icon_info.fIcon.as_bool() {icon_info.xHotspot as f64 / width as f64} else {0.5};- let mut hotspot_y = if icon_info.fIcon.as_bool() == false {+ let mut hotspot_y = if !icon_info.fIcon.as_bool() {icon_info.yHotspot as f64 / height as f64} else {0.5@@ -443,23 +440,21 @@ fn get_cursor_data() -> Option<CursorData> {// CleanupSelectObject(mem_dc, old_bitmap);- DeleteObject(dib.into());- DeleteDC(mem_dc);+ let _ = DeleteObject(dib.into());+ let _ = DeleteDC(mem_dc);ReleaseDC(Some(HWND::default()), screen_dc);if !icon_info.hbmColor.is_invalid() {- DeleteObject(icon_info.hbmColor.into());+ let _ = DeleteObject(icon_info.hbmColor.into());}if !icon_info.hbmMask.is_invalid() {- DeleteObject(icon_info.hbmMask.into());+ let _ = DeleteObject(icon_info.hbmMask.into());}// Process the image data to ensure proper alpha channelfor i in (0..size).step_by(4) {// Windows DIB format is BGRA, we need to:// 1. Swap B and R channels- let b = image_data[i];- image_data[i] = image_data[i + 2]; // B <- R- image_data[i + 2] = b; // R <- B+ image_data.swap(i, i + 2); // R <- B// 2. Pre-multiply alpha if needed// This is already handled by DrawIconEx@@ -489,8 +484,8 @@ fn get_cursor_data() -> Option<CursorData> {// Skip if out of bounds or same pixelif nx < 0|| ny < 0- || nx >= width as i32- || ny >= height as i32+ || nx >= width+ || ny >= height|| (*dx == 0 && *dy == 0){continue;diff --git a/crates/recording/src/instant_recording.rs b/crates/recording/src/instant_recording.rsindex 8be7882ab..eb90c59a9 100644--- a/crates/recording/src/instant_recording.rs+++ b/crates/recording/src/instant_recording.rs@@ -1,30 +1,31 @@use std::{path::PathBuf,- sync::{atomic::AtomicBool, Arc},+ sync::{Arc, atomic::AtomicBool},time::{SystemTime, UNIX_EPOCH},};use cap_media::{+ MediaError,feeds::AudioInputFeed,pipeline::{Pipeline, RealTimeClock},platform::Bounds,sources::{ScreenCaptureSource, ScreenCaptureTarget},- MediaError,};use cap_media_info::VideoInfo;use cap_project::InstantRecordingMeta;use cap_utils::{ensure_dir, spawn_actor};use flume::Receiver;use tokio::sync::oneshot;-use tracing::{debug, error, info, trace, Instrument};+use tracing::{Instrument, debug, error, info, trace};use crate::{- capture_pipeline::{create_screen_capture, MakeCapturePipeline},ActorError, RecordingBaseInputs, RecordingError,+ capture_pipeline::{MakeCapturePipeline, create_screen_capture},};struct InstantRecordingPipeline {pub inner: Pipeline<RealTimeClock<()>>,+ #[allow(unused)]pub output_path: PathBuf,pub pause_flag: Arc<AtomicBool>,}@@ -252,7 +253,7 @@ pub async fn spawn_instant_recording_actor<'a>(InstantRecordingHandle {ctrl_tx,capture_target: inputs.capture_target,- bounds: screen_source.get_bounds().clone(),+ bounds: *screen_source.get_bounds(),},done_rx,))diff --git a/crates/recording/src/lib.rs b/crates/recording/src/lib.rsindex 8cc6c065f..e4258a43c 100644--- a/crates/recording/src/lib.rs+++ b/crates/recording/src/lib.rs@@ -3,21 +3,13 @@ pub mod cursor;pub mod instant_recording;pub mod studio_recording;-use std::sync::Arc;-pub use studio_recording::{- spawn_studio_recording_actor, CompletedStudioRecording, StudioRecordingHandle,+ CompletedStudioRecording, StudioRecordingHandle, spawn_studio_recording_actor,};-use cap_media::{- feeds::{AudioInputFeed, CameraFeed},- platform::Bounds,- sources::*,- MediaError,-};+use cap_media::{MediaError, feeds::AudioInputFeed, platform::Bounds, sources::*};use serde::{Deserialize, Serialize};use thiserror::Error;-use tokio::sync::Mutex;#[derive(specta::Type, Serialize, Deserialize, Clone, Debug, Copy)]#[serde(rename_all = "camelCase")]diff --git a/crates/recording/src/studio_recording.rs b/crates/recording/src/studio_recording.rsindex 80413acb3..8be8add85 100644--- a/crates/recording/src/studio_recording.rs+++ b/crates/recording/src/studio_recording.rs@@ -1,16 +1,16 @@use std::{collections::HashMap,- path::PathBuf,+ path::{Path, PathBuf},sync::Arc,time::{Duration, Instant, SystemTime, UNIX_EPOCH},};use cap_media::{+ MediaError,feeds::{AudioInputFeed, CameraFeed},pipeline::{Pipeline, RealTimeClock},platform::Bounds,sources::{AudioInputSource, CameraSource, ScreenCaptureFormat, ScreenCaptureTarget},- MediaError,};use cap_media_encoders::{H264Encoder, MP4File, OggFile, OpusEncoder};use cap_media_info::VideoInfo;@@ -18,15 +18,16 @@ use cap_project::{CursorEvents, StudioRecordingMeta};use cap_utils::spawn_actor;use flume::Receiver;use relative_path::RelativePathBuf;-use tokio::sync::{oneshot, Mutex};+use tokio::sync::{Mutex, oneshot};use tracing::{debug, info, trace};use crate::{- capture_pipeline::{create_screen_capture, MakeCapturePipeline, ScreenCaptureMethod},- cursor::{spawn_cursor_recorder, CursorActor, Cursors},ActorError, RecordingBaseInputs, RecordingError,+ capture_pipeline::{MakeCapturePipeline, ScreenCaptureMethod, create_screen_capture},+ cursor::{CursorActor, Cursors, spawn_cursor_recorder},};+#[allow(clippy::large_enum_variant)]enum StudioRecordingActorState {Recording {pipeline: StudioRecordingPipeline,@@ -54,6 +55,7 @@ pub struct StudioRecordingActor {recording_dir: PathBuf,fps: u32,segments: Vec<StudioRecordingSegment>,+ #[allow(unused)]start_instant: Instant,}@@ -162,7 +164,7 @@ pub async fn spawn_studio_recording_actor<'a>(let mut segment_pipeline_factory = SegmentPipelineFactory::new(segments_dir,cursors_dir,- base_inputs.capture_target.clone(),+ base_inputs.capture_target,audio_input_feed,base_inputs.capture_system_audio,camera_feed,@@ -319,11 +321,10 @@ async fn run_actor_iteration(result = &mut pipeline_done_rx => {return match result {Ok(Ok(())) => {- if let Some(cursor) = &mut pipeline.cursor {- if let Some(actor) = cursor.actor.take() {+ if let Some(cursor) = &mut pipeline.cursor+ && let Some(actor) = cursor.actor.take() {actor.stop().await;}- }Ok(None)},@@ -374,7 +375,7 @@ async fn run_actor_iteration(Err(e) => (Err(e), HashMap::new(), 0),};- send_response!(tx, res.map_err(Into::into));+ send_response!(tx, res);Some((State::Paused {@@ -440,7 +441,7 @@ async fn run_actor_iteration())}Err(e) => {- send_response!(tx, Err(e.into()));+ send_response!(tx, Err(e));None}}@@ -476,8 +477,7 @@ async fn stop_recording(use cap_project::*;let make_relative = |path: &PathBuf| {- RelativePathBuf::from_path(path.strip_prefix(&actor.recording_dir).unwrap().to_owned())- .unwrap()+ RelativePathBuf::from_path(path.strip_prefix(&actor.recording_dir).unwrap()).unwrap()};let recv_timestamp = |pipeline: &PipelineOutput| pipeline.first_timestamp_rx.try_recv().ok();@@ -501,7 +501,7 @@ async fn stop_recording(}),mic: s.pipeline.microphone.as_ref().map(|mic| AudioMeta {path: make_relative(&mic.path),- start_time: recv_timestamp(&mic),+ start_time: recv_timestamp(mic),}),cursor: s.pipeline@@ -563,6 +563,7 @@ struct SegmentPipelineFactory {}impl SegmentPipelineFactory {+ #[allow(clippy::too_many_arguments)]pub fn new(segments_dir: PathBuf,cursors_dir: PathBuf,@@ -622,9 +623,10 @@ impl SegmentPipelineFactory {}#[tracing::instrument(skip_all, name = "segment", fields(index = index))]+#[allow(clippy::too_many_arguments)]async fn create_segment_pipeline(segments_dir: &PathBuf,- cursors_dir: &PathBuf,+ cursors_dir: &Path,index: u32,capture_target: ScreenCaptureTarget,mic_feed: &Option<AudioInputFeed>,@@ -658,6 +660,7 @@ async fn create_segment_pipeline(start_time,).await?;+ #[cfg(target_os = "macos")]let screen_crop_ratio = screen_source.crop_ratio();let camera_feed = match camera_feed.as_ref() {@@ -676,7 +679,7 @@ async fn create_segment_pipeline(trace!("preparing segment pipeline {index}");let screen = {- let bounds = screen_source.get_bounds().clone();+ let bounds = *screen_source.get_bounds();let video_info = screen_source.info();let (pipeline_builder_, screen_timestamp_rx) =@@ -690,7 +693,7 @@ async fn create_segment_pipeline(info!(r#"screen pipeline prepared, will output to "{}""#,screen_output_path- .strip_prefix(&segments_dir)+ .strip_prefix(segments_dir).unwrap().display());@@ -740,7 +743,7 @@ async fn create_segment_pipeline(info!("mic pipeline prepared, will output to {}",- output_path.strip_prefix(&segments_dir).unwrap().display()+ output_path.strip_prefix(segments_dir).unwrap().display());Some(PipelineOutput {@@ -835,7 +838,7 @@ async fn create_segment_pipeline(info!("camera pipeline prepared, will output to {}",- output_path.strip_prefix(&segments_dir).unwrap().display()+ output_path.strip_prefix(segments_dir).unwrap().display());Some(CameraPipelineInfo {@@ -851,7 +854,7 @@ async fn create_segment_pipeline(let cursor = custom_cursor_capture.then(move || {let cursor = spawn_cursor_recorder(- screen.bounds.clone(),+ screen.bounds,#[cfg(target_os = "macos")]cap_displays::Display::list().into_iter()@@ -868,7 +871,7 @@ async fn create_segment_pipeline(.unwrap(),#[cfg(target_os = "macos")]screen_crop_ratio,- cursors_dir.clone(),+ cursors_dir.to_path_buf(),prev_cursors,next_cursors_id,start_time,@@ -905,7 +908,7 @@ struct CameraPipelineInfo {}fn ensure_dir(path: &PathBuf) -> Result<PathBuf, MediaError> {- std::fs::create_dir_all(&path)?;+ std::fs::create_dir_all(path)?;Ok(path.clone())}diff --git a/crates/rendering-skia/Cargo.toml b/crates/rendering-skia/Cargo.tomlindex 69f43ca41..ba93ea32f 100644--- a/crates/rendering-skia/Cargo.toml+++ b/crates/rendering-skia/Cargo.toml@@ -1,7 +1,7 @@[package]name = "cap-rendering-skia"version = "0.1.0"-edition = "2021"+edition = "2024"[lints]workspace = true@@ -13,13 +13,14 @@ tracing.workspace = truefutures = "0.3"# Skia dependencies-skia-safe = { version = "0.86.1", features = ["metal"] }+skia-safe = "0.86.1"tracing-subscriber = "0.3"# Project dependenciescap-project = { path = "../project" }[target.'cfg(target_os = "macos")'.dependencies]+skia-safe = { version = "0.86.1", features = ["metal"] }metal = "0.27"foreign-types-shared = "0.3"@@ -29,4 +30,4 @@ path = "src/bin/test_skia.rs"[[bin]]name = "test-background"-path = "src/bin/test_background.rs"\ No newline at end of file+path = "src/bin/test_background.rs"diff --git a/crates/rendering-skia/src/bin/test_background.rs b/crates/rendering-skia/src/bin/test_background.rsindex 0df1657a3..16ac9f6d1 100644--- a/crates/rendering-skia/src/bin/test_background.rs+++ b/crates/rendering-skia/src/bin/test_background.rs@@ -21,7 +21,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {// Create output directorylet output_dir = "test_output";fs::create_dir_all(output_dir)?;- println!("✓ Created output directory: {}", output_dir);+ println!("✓ Created output directory: {output_dir}");// Test 1: Solid Color Backgroundprintln!("\n1. Testing solid color background...");@@ -40,7 +40,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {test_caching(&mut context, width, height)?;println!("\n=== All tests completed successfully! ===");- println!("Check the '{}' directory for output images.", output_dir);+ println!("Check the '{output_dir}' directory for output images.");Ok(())}@@ -99,12 +99,12 @@ fn test_color_background();match image.encode(context.direct_context(), EncodedImageFormat::PNG, 100) {Some(data) => {- let path = format!("{}/background_color_{}.png", output_dir, name);+ let path = format!("{output_dir}/background_color_{name}.png");fs::write(&path, data.as_bytes())?;- println!(" ✓ Saved {} background to: {}", name, path);+ println!(" ✓ Saved {name} background to: {path}");}None => {- println!(" ✗ Failed to encode {} color image to PNG", name);+ println!(" ✗ Failed to encode {name} color image to PNG");}}}@@ -161,9 +161,9 @@ fn test_gradient_background();match image.encode(context.direct_context(), EncodedImageFormat::PNG, 100) {Some(data) => {- let path = format!("{}/background_gradient.png", output_dir);+ let path = format!("{output_dir}/background_gradient.png");fs::write(&path, data.as_bytes())?;- println!(" ✓ Saved gradient background to: {}", path);+ println!(" ✓ Saved gradient background to: {path}");}None => {println!(" ✗ Failed to encode gradient image to PNG");@@ -231,13 +231,10 @@ fn test_gradient_angles(output_dir, angle as i32);fs::write(&path, data.as_bytes())?;- println!(" ✓ Saved gradient with angle {} to: {}", angle, path);+ println!(" ✓ Saved gradient with angle {angle} to: {path}");}None => {- println!(- " ✗ Failed to encode gradient angle {} image to PNG",- angle- );+ println!(" ✗ Failed to encode gradient angle {angle} image to PNG");}}}@@ -280,7 +277,7 @@ fn test_caching(let canvas = surface.canvas();layer_stack.render(canvas, &uniforms);let first_render_time = start.elapsed();- println!(" Time: {:?}", first_render_time);+ println!(" Time: {first_render_time:?}");// Second render with same uniforms - should use cacheprintln!(" - Second render (using cache)...");@@ -288,7 +285,7 @@ fn test_caching(let canvas = surface.canvas();layer_stack.render(canvas, &uniforms);let cached_render_time = start.elapsed();- println!(" Time: {:?}", cached_render_time);+ println!(" Time: {cached_render_time:?}");// Cache should make it fasterif cached_render_time < first_render_time {@@ -323,7 +320,7 @@ fn test_caching(let canvas = surface.canvas();layer_stack.render(canvas, &new_uniforms);let new_render_time = start.elapsed();- println!(" Time: {:?}", new_render_time);+ println!(" Time: {new_render_time:?}");Ok(())}diff --git a/crates/rendering-skia/src/bin/test_skia.rs b/crates/rendering-skia/src/bin/test_skia.rsindex 12f183836..554680cb6 100644--- a/crates/rendering-skia/src/bin/test_skia.rs+++ b/crates/rendering-skia/src/bin/test_skia.rs@@ -16,7 +16,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {ctx}Err(e) => {- println!(" ✗ Failed to create Skia context: {}", e);+ println!(" ✗ Failed to create Skia context: {e}");return Err(e.into());}};@@ -35,10 +35,10 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {for (width, height) in test_sizes {match context.create_surface(width, height) {Ok(_) => {- println!(" ✓ Created {}x{} surface", width, height);+ println!(" ✓ Created {width}x{height} surface");}Err(e) => {- println!(" ✗ Failed to create {}x{} surface: {}", width, height, e);+ println!(" ✗ Failed to create {width}x{height} surface: {e}");}}}@@ -53,7 +53,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {println!(" ✓ Correctly rejected invalid dimensions");}Err(e) => {- println!(" ✗ Wrong error type: {}", e);+ println!(" ✗ Wrong error type: {e}");}}@@ -74,14 +74,14 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {// Save as PPM for easy verificationlet output_path = "test_render.ppm";save_as_ppm(&pixels, render_width, render_height, output_path)?;- println!(" ✓ Saved test render to: {}", output_path);+ println!(" ✓ Saved test render to: {output_path}");// Verify some pixelsprintln!("\n5. Verifying pixel data...");let center_idx =(((render_height / 2) * render_width + (render_width / 2)) * 4) as usize;let center_pixel = &pixels[center_idx..center_idx + 4];- println!(" - Center pixel RGBA: {:?}", center_pixel);+ println!(" - Center pixel RGBA: {center_pixel:?}");// The center should be greenish (from the circle)if center_pixel[1] > center_pixel[0] && center_pixel[1] > center_pixel[2] {@@ -91,7 +91,7 @@ fn main() -> Result<(), Box<dyn std::error::Error>> {}}Err(e) => {- println!(" ✗ Rendering failed: {}", e);+ println!(" ✗ Rendering failed: {e}");return Err(e.into());}}@@ -109,7 +109,7 @@ fn save_as_ppm(pixels: &[u8], width: u32, height: u32, path: &str) -> std::io::R// PPM headerwriteln!(file, "P3")?;- writeln!(file, "{} {}", width, height)?;+ writeln!(file, "{width} {height}")?;writeln!(file, "255")?;// Write pixels (PPM is RGB, our data is RGBA)@@ -119,7 +119,7 @@ fn save_as_ppm(pixels: &[u8], width: u32, height: u32, path: &str) -> std::io::Rlet r = pixels[idx];let g = pixels[idx + 1];let b = pixels[idx + 2];- write!(file, "{} {} {} ", r, g, b)?;+ write!(file, "{r} {g} {b} ")?;}writeln!(file)?;}diff --git a/crates/rendering-skia/src/context.rs b/crates/rendering-skia/src/context.rsindex fbc45c93c..19e209340 100644--- a/crates/rendering-skia/src/context.rs+++ b/crates/rendering-skia/src/context.rs@@ -1,8 +1,8 @@use crate::SkiaRenderingError;-use skia_safe::{gpu, surfaces, Color, Surface};+use skia_safe::{Color, Surface, gpu::DirectContext, surfaces};#[cfg(target_os = "macos")]-use skia_safe::gpu::{mtl, DirectContext, SurfaceOrigin};+use skia_safe::gpu::{SurfaceOrigin, mtl};pub struct SkiaRenderContext {#[cfg(target_os = "macos")]@@ -52,6 +52,7 @@ impl SkiaRenderContext {#[cfg(target_os = "macos")]fn create_metal_context() -> Result<GpuContext, SkiaRenderingError> {use foreign_types_shared::ForeignType;+ use skia_safe::gpu;let device =metal::Device::system_default().ok_or_else(|| SkiaRenderingError::NoGpuContext)?;@@ -82,13 +83,14 @@ impl SkiaRenderContext {) -> Result<Surface, SkiaRenderingError> {if width == 0 || height == 0 {return Err(SkiaRenderingError::InvalidDimensions(format!(- "Invalid surface dimensions: {}x{}",- width, height+ "Invalid surface dimensions: {width}x{height}")));}#[cfg(target_os = "macos")]{+ use skia_safe::gpu;+if let Some(ref mut gpu_context) = self.gpu_context {tracing::debug!("Creating GPU surface with dimensions {}x{}", width, height);@@ -109,8 +111,7 @@ impl SkiaRenderContext {).ok_or_else(|| {SkiaRenderingError::SurfaceCreationFailed(format!(- "Failed to create {}x{} GPU surface",- width, height+ "Failed to create {width}x{height} GPU surface"))});}@@ -120,8 +121,7 @@ impl SkiaRenderContext {tracing::debug!("Creating CPU surface with dimensions {}x{}", width, height);surfaces::raster_n32_premul((width as i32, height as i32)).ok_or_else(|| {SkiaRenderingError::SurfaceCreationFailed(format!(- "Failed to create {}x{} surface",- width, height+ "Failed to create {width}x{height} surface"))})}diff --git a/crates/rendering-skia/src/layers/background.rs b/crates/rendering-skia/src/layers/background.rsindex 0c35d5b91..5ce87ccc7 100644--- a/crates/rendering-skia/src/layers/background.rs+++ b/crates/rendering-skia/src/layers/background.rs@@ -1,5 +1,5 @@-use crate::layers::{FrameData, RecordableLayer, SkiaProjectUniforms};use crate::SkiaRenderingError;+use crate::layers::{FrameData, RecordableLayer, SkiaProjectUniforms};use cap_project::BackgroundSource;use skia_safe::{Canvas, Color, Image, Paint, Picture, PictureRecorder, Point, Rect, Shader, TileMode,@@ -229,7 +229,7 @@ impl RecordableLayer for BackgroundLayer {// Handle image loading if neededmatch &new_background {- Background::Image { ref path } | Background::Wallpaper { ref path } => {+ Background::Image { path } | Background::Wallpaper { path } => {if self.image_path.as_ref() != Some(path) || self.loaded_image.is_none() {// For now, we'll do synchronous loading. In a real implementation,// this should be async or cached at a higher leveldiff --git a/crates/rendering-skia/src/layers/mod.rs b/crates/rendering-skia/src/layers/mod.rsindex 724acc191..0e3ecac81 100644--- a/crates/rendering-skia/src/layers/mod.rs+++ b/crates/rendering-skia/src/layers/mod.rs@@ -182,10 +182,10 @@ impl LayerStack {}}LayerEntry::Surface(layer) => {- if layer.is_enabled() {- if let Some(picture) = layer.render_to_surface(uniforms) {- layer.composite(canvas, &picture, uniforms);- }+ if layer.is_enabled()+ && let Some(picture) = layer.render_to_surface(uniforms)+ {+ layer.composite(canvas, &picture, uniforms);}}}diff --git a/crates/rendering/src/composite_frame.rs b/crates/rendering/src/composite_frame.rsindex 02b0ff9bc..992246caa 100644--- a/crates/rendering/src/composite_frame.rs+++ b/crates/rendering/src/composite_frame.rs@@ -40,12 +40,12 @@ impl CompositeVideoFrameUniforms {}}-pub struct CompositeFrameResources {- pub bind_group: wgpu::BindGroup,- pub bind_group_layout: wgpu::BindGroupLayout,- pub uniforms_buffer: wgpu::Buffer,- pub sampler: wgpu::Sampler,-}+// pub struct CompositeFrameResources {+// pub bind_group: wgpu::BindGroup,+// pub bind_group_layout: wgpu::BindGroupLayout,+// pub uniforms_buffer: wgpu::Buffer,+// pub sampler: wgpu::Sampler,+// }impl CompositeVideoFramePipeline {pub fn new(device: &wgpu::Device) -> Self {@@ -114,7 +114,7 @@ impl CompositeVideoFramePipeline {}),);- let bind_group = device.create_bind_group(+ device.create_bind_group(&(wgpu::BindGroupDescriptor {layout: &self.bind_group_layout,entries: &[@@ -133,9 +133,7 @@ impl CompositeVideoFramePipeline {],label: Some("bind_group"),}),- );-- bind_group+ )}pub fn create_frame_texture(device: &wgpu::Device, width: u32, height: u32) -> wgpu::Texture {diff --git a/crates/rendering/src/cursor_interpolation.rs b/crates/rendering/src/cursor_interpolation.rsindex 3b8992366..fff16b9f8 100644--- a/crates/rendering/src/cursor_interpolation.rs+++ b/crates/rendering/src/cursor_interpolation.rs@@ -8,6 +8,7 @@ use crate::{#[derive(Debug, Clone)]pub struct InterpolatedCursorPosition {pub position: Coord<RawDisplayUVSpace>,+ #[allow(unused)]pub velocity: XY<f32>,pub cursor_id: String,}@@ -23,7 +24,7 @@ pub fn interpolate_cursor(return None;}- if cursor.moves[0].time_ms > time_ms.into() {+ if cursor.moves[0].time_ms > time_ms {let event = &cursor.moves[0];return Some(InterpolatedCursorPosition {@@ -36,35 +37,31 @@ pub fn interpolate_cursor(});}- if let Some(event) = cursor.moves.last() {- if event.time_ms < time_ms.into() {- return Some(InterpolatedCursorPosition {- position: Coord::new(XY {- x: event.x,- y: event.y,- }),- velocity: XY::new(0.0, 0.0),- cursor_id: event.cursor_id.clone(),- });- }+ if let Some(event) = cursor.moves.last()+ && event.time_ms < time_ms+ {+ return Some(InterpolatedCursorPosition {+ position: Coord::new(XY {+ x: event.x,+ y: event.y,+ }),+ velocity: XY::new(0.0, 0.0),+ cursor_id: event.cursor_id.clone(),+ });}if let Some(smoothing_config) = smoothing {let events = get_smoothed_cursor_events(&cursor.moves, smoothing_config);interpolate_smoothed_position(&events, time_secs as f64, smoothing_config)} else {- let (pos, cursor_id) = cursor- .moves- .windows(2)- .enumerate()- .find_map(|(_i, chunk)| {- if time_ms >= chunk[0].time_ms && time_ms < chunk[1].time_ms {- let c = &chunk[0];- Some((XY::new(c.x as f32, c.y as f32), c.cursor_id.clone()))- } else {- None- }- })?;+ let (pos, cursor_id) = cursor.moves.windows(2).find_map(|chunk| {+ if time_ms >= chunk[0].time_ms && time_ms < chunk[1].time_ms {+ let c = &chunk[0];+ Some((XY::new(c.x as f32, c.y as f32), c.cursor_id.clone()))+ } else {+ None+ }+ })?;Some(InterpolatedCursorPosition {position: Coord::new(XY {diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rsindex 6b3fc203a..6eb8d448f 100644--- a/crates/rendering/src/decoder/avassetreader.rs+++ b/crates/rendering/src/decoder/avassetreader.rs@@ -39,7 +39,7 @@ impl CachedFrame {);let data = if matches!(format, format::Pixel::RGBA) {- let _lock = unsafe {+ unsafe {image_buf.lock_base_addr(LockFlags::READ_ONLY).result()@@ -47,7 +47,7 @@ impl CachedFrame {};let bytes_per_row = image_buf.plane_bytes_per_row(0);- let width = image_buf.width() as usize;+ let width = image_buf.width();let height = image_buf.height();let slice = unsafe {@@ -78,7 +78,7 @@ impl CachedFrame {image_buf.height() as u32,);- let _lock = unsafe {+ unsafe {image_buf.lock_base_addr(LockFlags::READ_ONLY).result()@@ -215,7 +215,7 @@ impl AVAssetReaderDecoder {}fn run(- name: &'static str,+ _name: &'static str,path: PathBuf,fps: u32,rx: mpsc::Receiver<VideoDecoderMessage>,@@ -235,6 +235,7 @@ impl AVAssetReaderDecoder {let mut cache = BTreeMap::<u32, CachedFrame>::new();+ #[allow(unused)]let mut last_active_frame = None::<u32>;let last_sent_frame = Rc::new(RefCell::new(None::<ProcessedFrame>));@@ -307,25 +308,24 @@ impl AVAssetReaderDecoder {// We use the cache instead of last_sent_frame as newer non-matching frames could have been decoded.if let Some(most_recent_prev_frame) =cache.iter_mut().rev().find(|v| *v.0 < requested_frame)+ && let Some(sender) = sender.take(){- if let Some(sender) = sender.take() {- (sender)(most_recent_prev_frame.1.process());- }+ (sender)(most_recent_prev_frame.1.process());}let exceeds_cache_bounds = current_frame > cache_max;let too_small_for_cache_bounds = current_frame < cache_min;if !too_small_for_cache_bounds {- if current_frame == requested_frame {- if let Some(sender) = sender.take() {- let data = cache_frame.process();- // info!("sending frame {requested_frame}");+ if current_frame == requested_frame+ && let Some(sender) = sender.take()+ {+ let data = cache_frame.process();+ // info!("sending frame {requested_frame}");- (sender)(data);+ (sender)(data);- break;- }+ break;}if cache.len() >= FRAME_CACHE_SIZE {diff --git a/crates/rendering/src/decoder/ffmpeg.rs b/crates/rendering/src/decoder/ffmpeg.rsindex d60e65aca..5a72a9f5c 100644--- a/crates/rendering/src/decoder/ffmpeg.rs+++ b/crates/rendering/src/decoder/ffmpeg.rs@@ -6,8 +6,8 @@ use std::{sync::{Arc, mpsc},};-use ffmpeg::{Codec, codec, format, frame, software};-use ffmpeg_sys_next::{AVHWDeviceType, avcodec_find_decoder};+use ffmpeg::{format, frame, software};+use ffmpeg_sys_next::AVHWDeviceType;use log::debug;use tokio::sync::oneshot;@@ -30,7 +30,7 @@ impl CachedFrame {.unwrap();let mut rgb_frame = frame::Video::empty();- scaler.run(&frame, &mut rgb_frame).unwrap();+ scaler.run(frame, &mut rgb_frame).unwrap();rgb_frame} else {std::mem::replace(frame, frame::Video::empty())@@ -74,7 +74,7 @@ pub struct FfmpegDecoder;impl FfmpegDecoder {pub fn spawn(- name: &'static str,+ _name: &'static str,path: PathBuf,fps: u32,rx: mpsc::Receiver<VideoDecoderMessage>,@@ -98,17 +98,16 @@ impl FfmpegDecoder {let mut cache = BTreeMap::<u32, CachedFrame>::new();// active frame is a frame that triggered decode.// frames that are within render_more_margin of this frame won't trigger decode.+ #[allow(unused)]let mut last_active_frame = None::<u32>;let last_sent_frame = Rc::new(RefCell::new(None::<ProcessedFrame>));- let mut peekable_requests = PeekableReceiver { rx, peeked: None };-let mut frames = this.frames();let _ = ready_tx.send(Ok(()));- while let Ok(r) = peekable_requests.recv() {+ while let Ok(r) = rx.recv() {match r {VideoDecoderMessage::GetFrame(requested_time, sender) => {let requested_frame = (requested_time * fps as f32).floor() as u32;@@ -143,7 +142,7 @@ impl FfmpegDecoder {}).unwrap_or(true){- debug!("seeking to {}", requested_frame);+ debug!("seeking to {requested_frame}");let _ = this.reset(requested_time);frames = this.frames();@@ -170,25 +169,24 @@ impl FfmpegDecoder {// We use the cache instead of last_sent_frame as newer non-matching frames could have been decoded.if let Some(most_recent_prev_frame) =cache.iter_mut().rev().find(|v| *v.0 < requested_frame)+ && let Some(sender) = sender.take(){- if let Some(sender) = sender.take() {- (sender)(most_recent_prev_frame.1.process(width, height));- }+ (sender)(most_recent_prev_frame.1.process(width, height));}let exceeds_cache_bounds = current_frame > cache_max;let too_small_for_cache_bounds = current_frame < cache_min;let cache_frame = if !too_small_for_cache_bounds {- if current_frame == requested_frame {- if let Some(sender) = sender.take() {- let data = cache_frame.process(width, height);- // info!("sending frame {requested_frame}");+ if current_frame == requested_frame+ && let Some(sender) = sender.take()+ {+ let data = cache_frame.process(width, height);+ // info!("sending frame {requested_frame}");- (sender)(data);+ (sender)(data);- break;- }+ break;}if cache.len() >= FRAME_CACHE_SIZE {@@ -265,60 +263,60 @@ impl FfmpegDecoder {}}-pub fn find_decoder(- s: &format::context::Input,- st: &format::stream::Stream,- codec_id: codec::Id,-) -> Option<Codec> {- unsafe {- use ffmpeg::media::Type;- let codec = match st.parameters().medium() {- Type::Video => Some((*s.as_ptr()).video_codec),- Type::Audio => Some((*s.as_ptr()).audio_codec),- Type::Subtitle => Some((*s.as_ptr()).subtitle_codec),- _ => None,- };-- if let Some(codec) = codec {- if !codec.is_null() {- return Some(Codec::wrap(codec));- }- }-- let found = avcodec_find_decoder(codec_id.into());-- if found.is_null() {- return None;- }- Some(Codec::wrap(found))- }-}--struct PeekableReceiver<T> {- rx: mpsc::Receiver<T>,- peeked: Option<T>,-}--impl<T> PeekableReceiver<T> {- fn peek(&mut self) -> Option<&T> {- if self.peeked.is_some() {- self.peeked.as_ref()- } else {- match self.rx.try_recv() {- Ok(value) => {- self.peeked = Some(value);- self.peeked.as_ref()- }- Err(_) => None,- }- }- }-- fn recv(&mut self) -> Result<T, mpsc::RecvError> {- if let Some(value) = self.peeked.take() {- Ok(value)- } else {- self.rx.recv()- }- }-}+// pub fn find_decoder(+// s: &format::context::Input,+// st: &format::stream::Stream,+// codec_id: codec::Id,+// ) -> Option<Codec> {+// unsafe {+// use ffmpeg::media::Type;+// let codec = match st.parameters().medium() {+// Type::Video => Some((*s.as_ptr()).video_codec),+// Type::Audio => Some((*s.as_ptr()).audio_codec),+// Type::Subtitle => Some((*s.as_ptr()).subtitle_codec),+// _ => None,+// };++// if let Some(codec) = codec {+// if !codec.is_null() {+// return Some(Codec::wrap(codec));+// }+// }++// let found = avcodec_find_decoder(codec_id.into());++// if found.is_null() {+// return None;+// }+// Some(Codec::wrap(found))+// }+// }++// struct PeekableReceiver<T> {+// rx: mpsc::Receiver<T>,+// peeked: Option<T>,+// }++// impl<T> PeekableReceiver<T> {+// fn peek(&mut self) -> Option<&T> {+// if self.peeked.is_some() {+// self.peeked.as_ref()+// } else {+// match self.rx.try_recv() {+// Ok(value) => {+// self.peeked = Some(value);+// self.peeked.as_ref()+// }+// Err(_) => None,+// }+// }+// }++// fn recv(&mut self) -> Result<T, mpsc::RecvError> {+// if let Some(value) = self.peeked.take() {+// Ok(value)+// } else {+// self.rx.recv()+// }+// }+// }diff --git a/crates/rendering/src/frame_pipeline.rs b/crates/rendering/src/frame_pipeline.rsindex e69f60024..700176605 100644--- a/crates/rendering/src/frame_pipeline.rs+++ b/crates/rendering/src/frame_pipeline.rs@@ -1,35 +1,35 @@use futures_intrusive::channel::shared::oneshot_channel;use wgpu::COPY_BYTES_PER_ROW_ALIGNMENT;-use crate::{ProjectUniforms, RenderSession, RenderVideoConstants, RenderingError};--pub struct FramePipelineState<'a> {- pub constants: &'a RenderVideoConstants,- pub uniforms: &'a ProjectUniforms,- pub texture: &'a wgpu::Texture,- pub texture_view: wgpu::TextureView,-}--impl<'a> FramePipelineState<'a> {- pub fn new(- constants: &'a RenderVideoConstants,- uniforms: &'a ProjectUniforms,- texture: &'a wgpu::Texture,- ) -> Self {- let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());-- Self {- constants,- uniforms,- texture,- texture_view,- }- }-}--pub struct FramePipelineEncoder {- pub encoder: wgpu::CommandEncoder,-}+use crate::{ProjectUniforms, RenderSession, RenderingError};++// pub struct FramePipelineState<'a> {+// pub constants: &'a RenderVideoConstants,+// pub uniforms: &'a ProjectUniforms,+// pub texture: &'a wgpu::Texture,+// pub texture_view: wgpu::TextureView,+// }++// impl<'a> FramePipelineState<'a> {+// pub fn new(+// constants: &'a RenderVideoConstants,+// uniforms: &'a ProjectUniforms,+// texture: &'a wgpu::Texture,+// ) -> Self {+// let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());++// Self {+// constants,+// uniforms,+// texture,+// texture_view,+// }+// }+// }++// pub struct FramePipelineEncoder {+// pub encoder: wgpu::CommandEncoder,+// }#[derive(Clone)]pub struct RenderedFrame {@@ -39,17 +39,17 @@ pub struct RenderedFrame {pub padded_bytes_per_row: u32,}-impl FramePipelineEncoder {- pub fn new(state: &FramePipelineState) -> Self {- Self {- encoder: state.constants.device.create_command_encoder(- &(wgpu::CommandEncoderDescriptor {- label: Some("Render Encoder"),- }),- ),- }- }-}+// impl FramePipelineEncoder {+// pub fn new(state: &FramePipelineState) -> Self {+// Self {+// encoder: state.constants.device.create_command_encoder(+// &(wgpu::CommandEncoderDescriptor {+// label: Some("Render Encoder"),+// }),+// ),+// }+// }+// }pub fn padded_bytes_per_row(output_size: (u32, u32)) -> u32 {// Calculate the aligned bytes per row@@ -119,7 +119,7 @@ pub async fn finish_encoder(buffer_slice.map_async(wgpu::MapMode::Read, move |result| {tx.send(result).ok();});- device.poll(wgpu::PollType::Wait);+ device.poll(wgpu::PollType::Wait)?;rx.receive().awaitdiff --git a/crates/rendering/src/layers/background.rs b/crates/rendering/src/layers/background.rsindex 441e9f449..c4d5418c6 100644--- a/crates/rendering/src/layers/background.rs+++ b/crates/rendering/src/layers/background.rs@@ -11,14 +11,14 @@ use crate::{};#[derive(PartialEq, Debug, Clone, Copy, Serialize, Deserialize, Type)]-struct Gradient {+pub struct Gradient {start: [f32; 4],end: [f32; 4],angle: f32,}#[derive(PartialEq)]-enum ColorOrGradient {+pub enum ColorOrGradient {Color([f32; 4]),Gradient(Gradient),}@@ -55,16 +55,16 @@ impl From<BackgroundSource> for Background {angle: angle as f32,}),BackgroundSource::Image { path } | BackgroundSource::Wallpaper { path } => {- if let Some(path) = path {- if !path.is_empty() {- let clean_path = path- .replace("asset://localhost/", "/")- .replace("asset://", "")- .replace("localhost//", "/");-- if std::path::Path::new(&clean_path).exists() {- return Background::Image { path: clean_path };- }+ if let Some(path) = path+ && !path.is_empty()+ {+ let clean_path = path+ .replace("asset://localhost/", "/")+ .replace("asset://", "")+ .replace("localhost//", "/");++ if std::path::Path::new(&clean_path).exists() {+ return Background::Image { path: clean_path };}}Background::Color([1.0, 1.0, 1.0, 1.0])@@ -80,6 +80,7 @@ pub enum Inner {},ColorOrGradient {value: ColorOrGradient,+ #[allow(unused)]buffer: wgpu::Buffer,bind_group: wgpu::BindGroup,},@@ -208,7 +209,7 @@ impl BackgroundLayer {self.inner = Some(Inner::Image {path,bind_group: self.image_pipeline.bind_group(- &device,+ device,&uniform_buffer,&texture_view,),@@ -483,15 +484,13 @@ impl GradientOrColorPipeline {}pub fn bind_group(&self, device: &wgpu::Device, uniforms: &wgpu::Buffer) -> wgpu::BindGroup {- let bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor {+ device.create_bind_group(&wgpu::BindGroupDescriptor {layout: &self.bind_group_layout,entries: &[wgpu::BindGroupEntry {binding: 0,resource: uniforms.as_entire_binding(),}],label: Some("bind_group"),- });-- bind_group+ })}}diff --git a/crates/rendering/src/layers/blur.rs b/crates/rendering/src/layers/blur.rsindex a635f143e..f26966cc4 100644--- a/crates/rendering/src/layers/blur.rs+++ b/crates/rendering/src/layers/blur.rs@@ -61,12 +61,9 @@ impl BlurLayer {pass.set_pipeline(&self.pipeline.render_pipeline);pass.set_bind_group(0,- &self.pipeline.bind_group(- &device,- &self.uniforms_buffer,- &source_texture,- &self.sampler,- ),+ &self+ .pipeline+ .bind_group(device, &self.uniforms_buffer, source_texture, &self.sampler),&[],);pass.draw(0..4, 0..1);diff --git a/crates/rendering/src/layers/camera.rs b/crates/rendering/src/layers/camera.rsindex c6852981e..661944de7 100644--- a/crates/rendering/src/layers/camera.rs+++ b/crates/rendering/src/layers/camera.rs@@ -29,7 +29,7 @@ impl CameraLayer {}),);- let bind_group = Some(pipeline.bind_group(&device, &uniforms_buffer, &frame_texture_view));+ let bind_group = Some(pipeline.bind_group(device, &uniforms_buffer, &frame_texture_view));Self {frame_texture,@@ -63,7 +63,7 @@ impl CameraLayer {self.frame_texture_view = self.frame_texture.create_view(&Default::default());self.bind_group = Some(self.pipeline.bind_group(- &device,+ device,&self.uniforms_buffer,&self.frame_texture_view,));diff --git a/crates/rendering/src/layers/captions.rs b/crates/rendering/src/layers/captions.rsindex 1a8b3461d..5e1f6bcb8 100644--- a/crates/rendering/src/layers/captions.rs+++ b/crates/rendering/src/layers/captions.rs@@ -1,3 +1,5 @@+#![allow(unused)] // TODO: This module is still being implemented+use bytemuck::{Pod, Zeroable};use cap_project::XY;use glyphon::{@@ -110,10 +112,10 @@ impl CaptionsLayer {/// Update the current caption text and timingpub fn update_caption(&mut self, text: Option<String>, time: f32) {- debug!("Updating caption - Text: {:?}, Time: {}", text, time);+ debug!("Updating caption - Text: {text:?}, Time: {time}");if self.current_text != text {if let Some(content) = &text {- info!("Setting new caption text: {}", content);+ info!("Setting new caption text: {content}");// Update the text buffer with new contentlet metrics = Metrics::new(24.0, 24.0 * 1.2);self.text_buffer = Buffer::new_empty(metrics);@@ -137,224 +139,216 @@ impl CaptionsLayer {constants: &RenderVideoConstants,) {// Render captions if there are any caption segments to display- if let Some(caption_data) = &uniforms.project.captions {- if caption_data.settings.enabled {- // Find the current caption for this time- let current_time = segment_frames.segment_time;-- if let Some(current_caption) =- find_caption_at_time_project(current_time, &caption_data.segments)- {- // Get caption text and time for use in rendering- let caption_text = current_caption.text.clone();-- // Create settings for the caption- let settings = CaptionSettings {- enabled: 1,- font_size: caption_data.settings.size as f32,- color: [- parse_color_component(&caption_data.settings.color, 0),- parse_color_component(&caption_data.settings.color, 1),- parse_color_component(&caption_data.settings.color, 2),- 1.0,- ],- background_color: [- parse_color_component(&caption_data.settings.background_color, 0),- parse_color_component(&caption_data.settings.background_color, 1),- parse_color_component(&caption_data.settings.background_color, 2),- caption_data.settings.background_opacity as f32 / 100.0,- ],- position: match caption_data.settings.position.as_str() {- "top" => 0,- "middle" => 1,- _ => 2, // default to bottom- },- outline: if caption_data.settings.outline { 1 } else { 0 },- outline_color: [- parse_color_component(&caption_data.settings.outline_color, 0),- parse_color_component(&caption_data.settings.outline_color, 1),- parse_color_component(&caption_data.settings.outline_color, 2),- 1.0,- ],- font: match caption_data.settings.font.as_str() {- "System Serif" => 1,- "System Monospace" => 2,- _ => 0, // Default to SansSerif for "System Sans-Serif" and any other value- },- _padding: [0.0],- };+ if let Some(caption_data) = &uniforms.project.captions+ && caption_data.settings.enabled+ {+ // Find the current caption for this time+ let current_time = segment_frames.segment_time;++ if let Some(current_caption) =+ find_caption_at_time_project(current_time, &caption_data.segments)+ {+ // Get caption text and time for use in rendering+ let caption_text = current_caption.text.clone();++ // Create settings for the caption+ let settings = CaptionSettings {+ enabled: 1,+ font_size: caption_data.settings.size as f32,+ color: [+ parse_color_component(&caption_data.settings.color, 0),+ parse_color_component(&caption_data.settings.color, 1),+ parse_color_component(&caption_data.settings.color, 2),+ 1.0,+ ],+ background_color: [+ parse_color_component(&caption_data.settings.background_color, 0),+ parse_color_component(&caption_data.settings.background_color, 1),+ parse_color_component(&caption_data.settings.background_color, 2),+ caption_data.settings.background_opacity as f32 / 100.0,+ ],+ position: match caption_data.settings.position.as_str() {+ "top" => 0,+ "middle" => 1,+ _ => 2, // default to bottom+ },+ outline: if caption_data.settings.outline { 1 } else { 0 },+ outline_color: [+ parse_color_component(&caption_data.settings.outline_color, 0),+ parse_color_component(&caption_data.settings.outline_color, 1),+ parse_color_component(&caption_data.settings.outline_color, 2),+ 1.0,+ ],+ font: match caption_data.settings.font.as_str() {+ "System Serif" => 1,+ "System Monospace" => 2,+ _ => 0, // Default to SansSerif for "System Sans-Serif" and any other value+ },+ _padding: [0.0],+ };++ self.update_caption(Some(caption_text), current_time);++ if settings.enabled == 0 {+ return;+ }- self.update_caption(Some(caption_text), current_time);+ if self.current_text.is_none() {+ return;+ }- if settings.enabled == 0 {- return;- }+ if let Some(text) = &self.current_text {+ let (width, height) = (output_size.x, output_size.y);- if self.current_text.is_none() {- return;- }+ // Access device and queue from the pipeline's constants+ let device = &constants.device;+ let queue = &constants.queue;- if let Some(text) = &self.current_text {- let (width, height) = (output_size.x, output_size.y);-- // Access device and queue from the pipeline's constants- let device = &constants.device;- let queue = &constants.queue;-- // Find caption position based on settings- let y_position = match settings.position {- 0 => height as f32 * 0.1, // top- 1 => height as f32 * 0.5, // middle- _ => height as f32 * 0.85, // bottom (default)- };-- // Set up caption appearance- let color = Color::rgb(- (settings.color[0] * 255.0) as u8,- (settings.color[1] * 255.0) as u8,- (settings.color[2] * 255.0) as u8,- );-- // Get outline color if needed- let outline_color = Color::rgb(- (settings.outline_color[0] * 255.0) as u8,- (settings.outline_color[1] * 255.0) as u8,- (settings.outline_color[2] * 255.0) as u8,- );-- // Calculate text bounds- let font_size = settings.font_size * (height as f32 / 1080.0); // Scale font size based on resolution- let metrics = Metrics::new(font_size, font_size * 1.2); // 1.2 line height-- // Create a new buffer with explicit size for this frame- let mut updated_buffer = Buffer::new(&mut self.font_system, metrics);-- // Set explicit width to enable proper text wrapping and centering- // Set width to 90% of screen width for better appearance- let text_width = width as f32 * 0.9;- updated_buffer.set_size(&mut self.font_system, Some(text_width), None);- updated_buffer.set_wrap(&mut self.font_system, glyphon::Wrap::Word);-- // Position text in the center horizontally- // The bounds dictate the rendering area- let bounds = TextBounds {- left: ((width as f32 - text_width) / 2.0) as i32, // Center the text horizontally- top: y_position as i32,- right: ((width as f32 + text_width) / 2.0) as i32, // Center + width- bottom: (y_position + font_size * 4.0) as i32, // Increased height for better visibility- };-- // Apply text styling directly when setting the text- // Create text attributes with or without outline- let font_family = match settings.font {- 0 => Family::SansSerif,- 1 => Family::Serif,- 2 => Family::Monospace,- _ => Family::SansSerif, // Default to SansSerif for any other value- };- let attrs = Attrs::new().family(font_family).color(color);-- // Apply text to buffer- updated_buffer.set_text(- &mut self.font_system,- text,- &attrs,- Shaping::Advanced,- );-- // Replace the existing buffer- self.text_buffer = updated_buffer;-- // Update the viewport with explicit resolution- self.viewport.update(queue, Resolution { width, height });-- // Background color- let bg_color = if settings.background_color[3] > 0.01 {- // Create a new text area with background color- Color::rgba(- (settings.background_color[0] * 255.0) as u8,- (settings.background_color[1] * 255.0) as u8,- (settings.background_color[2] * 255.0) as u8,- (settings.background_color[3] * 255.0) as u8,- )- } else {- Color::rgba(0, 0, 0, 0)- };-- // Prepare text areas for rendering- let mut text_areas = Vec::new();-- // Add background if enabled- if settings.background_color[3] > 0.01 {- text_areas.push(TextArea {- buffer: &self.text_buffer,- left: bounds.left as f32, // Match the bounds left for positioning- top: y_position,- scale: 1.0,- bounds,- default_color: bg_color,- custom_glyphs: &[],- });- }+ // Find caption position based on settings+ let y_position = match settings.position {+ 0 => height as f32 * 0.1, // top+ 1 => height as f32 * 0.5, // middle+ _ => height as f32 * 0.85, // bottom (default)+ };- // Add outline if enabled (by rendering the text multiple times with slight offsets in different positions)- if settings.outline == 1 {- info!("Rendering with outline");- // Outline is created by drawing the text multiple times with small offsets in different directions- let outline_offsets = [- (-1.0, -1.0),- (0.0, -1.0),- (1.0, -1.0),- (-1.0, 0.0),- (1.0, 0.0),- (-1.0, 1.0),- (0.0, 1.0),- (1.0, 1.0),- ];-- for (offset_x, offset_y) in outline_offsets.iter() {- text_areas.push(TextArea {- buffer: &self.text_buffer,- left: bounds.left as f32 + offset_x, // Match bounds with small offset for outline- top: y_position + offset_y,- scale: 1.0,- bounds,- default_color: outline_color,- custom_glyphs: &[],- });- }- }+ // Set up caption appearance+ let color = Color::rgb(+ (settings.color[0] * 255.0) as u8,+ (settings.color[1] * 255.0) as u8,+ (settings.color[2] * 255.0) as u8,+ );++ // Get outline color if needed+ let outline_color = Color::rgb(+ (settings.outline_color[0] * 255.0) as u8,+ (settings.outline_color[1] * 255.0) as u8,+ (settings.outline_color[2] * 255.0) as u8,+ );++ // Calculate text bounds+ let font_size = settings.font_size * (height as f32 / 1080.0); // Scale font size based on resolution+ let metrics = Metrics::new(font_size, font_size * 1.2); // 1.2 line height++ // Create a new buffer with explicit size for this frame+ let mut updated_buffer = Buffer::new(&mut self.font_system, metrics);++ // Set explicit width to enable proper text wrapping and centering+ // Set width to 90% of screen width for better appearance+ let text_width = width as f32 * 0.9;+ updated_buffer.set_size(&mut self.font_system, Some(text_width), None);+ updated_buffer.set_wrap(&mut self.font_system, glyphon::Wrap::Word);++ // Position text in the center horizontally+ // The bounds dictate the rendering area+ let bounds = TextBounds {+ left: ((width as f32 - text_width) / 2.0) as i32, // Center the text horizontally+ top: y_position as i32,+ right: ((width as f32 + text_width) / 2.0) as i32, // Center + width+ bottom: (y_position + font_size * 4.0) as i32, // Increased height for better visibility+ };- // Add main text (rendered last, on top of everything)+ // Apply text styling directly when setting the text+ // Create text attributes with or without outline+ let font_family = match settings.font {+ 0 => Family::SansSerif,+ 1 => Family::Serif,+ 2 => Family::Monospace,+ _ => Family::SansSerif, // Default to SansSerif for any other value+ };+ let attrs = Attrs::new().family(font_family).color(color);++ // Apply text to buffer+ updated_buffer.set_text(&mut self.font_system, text, &attrs, Shaping::Advanced);++ // Replace the existing buffer+ self.text_buffer = updated_buffer;++ // Update the viewport with explicit resolution+ self.viewport.update(queue, Resolution { width, height });++ // Background color+ let bg_color = if settings.background_color[3] > 0.01 {+ // Create a new text area with background color+ Color::rgba(+ (settings.background_color[0] * 255.0) as u8,+ (settings.background_color[1] * 255.0) as u8,+ (settings.background_color[2] * 255.0) as u8,+ (settings.background_color[3] * 255.0) as u8,+ )+ } else {+ Color::rgba(0, 0, 0, 0)+ };++ // Prepare text areas for rendering+ let mut text_areas = Vec::new();++ // Add background if enabled+ if settings.background_color[3] > 0.01 {text_areas.push(TextArea {buffer: &self.text_buffer,left: bounds.left as f32, // Match the bounds left for positioningtop: y_position,scale: 1.0,bounds,- default_color: color,+ default_color: bg_color,custom_glyphs: &[],});+ }- // Prepare text rendering- match self.text_renderer.prepare(- device,- queue,- &mut self.font_system,- &mut self.text_atlas,- &self.viewport,- text_areas,- &mut self.swash_cache,- ) {- Ok(_) => {}- Err(e) => warn!("Error preparing text: {:?}", e),+ // Add outline if enabled (by rendering the text multiple times with slight offsets in different positions)+ if settings.outline == 1 {+ info!("Rendering with outline");+ // Outline is created by drawing the text multiple times with small offsets in different directions+ let outline_offsets = [+ (-1.0, -1.0),+ (0.0, -1.0),+ (1.0, -1.0),+ (-1.0, 0.0),+ (1.0, 0.0),+ (-1.0, 1.0),+ (0.0, 1.0),+ (1.0, 1.0),+ ];++ for (offset_x, offset_y) in outline_offsets.iter() {+ text_areas.push(TextArea {+ buffer: &self.text_buffer,+ left: bounds.left as f32 + offset_x, // Match bounds with small offset for outline+ top: y_position + offset_y,+ scale: 1.0,+ bounds,+ default_color: outline_color,+ custom_glyphs: &[],+ });}}- } else {++ // Add main text (rendered last, on top of everything)+ text_areas.push(TextArea {+ buffer: &self.text_buffer,+ left: bounds.left as f32, // Match the bounds left for positioning+ top: y_position,+ scale: 1.0,+ bounds,+ default_color: color,+ custom_glyphs: &[],+ });++ // Prepare text rendering+ match self.text_renderer.prepare(+ device,+ queue,+ &mut self.font_system,+ &mut self.text_atlas,+ &self.viewport,+ text_areas,+ &mut self.swash_cache,+ ) {+ Ok(_) => {}+ Err(e) => warn!("Error preparing text: {e:?}"),+ }}- } else {}- } else {}}@@ -365,7 +359,7 @@ impl CaptionsLayer {.render(&self.text_atlas, &self.viewport, pass){Ok(_) => {}- Err(e) => warn!("Error rendering text: {:?}", e),+ Err(e) => warn!("Error rendering text: {e:?}"),}}}@@ -393,13 +387,3 @@ pub fn find_caption_at_time_project(text: segment.text.clone(),})}--/// Convert from cap_project::CaptionSegment to our internal CaptionSegment-pub fn convert_project_caption(segment: &cap_project::CaptionSegment) -> CaptionSegment {- CaptionSegment {- id: segment.id.clone(),- start: segment.start,- end: segment.end,- text: segment.text.clone(),- }-}diff --git a/crates/rendering/src/layers/cursor.rs b/crates/rendering/src/layers/cursor.rsindex 8dd1b946e..00a580847 100644--- a/crates/rendering/src/layers/cursor.rs+++ b/crates/rendering/src/layers/cursor.rs@@ -1,7 +1,6 @@use std::collections::HashMap;use bytemuck::{Pod, Zeroable};-use cap_cursor_info::ResolvedCursor;use cap_project::*;use image::GenericImageView;use tracing::error;@@ -234,7 +233,7 @@ impl CursorLayer {},}) => cursors.get(&interpolated_cursor.cursor_id)- .and_then(|v| v.shape.clone()),+ .and_then(|v| v.shape),_ => None,};@@ -242,37 +241,32 @@ impl CursorLayer {// These are used instead of the OS provided cursor images when possible as the quality is better.if let Some(cursor_shape) = cursor_shape&& uniforms.project.cursor.use_svg+ && let Some(info) = cursor_shape.resolve(){- if let Some(info) = cursor_shape.resolve() {- cursor = CursorTexture::prepare_svg(&constants, info.raw, info.hotspot.into())- .map_err(|err| {- error!(- "Error loading SVG cursor {:?}: {err}",- interpolated_cursor.cursor_id- )- })- .ok();- }+ cursor = CursorTexture::prepare_svg(constants, info.raw, info.hotspot.into())+ .map_err(|err| {+ error!(+ "Error loading SVG cursor {:?}: {err}",+ interpolated_cursor.cursor_id+ )+ })+ .ok();}// If not we attempt to load the low-quality image cursorif let StudioRecordingMeta::MultipleSegments { inner, .. } = &constants.meta&& cursor.is_none()- {- if let Some(c) = inner+ && let Some(c) = inner.get_cursor_image(&constants.recording_meta, &interpolated_cursor.cursor_id)- {- if let Ok(img) = image::open(&c.path).map_err(|err| {- error!("Failed to load cursor image from {:?}: {err}", c.path)- }) {- cursor = Some(CursorTexture::prepare(- constants,- &img.to_rgba8(),- img.dimensions(),- c.hotspot,- ));- }- }+ && let Ok(img) = image::open(&c.path)+ .map_err(|err| error!("Failed to load cursor image from {:?}: {err}", c.path))+ {+ cursor = Some(CursorTexture::prepare(+ constants,+ &img.to_rgba8(),+ img.dimensions(),+ c.hotspot,+ ));}if let Some(cursor) = cursor {@@ -385,26 +379,6 @@ pub struct CursorUniforms {_alignment: [f32; 3],}-pub fn find_cursor_move(cursor: &CursorEvents, time: f32) -> &CursorMoveEvent {- let time_ms = time * 1000.0;-- if cursor.moves[0].time_ms > time_ms.into() {- return &cursor.moves[0];- }-- let event = cursor- .moves- .iter()- .rev()- .find(|event| {- // println!("Checking event at time: {}ms", event.process_time_ms);- event.time_ms <= time_ms.into()- })- .unwrap_or(&cursor.moves[0]);-- event-}-fn get_click_t(clicks: &[CursorClickEvent], time_ms: f64) -> f32 {fn smoothstep(low: f32, high: f32, v: f32) -> f32 {let t = f32::clamp((v - low) / (high - low), 0.0, 1.0);@@ -441,14 +415,16 @@ fn get_click_t(clicks: &[CursorClickEvent], time_ms: f64) -> f32 {);}- if let Some(next) = clicks.get(prev_i + 1) {- if !prev.down && next.down && next.time_ms - time_ms <= CURSOR_CLICK_DURATION_MS {- return smoothstep(- 0.0,- CURSOR_CLICK_DURATION_MS as f32,- (time_ms - next.time_ms).abs() as f32,- );- }+ if let Some(next) = clicks.get(prev_i + 1)+ && !prev.down+ && next.down+ && next.time_ms - time_ms <= CURSOR_CLICK_DURATION_MS+ {+ return smoothstep(+ 0.0,+ CURSOR_CLICK_DURATION_MS as f32,+ (time_ms - next.time_ms).abs() as f32,+ );}1.0@@ -489,7 +465,7 @@ impl CursorTexture {origin: wgpu::Origin3d::ZERO,aspect: wgpu::TextureAspect::All,},- &rgba,+ rgba,wgpu::TexelCopyBufferLayout {offset: 0,bytes_per_row: Some(4 * dimensions.0),@@ -512,7 +488,7 @@ impl CursorTexture {hotspot: XY<f64>,) -> Result<Self, String> {let rtree = resvg::usvg::Tree::from_str(svg_data, &resvg::usvg::Options::default())- .map_err(|e| format!("Failed to parse SVG: {}", e))?;+ .map_err(|e| format!("Failed to parse SVG: {e}"))?;// Although we could probably determine the size that the cursor is going to be render,// that would depend on the cursor size the user selects.@@ -522,7 +498,7 @@ impl CursorTexture {let aspect_ratio = rtree.size().width() / rtree.size().height();let width = (aspect_ratio * SVG_CURSOR_RASTERIZED_HEIGHT as f32) as u32;- let mut pixmap = tiny_skia::Pixmap::new(width as u32, SVG_CURSOR_RASTERIZED_HEIGHT as u32)+ let mut pixmap = tiny_skia::Pixmap::new(width, SVG_CURSOR_RASTERIZED_HEIGHT).ok_or("Failed to create pixmap")?;// Calculate scale to fit the SVG into the target size while maintaining aspect ratiodiff --git a/crates/rendering/src/layers/display.rs b/crates/rendering/src/layers/display.rsindex f86e40e5f..787826675 100644--- a/crates/rendering/src/layers/display.rs+++ b/crates/rendering/src/layers/display.rs@@ -20,7 +20,7 @@ impl DisplayLayer {let uniforms_buffer = CompositeVideoFrameUniforms::default().to_buffer(device);let pipeline = CompositeVideoFramePipeline::new(device);- let bind_group = Some(pipeline.bind_group(&device, &uniforms_buffer, &frame_texture_view));+ let bind_group = Some(pipeline.bind_group(device, &uniforms_buffer, &frame_texture_view));Self {frame_texture_view,@@ -49,7 +49,7 @@ impl DisplayLayer {self.frame_texture_view = self.frame_texture.create_view(&Default::default());self.bind_group = Some(self.pipeline.bind_group(- &device,+ device,&self.uniforms_buffer,&self.frame_texture_view,));diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex 37ec814a1..cbae60a98 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -167,6 +167,8 @@ pub enum RenderingError {ChannelSendFrameFailed(#[from] mpsc::error::SendError<(RenderedFrame, u32)>),#[error("Failed to load image: {0}")]ImageLoadError(String),+ #[error("Error polling wgpu: {0}")]+ PollError(#[from] wgpu::PollError),}pub struct RenderSegment {@@ -174,6 +176,7 @@ pub struct RenderSegment {pub decoders: RecordingSegmentDecoders,}+#[allow(clippy::too_many_arguments)]pub async fn render_video_to_channel(constants: &RenderVideoConstants,project: &ProjectConfiguration,@@ -190,13 +193,13 @@ pub async fn render_video_to_channel(let start_time = Instant::now();// Get the duration from the timeline if it exists, otherwise use the longest source duration- let duration = get_duration(recordings, recording_meta, meta, &project);+ let duration = get_duration(recordings, recording_meta, meta, project);let total_frames = (fps as f64 * duration).ceil() as u32;let mut frame_number = 0;- let mut frame_renderer = FrameRenderer::new(&constants);+ let mut frame_renderer = FrameRenderer::new(constants);let mut layers = RendererLayers::new(&constants.device, &constants.queue);@@ -225,8 +228,8 @@ pub async fn render_video_to_channel(.await{let uniforms = ProjectUniforms::new(- &constants,- &project,+ constants,+ project,frame_number,fps,resolution_base,@@ -264,14 +267,13 @@ pub fn get_duration(let mut max_duration = recordings.duration();// Check camera duration if it exists- if let Some(camera_path) = meta.camera_path() {- if let Ok(camera_duration) =+ if let Some(camera_path) = meta.camera_path()+ && let Ok(camera_duration) =recordings.get_source_duration(&recording_meta.path(&camera_path))- {- println!("Camera recording duration: {}", camera_duration);- max_duration = max_duration.max(camera_duration);- println!("New max duration after camera check: {}", max_duration);- }+ {+ println!("Camera recording duration: {camera_duration}");+ max_duration = max_duration.max(camera_duration);+ println!("New max duration after camera check: {max_duration}");}// If there's a timeline, ensure all segments extend to the max duration@@ -288,7 +290,7 @@ pub fn get_duration(// }timeline.duration()} else {- println!("No timeline found, using max_duration: {}", max_duration);+ println!("No timeline found, using max_duration: {max_duration}");max_duration}}@@ -384,6 +386,7 @@ impl ProjectUniforms {})}+ #[allow(unused)]fn get_padding(options: &RenderOptions, project: &ProjectConfiguration) -> f64 {let crop = Self::get_crop(options, project);@@ -454,7 +457,7 @@ impl ProjectUniforms {let scaled_width = ((base_width as f32 * scale) as u32 + 1) & !1;let scaled_height = ((base_height as f32 * scale) as u32 + 1) & !1;- return (scaled_width, scaled_height);+ (scaled_width, scaled_height)// ((base_width + 1) & !1, (base_height + 1) & !1)}@@ -545,7 +548,7 @@ impl ProjectUniforms {let interpolated_cursor = interpolate_cursor(cursor_events,segment_frames.recording_time,- (!project.cursor.raw).then(|| SpringMassDamperSimulationConfig {+ (!project.cursor.raw).then_some(SpringMassDamperSimulationConfig {tension: project.cursor.tension,mass: project.cursor.mass,friction: project.cursor.friction,@@ -564,7 +567,7 @@ impl ProjectUniforms {interpolate_cursor(cursor_events,(segment_frames.recording_time - 0.2).max(0.0),- (!project.cursor.raw).then(|| SpringMassDamperSimulationConfig {+ (!project.cursor.raw).then_some(SpringMassDamperSimulationConfig {tension: project.cursor.tension,mass: project.cursor.mass,friction: project.cursor.friction,@@ -818,6 +821,7 @@ pub struct RendererLayers {display: DisplayLayer,cursor: CursorLayer,camera: CameraLayer,+ #[allow(unused)]captions: CaptionsLayer,}@@ -842,7 +846,7 @@ impl RendererLayers {) -> Result<(), RenderingError> {self.background.prepare(- &constants,+ constants,uniforms,Background::from(uniforms.project.background.source.clone()),)@@ -1074,14 +1078,14 @@ async fn produce_frame(layers.render(&constants.device, &mut encoder, session);- Ok(finish_encoder(+ finish_encoder(session,&constants.device,&constants.queue,&uniforms,encoder,)- .await?)+ .await}// Helper function to parse color components from hex strings@@ -1174,6 +1178,6 @@ fn srgb_to_linear(c: u16) -> f32 {}}-fn get_either<T>((a, b): (T, T), left: bool) -> T {- if left { a } else { b }-}+// fn get_either<T>((a, b): (T, T), left: bool) -> T {+// if left { a } else { b }+// }diff --git a/crates/rendering/src/project_recordings.rs b/crates/rendering/src/project_recordings.rsindex 58401c6d0..a373fcaa7 100644--- a/crates/rendering/src/project_recordings.rs+++ b/crates/rendering/src/project_recordings.rs@@ -20,17 +20,17 @@ impl Video {pub fn new(path: impl AsRef<Path>, start_time: f64) -> Result<Self, String> {fn inner(path: &Path, start_time: f64) -> Result<Video, String> {let input =- ffmpeg::format::input(path).map_err(|e| format!("Failed to open video: {}", e))?;+ ffmpeg::format::input(path).map_err(|e| format!("Failed to open video: {e}"))?;let stream = input.streams().best(ffmpeg::media::Type::Video).ok_or_else(|| "No video stream found".to_string())?;let video_decoder = ffmpeg::codec::Context::from_parameters(stream.parameters())- .map_err(|e| format!("Failed to create decoder: {}", e))?+ .map_err(|e| format!("Failed to create decoder: {e}"))?.decoder().video()- .map_err(|e| format!("Failed to get video decoder: {}", e))?;+ .map_err(|e| format!("Failed to get video decoder: {e}"))?;let rate = stream.avg_frame_rate();let fps = rate.numerator() as f64 / rate.denominator() as f64;@@ -64,17 +64,17 @@ impl Audio {pub fn new(path: impl AsRef<Path>, start_time: f64) -> Result<Self, String> {fn inner(path: &Path, start_time: f64) -> Result<Audio, String> {let input =- ffmpeg::format::input(path).map_err(|e| format!("Failed to open audio: {}", e))?;+ ffmpeg::format::input(path).map_err(|e| format!("Failed to open audio: {e}"))?;let stream = input.streams().best(ffmpeg::media::Type::Audio).ok_or_else(|| "No audio stream found".to_string())?;let audio_decoder = ffmpeg::codec::Context::from_parameters(stream.parameters())- .map_err(|e| format!("Failed to create decoder: {}", e))?+ .map_err(|e| format!("Failed to create decoder: {e}"))?.decoder().audio()- .map_err(|e| format!("Failed to get audio decoder: {}", e))?;+ .map_err(|e| format!("Failed to get audio decoder: {e}"))?;Ok(Audio {duration: input.duration() as f64 / 1_000_000.0,@@ -124,7 +124,7 @@ impl ProjectRecordingsMeta {let has_start_times = RefCell::new(None);let ensure_start_time = |time: Option<f64>| {- let Some(has_start_times) = has_start_times.borrow_mut().clone() else {+ let Some(has_start_times) = *has_start_times.borrow_mut() else {*has_start_times.borrow_mut() = Some(time.is_some());return Ok(time.unwrap_or_default());};@@ -135,12 +135,10 @@ impl ProjectRecordingsMeta {} else {return Err("Missing start time".to_string());}+ } else if time.is_some() {+ return Err("Start time mismatch".to_string());} else {- if time.is_some() {- return Err("Start time mismatch".to_string());- } else {- 0.0- }+ 0.0})};diff --git a/crates/rendering/src/zoom.rs b/crates/rendering/src/zoom.rsindex 068badd92..a0291cf1b 100644--- a/crates/rendering/src/zoom.rs+++ b/crates/rendering/src/zoom.rs@@ -3,8 +3,6 @@ use cap_project::{XY, ZoomSegment};use crate::{Coord, RawDisplayUVSpace};pub const ZOOM_DURATION: f64 = 1.0;-// Added constant for cursor smoothing-pub const CURSOR_SMOOTHING_WINDOW: f64 = 0.15; // 150ms window for smoothing#[derive(Debug, Clone, Copy)]pub struct SegmentsCursor<'a> {diff --git a/crates/utils/Cargo.toml b/crates/utils/Cargo.tomlindex 2ff6ffe0b..d0680594a 100644--- a/crates/utils/Cargo.toml+++ b/crates/utils/Cargo.toml@@ -1,7 +1,7 @@[package]name = "cap-utils"version = "0.1.0"-edition = "2021"+edition = "2024"[target.'cfg(unix)'.dependencies]nix = { version = "0.29.0", features = ["fs"] }@@ -26,3 +26,6 @@ serde = { workspace = true }serde_json = "1.0"flume = "0.11.0"tracing.workspace = true++[lints]+workspace = truediff --git a/crates/utils/src/lib.rs b/crates/utils/src/lib.rsindex de3d38694..266de7409 100644--- a/crates/utils/src/lib.rs+++ b/crates/utils/src/lib.rs@@ -10,8 +10,8 @@ pub fn get_last_win32_error_formatted() -> String {#[cfg(windows)]pub fn format_error_message(error_code: u32) -> String {use windows::{+ Win32::System::Diagnostics::Debug::{FORMAT_MESSAGE_FROM_SYSTEM, FormatMessageW},core::PWSTR,- Win32::System::Diagnostics::Debug::{FormatMessageW, FORMAT_MESSAGE_FROM_SYSTEM},};let mut buffer = vec![0u16; 1024];@@ -44,6 +44,6 @@ where}pub fn ensure_dir(path: &PathBuf) -> Result<PathBuf, std::io::Error> {- std::fs::create_dir_all(&path)?;+ std::fs::create_dir_all(path)?;Ok(path.clone())}diff --git a/crates/video-decode/Cargo.toml b/crates/video-decode/Cargo.tomlindex ed78ebe19..cbb6c9fd9 100644--- a/crates/video-decode/Cargo.toml+++ b/crates/video-decode/Cargo.toml@@ -1,7 +1,7 @@[package]name = "cap-video-decode"version = "0.1.0"-edition = "2021"+edition = "2024"[lints]workspace = truediff --git a/crates/video-decode/src/avassetreader.rs b/crates/video-decode/src/avassetreader.rsindex 1d918848a..58eb04436 100644--- a/crates/video-decode/src/avassetreader.rs+++ b/crates/video-decode/src/avassetreader.rs@@ -112,7 +112,7 @@ impl AVAssetReaderDecoder {Ok((reader_track_output, reader))}- pub fn frames(&mut self) -> FramesIter {+ pub fn frames(&mut self) -> FramesIter<'_> {FramesIter {track_output: &mut self.track_output,}diff --git a/crates/video-decode/src/bin/print_frames.rs b/crates/video-decode/src/bin/print_frames.rsindex a6c9c61e7..e6d0b6bd8 100644--- a/crates/video-decode/src/bin/print_frames.rs+++ b/crates/video-decode/src/bin/print_frames.rs@@ -1,27 +1,37 @@-use std::path::PathBuf;--use cap_video_decode::AVAssetReaderDecoder;-#[tokio::main]pub async fn main() {- let handle = tokio::runtime::Handle::current();+ #[cfg(target_os = "macos")]+ mac::run().await;+ #[cfg(not(target_os = "macos"))]+ panic!("This example is only supported on macOS");+}- let path: PathBuf = std::env::args().collect::<Vec<_>>().swap_remove(1).into();+#[cfg(target_os = "macos")]+mod mac {+ use std::path::PathBuf;- let _ = std::thread::spawn(|| {- let mut decoder = AVAssetReaderDecoder::new(path, handle).unwrap();+ use cap_video_decode::AVAssetReaderDecoder;- for frame in decoder.frames() {- let Ok(frame) = frame else {- return;- };+ pub(super) async fn run() {+ let handle = tokio::runtime::Handle::current();- println!("{:?}", frame.pts());- }- })- .join();-}+ let path: PathBuf = std::env::args().collect::<Vec<_>>().swap_remove(1).into();++ let _ = std::thread::spawn(|| {+ let mut decoder = AVAssetReaderDecoder::new(path, handle).unwrap();++ for frame in decoder.frames() {+ let Ok(frame) = frame else {+ return;+ };++ println!("{:?}", frame.pts());+ }+ })+ .join();+ }-pub fn pts_to_frame(pts: i64, time_base: (f64, f64), fps: u32) -> u32 {- (fps as f64 * ((pts as f64 * time_base.0) / (time_base.1))).round() as u32+ // pub fn pts_to_frame(pts: i64, time_base: (f64, f64), fps: u32) -> u32 {+ // (fps as f64 * ((pts as f64 * time_base.0) / (time_base.1))).round() as u32+ // }}diff --git a/crates/video-decode/src/ffmpeg.rs b/crates/video-decode/src/ffmpeg.rsindex 401770527..b1844e577 100644--- a/crates/video-decode/src/ffmpeg.rs+++ b/crates/video-decode/src/ffmpeg.rs@@ -81,7 +81,7 @@ impl FFmpegDecoder {self.input.seek(position, ..position)}- pub fn frames(&mut self) -> FramesIter {+ pub fn frames(&mut self) -> FramesIter<'_> {FramesIter {packets: self.input.packets(),decoder: &mut self.decoder,@@ -126,16 +126,14 @@ impl<'a> Iterator for FramesIter<'a> {return match &self.hw_device {Some(hw_device) => Some(Ok(hw_device.get_hwframe(&frame).unwrap_or(frame))),None => Some(Ok(frame)),- }+ };}Err(ffmpeg::Error::Eof) => return None,Err(ffmpeg::Error::Other { errno }) if errno == EAGAIN => {}Err(e) => return Some(Err(e)),}- let Some((stream, packet)) = self.packets.next() else {- return None;- };+ let (stream, packet) = self.packets.next()?;if stream.index() != self.stream_index {continue;diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.tsindex a247206bb..9dcda632d 100644--- a/packages/ui-solid/src/auto-imports.d.ts+++ b/packages/ui-solid/src/auto-imports.d.ts@@ -75,6 +75,7 @@ declare global {const IconHugeiconsEaseCurveControlPoints: typeof import('~icons/hugeicons/ease-curve-control-points.jsx')['default']const IconIcBaselineMonitor: typeof import("~icons/ic/baseline-monitor.jsx")["default"]const IconIcRoundSearch: typeof import("~icons/ic/round-search.jsx")["default"]+ const IconLucideAppWindowMac: typeof import('~icons/lucide/app-window-mac.jsx')['default']const IconLucideBell: typeof import('~icons/lucide/bell.jsx')['default']const IconLucideBug: typeof import('~icons/lucide/bug.jsx')['default']const IconLucideCamera: typeof import("~icons/lucide/camera.jsx")["default"]@@ -106,6 +107,7 @@ declare global {const IconLucideVolume2: typeof import('~icons/lucide/volume2.jsx')['default']const IconLucideVolumeX: typeof import('~icons/lucide/volume-x.jsx')['default']const IconLucideX: typeof import("~icons/lucide/x.jsx")["default"]- const IconMdiMonitor: typeof import("~icons/mdi/monitor.jsx")["default"]+ const IconMaterialSymbolsScreenshotFrame2Rounded: typeof import('~icons/material-symbols/screenshot-frame2-rounded.jsx')['default']+ const IconMdiMonitor: typeof import('~icons/mdi/monitor.jsx')['default']const IconPhMonitorBold: typeof import('~icons/ph/monitor-bold.jsx')['default']}