Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
wip: More memory debugging
Richie McIlroy3cd7902fdf5f
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 4a6504b3e..2c7078ec8 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -782,7 +782,7 @@ async fn render_to_file_impl(tx};- let audio = if let Some(audio_data) = audio.lock().unwrap().as_ref() {+ let audio = if let Some((audio_data, _)) = audio.lock().unwrap().as_ref() {let pipe_path = audio_dir.path().join("audio.pipe");create_named_pipe(&pipe_path).unwrap();diff --git a/apps/desktop/src/routes/editor/Editor.tsx b/apps/desktop/src/routes/editor/Editor.tsxindex 69208512c..bb371df48 100644--- a/apps/desktop/src/routes/editor/Editor.tsx+++ b/apps/desktop/src/routes/editor/Editor.tsx@@ -14,6 +14,7 @@ import {createSignal,on,onMount,+ onCleanup,} from "solid-js";import { createStore } from "solid-js/store";import { createMutation } from "@tanstack/solid-query";@@ -67,7 +68,6 @@ export function Editor() {</Show>);}-function Inner() {const {project,@@ -79,11 +79,15 @@ function Inner() {previewTime,} = useEditorContext();- onMount(() => {- events.editorStateChanged.listen((e) => {+ onMount(async () => {+ const unsubscribe = await events.editorStateChanged.listen((e) => {renderFrame.clear();setPlaybackTime(e.payload.playhead_position / 30);});++ onCleanup(() => {+ unsubscribe();+ });});const renderFrame = throttle((time: number) => {@@ -141,9 +145,9 @@ function Inner() {document.addEventListener("keydown", handleKeyDown);- return () => {+ onCleanup(() => {document.removeEventListener("keydown", handleKeyDown);- };+ });});return (diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rsindex 4cb6a6a51..304850936 100644--- a/crates/editor/src/editor.rs+++ b/crates/editor/src/editor.rs@@ -1,4 +1,8 @@-use std::{sync::Arc, time::Instant};+use std::{+ sync::atomic::{AtomicBool, Ordering},+ sync::Arc,+ time::Instant,+};use cap_project::{BackgroundSource, ProjectConfiguration};use cap_rendering::{decoder::DecodedFrame, produce_frame, ProjectUniforms, RenderVideoConstants};@@ -114,10 +118,12 @@ pub struct Renderer {rx: mpsc::Receiver<RendererMessage>,frame_tx: mpsc::UnboundedSender<SocketMessage>,render_constants: Arc<RenderVideoConstants>,+ shutdown: Arc<AtomicBool>,}pub struct RendererHandle {tx: mpsc::Sender<RendererMessage>,+ shutdown: Arc<AtomicBool>,}impl Renderer {@@ -126,78 +132,85 @@ impl Renderer {frame_tx: mpsc::UnboundedSender<SocketMessage>,) -> RendererHandle {let (tx, rx) = mpsc::channel(4);+ let shutdown = Arc::new(AtomicBool::new(false));let this = Self {rx,frame_tx,render_constants,+ shutdown: shutdown.clone(),};tokio::spawn(this.run());- RendererHandle { tx }+ RendererHandle { tx, shutdown }}async fn run(mut self) {let mut frame_task: Option<JoinHandle<()>> = None;- loop {- while let Some(msg) = self.rx.recv().await {- match msg {- RendererMessage::RenderFrame {- screen_frame,- camera_frame,- background,- uniforms,- finished,- } => {- if let Some(task) = frame_task.as_ref() {- if task.is_finished() {- frame_task = None- } else {- continue;+ while !self.shutdown.load(Ordering::SeqCst) {+ tokio::select! {+ Some(msg) = self.rx.recv() => {+ match msg {+ RendererMessage::RenderFrame {+ screen_frame,+ camera_frame,+ background,+ uniforms,+ finished,+ } => {+ if let Some(task) = frame_task.as_ref() {+ if task.is_finished() {+ frame_task = None+ } else {+ continue;+ }}- }- let render_constants = self.render_constants.clone();- let frame_tx = self.frame_tx.clone();-- frame_task = Some(tokio::spawn(async move {- let time = Instant::now();- let frame = produce_frame(- &render_constants,- &screen_frame,- &camera_frame,- cap_rendering::Background::from(background),- &uniforms,- )- .await- .unwrap();- // println!("produced frame in {:?}", time.elapsed());-- frame_tx- .send(SocketMessage::Frame {- data: frame,- width: uniforms.output_size.0,- height: uniforms.output_size.1,- })- .ok();- finished.send(()).ok();- }));- }- RendererMessage::Stop { finished } => {- // Cancel any ongoing frame task- if let Some(task) = frame_task.take() {- task.abort();+ let render_constants = self.render_constants.clone();+ let frame_tx = self.frame_tx.clone();++ frame_task = Some(tokio::spawn(async move {+ let time = Instant::now();+ let frame = produce_frame(+ &render_constants,+ &screen_frame,+ &camera_frame,+ cap_rendering::Background::from(background),+ &uniforms,+ )+ .await+ .unwrap();++ frame_tx+ .send(SocketMessage::Frame {+ data: frame,+ width: uniforms.output_size.0,+ height: uniforms.output_size.1,+ })+ .ok();+ finished.send(()).ok();+ }));+ }+ RendererMessage::Stop { finished } => {+ // Cancel any ongoing frame task+ if let Some(task) = frame_task.take() {+ task.abort();+ }+ // Acknowledge the stop+ let _ = finished.send(());+ // Set the shutdown flag+ self.shutdown.store(true, Ordering::SeqCst);}- // Acknowledge the stop- let _ = finished.send(());- // Exit the run loop- return;}}+ _ = tokio::time::sleep(tokio::time::Duration::from_millis(100)) => {+ // Check shutdown flag periodically+ }}}+ println!("Renderer run loop exited");}}@@ -228,12 +241,22 @@ impl RendererHandle {}pub async fn stop(&self) {- // Send a stop message to the renderer- let (tx, rx) = oneshot::channel();- if let Err(_) = self.tx.send(RendererMessage::Stop { finished: tx }).await {- println!("Failed to send stop message to renderer");+ // Only proceed if we haven't already shut down+ if !self.shutdown.swap(true, Ordering::SeqCst) {+ // Send a stop message to the renderer+ let (tx, rx) = oneshot::channel();+ match self.tx.send(RendererMessage::Stop { finished: tx }).await {+ Ok(_) => {+ // Wait for the renderer to acknowledge the stop+ let _ = rx.await;+ println!("Renderer stopped successfully");+ }+ Err(_) => {+ println!("Renderer was already stopped");+ }+ }+ } else {+ println!("Renderer stop was already requested");}- // Wait for the renderer to acknowledge the stop- let _ = rx.await;}}diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rsindex 263b3f929..bea48582c 100644--- a/crates/editor/src/editor_instance.rs+++ b/crates/editor/src/editor_instance.rs@@ -7,6 +7,7 @@ use cap_project::{ProjectConfiguration, RecordingMeta};use cap_rendering::decoder::AsyncVideoDecoder;use cap_rendering::{ProjectUniforms, RecordingDecoders, RenderOptions, RenderVideoConstants};use std::ops::Deref;+use std::process::Child;use std::sync::Mutex as StdMutex;use std::{path::PathBuf, sync::Arc};use tokio::sync::{mpsc, watch, Mutex};@@ -16,7 +17,7 @@ const FPS: u32 = 30;pub struct EditorInstance {pub project_path: PathBuf,pub id: String,- pub audio: Arc<StdMutex<Option<AudioData>>>,+ pub audio: Arc<StdMutex<Option<(AudioData, Child)>>>,pub ws_port: u16,pub decoders: RecordingDecoders,pub recordings: ProjectRecordings,@@ -78,28 +79,35 @@ impl EditorInstance {let audio_path = project_path.join(&meta.path);// TODO: Use ffmpeg crate instead of command line- let stdout = FFmpeg::new()+ let mut ffmpeg = FFmpeg::new();+ let mut child = ffmpeg.command.arg("-i").arg(audio_path).args(["-f", "f64le", "-acodec", "pcm_f64le"]).args(["-ar", &recording.sample_rate.to_string()]).args(["-ac", &recording.channels.to_string(), "-"])- .output()- .unwrap()- .stdout;+ .stdout(std::process::Stdio::piped())+ .spawn()+ .unwrap();- let buffer = stdout+ let stdout = child.stdout.take().unwrap();+ let buffer = std::io::Read::bytes(stdout)+ .collect::<Result<Vec<u8>, _>>()+ .unwrap().chunks_exact(8)- .map(|c| f64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]))+ .map(|chunk| f64::from_le_bytes(chunk.try_into().unwrap())).collect::<Vec<_>>();println!("audio buffer length: {}", buffer.len());- AudioData {- buffer: Arc::new(buffer),- sample_rate: recording.sample_rate,- }+ (+ AudioData {+ buffer: Arc::new(buffer),+ sample_rate: recording.sample_rate,+ },+ child,+ )});let (frame_tx, frame_rx) = tokio::sync::mpsc::unbounded_channel();@@ -162,7 +170,7 @@ impl EditorInstance {if let Some(task) = state.preview_task.take() {println!("Stopping preview");task.abort();- task.await.ok(); // Await the task to ensure it's fully stopped+ task.await.ok();}// Stop WebSocket server@@ -179,10 +187,11 @@ impl EditorInstance {println!("Stopping decoders");self.decoders.stop().await;- // Clear audio data- if self.audio.lock().unwrap().is_some() {- println!("Clearing audio data");- *self.audio.lock().unwrap() = None; // Explicitly drop the audio data+ // Clear audio data and stop FFmpeg process+ if let Some((_, mut child)) = self.audio.lock().unwrap().take() {+ println!("Stopping FFmpeg process and clearing audio data");+ child.kill().expect("Failed to kill FFmpeg process");+ child.wait().expect("Failed to wait for FFmpeg process");}// Cancel any remaining tasks@@ -207,8 +216,16 @@ impl EditorInstance {let start_frame_number = state.playhead_position;+ // Clone the AudioData outside the MutexGuard+ let audio_data = self+ .audio+ .lock()+ .unwrap()+ .as_ref()+ .map(|(audio_data, _)| audio_data.clone());+let playback_handle = playback::Playback {- audio: Arc::clone(&self.audio),+ audio: Arc::new(StdMutex::new(audio_data)),renderer: self.renderer.clone(),render_constants: self.render_constants.clone(),decoders: self.decoders.clone(),diff --git a/crates/rendering/src/decoder.rs b/crates/rendering/src/decoder.rsindex fd05de351..2f7781beb 100644--- a/crates/rendering/src/decoder.rs+++ b/crates/rendering/src/decoder.rs@@ -3,7 +3,10 @@ use std::{collections::BTreeMap,path::PathBuf,ptr::{null, null_mut},- sync::{mpsc, Arc},+ sync::{+ atomic::{AtomicBool, Ordering},+ mpsc, Arc,+ },};use ffmpeg::{@@ -22,6 +25,7 @@ pub type DecodedFrame = Arc<Vec<u8>>;enum VideoDecoderMessage {GetFrame(u32, tokio::sync::oneshot::Sender<Option<Arc<Vec<u8>>>>),+ Stop(tokio::sync::oneshot::Sender<()>),}fn ts_to_frame(ts: i64, time_base: Rational, frame_rate: Rational) -> u32 {@@ -37,6 +41,7 @@ pub struct AsyncVideoDecoder;impl AsyncVideoDecoder {pub fn spawn(path: PathBuf) -> AsyncVideoDecoderHandle {let (tx, rx) = mpsc::channel();+ let is_stopped = Arc::new(AtomicBool::new(false));std::thread::spawn(move || {let mut input = ffmpeg::format::input(&path).unwrap();@@ -275,25 +280,45 @@ impl AsyncVideoDecoder {println!("failed to send frame {frame_number}");}}+ VideoDecoderMessage::Stop(sender) => {+ sender.send(()).ok();+ break;+ }}}});- AsyncVideoDecoderHandle { sender: tx }+ AsyncVideoDecoderHandle {+ sender: tx,+ is_stopped,+ }}}#[derive(Clone)]pub struct AsyncVideoDecoderHandle {sender: mpsc::Sender<VideoDecoderMessage>,+ is_stopped: Arc<AtomicBool>,}impl AsyncVideoDecoderHandle {+ pub async fn stop(&self) {+ if !self.is_stopped.load(Ordering::SeqCst) {+ let (tx, rx) = tokio::sync::oneshot::channel();+ self.sender.send(VideoDecoderMessage::Stop(tx)).ok();+ rx.await.ok();+ self.is_stopped.store(true, Ordering::SeqCst);+ }+ }+pub async fn get_frame(&self, frame_number: u32) -> Option<Arc<Vec<u8>>> {+ if self.is_stopped.load(Ordering::SeqCst) {+ return None;+ }let (tx, rx) = tokio::sync::oneshot::channel();self.sender.send(VideoDecoderMessage::GetFrame(frame_number, tx))- .unwrap();+ .ok()?;rx.await.ok().flatten()}}diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rsindex 5e18ec839..50b2715a5 100644--- a/crates/rendering/src/lib.rs+++ b/crates/rendering/src/lib.rs@@ -94,9 +94,6 @@ impl RecordingDecoders {}pub async fn stop(&self) {- // Implement the stop logic for the decoders- // This might involve stopping any running decoding tasks- // and cleaning up resourcesif let Some(camera) = &self.camera {camera.stop().await;}@@ -1039,16 +1036,3 @@ fn get_either<T>((a, b): (T, T), left: bool) -> T {b}}--// Add this to the AsyncVideoDecoderHandle struct or impl block--impl AsyncVideoDecoderHandle {- // ... (existing methods)-- pub async fn stop(&self) {- // Implement the stop logic for the video decoder- // This might involve sending a stop signal to a running task- // or cleaning up resources- println!("Video decoder stopped");- }-}