Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

Revert "wip: More memory debugging"

Richie McIlroyd51145056d25
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 2c7078ec8..4a6504b3e 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.tsx
index bb371df48..69208512c 100644
--- a/apps/desktop/src/routes/editor/Editor.tsx
+++ b/apps/desktop/src/routes/editor/Editor.tsx
@@ -14,7 +14,6 @@ import {
createSignal,
on,
onMount,
- onCleanup,
} from "solid-js";
import { createStore } from "solid-js/store";
import { createMutation } from "@tanstack/solid-query";
@@ -68,6 +67,7 @@ export function Editor() {
</Show>
);
}
+
function Inner() {
const {
project,
@@ -79,15 +79,11 @@ function Inner() {
previewTime,
} = useEditorContext();
- onMount(async () => {
- const unsubscribe = await events.editorStateChanged.listen((e) => {
+ onMount(() => {
+ events.editorStateChanged.listen((e) => {
renderFrame.clear();
setPlaybackTime(e.payload.playhead_position / 30);
});
-
- onCleanup(() => {
- unsubscribe();
- });
});
const renderFrame = throttle((time: number) => {
@@ -145,9 +141,9 @@ function Inner() {
document.addEventListener("keydown", handleKeyDown);
- onCleanup(() => {
+ return () => {
document.removeEventListener("keydown", handleKeyDown);
- });
+ };
});
return (
diff --git a/crates/editor/src/editor.rs b/crates/editor/src/editor.rs
index 304850936..4cb6a6a51 100644
--- a/crates/editor/src/editor.rs
+++ b/crates/editor/src/editor.rs
@@ -1,8 +1,4 @@
-use std::{
- sync::atomic::{AtomicBool, Ordering},
- sync::Arc,
- time::Instant,
-};
+use std::{sync::Arc, time::Instant};
use cap_project::{BackgroundSource, ProjectConfiguration};
use cap_rendering::{decoder::DecodedFrame, produce_frame, ProjectUniforms, RenderVideoConstants};
@@ -118,12 +114,10 @@ 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 {
@@ -132,85 +126,78 @@ 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, shutdown }
+ RendererHandle { tx }
}
async fn run(mut self) {
let mut frame_task: Option<JoinHandle<()>> = None;
- 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;
- }
+ 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;
}
-
- 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);
+
+ 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();
}
+ // 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");
}
}
@@ -241,22 +228,12 @@ impl RendererHandle {
}
pub async fn stop(&self) {
- // 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");
+ // 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");
}
+ // 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.rs
index bea48582c..263b3f929 100644
--- a/crates/editor/src/editor_instance.rs
+++ b/crates/editor/src/editor_instance.rs
@@ -7,7 +7,6 @@ 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};
@@ -17,7 +16,7 @@ const FPS: u32 = 30;
pub struct EditorInstance {
pub project_path: PathBuf,
pub id: String,
- pub audio: Arc<StdMutex<Option<(AudioData, Child)>>>,
+ pub audio: Arc<StdMutex<Option<AudioData>>>,
pub ws_port: u16,
pub decoders: RecordingDecoders,
pub recordings: ProjectRecordings,
@@ -79,35 +78,28 @@ impl EditorInstance {
let audio_path = project_path.join(&meta.path);
// TODO: Use ffmpeg crate instead of command line
- let mut ffmpeg = FFmpeg::new();
- let mut child = ffmpeg
+ let stdout = FFmpeg::new()
.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(), "-"])
- .stdout(std::process::Stdio::piped())
- .spawn()
- .unwrap();
-
- let stdout = child.stdout.take().unwrap();
- let buffer = std::io::Read::bytes(stdout)
- .collect::<Result<Vec<u8>, _>>()
+ .output()
.unwrap()
+ .stdout;
+
+ let buffer = stdout
.chunks_exact(8)
- .map(|chunk| f64::from_le_bytes(chunk.try_into().unwrap()))
+ .map(|c| f64::from_le_bytes([c[0], c[1], c[2], c[3], c[4], c[5], c[6], c[7]]))
.collect::<Vec<_>>();
println!("audio buffer length: {}", buffer.len());
- (
- AudioData {
- buffer: Arc::new(buffer),
- sample_rate: recording.sample_rate,
- },
- child,
- )
+ AudioData {
+ buffer: Arc::new(buffer),
+ sample_rate: recording.sample_rate,
+ }
});
let (frame_tx, frame_rx) = tokio::sync::mpsc::unbounded_channel();
@@ -170,7 +162,7 @@ impl EditorInstance {
if let Some(task) = state.preview_task.take() {
println!("Stopping preview");
task.abort();
- task.await.ok();
+ task.await.ok(); // Await the task to ensure it's fully stopped
}
// Stop WebSocket server
@@ -187,11 +179,10 @@ impl EditorInstance {
println!("Stopping decoders");
self.decoders.stop().await;
- // 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");
+ // Clear audio data
+ if self.audio.lock().unwrap().is_some() {
+ println!("Clearing audio data");
+ *self.audio.lock().unwrap() = None; // Explicitly drop the audio data
}
// Cancel any remaining tasks
@@ -216,16 +207,8 @@ 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::new(StdMutex::new(audio_data)),
+ audio: Arc::clone(&self.audio),
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.rs
index 2f7781beb..fd05de351 100644
--- a/crates/rendering/src/decoder.rs
+++ b/crates/rendering/src/decoder.rs
@@ -3,10 +3,7 @@ use std::{
collections::BTreeMap,
path::PathBuf,
ptr::{null, null_mut},
- sync::{
- atomic::{AtomicBool, Ordering},
- mpsc, Arc,
- },
+ sync::{mpsc, Arc},
};
use ffmpeg::{
@@ -25,7 +22,6 @@ 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 {
@@ -41,7 +37,6 @@ 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();
@@ -280,45 +275,25 @@ impl AsyncVideoDecoder {
println!("failed to send frame {frame_number}");
}
}
- VideoDecoderMessage::Stop(sender) => {
- sender.send(()).ok();
- break;
- }
}
}
});
- AsyncVideoDecoderHandle {
- sender: tx,
- is_stopped,
- }
+ AsyncVideoDecoderHandle { sender: tx }
}
}
#[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))
- .ok()?;
+ .unwrap();
rx.await.ok().flatten()
}
}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 50b2715a5..5e18ec839 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -94,6 +94,9 @@ 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 resources
if let Some(camera) = &self.camera {
camera.stop().await;
}
@@ -1036,3 +1039,16 @@ 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");
+ }
+}