Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
handle some errors better + error boundary
Brendan Allan3a6f97589b81
diff --git a/Cargo.lock b/Cargo.lockindex 033e8a89b..335dec903 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -854,7 +854,7 @@ dependencies = [[[package]]name = "cap-desktop"-version = "0.3.16"+version = "0.3.17"dependencies = ["anyhow","axum",diff --git a/apps/cli/src/main.rs b/apps/cli/src/main.rsindex 90b2c1e0f..6085dc621 100644--- a/apps/cli/src/main.rs+++ b/apps/cli/src/main.rs@@ -164,7 +164,7 @@ impl Export {.unwrap(),);- let segments = create_segments(&meta);+ let segments = create_segments(&meta).await.unwrap();let fps = meta.content.max_fps();let project_output_path = self.project_path.join("output/result.mp4");@@ -180,6 +180,7 @@ impl Export {XY::new(1920, 1080),true,)+ .await.unwrap();exporter.export_with_custom_muxer().await.unwrap();diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 42a79c8dc..75aaaf9a7 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -34,6 +34,7 @@"@solidjs/start": "^1.0.6","@tanstack/solid-query": "^5.51.21","@tauri-apps/api": "^2.1.1",+ "@tauri-apps/plugin-clipboard-manager": "^2.2.1","@tauri-apps/plugin-deep-link": "^2.2.0","@tauri-apps/plugin-dialog": "2.0.1","@tauri-apps/plugin-fs": "2.0.3",diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rsindex 887751959..241ab3df2 100644--- a/apps/desktop/src-tauri/src/export.rs+++ b/apps/desktop/src-tauri/src/export.rs@@ -45,7 +45,7 @@ pub async fn export_video(.unwrap_or(screen_metadata.duration),);- let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;+ let editor_instance = upsert_editor_instance(&app, video_id.clone()).await?;let total_frames = editor_instance.get_total_frames(fps);let output_path = editor_instance.meta().output_path();@@ -94,6 +94,7 @@ pub async fn export_video(resolution_base,is_upgraded,)+ .await.map_err(|e| {sentry::capture_message(&e.to_string(), sentry::Level::Error);e.to_string()@@ -136,7 +137,7 @@ pub async fn get_export_estimates(.await.ok();- let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;+ let editor_instance = upsert_editor_instance(&app, video_id.clone()).await?;let total_frames = editor_instance.get_total_frames(fps);let raw_duration = screen_metadata.duration.max(diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex f36128c01..0df39f341 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -659,7 +659,7 @@ async fn create_thumbnail(input: PathBuf, output: PathBuf, size: (u32, u32)) ->}async fn get_rendered_video_path(app: AppHandle, video_id: String) -> Result<PathBuf, String> {- let editor_instance = upsert_editor_instance(&app, video_id.clone()).await;+ let editor_instance = upsert_editor_instance(&app, video_id.clone()).await?;let output_path = editor_instance.meta().output_path();// If the file doesn't exist, return an error to trigger the progress-enabled path@@ -877,9 +877,14 @@ impl EditorStateChanged {#[tauri::command]#[specta::specta]-async fn start_playback(app: AppHandle, video_id: String, fps: u32, resolution_base: XY<u32>) {+async fn start_playback(+ app: AppHandle,+ video_id: String,+ fps: u32,+ resolution_base: XY<u32>,+) -> Result<(), String> {upsert_editor_instance(&app, video_id)- .await+ .await?.start_playback(fps,resolution_base,@@ -889,19 +894,23 @@ async fn start_playback(app: AppHandle, video_id: String, fps: u32, resolution_b.map(|s| s.is_upgraded()).unwrap_or(false),)- .await+ .await;++ Ok(())}#[tauri::command]#[specta::specta]-async fn stop_playback(app: AppHandle, video_id: String) {- let editor_instance = upsert_editor_instance(&app, video_id).await;+async fn stop_playback(app: AppHandle, video_id: String) -> Result<(), String> {+ let editor_instance = upsert_editor_instance(&app, video_id).await?;let mut state = editor_instance.state.lock().await;if let Some(handle) = state.playback_task.take() {handle.stop();}++ Ok(())}#[derive(Serialize, Type, Debug)]@@ -921,7 +930,7 @@ async fn create_editor_instance(app: AppHandle,video_id: String,) -> Result<SerializedEditorInstance, String> {- let editor_instance = upsert_editor_instance(&app, video_id).await;+ let editor_instance = upsert_editor_instance(&app, video_id).await?;// Load the RecordingMeta to get the pretty namelet meta = RecordingMeta::load_for_project(&editor_instance.project_path)@@ -1113,24 +1122,36 @@ pub enum RenderProgress {#[tauri::command]#[specta::specta]-async fn set_playhead_position(app: AppHandle, video_id: String, frame_number: u32) {- let editor_instance = upsert_editor_instance(&app, video_id).await;+async fn set_playhead_position(+ app: AppHandle,+ video_id: String,+ frame_number: u32,+) -> Result<(), String> {+ let editor_instance = upsert_editor_instance(&app, video_id).await?;editor_instance.modify_and_emit_state(|state| {state.playhead_position = frame_number;}).await;++ Ok(())}#[tauri::command]#[specta::specta]-async fn set_project_config(app: AppHandle, video_id: String, config: ProjectConfiguration) {- let editor_instance = upsert_editor_instance(&app, video_id).await;+async fn set_project_config(+ app: AppHandle,+ video_id: String,+ config: ProjectConfiguration,+) -> Result<(), String> {+ let editor_instance = upsert_editor_instance(&app, video_id).await?;config.write(&editor_instance.project_path).unwrap();editor_instance.project_config.0.send(config).ok();++ Ok(())}#[tauri::command]@@ -1868,14 +1889,16 @@ async fn is_camera_window_open(app: AppHandle) -> bool {#[tauri::command]#[specta::specta]-async fn seek_to(app: AppHandle, video_id: String, frame_number: u32) {- let editor_instance = upsert_editor_instance(&app, video_id).await;+async fn seek_to(app: AppHandle, video_id: String, frame_number: u32) -> Result<(), String> {+ let editor_instance = upsert_editor_instance(&app, video_id).await?;editor_instance.modify_and_emit_state(|state| {state.playhead_position = frame_number;}).await;++ Ok(())}// keep this async otherwise opening windows may hang on windows@@ -2356,7 +2379,10 @@ pub async fn remove_editor_instance(}}-pub async fn upsert_editor_instance(app: &AppHandle, video_id: String) -> Arc<EditorInstance> {+pub async fn upsert_editor_instance(+ app: &AppHandle,+ video_id: String,+) -> Result<Arc<EditorInstance>, String> {let map = match app.try_state::<EditorInstancesState>() {Some(s) => (*s).clone(),None => {@@ -2369,17 +2395,20 @@ pub async fn upsert_editor_instance(app: &AppHandle, video_id: String) -> Arc<Edlet mut map = map.lock().await;use std::collections::hash_map::Entry;- match map.entry(video_id.clone()) {+ Ok(match map.entry(video_id.clone()) {Entry::Occupied(o) => o.get().clone(),Entry::Vacant(v) => {- let instance = create_editor_instance_impl(app, video_id).await;+ let instance = create_editor_instance_impl(app, video_id).await?;v.insert(instance.clone());instance}- }+ })}-async fn create_editor_instance_impl(app: &AppHandle, video_id: String) -> Arc<EditorInstance> {+async fn create_editor_instance_impl(+ app: &AppHandle,+ video_id: String,+) -> Result<Arc<EditorInstance>, String> {let app = app.clone();let instance = EditorInstance::new(@@ -2402,7 +2431,7 @@ async fn create_editor_instance_impl(app: &AppHandle, video_id: String) -> Arc<E}},)- .await;+ .await?;RenderFrameEvent::listen_any(&app, {let preview_tx = instance.preview_tx.clone();@@ -2417,7 +2446,7 @@ async fn create_editor_instance_impl(app: &AppHandle, video_id: String) -> Arc<E}});- instance+ Ok(instance)}// use EditorInstance.project_path instead of thisdiff --git a/apps/desktop/src/App.tsx b/apps/desktop/src/App.tsxindex 43d3b19b7..4a6f24414 100644--- a/apps/desktop/src/App.tsx+++ b/apps/desktop/src/App.tsx@@ -9,6 +9,7 @@ import {} from "solid-js";import { QueryClient, QueryClientProvider } from "@tanstack/solid-query";import { message } from "@tauri-apps/plugin-dialog";+import { writeText } from "@tauri-apps/plugin-clipboard-manager";import "@cap/ui-solid/main.css";import "unfonts.css";@@ -20,6 +21,8 @@ import {getCurrentWebviewWindow,WebviewWindow,} from "@tauri-apps/api/webviewWindow";+import { Button } from "@cap/ui-solid";+import { Toaster } from "solid-toast";const queryClient = new QueryClient({defaultOptions: {@@ -44,47 +47,73 @@ function Inner() {createThemeListener(currentWindow);return (- <ErrorBoundary- fallback={(e: Error) => {- console.error(e);- return (- <>- <p>{e.toString()}</p>- <p>{e.stack?.toString()}</p>- </>- );- }}- >- <QueryClientProvider client={queryClient}>- <Router- root={(props) => {- const matches = useCurrentMatches();+ <>+ <Toaster+ position="top-right"+ toastOptions={{+ duration: 3500,+ style: {+ padding: "8px 16px",+ "border-radius": "15px",+ "font-size": "1rem",+ },+ }}+ />+ <ErrorBoundary+ fallback={(e: Error) => {+ console.error(e);+ return (+ <div class="w-screen h-screen flex flex-col justify-center items-center bg-gray-100 border-gray-200 max-h-screen overflow-hidden transition-[border-radius] duration-200 text-[--text-secondary] gap-y-4">+ <IconCapLogo />+ <h1 class="text-[--text-primary] text-3xl font-bold">+ An Error Occured+ </h1>+ <p>We're very sorry, but something has gone very wrong.</p>+ <div class="flex flex-row gap-x-4">+ <Button+ onClick={() => {+ clipboard.copyText(`${e.toString()}\n\n${e.stack}`);+ }}+ >+ Copy Error to Clipboard+ </Button>+ <Button variant="secondary">Reload</Button>+ </div>+ </div>+ );+ }}+ >+ <QueryClientProvider client={queryClient}>+ <Router+ root={(props) => {+ const matches = useCurrentMatches();- onMount(() => {- for (const match of matches()) {- if (match.route.info?.AUTO_SHOW_WINDOW === false) return;- }+ onMount(() => {+ for (const match of matches()) {+ if (match.route.info?.AUTO_SHOW_WINDOW === false) return;+ }- currentWindow.show();- });+ currentWindow.show();+ });- return (- <Suspense- fallback={- (() => {- console.log("Root suspense fallback showing");- }) as any- }- >- {props.children}- </Suspense>- );- }}- >- <FileRoutes />- </Router>- </QueryClientProvider>- </ErrorBoundary>+ return (+ <Suspense+ fallback={+ (() => {+ console.log("Root suspense fallback showing");+ }) as any+ }+ >+ {props.children}+ </Suspense>+ );+ }}+ >+ <FileRoutes />+ </Router>+ </QueryClientProvider>+ </ErrorBoundary>+ </>);}diff --git a/apps/desktop/src/routes/(window-chrome)/(main).tsx b/apps/desktop/src/routes/(window-chrome)/(main).tsxindex 4a3c0dc70..e2e40dbbf 100644--- a/apps/desktop/src/routes/(window-chrome)/(main).tsx+++ b/apps/desktop/src/routes/(window-chrome)/(main).tsx@@ -53,7 +53,6 @@ import {} from "../editor/ui";const getAuth = cache(async () => {- throw new Error("");const value = await authStore.get();const local = import.meta.env.VITE_LOCAL_MODE === "true";diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.tsindex 897ae6a07..f97a18e92 100644--- a/apps/desktop/src/utils/tauri.ts+++ b/apps/desktop/src/utils/tauri.ts@@ -77,17 +77,17 @@ async getVideoMetadata(videoId: string, videoType: VideoType | null) : Promise<Vasync createEditorInstance(videoId: string) : Promise<SerializedEditorInstance> {return await TAURI_INVOKE("create_editor_instance", { videoId });},-async startPlayback(videoId: string, fps: number, resolutionBase: XY<number>) : Promise<void> {- await TAURI_INVOKE("start_playback", { videoId, fps, resolutionBase });+async startPlayback(videoId: string, fps: number, resolutionBase: XY<number>) : Promise<null> {+ return await TAURI_INVOKE("start_playback", { videoId, fps, resolutionBase });},-async stopPlayback(videoId: string) : Promise<void> {- await TAURI_INVOKE("stop_playback", { videoId });+async stopPlayback(videoId: string) : Promise<null> {+ return await TAURI_INVOKE("stop_playback", { videoId });},-async setPlayheadPosition(videoId: string, frameNumber: number) : Promise<void> {- await TAURI_INVOKE("set_playhead_position", { videoId, frameNumber });+async setPlayheadPosition(videoId: string, frameNumber: number) : Promise<null> {+ return await TAURI_INVOKE("set_playhead_position", { videoId, frameNumber });},-async setProjectConfig(videoId: string, config: ProjectConfiguration) : Promise<void> {- await TAURI_INVOKE("set_project_config", { videoId, config });+async setProjectConfig(videoId: string, config: ProjectConfiguration) : Promise<null> {+ return await TAURI_INVOKE("set_project_config", { videoId, config });},async openEditor(id: string) : Promise<void> {await TAURI_INVOKE("open_editor", { id });@@ -143,8 +143,8 @@ async resetMicrophonePermissions() : Promise<null> {async isCameraWindowOpen() : Promise<boolean> {return await TAURI_INVOKE("is_camera_window_open");},-async seekTo(videoId: string, frameNumber: number) : Promise<void> {- await TAURI_INVOKE("seek_to", { videoId, frameNumber });+async seekTo(videoId: string, frameNumber: number) : Promise<null> {+ return await TAURI_INVOKE("seek_to", { videoId, frameNumber });},async sendFeedbackRequest(feedback: string) : Promise<null> {return await TAURI_INVOKE("send_feedback_request", { feedback });diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rsindex 2dec50ffe..923541b22 100644--- a/crates/editor/src/editor_instance.rs+++ b/crates/editor/src/editor_instance.rs@@ -41,7 +41,7 @@ impl EditorInstance {video_id: String,on_state_change: impl Fn(&EditorState) + Send + Sync + 'static,get_is_upgraded: impl Fn() -> bool + Send + 'static,- ) -> Arc<Self> {+ ) -> Result<Arc<Self>, String> {sentry::configure_scope(|scope| {scope.set_tag("crate", "editor");});@@ -76,7 +76,7 @@ impl EditorInstance {.map(|c| XY::new(c.width, c.height)),};- let segments = create_segments(&meta);+ let segments = create_segments(&meta).await?;let (frame_tx, frame_rx) = flume::bounded(4);@@ -121,7 +121,7 @@ impl EditorInstance {.spawn_preview_renderer(preview_rx, get_is_upgraded),);- this+ Ok(this)}pub fn meta(&self) -> RecordingMeta {@@ -315,12 +315,14 @@ pub struct Segment {pub decoders: RecordingSegmentDecoders,}-pub fn create_segments(meta: &RecordingMeta) -> Vec<Segment> {+pub async fn create_segments(meta: &RecordingMeta) -> Result<Vec<Segment>, String> {match &meta.content {cap_project::Content::SingleSegment { segment: s } => {- let audio = Arc::new(s.audio.as_ref().map(|audio_meta| {- AudioData::from_file(meta.path(&audio_meta.path)).unwrap()- }));+ let audio = Arc::new(+ s.audio+ .as_ref()+ .map(|audio_meta| AudioData::from_file(meta.path(&audio_meta.path)).unwrap()),+ );let cursor = Arc::new(s.cursor_data(&meta).into());@@ -330,21 +332,24 @@ pub fn create_segments(meta: &RecordingMeta) -> Vec<Segment> {display: meta.path(&s.display.path),camera: s.camera.as_ref().map(|c| meta.path(&c.path)),},- );+ )+ .await+ .map_err(|e| format!("SingleSegment:{e}"))?;- vec![Segment {+ Ok(vec![Segment {audio,cursor,decoders,- }]+ }])}cap_project::Content::MultipleSegments { inner } => {let mut segments = vec![];- for s in &inner.segments {- let audio = Arc::new(s.audio.as_ref().map(|audio_meta| {- AudioData::from_file(meta.path(&audio_meta.path)).unwrap()- }));+ for (i, s) in inner.segments.iter().enumerate() {+ let audio =+ Arc::new(s.audio.as_ref().map(|audio_meta| {+ AudioData::from_file(meta.path(&audio_meta.path)).unwrap()+ }));let cursor = Arc::new(s.cursor_events(&meta));@@ -354,7 +359,9 @@ pub fn create_segments(meta: &RecordingMeta) -> Vec<Segment> {display: meta.path(&s.display.path),camera: s.camera.as_ref().map(|c| meta.path(&c.path)),},- );+ )+ .await+ .map_err(|e| format!("MultipleSegments/{i}:{e}"))?;segments.push(Segment {audio,@@ -363,7 +370,7 @@ pub fn create_segments(meta: &RecordingMeta) -> Vec<Segment> {});}- segments+ Ok(segments)}}}diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rsindex b2b0725f7..988a302b9 100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@ -30,6 +30,9 @@ pub enum ExportError {#[error("Join: {0}")]Join(#[from] tokio::task::JoinError),++ #[error("Other:{0}")]+ Other(String),}pub struct Exporter<TOnProgress> {@@ -51,7 +54,7 @@ impl<TOnProgress> Exporter<TOnProgress>whereTOnProgress: Fn(u32) + Send + 'static,{- pub fn new(+ pub async fn new(project: ProjectConfiguration,output_path: PathBuf,on_progress: TOnProgress,@@ -69,34 +72,32 @@ wherelet output_size =ProjectUniforms::get_output_size(&render_constants.options, &project, resolution_base);- let (render_segments, audio_segments): (Vec<_>, Vec<_>) = segments- .iter()- .enumerate()- .map(|(i, segment)| {- let segment_paths = match &meta.content {- cap_project::Content::SingleSegment { segment: s } => SegmentVideoPaths {+ let mut render_segments = vec![];+ let mut audio_segments = vec![];++ for (i, s) in segments.iter().enumerate() {+ let segment_paths = match &meta.content {+ cap_project::Content::SingleSegment { segment: s } => SegmentVideoPaths {+ display: meta.path(&s.display.path),+ camera: s.camera.as_ref().map(|c| meta.path(&c.path)),+ },+ cap_project::Content::MultipleSegments { inner } => {+ let s = &inner.segments[i];++ SegmentVideoPaths {display: meta.path(&s.display.path),camera: s.camera.as_ref().map(|c| meta.path(&c.path)),- },- cap_project::Content::MultipleSegments { inner } => {- let s = &inner.segments[i];-- SegmentVideoPaths {- display: meta.path(&s.display.path),- camera: s.camera.as_ref().map(|c| meta.path(&c.path)),- }}- };-- (- RenderSegment {- cursor: segment.cursor.clone(),- decoders: RecordingSegmentDecoders::new(&meta, segment_paths),- },- segment.audio.clone(),- )- })- .unzip();+ }+ };+ render_segments.push(RenderSegment {+ cursor: s.cursor.clone(),+ decoders: RecordingSegmentDecoders::new(&meta, segment_paths)+ .await+ .map_err(ExportError::Other)?,+ });+ audio_segments.push(s.audio.clone());+ }Ok(Self {project,diff --git a/crates/media/src/pipeline/builder.rs b/crates/media/src/pipeline/builder.rsindex 47075b2d5..f81691aa3 100644--- a/crates/media/src/pipeline/builder.rs+++ b/crates/media/src/pipeline/builder.rs@@ -71,10 +71,13 @@ impl<T> PipelineBuilder<T> {let join_handle = thread::spawn(move || {tracing::dispatcher::with_default(&dispatcher, || {span.in_scope(|| {- launch(ready_sender);- })+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {+ launch(ready_sender);+ }))+ .ok();+ });+ done_tx.send(()).ok();});- done_tx.send(()).ok();});self.tasks.insert(diff --git a/crates/media/src/sources/screen_capture.rs b/crates/media/src/sources/screen_capture.rsindex e9ad09c94..3ba4e593a 100644--- a/crates/media/src/sources/screen_capture.rs+++ b/crates/media/src/sources/screen_capture.rs@@ -375,7 +375,7 @@ fn inner<T>(error!("Failed to build capturer: {e}");ready_signal.send(Err(MediaError::Any("Failed to build capturer")))- .unwrap();+ .ok();return;}};@@ -383,7 +383,7 @@ fn inner<T>(info!("Capturer built");let mut capturing = false;- ready_signal.send(Ok(())).unwrap();+ ready_signal.send(Ok(())).ok();let t = std::time::Instant::now();@@ -489,7 +489,13 @@ pub fn list_screens() -> Vec<(CaptureScreen, Target)> {.get(&screen.id).cloned().unwrap_or_else(|| format!("Screen {}", idx + 1)),- refresh_rate: get_target_fps(&Target::Display(screen.clone())).unwrap(),+ refresh_rate: {+ let Some(fps) = get_target_fps(&Target::Display(screen.clone())) else {+ continue;+ };++ fps+ },},Target::Display(screen),));diff --git a/crates/rendering/src/decoder/avassetreader.rs b/crates/rendering/src/decoder/avassetreader.rsindex c08319c8e..59ba13507 100644--- a/crates/rendering/src/decoder/avassetreader.rs+++ b/crates/rendering/src/decoder/avassetreader.rs@@ -12,7 +12,7 @@ use cidre::{ns,};use ffmpeg::{codec, format, frame, Rational};-use tokio::runtime::Handle as TokioHandle;+use tokio::{runtime::Handle as TokioHandle, sync::oneshot};use super::{pts_to_frame, DecodedFrame, VideoDecoderMessage, FRAME_CACHE_SIZE};@@ -168,83 +168,64 @@ impl AVAssetReaderDecoder {path: PathBuf,fps: u32,rx: mpsc::Receiver<VideoDecoderMessage>,+ ready_tx: oneshot::Sender<Result<(), String>>,) {let handle = tokio::runtime::Handle::current();- std::thread::spawn(move || {- let (pixel_format, width, height) = {- let input = ffmpeg::format::input(&path).unwrap();-- let input_stream = input- .streams()- .best(ffmpeg::media::Type::Video)- .ok_or("Could not find a video stream")+ let handle = std::thread::spawn(move || {+ let init = || {+ let (pixel_format, width, height) = {+ let input = ffmpeg::format::input(&path).unwrap();++ let input_stream = input+ .streams()+ .best(ffmpeg::media::Type::Video)+ .ok_or("Could not find a video stream")+ .unwrap();++ let decoder_codec = super::ffmpeg::find_decoder(+ &input,+ &input_stream,+ input_stream.parameters().id(),+ ).unwrap();- let decoder_codec = super::ffmpeg::find_decoder(- &input,- &input_stream,- input_stream.parameters().id(),- )- .unwrap();+ let mut context = codec::context::Context::new_with_codec(decoder_codec);+ context.set_parameters(input_stream.parameters()).unwrap();- let mut context = codec::context::Context::new_with_codec(decoder_codec);- context.set_parameters(input_stream.parameters()).unwrap();-- let decoder = context.decoder().video().unwrap();- (- pixel_to_pixel_format(decoder.format()),- decoder.width(),- decoder.height(),- )- };-- let asset = av::UrlAsset::with_url(- &ns::Url::with_fs_path_str(path.to_str().unwrap(), false),- None,- )- .unwrap();-- fn get_reader_track_output(- asset: &av::UrlAsset,- time: f32,- handle: &TokioHandle,- pixel_format: cv::PixelFormat,- ) -> R<av::AssetReaderTrackOutput> {- let mut reader = av::AssetReader::with_asset(&asset).unwrap();-- let time_range = cm::TimeRange {- start: cm::Time::with_secs(time as f64, 100),- duration: asset.duration(),+ let decoder = context.decoder().video().unwrap();+ (+ pixel_to_pixel_format(decoder.format()),+ decoder.width(),+ decoder.height(),+ )};- reader.set_time_range(time_range);-- let tracks = handle- .block_on(asset.load_tracks_with_media_type(av::MediaType::video()))- .unwrap();-- let track = tracks.get(0).unwrap();-- let mut reader_track_output = av::AssetReaderTrackOutput::with_track(- &track,- Some(&ns::Dictionary::with_keys_values(- &[cv::pixel_buffer::keys::pixel_format().as_ns()],- &[pixel_format.to_cf_number().as_ns().as_id_ref()],- )),+ let asset = av::UrlAsset::with_url(+ &ns::Url::with_fs_path_str(path.to_str().unwrap(), false),+ None,)- .unwrap();-- reader_track_output.set_always_copies_sample_data(false);-- reader.add_output(&reader_track_output).unwrap();-- reader.start_reading().ok();-- reader_track_output- }+ .ok_or_else(|| format!("UrlAsset::with_url{{{path:?}}}"))?;++ Ok((+ get_reader_track_output(&asset, 0.0, &handle, pixel_format)?,+ width,+ height,+ asset,+ pixel_format,+ ))+ };- let mut track_output = get_reader_track_output(&asset, 0.0, &handle, pixel_format);+ let (mut track_output, width, height, asset, pixel_format) = match init() {+ Ok(v) => {+ ready_tx.send(Ok(())).ok();+ v+ }+ Err(e) => {+ ready_tx.send(Err(e)).ok();+ return;+ }+ };let black_frame = LazyCell::new(|| Arc::new(vec![0; (width * height * 4) as usize]));@@ -288,7 +269,8 @@ impl AVAssetReaderDecoder {requested_time,&handle,pixel_format,- );+ )+ .unwrap();last_decoded_frame = None;}@@ -419,3 +401,47 @@ fn pixel_format_to_pixel(format: cv::PixelFormat) -> format::Pixel {_ => todo!(),}}++fn get_reader_track_output(+ asset: &av::UrlAsset,+ time: f32,+ handle: &TokioHandle,+ pixel_format: cv::PixelFormat,+) -> Result<R<av::AssetReaderTrackOutput>, String> {+ let mut reader =+ av::AssetReader::with_asset(&asset).map_err(|e| format!("AssetReader::with_asset: {e}"))?;++ let time_range = cm::TimeRange {+ start: cm::Time::with_secs(time as f64, 100),+ duration: asset.duration(),+ };++ reader.set_time_range(time_range);++ let tracks = handle+ .block_on(asset.load_tracks_with_media_type(av::MediaType::video()))+ .map_err(|e| format!("asset.load_tracks_with_media_type: {e}"))?;++ let track = tracks.get(0).map_err(|e| e.to_string())?;++ let mut reader_track_output = av::AssetReaderTrackOutput::with_track(+ &track,+ Some(&ns::Dictionary::with_keys_values(+ &[cv::pixel_buffer::keys::pixel_format().as_ns()],+ &[pixel_format.to_cf_number().as_ns().as_id_ref()],+ )),+ )+ .map_err(|e| format!("asset.reader_track_output{{{pixel_format:?}}}): {e}"))?;++ reader_track_output.set_always_copies_sample_data(false);++ reader+ .add_output(&reader_track_output)+ .map_err(|e| format!("reader.add_output: {e}"))?;++ reader+ .start_reading()+ .map_err(|e| format!("reader.start_reading: {e}"))?;++ Ok(reader_track_output)+}diff --git a/crates/rendering/src/decoder/mod.rs b/crates/rendering/src/decoder/mod.rsindex 482ef2d70..4f757d10b 100644--- a/crates/rendering/src/decoder/mod.rs+++ b/crates/rendering/src/decoder/mod.rs@@ -3,6 +3,7 @@ use std::{path::PathBuf,sync::{mpsc, Arc},};+use tokio::sync::oneshot;#[cfg(target_os = "macos")]mod avassetreader;@@ -36,14 +37,19 @@ impl AsyncVideoDecoderHandle {}}-pub fn spawn_decoder(name: &'static str, path: PathBuf, fps: u32) -> AsyncVideoDecoderHandle {+pub async fn spawn_decoder(+ name: &'static str,+ path: PathBuf,+ fps: u32,+) -> Result<AsyncVideoDecoderHandle, String> {+ let (ready_tx, ready_rx) = oneshot::channel();let (tx, rx) = mpsc::channel();let handle = AsyncVideoDecoderHandle { sender: tx };#[cfg(target_os = "macos")]{- avassetreader::AVAssetReaderDecoder::spawn(name, path, fps, rx);+ avassetreader::AVAssetReaderDecoder::spawn(name, path, fps, rx, ready_tx);}#[cfg(not(target_os = "macos"))]@@ -51,5 +57,5 @@ pub fn spawn_decoder(name: &'static str, path: PathBuf, fps: u32) -> AsyncVideoDffmpeg::FfmpegDecoder::spawn(name, path, fps, rx);}- handle+ ready_rx.await.map_err(|e| e.to_string())?.map(|()| handle)}diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex 37c4399a3..5909f900d 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -11,6 +11,7 @@ use cap_project::{use core::f64;use decoder::{spawn_decoder, AsyncVideoDecoderHandle};use futures::future::OptionFuture;+use futures::FutureExt;use futures_intrusive::channel::shared::oneshot_channel;use serde::{Deserialize, Serialize};use specta::Type;@@ -99,7 +100,7 @@ pub struct SegmentVideoPaths {}impl RecordingSegmentDecoders {- pub fn new(meta: &RecordingMeta, segment: SegmentVideoPaths) -> Self {+ pub async fn new(meta: &RecordingMeta, segment: SegmentVideoPaths) -> Result<Self, String> {let screen = spawn_decoder("screen",meta.project_path.join(segment.display),@@ -107,8 +108,10 @@ impl RecordingSegmentDecoders {Content::SingleSegment { segment } => segment.display.fps,Content::MultipleSegments { inner } => inner.segments[0].display.fps,},- );- let camera = segment.camera.map(|camera| {+ )+ .await+ .map_err(|e| format!("Screen:{e}"))?;+ let camera = OptionFuture::from(segment.camera.map(|camera| {spawn_decoder("camera",meta.project_path.join(camera),@@ -119,9 +122,12 @@ impl RecordingSegmentDecoders {}},)- });+ .then(|r| async { r.map_err(|e| format!("Camera:{e}")) })+ }))+ .await+ .transpose()?;- Self { screen, camera }+ Ok(Self { screen, camera })}pub async fn get_frames(diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 2df25332f..7a84e47af 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -109,6 +109,9 @@ importers:'@tauri-apps/api':specifier: ^2.1.1version: 2.1.1+ '@tauri-apps/plugin-clipboard-manager':+ specifier: ^2.2.1+ version: 2.2.1'@tauri-apps/plugin-deep-link':specifier: ^2.2.0version: 2.2.0@@ -4303,10 +4306,10 @@ packages:react-dom:optional: true- '@storybook/[email protected]':- resolution: {integrity: sha512-14mIpBx5oxjliGokiejGxUGReG0UNQwrkeu4FiObX8QQWl94/eCO9ExxdyYPNjMx7OfOfhqwIL3SQnoChp+2yA==}+ '@storybook/[email protected]':+ resolution: {integrity: sha512-O5Ha7ub4dsXSbOo4/yBa9mBGuBp6puJHH47m528KXFiuaj4FgP0OHdD2ztbk3mMGTYl+HM8m8JuByPkBZm0RRg==}peerDependencies:- storybook: ^8.6.0-alpha.1+ storybook: ^8.6.0-alpha.2vite: ^4.0.0 || ^5.0.0 || ^6.0.0'@storybook/[email protected]':@@ -4317,10 +4320,10 @@ packages:peerDependencies:storybook: ^8.3.3- '@storybook/[email protected]':- resolution: {integrity: sha512-Us0p0WaM4QUigPTQ9pRjfUM8PtuflPriuN51FFlTiJDmLF/OEmr/AvWnYhET6RZCYD4p912TVJN/t2xig+nMdA==}+ '@storybook/[email protected]':+ resolution: {integrity: sha512-g5XY9SAe5hp8YzjBk6jHORt0Mn6YF4JI1upFFxTa+YjMMgx7R3tERN+rDoAIZcVTCTTqrjG0LhR8KhMVdY4yMA==}peerDependencies:- storybook: ^8.6.0-alpha.1+ storybook: ^8.6.0-alpha.2'@storybook/[email protected]':resolution: {integrity: sha512-dHYFQH3mA+EtnCkHXzicbLgsvzYjcDJ1JWsogbItZogkPHgSJM/Wr71uMkcvw8v9mmCyP4NpXJuu6bPoVsOnzg==}@@ -4547,6 +4550,9 @@ packages:engines: {node: '>= 10'}hasBin: true+ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-+7YDULB9Bk4fejxYrVNBQcxs3KsjPA3A3r53wwn7K8zOQvxjNBSYBRx/FW1OUBPGzm8BrreJFBkPVzQZSF2R4A==}+'@tauri-apps/[email protected]':resolution: {integrity: sha512-H6mkxr2KZ3XJcKL44tiq6cOjCw9DL8OgU1xjn3j26Qsn+H/roPFiyhR7CHuB8Ar+sQFj4YVlfmJwtBajK2FETQ==}@@ -15055,9 +15061,9 @@ snapshots:react: 18.3.1react-dom: 18.3.1([email protected])- '@storybook/[email protected]([email protected])([email protected](@types/[email protected])([email protected]))':+ '@storybook/[email protected]([email protected])([email protected](@types/[email protected])([email protected]))':dependencies:- '@storybook/csf-plugin': 8.6.0-alpha.1([email protected])+ '@storybook/csf-plugin': 8.6.0-alpha.2([email protected])browser-assert: 1.2.1storybook: 8.3.3ts-dedent: 2.2.0@@ -15088,7 +15094,7 @@ snapshots:storybook: 8.3.3unplugin: 1.16.0- '@storybook/[email protected]([email protected])':+ '@storybook/[email protected]([email protected])':dependencies:storybook: 8.3.3unplugin: 1.16.0@@ -15280,6 +15286,10 @@ snapshots:'@tauri-apps/cli-win32-ia32-msvc': 2.1.0'@tauri-apps/cli-win32-x64-msvc': 2.1.0+ '@tauri-apps/[email protected]':+ dependencies:+ '@tauri-apps/api': 2.1.1+'@tauri-apps/[email protected]':dependencies:'@tauri-apps/api': 2.1.1@@ -17823,7 +17833,7 @@ snapshots:doctrine: 2.1.0eslint: 8.57.1eslint-import-resolver-node: 0.3.9- eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected])([email protected]))([email protected])+ eslint-module-utils: 2.12.0(@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected](@typescript-eslint/[email protected]([email protected])([email protected]))([email protected])([email protected]([email protected]))([email protected]))([email protected])hasown: 2.0.2is-core-module: 2.15.1is-glob: 4.0.3@@ -22630,7 +22640,7 @@ snapshots:[email protected]([email protected])([email protected](@types/[email protected])([email protected])):dependencies:- '@storybook/builder-vite': 8.6.0-alpha.1([email protected])([email protected](@types/[email protected])([email protected]))+ '@storybook/builder-vite': 8.6.0-alpha.2([email protected])([email protected](@types/[email protected])([email protected]))transitivePeerDependencies:- storybook- vite