Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
fix(desktop): decode thumbnails at the requested clip time
Richie McIlroyb64c96149d96
diff --git a/apps/desktop-gpui/src/editor_clips.rs b/apps/desktop-gpui/src/editor_clips.rsindex ada39180a..4d0fb144a 100644--- a/apps/desktop-gpui/src/editor_clips.rs+++ b/apps/desktop-gpui/src/editor_clips.rs@@ -2115,6 +2115,14 @@ fn decode_thumbnail_frame(input: &Path, time: f64) -> Result<Arc<RenderImage>, S.best(ffmpeg::media::Type::Video).ok_or("No video stream found")?;let stream_index = stream.index();+ let stream_time_base = stream.time_base();+ let stream_start = match stream.start_time() {+ ffmpeg::ffi::AV_NOPTS_VALUE => 0,+ timestamp => timestamp,+ };+ let target_timestamp = ((time * 1_000_000.0) as i64)+ .rescale((1, 1_000_000), stream_time_base)+ .saturating_add(stream_start);let mut decoder = ffmpeg::codec::context::Context::from_parameters(stream.parameters()).map_err(|e| e.to_string())?@@ -2147,14 +2155,17 @@ fn decode_thumbnail_frame(input: &Path, time: f64) -> Result<Arc<RenderImage>, Sif time > 0.0 {let position_us = (time * 1_000_000.0) as i64;- let seek_target = position_us.rescale((1, 1_000_000), TIME_BASE);+ let seek_target = target_timestamp.rescale(stream_time_base, TIME_BASE);decoder.flush();ictx.seek(seek_target, ..seek_target).map_err(|e| format!("Failed to seek to {position_us}us: {e}"))?;}let mut frame = ffmpeg::frame::Video::empty();+ let mut decoded = ffmpeg::frame::Video::empty();let mut got_frame = false;+ let mut reached_target = false;+ let mut decoder_finished = false;let mut packets_tried = 0usize;'outer: for (packet_stream, packet) in ictx.packets() {@@ -2171,16 +2182,26 @@ fn decode_thumbnail_frame(input: &Path, time: f64) -> Result<Arc<RenderImage>, Scontinue;}- match decoder.receive_frame(&mut frame) {- Ok(()) => {- got_frame = true;- break 'outer;- }- Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => {}- Err(ffmpeg::Error::Eof) => break 'outer,- Err(e) => {- if packets_tried >= SEEK_DECODE_PACKET_LIMIT {- return Err(format!("Failed to decode frame: {e}"));+ loop {+ match decoder.receive_frame(&mut decoded) {+ Ok(()) => {+ std::mem::swap(&mut frame, &mut decoded);+ got_frame = true;+ if thumbnail_frame_reaches_target(&frame, target_timestamp) {+ reached_target = true;+ break 'outer;+ }+ }+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => break,+ Err(ffmpeg::Error::Eof) => {+ decoder_finished = true;+ break 'outer;+ }+ Err(e) => {+ if packets_tried >= SEEK_DECODE_PACKET_LIMIT {+ return Err(format!("Failed to decode frame: {e}"));+ }+ break;}}}@@ -2190,18 +2211,21 @@ fn decode_thumbnail_frame(input: &Path, time: f64) -> Result<Arc<RenderImage>, S}}- if !got_frame {+ if !reached_target && !decoder_finished {decoder.send_eof().map_err(|e| format!("Failed to flush decoder: {e}"))?;loop {- match decoder.receive_frame(&mut frame) {+ match decoder.receive_frame(&mut decoded) {Ok(()) => {+ std::mem::swap(&mut frame, &mut decoded);got_frame = true;- break;+ if thumbnail_frame_reaches_target(&frame, target_timestamp) {+ break;+ }}Err(ffmpeg::Error::Eof) => break,- Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => continue,+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => break,Err(e) => return Err(format!("Failed to flush decoder: {e}")),}}@@ -2237,6 +2261,13 @@ fn decode_thumbnail_frame(input: &Path, time: f64) -> Result<Arc<RenderImage>, S])))}+fn thumbnail_frame_reaches_target(frame: &ffmpeg::frame::Video, target_timestamp: i64) -> bool {+ frame+ .timestamp()+ .or_else(|| frame.pts())+ .is_none_or(|timestamp| timestamp >= target_timestamp)+}+// ---------------------------------------------------------------------------// "Existing recording" -- `add_existing_recording_to_editor` and its helpers// (`apps/desktop/src-tauri/src/import.rs`), the `.cap` branch. The MP4 branch@@ -3335,6 +3366,27 @@ mod tests {use super::*;use gpui::{point, size};+ #[test]+ fn split_thumbnails_use_requested_time_inside_keyframe_interval() {+ let fixture = ImportFixture::new(include_bytes!(+ "../../desktop/src-tauri/test-data/clip-thumbnail-gop.mp4"+ ));+ for (time, expected_channel) in [(0.0, 2), (1.5, 1), (2.5, 0), (3.0, 0)] {+ let thumbnail = decode_thumbnail_frame(&fixture.source, time).unwrap();+ let data = thumbnail.as_bytes(0).unwrap();+ let pixel = &data[..4];+ assert!(+ pixel[expected_channel] > 100,+ "requested {time}s, got {pixel:?}"+ );+ for (channel, value) in pixel[..3].iter().enumerate() {+ if channel != expected_channel {+ assert!(*value < 20, "requested {time}s, got {pixel:?}");+ }+ }+ }+ }+const MP4_WITHOUT_AUDIO: &[u8] =include_bytes!("../../media-server/src/__tests__/fixtures/test-no-audio.mp4");const MP4_WITH_AUDIO: &[u8] =diff --git a/apps/desktop/src-tauri/src/clip_thumbnails.rs b/apps/desktop/src-tauri/src/clip_thumbnails.rsindex bc898f7fc..929803550 100644--- a/apps/desktop/src-tauri/src/clip_thumbnails.rs+++ b/apps/desktop/src-tauri/src/clip_thumbnails.rs@@ -38,16 +38,19 @@ pub async fn get_clip_thumbnail(};let time = time.max(0.0);- let cache_path = project_path.join("thumbnails").join("clips").join(format!(- "seg{recording_segment}_{}.jpg",- (time * 1000.0).round() as i64- ));+ let cache_path = project_path+ .join("thumbnails")+ .join("clips-v2")+ .join(format!(+ "seg{recording_segment}_{}.jpg",+ (time * 1000.0).round() as i64+ ));if tokio::fs::try_exists(&cache_path).await.unwrap_or(false) {return Ok(cache_path.to_string_lossy().into_owned());}- let _permit = THUMBNAIL_SEMAPHORE+ let permit = THUMBNAIL_SEMAPHORE.acquire().await.map_err(|e| format!("Failed to acquire thumbnail permit: {e}"))?;@@ -57,9 +60,12 @@ pub async fn get_clip_thumbnail(}let output = cache_path.clone();- tokio::task::spawn_blocking(move || decode_clip_thumbnail(&display_path, time, &output))- .await- .map_err(|e| format!("Thumbnail task failed: {e}"))??;+ tokio::task::spawn_blocking(move || {+ let _permit = permit;+ decode_clip_thumbnail(&display_path, time, &output)+ })+ .await+ .map_err(|e| format!("Thumbnail task failed: {e}"))??;Ok(cache_path.to_string_lossy().into_owned())}@@ -75,6 +81,14 @@ fn decode_clip_thumbnail(input: &Path, time: f64, output: &Path) -> Result<(), S.best(ffmpeg::media::Type::Video).ok_or("No video stream found")?;let stream_index = stream.index();+ let stream_time_base = stream.time_base();+ let stream_start = match stream.start_time() {+ ffmpeg::ffi::AV_NOPTS_VALUE => 0,+ timestamp => timestamp,+ };+ let target_timestamp = ((time * 1_000_000.0) as i64)+ .rescale((1, 1_000_000), stream_time_base)+ .saturating_add(stream_start);let mut decoder = ffmpeg::codec::context::Context::from_parameters(stream.parameters()).map_err(|e| e.to_string())?@@ -105,14 +119,17 @@ fn decode_clip_thumbnail(input: &Path, time: f64, output: &Path) -> Result<(), Sif time > 0.0 {let position_us = (time * 1_000_000.0) as i64;- let seek_target = position_us.rescale((1, 1_000_000), TIME_BASE);+ let seek_target = target_timestamp.rescale(stream_time_base, TIME_BASE);decoder.flush();ictx.seek(seek_target, ..seek_target).map_err(|e| format!("Failed to seek to {position_us}us: {e}"))?;}let mut frame = ffmpeg::frame::Video::empty();+ let mut decoded = ffmpeg::frame::Video::empty();let mut got_frame = false;+ let mut reached_target = false;+ let mut decoder_finished = false;let mut packets_tried = 0usize;'outer: for (packet_stream, packet) in ictx.packets() {@@ -129,16 +146,26 @@ fn decode_clip_thumbnail(input: &Path, time: f64, output: &Path) -> Result<(), Scontinue;}- match decoder.receive_frame(&mut frame) {- Ok(()) => {- got_frame = true;- break 'outer;- }- Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => {}- Err(ffmpeg::Error::Eof) => break 'outer,- Err(e) => {- if packets_tried >= SEEK_DECODE_PACKET_LIMIT {- return Err(format!("Failed to decode frame: {e}"));+ loop {+ match decoder.receive_frame(&mut decoded) {+ Ok(()) => {+ std::mem::swap(&mut frame, &mut decoded);+ got_frame = true;+ if thumbnail_frame_reaches_target(&frame, target_timestamp) {+ reached_target = true;+ break 'outer;+ }+ }+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => break,+ Err(ffmpeg::Error::Eof) => {+ decoder_finished = true;+ break 'outer;+ }+ Err(e) => {+ if packets_tried >= SEEK_DECODE_PACKET_LIMIT {+ return Err(format!("Failed to decode frame: {e}"));+ }+ break;}}}@@ -148,18 +175,21 @@ fn decode_clip_thumbnail(input: &Path, time: f64, output: &Path) -> Result<(), S}}- if !got_frame {+ if !reached_target && !decoder_finished {decoder.send_eof().map_err(|e| format!("Failed to flush decoder: {e}"))?;loop {- match decoder.receive_frame(&mut frame) {+ match decoder.receive_frame(&mut decoded) {Ok(()) => {+ std::mem::swap(&mut frame, &mut decoded);got_frame = true;- break;+ if thumbnail_frame_reaches_target(&frame, target_timestamp) {+ break;+ }}Err(ffmpeg::Error::Eof) => break,- Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => continue,+ Err(ffmpeg::Error::Other { errno }) if errno == ffmpeg::ffi::EAGAIN => break,Err(e) => return Err(format!("Failed to flush decoder: {e}")),}}@@ -201,15 +231,163 @@ fn decode_clip_thumbnail(input: &Path, time: f64, output: &Path) -> Result<(), S).map_err(|e| format!("Failed to encode thumbnail: {e}"))?;- if let Some(parent) = output.parent() {- std::fs::create_dir_all(parent)- .map_err(|e| format!("Failed to create thumbnail directory: {e}"))?;- }+ persist_clip_thumbnail(output, &jpeg_bytes)+}++fn thumbnail_frame_reaches_target(frame: &ffmpeg::frame::Video, target_timestamp: i64) -> bool {+ frame+ .timestamp()+ .or_else(|| frame.pts())+ .is_none_or(|timestamp| timestamp >= target_timestamp)+}- let tmp_path = output.with_extension("jpg.tmp");- std::fs::write(&tmp_path, &jpeg_bytes)+fn persist_clip_thumbnail(output: &Path, jpeg_bytes: &[u8]) -> Result<(), String> {+ use std::io::Write;++ let parent = output.parent().unwrap_or_else(|| Path::new("."));+ std::fs::create_dir_all(parent)+ .map_err(|e| format!("Failed to create thumbnail directory: {e}"))?;++ let mut staged = tempfile::NamedTempFile::new_in(parent)+ .map_err(|e| format!("Failed to stage thumbnail: {e}"))?;+ staged+ .write_all(jpeg_bytes).map_err(|e| format!("Failed to write thumbnail: {e}"))?;- std::fs::rename(&tmp_path, output).map_err(|e| format!("Failed to persist thumbnail: {e}"))?;+ staged+ .persist(output)+ .map_err(|e| format!("Failed to persist thumbnail: {e}"))?;Ok(())}++#[cfg(test)]+mod persistence_tests {+ use super::*;+ use std::sync::{Arc, Barrier};++ #[test]+ fn concurrent_identical_thumbnails_are_all_persisted() {+ let root = tempfile::tempdir().unwrap();+ let output = root.path().join("clips").join("segment.jpg");+ let barrier = Arc::new(Barrier::new(4));+ let pixels = [35; 24 * 24 * 3];+ let mut jpeg = Vec::new();+ image::codecs::jpeg::JpegEncoder::new(&mut jpeg)+ .encode(&pixels, 24, 24, image::ExtendedColorType::Rgb8)+ .unwrap();++ std::thread::scope(|scope| {+ let tasks = (0..4)+ .map(|_| {+ let output = &output;+ let jpeg = &jpeg;+ let barrier = barrier.clone();+ scope.spawn(move || {+ barrier.wait();+ persist_clip_thumbnail(output, jpeg)+ })+ })+ .collect::<Vec<_>>();++ for task in tasks {+ task.join().unwrap().unwrap();+ }+ });++ assert_eq!(std::fs::read(&output).unwrap(), jpeg);+ assert_eq!(image::open(&output).unwrap().width(), 24);+ assert_eq!(+ std::fs::read_dir(output.parent().unwrap()).unwrap().count(),+ 1+ );+ }++ #[test]+ fn replacing_cached_thumbnail_preserves_contents() {+ let root = tempfile::tempdir().unwrap();+ let output = root.path().join("segment.jpg");+ persist_clip_thumbnail(&output, b"old thumbnail").unwrap();+ persist_clip_thumbnail(&output, b"replacement thumbnail").unwrap();+ assert_eq!(std::fs::read(&output).unwrap(), b"replacement thumbnail");+ assert_eq!(std::fs::read_dir(root.path()).unwrap().count(), 1);+ }+}++#[cfg(test)]+mod decoding_tests {+ use super::*;+ use std::{+ path::PathBuf,+ sync::{Arc, Barrier},+ };++ fn fixture() -> (tempfile::TempDir, PathBuf) {+ ffmpeg::init().unwrap();+ let root = tempfile::tempdir().unwrap();+ let input = root.path().join("gop.mp4");+ std::fs::write(+ &input,+ include_bytes!("../test-data/clip-thumbnail-gop.mp4"),+ )+ .unwrap();+ (root, input)+ }++ #[test]+ fn split_thumbnails_use_requested_time_inside_keyframe_interval() {+ let (root, input) = fixture();+ for (time, expected_channel) in [(0.0, 0), (1.5, 1), (2.5, 2), (3.0, 2)] {+ let output = root.path().join(format!("{time}.jpg"));+ decode_clip_thumbnail(&input, time, &output).unwrap();+ let image = image::open(&output).unwrap().to_rgb8();+ let pixel = image.get_pixel(80, 45).0;+ assert!(+ pixel[expected_channel] > 100,+ "requested {time}s, got {pixel:?}"+ );+ for (channel, value) in pixel.iter().enumerate() {+ if channel != expected_channel {+ assert!(*value < 20, "requested {time}s, got {pixel:?}");+ }+ }+ }+ }++ #[test]+ fn simultaneous_decodes_of_one_clip_all_produce_valid_thumbnail() {+ let (root, input) = fixture();+ let output = root.path().join("same-clip.jpg");+ let barrier = Arc::new(Barrier::new(4));++ std::thread::scope(|scope| {+ let tasks = (0..4)+ .map(|_| {+ let input = &input;+ let output = &output;+ let barrier = barrier.clone();+ scope.spawn(move || {+ barrier.wait();+ decode_clip_thumbnail(input, 1.5, output)+ })+ })+ .collect::<Vec<_>>();+ for task in tasks {+ task.join().unwrap().unwrap();+ }+ });++ let image = image::open(output).unwrap().to_rgb8();+ let pixel = image.get_pixel(80, 45).0;+ assert!(pixel[1] > 100 && pixel[0] < 20 && pixel[2] < 20);+ }++ #[test]+ fn frames_without_timestamps_preserve_first_frame_fallback() {+ let mut frame = ffmpeg::frame::Video::empty();+ assert!(thumbnail_frame_reaches_target(&frame, 100));+ frame.set_pts(Some(99));+ assert!(!thumbnail_frame_reaches_target(&frame, 100));+ frame.set_pts(Some(100));+ assert!(thumbnail_frame_reaches_target(&frame, 100));+ }+}diff --git a/apps/desktop/src-tauri/test-data/clip-thumbnail-gop.mp4 b/apps/desktop/src-tauri/test-data/clip-thumbnail-gop.mp4new file mode 100644index 000000000..fe7800a78Binary files /dev/null and b/apps/desktop/src-tauri/test-data/clip-thumbnail-gop.mp4 differ