Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

WIP Pause/Resume (#87)

Brendan Allan2f7d15b538fd
diff --git a/Cargo.lock b/Cargo.lock
index 646572d8f..5aa93a320 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -659,6 +659,7 @@ version = "0.1.0"
dependencies = [
"cap-utils",
"ffmpeg-sidecar 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)",
+ "nix 0.29.0",
"tauri",
"tauri-plugin-shell",
]
diff --git a/apps/desktop/app.config.timestamp_1726573950462.js b/apps/desktop/app.config.timestamp_1726573950462.js
deleted file mode 100644
index ed99ad588..000000000
--- a/apps/desktop/app.config.timestamp_1726573950462.js
+++ /dev/null
@@ -1,34 +0,0 @@
-// app.config.ts
-import { defineConfig } from "@solidjs/start/config";
-import capUIPlugin from "@cap/ui-solid/vite";
-import tsconfigPaths from "vite-tsconfig-paths";
-var app_config_default = defineConfig({
- ssr: false,
- server: { preset: "static" },
- // https://vitejs.dev/config
- vite: () => ({
- // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
- // 1. tauri expects a fixed port, fail if that port is not available
- server: {
- port: 3001,
- strictPort: true,
- watch: {
- // 2. tell vite to ignore watching `src-tauri`
- ignored: ["**/src-tauri/**"]
- }
- },
- // 3. to make use of `TAURI_DEBUG` and other env variables
- // https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
- envPrefix: ["VITE_", "TAURI_"],
- plugins: [
- capUIPlugin,
- tsconfigPaths({
- // If this isn't set Vinxi hangs on startup
- root: "."
- })
- ]
- })
-});
-export {
- app_config_default as default
-};
diff --git a/apps/desktop/app.config.timestamp_1726574045475.js b/apps/desktop/app.config.timestamp_1726574045475.js
deleted file mode 100644
index ed99ad588..000000000
--- a/apps/desktop/app.config.timestamp_1726574045475.js
+++ /dev/null
@@ -1,34 +0,0 @@
-// app.config.ts
-import { defineConfig } from "@solidjs/start/config";
-import capUIPlugin from "@cap/ui-solid/vite";
-import tsconfigPaths from "vite-tsconfig-paths";
-var app_config_default = defineConfig({
- ssr: false,
- server: { preset: "static" },
- // https://vitejs.dev/config
- vite: () => ({
- // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
- // 1. tauri expects a fixed port, fail if that port is not available
- server: {
- port: 3001,
- strictPort: true,
- watch: {
- // 2. tell vite to ignore watching `src-tauri`
- ignored: ["**/src-tauri/**"]
- }
- },
- // 3. to make use of `TAURI_DEBUG` and other env variables
- // https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
- envPrefix: ["VITE_", "TAURI_"],
- plugins: [
- capUIPlugin,
- tsconfigPaths({
- // If this isn't set Vinxi hangs on startup
- root: "."
- })
- ]
- })
-});
-export {
- app_config_default as default
-};
diff --git a/apps/desktop/app.config.timestamp_1726574142405.js b/apps/desktop/app.config.timestamp_1726574142405.js
deleted file mode 100644
index ed99ad588..000000000
--- a/apps/desktop/app.config.timestamp_1726574142405.js
+++ /dev/null
@@ -1,34 +0,0 @@
-// app.config.ts
-import { defineConfig } from "@solidjs/start/config";
-import capUIPlugin from "@cap/ui-solid/vite";
-import tsconfigPaths from "vite-tsconfig-paths";
-var app_config_default = defineConfig({
- ssr: false,
- server: { preset: "static" },
- // https://vitejs.dev/config
- vite: () => ({
- // Vite options tailored for Tauri development and only applied in `tauri dev` or `tauri build`
- // 1. tauri expects a fixed port, fail if that port is not available
- server: {
- port: 3001,
- strictPort: true,
- watch: {
- // 2. tell vite to ignore watching `src-tauri`
- ignored: ["**/src-tauri/**"]
- }
- },
- // 3. to make use of `TAURI_DEBUG` and other env variables
- // https://tauri.studio/v1/api/config#buildconfig.beforedevcommand
- envPrefix: ["VITE_", "TAURI_"],
- plugins: [
- capUIPlugin,
- tsconfigPaths({
- // If this isn't set Vinxi hangs on startup
- root: "."
- })
- ]
- })
-});
-export {
- app_config_default as default
-};
diff --git a/apps/desktop/src-tauri/src/audio.rs b/apps/desktop/src-tauri/src/audio.rs
index 80b5ef0f8..d92cf91b5 100644
--- a/apps/desktop/src-tauri/src/audio.rs
+++ b/apps/desktop/src-tauri/src/audio.rs
@@ -1,18 +1,20 @@
-use cap_ffmpeg::NamedPipeCapture;
-use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
-use cpal::{Device, SampleFormat, SizedSample, Stream, StreamConfig, SupportedStreamConfig};
+use cap_utils::create_named_pipe;
+use cpal::{
+ traits::{DeviceTrait, HostTrait, StreamTrait},
+ Device, SampleFormat, SizedSample, Stream, StreamConfig, SupportedStreamConfig,
+};
+use ffmpeg_next as ffmpeg;
use indexmap::IndexMap;
use num_traits::ToBytes;
-use std::fs::File;
-use std::io::Write;
-use std::sync::atomic::Ordering;
-use std::time::Instant;
-use std::{path::PathBuf, sync::Arc};
-use tokio::sync::mpsc;
-use tokio::sync::mpsc::error::TrySendError;
-use tokio::sync::{oneshot, watch};
+use std::{fs::File, io::Write, path::PathBuf, sync::Arc, time::Instant};
+use tokio::sync::{
+ mpsc::{self, error::TrySendError},
+ oneshot, watch,
+};
-type SampleReceiver = mpsc::Receiver<Arc<Vec<u8>>>;
+use crate::{capture::CaptureController, encoder::MP3Encoder};
+
+type SampleReceiver = mpsc::Receiver<Arc<Vec<f32>>>;
pub struct AudioCapturer {
device: Device,
@@ -25,7 +27,7 @@ pub struct AudioCapturer {
unsafe impl Send for AudioCapturer {}
unsafe impl Sync for AudioCapturer {}
-const MAX_CHANNELS: u16 = 2;
+const MAX_CHANNELS: u16 = 1;
impl AudioCapturer {
pub fn init(name: &str) -> Option<Self> {
@@ -52,25 +54,33 @@ impl AudioCapturer {
}
pub fn log_info(&self) {
- tracing::info!("Sample rate: {}", self.sample_rate());
- tracing::info!("Channels: {}", self.channels());
- tracing::info!("Sample format: {}", self.sample_format());
+ println!("Sample rate: {}", self.sample_rate());
+ println!("Channels: {}", self.channels());
+ println!("Sample format: {}", self.sample_format());
}
pub fn start(&mut self, start_time_tx: oneshot::Sender<Instant>) -> Result<(), String> {
+ self.log_info();
tracing::trace!("Building input stream...");
- let (receiver, stream) = (match self.supported_config.sample_format() {
- SampleFormat::I8 => self.build_stream::<i8>(start_time_tx),
- SampleFormat::I16 => self.build_stream::<i16>(start_time_tx),
- SampleFormat::I32 => self.build_stream::<i32>(start_time_tx),
- SampleFormat::U8 => self.build_stream::<u8>(start_time_tx),
- SampleFormat::U16 => self.build_stream::<u16>(start_time_tx),
- SampleFormat::U32 => self.build_stream::<u32>(start_time_tx),
- SampleFormat::F32 => self.build_stream::<f32>(start_time_tx),
- SampleFormat::F64 => self.build_stream::<f64>(start_time_tx),
- _ => unreachable!(),
- })?;
+ let (receiver, stream) =
+ (match self.supported_config.sample_format() {
+ SampleFormat::I8 => self
+ .build_stream::<i8>(start_time_tx, |n| n as f32 / i8::MAX as f32 * 2.0 - 1.0),
+ SampleFormat::I16 => self
+ .build_stream::<i16>(start_time_tx, |n| n as f32 / i16::MAX as f32 * 2.0 - 1.0),
+ SampleFormat::I32 => self
+ .build_stream::<i32>(start_time_tx, |n| n as f32 / i32::MAX as f32 * 2.0 - 1.0),
+ SampleFormat::U8 => self
+ .build_stream::<u8>(start_time_tx, |n| n as f32 / u8::MAX as f32 * 2.0 - 1.0),
+ SampleFormat::U16 => self
+ .build_stream::<u16>(start_time_tx, |n| n as f32 / u16::MAX as f32 * 2.0 - 1.0),
+ SampleFormat::U32 => self
+ .build_stream::<u32>(start_time_tx, |n| n as f32 / u32::MAX as f32 * 2.0 - 1.0),
+ SampleFormat::F32 => self.build_stream::<f32>(start_time_tx, |n| n),
+ SampleFormat::F64 => self.build_stream::<f64>(start_time_tx, |n| n as f32),
+ _ => unreachable!(),
+ })?;
stream
.play()
@@ -82,6 +92,26 @@ impl AudioCapturer {
Ok(())
}
+ pub fn pause(&mut self) -> Result<(), String> {
+ if let Some(ref mut stream) = self.stream {
+ stream
+ .pause()
+ .map_err(|_| "Failed to pause stream".to_string())
+ } else {
+ Err("Stream not started".to_string())
+ }
+ }
+
+ pub fn resume(&mut self) -> Result<(), String> {
+ if let Some(ref mut stream) = self.stream {
+ stream
+ .play()
+ .map_err(|_| "Failed to resume stream".to_string())
+ } else {
+ Err("Stream not started".to_string())
+ }
+ }
+
pub fn stop(&mut self) -> Result<(), String> {
if let Some(ref mut stream) = self.stream {
stream.pause().map_err(|_| "Failed to pause stream")?;
@@ -127,13 +157,11 @@ impl AudioCapturer {
}
}
- fn build_stream<T>(
+ fn build_stream<T: SizedSample + 'static>(
&self,
start_time_tx: oneshot::Sender<Instant>,
- ) -> Result<(SampleReceiver, Stream), String>
- where
- T: SizedSample + ToBytes<Bytes: AsRef<[u8]>>,
- {
+ convert_fn: fn(T) -> f32,
+ ) -> Result<(SampleReceiver, Stream), String> {
let (sender, receiver) = mpsc::channel(2048);
let mut start_time_tx = Some(start_time_tx);
@@ -142,20 +170,13 @@ impl AudioCapturer {
.build_input_stream(
&self.config.clone(),
move |data: &[T], _| {
- let sample_size = std::mem::size_of::<T>();
- let mut bytes = vec![0; std::mem::size_of_val(data)];
- let size = bytes.len();
- for (dest, source) in bytes.chunks_exact_mut(sample_size).zip(data.iter()) {
- dest.copy_from_slice(source.to_le_bytes().as_ref());
- }
-
- let sample_data = Arc::new(bytes);
- match sender.try_send(sample_data) {
+ match sender.try_send(Arc::new(
+ data.iter().map(|sample| convert_fn(*sample)).collect(),
+ )) {
Ok(_) => {
if let Some(start_time_option) = start_time_tx.take() {
start_time_option.send(Instant::now()).ok();
- tracing::info!("Audio sample size: {size}");
tracing::trace!("Audio start time captured");
}
}
@@ -228,49 +249,154 @@ pub fn get_input_devices() -> IndexMap<String, (Device, SupportedStreamConfig)>
}
pub async fn start_capturing(
- capturer: &mut AudioCapturer,
+ mut capturer: AudioCapturer,
pipe_path: PathBuf,
start_writing_rx: watch::Receiver<bool>,
-) -> (NamedPipeCapture, Instant) {
- let (capture, is_stopped) = NamedPipeCapture::new(&pipe_path);
+) -> (CaptureController, AudioCapturer) {
+ let controller = CaptureController::new(pipe_path.clone());
let (tx, rx) = oneshot::channel();
capturer.start(tx).unwrap();
+ create_named_pipe(&pipe_path).unwrap();
+
println!("Starting audio channel senders...");
let mut receiver = capturer
.sample_receiver
.take()
.expect("Audio sample collection already started!");
- tokio::spawn(async move {
- println!("Opening audio pipe...");
- let mut pipe = File::create(&pipe_path).unwrap();
- println!("Audio pipe opened");
+ tokio::spawn({
+ let controller = controller.clone();
+ async move {
+ println!("Opening audio pipe...");
+ let mut pipe = File::create(&pipe_path).unwrap();
+ println!("Audio pipe opened");
+
+ while let Some(samples) = receiver.recv().await {
+ if controller.is_stopped() {
+ println!("Stopping receiving camera frames");
+ break;
+ }
- while let Some(bytes) = receiver.recv().await {
- if is_stopped.load(Ordering::Relaxed) {
- println!("Stopping receiving camera frames");
- return;
- }
+ if !*start_writing_rx.borrow() || controller.is_paused() {
+ continue;
+ }
- if !*start_writing_rx.borrow() {
- continue;
+ pipe.write_all(
+ &samples
+ .iter()
+ .flat_map(|f| f.to_le_bytes())
+ .collect::<Vec<_>>(),
+ )
+ .unwrap();
}
- pipe.write_all(&bytes).unwrap();
- }
-
- println!("Done receiving audio frames");
+ println!("Done receiving audio frames");
- pipe.sync_all().ok();
+ pipe.sync_all().ok();
+ }
});
- (capture, rx.await.unwrap())
+ rx.await.unwrap(); // wait for first frame
+
+ (controller, capturer)
}
-pub fn play_audio<const N: usize>(bytes: &'static [u8; N]) {
+// ffmpeg
+// .command
+// .args(["-ac", &capturer.channels().to_string(), "-async", "1"])
+// .args([
+// "-af",
+// "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
+// ])
+// .arg(&output_path);
+
+// pub async fn start_capturing(
+// mut capturer: AudioCapturer,
+// output_path: PathBuf,
+// start_writing_rx: watch::Receiver<bool>,
+// ) -> CaptureController {
+// let controller = CaptureController::new(output_path);
+
+// let (tx, rx) = oneshot::channel();
+
+// capturer.start(tx).unwrap();
+// let sample_rate = capturer.sample_rate();
+
+// tokio::spawn({
+// let controller = controller.clone();
+// async move {
+// let mut receiver = capturer
+// .sample_receiver
+// .take()
+// .expect("Audio sample collection already started!");
+
+// let mut encoder = MP3Encoder::new(&controller.output_path, sample_rate);
+
+// dbg!(encoder.context.frame_size());
+// let mut frame_buffer = Vec::<f32>::with_capacity(encoder.context.frame_size() as usize);
+
+// while let Some(samples) = receiver.recv().await {
+// if controller.is_stopped() {
+// println!("Stopping receiving audio frames");
+// break;
+// }
+
+// if !*start_writing_rx.borrow() {
+// continue;
+// }
+
+// if controller.is_paused() {
+// // Skip writing data to pipe while paused
+// continue;
+// }
+
+// let mut processed_samples = 0;
+// while processed_samples < samples.len() {
+// let buffer_remaining = frame_buffer.capacity() - frame_buffer.len();
+// let src_range = 0..usize::min(samples.len(), buffer_remaining);
+
+// processed_samples += src_range.len();
+
+// frame_buffer.extend_from_slice(&samples[src_range]);
+
+// if frame_buffer.len() < frame_buffer.capacity() {
+// continue;
+// }
+
+// let mut frame = ffmpeg::frame::Audio::new(
+// ffmpeg::format::Sample::F32(ffmpeg::format::sample::Type::Packed),
+// frame_buffer.len(),
+// ffmpeg::ChannelLayout::MONO,
+// );
+
+// frame.data_mut(0).copy_from_slice(
+// &frame_buffer
+// .iter()
+// .flat_map(|float| float.to_ne_bytes())
+// .collect::<Vec<_>>(),
+// );
+
+// frame_buffer.clear();
+
+// encoder.encode_frame(frame);
+// }
+// }
+
+// capturer.stop().ok();
+
+// println!("Done receiving audio frames");
+// }
+// });
+
+// rx.await.unwrap(); // wait for first frame
+
+// controller
+// }
+
+fn play_audio<const N: usize>(bytes: &'static [u8; N]) {
use rodio::{Decoder, OutputStream, Sink};
use std::io::Cursor;
@@ -282,3 +408,21 @@ pub fn play_audio<const N: usize>(bytes: &'static [u8; N]) {
sink.sleep_until_end();
}
}
+
+pub enum AppSounds {
+ StartRecording,
+ StopRecording,
+ Screenshot,
+}
+
+impl AppSounds {
+ pub fn play(self) {
+ match self {
+ AppSounds::StartRecording => {
+ play_audio(include_bytes!("../sounds/start-recording.ogg"))
+ }
+ AppSounds::StopRecording => play_audio(include_bytes!("../sounds/stop-recording.ogg")),
+ AppSounds::Screenshot => play_audio(include_bytes!("../sounds/screenshot.ogg")),
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/camera.rs b/apps/desktop/src-tauri/src/camera.rs
index 12a8fea93..04dce5b80 100644
--- a/apps/desktop/src-tauri/src/camera.rs
+++ b/apps/desktop/src-tauri/src/camera.rs
@@ -1,12 +1,15 @@
-use nokhwa::utils::CameraFormat;
+use ffmpeg_next as ffmpeg;
use serde::Serialize;
use specta::Type;
-use std::{fs::File, io::Write, path::PathBuf, sync::atomic::Ordering, time::Instant};
+use std::{path::PathBuf, time::Instant};
use tokio::sync::{oneshot, watch};
use tauri::{AppHandle, Manager, WebviewUrl};
-use cap_ffmpeg::NamedPipeCapture;
+use crate::{
+ capture::CaptureController,
+ encoder::{uyvy422_frame, H264Encoder},
+};
pub const WINDOW_LABEL: &str = "camera";
const CAMERA_ROUTE: &str = "/camera";
@@ -75,73 +78,100 @@ pub struct CameraInfo {
pub description: String,
}
+// ffmpeg
+// .command
+// .args(["-f", "mp4", "-map", &format!("{}:v", ffmpeg_input.index)])
+// .args(["-codec:v", "libx264", "-preset", "ultrafast"])
+// .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
+// .args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
+// .args(["-movflags", "frag_keyframe+empty_moov"])
+// .args(["-g", &keyframe_interval_str])
+// .args(["-keyint_min", &keyframe_interval_str])
+// .args([
+// "-vf",
+// &format!(
+// "fps={},scale=in_range=full:out_range=limited",
+// ffmpeg_input.fps
+// ),
+// ])
+// .arg(&output_path);
+
pub async fn start_capturing(
- pipe_path: PathBuf,
+ output_path: PathBuf,
camera_info: nokhwa::utils::CameraInfo,
mut start_writing_rx: watch::Receiver<bool>,
-) -> (CameraFormat, NamedPipeCapture, Instant) {
- let (video_info_tx, video_info_rx) = oneshot::channel();
-
- let (capture, is_stopped) = NamedPipeCapture::new(&pipe_path);
+) -> CaptureController {
+ let controller = CaptureController::new(output_path);
let (start_tx, start_rx) = oneshot::channel();
- let (frame_tx, mut frame_rx) = watch::channel(None);
- std::thread::spawn(move || {
- use nokhwa::{pixel_format::*, utils::*, *};
+ std::thread::spawn({
+ let controller = controller.clone();
+ move || {
+ use nokhwa::{pixel_format::*, utils::*, *};
- nokhwa::nokhwa_initialize(move |granted| {
- if granted {
- println!("Camera access granted");
- } else {
- println!("Camera access denied");
- }
- });
+ nokhwa::nokhwa_initialize(move |granted| {
+ if granted {
+ println!("Camera access granted");
+ } else {
+ println!("Camera access denied");
+ }
+ });
- let format =
- RequestedFormat::new::<RgbFormat>(RequestedFormatType::AbsoluteHighestFrameRate);
- let mut camera = Camera::new(camera_info.index().clone(), format).unwrap();
+ let format =
+ RequestedFormat::new::<RgbFormat>(RequestedFormatType::AbsoluteHighestFrameRate);
+ let mut camera = Camera::new(camera_info.index().clone(), format).unwrap();
- video_info_tx.send(camera.camera_format()).ok();
+ let format = camera.camera_format();
- camera.open_stream().unwrap();
+ let capture_format = ffmpeg::format::Pixel::UYVY422;
+ let output_format = H264Encoder::output_format();
- let mut start_tx = Some(start_tx);
+ let (width, height) = (format.resolution().width(), format.resolution().height());
- loop {
- if is_stopped.load(Ordering::Relaxed) {
- println!("Stopping receiving camera frames");
- return;
- }
- let frame = camera.frame().unwrap();
+ let mut encoder = H264Encoder::new(&controller.output_path, width, height, 30.0);
- if let Some(start_tx) = start_tx.take() {
- start_tx.send(Instant::now()).unwrap();
- }
+ let mut scaler =
+ ffmpeg::software::converter((width, height), capture_format, output_format)
+ .unwrap();
- if *start_writing_rx.borrow_and_update() {
- frame_tx.send(Some(frame)).ok();
- }
- }
- });
+ camera.open_stream().unwrap();
- tokio::spawn(async move {
- frame_rx.borrow_and_update();
+ let mut start_tx = Some(start_tx);
- let mut file = File::create(&pipe_path).unwrap();
+ loop {
+ if controller.is_stopped() {
+ println!("Stopping receiving camera frames");
+ break;
+ }
- loop {
- frame_rx.changed().await.unwrap();
+ let frame = camera.frame().unwrap();
- if let Some(frame) = &*frame_rx.borrow() {
- file.write_all(frame.buffer()).ok();
+ if controller.is_paused() {
+ continue;
+ }
+
+ if let Some(start_tx) = start_tx.take() {
+ start_tx.send(Instant::now()).unwrap();
+ }
+
+ if !*start_writing_rx.borrow_and_update() {
+ continue;
+ }
+
+ let yuyv422_frame = uyvy422_frame(frame.buffer(), width, height);
+
+ let mut yuv_frame = ffmpeg::util::frame::Video::empty();
+ scaler.run(&yuyv422_frame, &mut yuv_frame).unwrap();
+
+ encoder.encode_frame(yuv_frame);
}
+
+ encoder.close();
}
});
- (
- video_info_rx.await.unwrap(),
- capture,
- start_rx.await.unwrap(),
- )
+ start_rx.await.unwrap(); // wait for first frame
+
+ controller
}
diff --git a/apps/desktop/src-tauri/src/capture.rs b/apps/desktop/src-tauri/src/capture.rs
new file mode 100644
index 000000000..d546b1f80
--- /dev/null
+++ b/apps/desktop/src-tauri/src/capture.rs
@@ -0,0 +1,45 @@
+use std::{
+ path::PathBuf,
+ sync::{
+ atomic::{AtomicBool, Ordering},
+ Arc,
+ },
+};
+
+#[derive(Clone)]
+pub struct CaptureController {
+ pub output_path: PathBuf,
+ is_stopped: Arc<AtomicBool>,
+ is_paused: Arc<AtomicBool>,
+}
+
+impl CaptureController {
+ pub fn new(output_path: PathBuf) -> Self {
+ Self {
+ output_path,
+ is_stopped: Arc::new(AtomicBool::new(false)),
+ is_paused: Arc::new(AtomicBool::new(false)),
+ }
+ }
+
+ pub fn stop(&self) {
+ self.is_stopped.store(true, Ordering::Relaxed);
+ }
+
+ pub fn pause(&mut self) {
+ println!("setting is_paused to true");
+ self.is_paused.store(true, Ordering::Relaxed);
+ }
+
+ pub fn resume(&mut self) {
+ self.is_paused.store(false, Ordering::Relaxed);
+ }
+
+ pub fn is_stopped(&self) -> bool {
+ self.is_stopped.load(Ordering::Relaxed)
+ }
+
+ pub fn is_paused(&self) -> bool {
+ self.is_paused.load(Ordering::Relaxed)
+ }
+}
diff --git a/apps/desktop/src-tauri/src/display.rs b/apps/desktop/src-tauri/src/display.rs
index 4918c57d9..1f7268fed 100644
--- a/apps/desktop/src-tauri/src/display.rs
+++ b/apps/desktop/src-tauri/src/display.rs
@@ -1,4 +1,8 @@
-use std::{fs::File, io::Write, path::PathBuf, sync::atomic::Ordering, time::Instant};
+use ffmpeg_next::{format as avformat, frame::Video, software};
+use std::{
+ path::PathBuf,
+ time::{Instant, SystemTime},
+};
use scap::{
capturer::{Area, Capturer, Options, Point, Resolution, Size},
@@ -9,8 +13,11 @@ use serde::{Deserialize, Serialize};
use specta::Type;
use tokio::sync::{oneshot, watch};
-use crate::macos;
-use cap_ffmpeg::NamedPipeCapture;
+use crate::{
+ capture::CaptureController,
+ encoder::{bgra_frame, H264Encoder},
+ macos,
+};
#[derive(Type, Serialize, Deserialize, Debug, Clone)]
pub struct Bounds {
@@ -65,11 +72,26 @@ pub fn list_capture_windows() -> Vec<CaptureWindow> {
pub const FPS: u32 = 30;
+// ffmpeg
+// .command
+// .args(["-f", "mp4", "-map", &format!("{}:v", ffmpeg_input.index)])
+// .args(["-codec:v", "libx264", "-preset", "ultrafast"])
+// .args(["-g", &keyframe_interval_str])
+// .args(["-keyint_min", &keyframe_interval_str])
+// .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
+// // .args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
+// // .args(["-movflags", "frag_keyframe+empty_moov"])
+// .args([
+// "-vf",
+// &format!("fps={},scale=in_range=full:out_range=limited", display::FPS),
+// ])
+// .arg(&output_path);
+
pub async fn start_capturing(
- pipe_path: PathBuf,
+ output_path: PathBuf,
capture_target: &CaptureTarget,
start_writing_rx: watch::Receiver<bool>,
-) -> ((u32, u32), NamedPipeCapture, Instant) {
+) -> CaptureController {
dbg!(capture_target);
let targets = scap::get_all_targets();
@@ -114,7 +136,7 @@ pub async fn start_capturing(
fps: FPS,
show_highlight: true,
output_type: FrameType::BGRAFrame,
- output_resolution: Resolution::_2160p,
+ output_resolution: Resolution::_1080p,
crop_area,
excluded_targets: Some(excluded_targets),
..Default::default()
@@ -125,58 +147,67 @@ pub async fn start_capturing(
let [width, height] = capturer.get_output_frame_size();
- let (capture, is_stopped) = NamedPipeCapture::new(&pipe_path);
+ let controller = CaptureController::new(output_path);
let (tx, rx) = oneshot::channel();
- let (frame_tx, mut frame_rx) = watch::channel(vec![]);
+ std::thread::spawn({
+ let controller = controller.clone();
+ move || {
+ let capture_format = avformat::Pixel::BGRA;
+ let output_format = H264Encoder::output_format();
- std::thread::spawn(move || {
- capturer.start_capture();
+ let mut encoder = H264Encoder::new(&controller.output_path, width, height, FPS as f64);
- let mut start_time = Some(tx);
- loop {
- if is_stopped.load(Ordering::Relaxed) {
- println!("Stopping receiving capture frames");
- return;
- }
+ let mut scaler =
+ software::converter((width, height), capture_format, output_format).unwrap();
- let frame = capturer.get_next_frame();
+ capturer.start_capture();
- if let Some(tx) = start_time.take() {
- tx.send(Instant::now()).ok();
- }
+ let mut start_time_tx = Some(tx);
- if !*start_writing_rx.borrow() {
- continue;
- }
+ let mut start = Instant::now();
- match frame {
- Ok(Frame::BGRA(frame)) => {
- frame_tx.send(frame.data).ok();
+ loop {
+ if controller.is_stopped() {
+ break;
}
- _ => println!("Failed to get frame"),
- }
- }
- });
- tokio::spawn(async move {
- frame_rx.borrow_and_update();
+ let frame = capturer.get_next_frame();
+ let timestamp = SystemTime::now();
- let mut file = File::create(&pipe_path).unwrap();
+ if controller.is_paused() {
+ continue;
+ }
+
+ if let Some(tx) = start_time_tx.take() {
+ tx.send(Instant::now()).ok();
+ }
+
+ if !*start_writing_rx.borrow() {
+ continue;
+ }
- loop {
- if frame_rx.changed().await.is_err() {
- println!("Closing display pipe writer");
- return;
+ match frame {
+ Ok(Frame::BGRA(frame)) => {
+ let rgb_frame = bgra_frame(&frame.data, width, height);
+
+ let mut yuv_frame = Video::empty();
+ scaler.run(&rgb_frame, &mut yuv_frame).unwrap();
+
+ encoder.encode_frame(yuv_frame);
+ }
+ _ => println!("Failed to get frame"),
+ }
}
- let frame = frame_rx.borrow();
- file.write_all(&frame).ok();
+ encoder.close();
}
});
- ((width, height), capture, rx.await.unwrap())
+ rx.await.unwrap(); // wait for first frame
+
+ controller
}
pub fn get_window_bounds(window_number: u32) -> Option<Bounds> {
diff --git a/apps/desktop/src-tauri/src/editor.rs b/apps/desktop/src-tauri/src/editor.rs
index 4a6f0bf3d..5644f90f8 100644
--- a/apps/desktop/src-tauri/src/editor.rs
+++ b/apps/desktop/src-tauri/src/editor.rs
@@ -1,4 +1,4 @@
-use std::sync::Arc;
+use std::{sync::Arc, time::Instant};
use cap_project::{BackgroundSource, ProjectConfiguration};
use cap_rendering::{decoder::DecodedFrame, produce_frame, ProjectUniforms, RenderVideoConstants};
@@ -160,6 +160,7 @@ impl Renderer {
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,
@@ -169,6 +170,7 @@ impl Renderer {
)
.await
.unwrap();
+ // println!("produced frame in {:?}", time.elapsed());
frame_tx
.send(SocketMessage::Frame {
diff --git a/apps/desktop/src-tauri/src/encoder.rs b/apps/desktop/src-tauri/src/encoder.rs
new file mode 100644
index 000000000..1900bde96
--- /dev/null
+++ b/apps/desktop/src-tauri/src/encoder.rs
@@ -0,0 +1,222 @@
+use std::path::PathBuf;
+
+use ffmpeg_next::{self as ffmpeg, Dictionary};
+
+macro_rules! dict {
+ ( $($key:expr => $value:expr),* $(,)*) => ({
+ let mut dict = ffmpeg::Dictionary::new();
+
+ $(
+ dict.set($key, $value);
+ )*
+
+ dict
+ }
+ );
+}
+
+pub struct H264Encoder {
+ pub output: ffmpeg::format::context::Output,
+ pub context: ffmpeg::encoder::Video,
+ pub stream_index: usize,
+ frame_number: usize,
+ pub fps: f64,
+}
+
+impl H264Encoder {
+ pub fn output_format() -> ffmpeg::format::Pixel {
+ ffmpeg::format::Pixel::YUV420P
+ }
+
+ pub fn new(path: &PathBuf, width: u32, height: u32, fps: f64) -> Self {
+ let mut output = ffmpeg::format::output(path).unwrap();
+ let output_flags = output.format().flags();
+
+ let codec = ffmpeg::encoder::find(ffmpeg::codec::Id::H264).unwrap();
+
+ let mut stream = output.add_stream(codec).unwrap();
+ let stream_index = stream.index();
+
+ let mut encoder = ffmpeg::codec::context::Context::new_with_codec(codec)
+ .encoder()
+ .video()
+ .unwrap();
+
+ stream.set_parameters(&encoder);
+ encoder.set_width(width);
+ encoder.set_height(height);
+ encoder.set_format(Self::output_format());
+ encoder.set_frame_rate(Some(fps));
+ encoder.set_time_base(1.0 / fps);
+ encoder.set_gop(fps as u32);
+
+ if output_flags.contains(ffmpeg::format::Flags::GLOBAL_HEADER) {
+ encoder.set_flags(ffmpeg::codec::Flags::GLOBAL_HEADER);
+ }
+
+ let encoder = encoder
+ .open_as_with(
+ codec,
+ dict!("preset" => "ultrafast", "tune" => "zerolatency"),
+ )
+ .unwrap();
+ stream.set_parameters(&encoder);
+ stream.set_time_base(1.0 / fps);
+
+ stream.set_metadata(Dictionary::from_iter(vec![("tune", "zerolatency")]));
+
+ output.write_header().unwrap();
+
+ Self {
+ output,
+ context: encoder,
+ stream_index,
+ frame_number: 0,
+ fps,
+ }
+ }
+
+ pub fn encode_frame(&mut self, mut frame: ffmpeg::util::frame::Video) {
+ frame.set_pts(Some(self.frame_number as i64));
+
+ // println!("sending frame - pts: {:?}", frame.pts());
+
+ self.context.send_frame(&frame).unwrap();
+ self.frame_number += 1;
+
+ self.receive_and_process_packets();
+ }
+
+ fn receive_and_process_packets(&mut self) {
+ let mut encoded = ffmpeg::Packet::empty();
+ while self.context.receive_packet(&mut encoded).is_ok() {
+ encoded.set_stream(self.stream_index);
+ encoded.rescale_ts(
+ 1.0 / self.fps,
+ self.output.stream(self.stream_index).unwrap().time_base(),
+ );
+
+ // println!(
+ // "writing packet - dts: {:?}, pts: {:?}, flags: {:?}",
+ // encoded.dts(),
+ // encoded.pts(),
+ // encoded.flags()
+ // );
+
+ encoded.write_interleaved(&mut self.output).unwrap();
+ }
+ }
+
+ pub fn close(mut self) {
+ self.context.send_eof().unwrap();
+
+ self.receive_and_process_packets();
+
+ self.output.write_trailer().unwrap();
+ }
+}
+
+pub fn bgra_frame(bytes: &[u8], width: u32, height: u32) -> ffmpeg::frame::Video {
+ let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::BGRA, width, height);
+
+ let stride = frame.stride(0);
+
+ for (in_line, out_line) in bytes
+ .chunks(width as usize * 4)
+ .zip(frame.data_mut(0).chunks_mut(stride))
+ {
+ out_line[0..(width as usize * 4)].copy_from_slice(in_line);
+ }
+
+ frame
+}
+
+pub fn uyvy422_frame(bytes: &[u8], width: u32, height: u32) -> ffmpeg::frame::Video {
+ let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::UYVY422, width, height);
+
+ frame.data_mut(0).copy_from_slice(bytes);
+
+ frame
+}
+
+pub fn nv12_frame(bytes: &[u8], width: u32, height: u32) -> ffmpeg::frame::Video {
+ let mut frame = ffmpeg::frame::Video::new(ffmpeg::format::Pixel::NV12, width, height);
+ let y_size = (width * height) as usize;
+ let uv_size = y_size / 2;
+
+ frame.data_mut(0)[..y_size].copy_from_slice(&bytes[..y_size]);
+ frame.data_mut(1)[..uv_size].copy_from_slice(&bytes[y_size..y_size + uv_size]);
+
+ frame
+}
+
+pub struct MP3Encoder {
+ pub output: ffmpeg::format::context::Output,
+ pub context: ffmpeg::encoder::Audio,
+ pub stream_index: usize,
+ pub sample_rate: u32,
+ sample_number: i64,
+}
+
+impl MP3Encoder {
+ pub fn new(path: &PathBuf, sample_rate: u32) -> Self {
+ dbg!(sample_rate);
+ let mut output = ffmpeg::format::output(path).unwrap();
+ let output_flags = output.format().flags();
+
+ let codec = ffmpeg::encoder::find(ffmpeg::codec::Id::MP3).unwrap();
+ let audio_codec = codec.audio().unwrap();
+
+ let mut stream = output.add_stream(audio_codec).unwrap();
+ let stream_index = stream.index();
+
+ let mut encoder = ffmpeg::codec::context::Context::new_with_codec(codec)
+ .encoder()
+ .audio()
+ .unwrap();
+
+ stream.set_parameters(&encoder);
+ encoder.set_rate(sample_rate as i32);
+ encoder.set_bit_rate(128000);
+ encoder.set_max_bit_rate(128000);
+ encoder.set_channel_layout(ffmpeg::ChannelLayout::MONO);
+ encoder.set_time_base((1, sample_rate as i32));
+ encoder.set_format(ffmpeg::format::Sample::F32(
+ ffmpeg::format::sample::Type::Packed,
+ ));
+
+ if output_flags.contains(ffmpeg::format::Flags::GLOBAL_HEADER) {
+ encoder.set_flags(ffmpeg::codec::Flags::GLOBAL_HEADER);
+ }
+
+ let encoder = encoder.open_as(codec).unwrap();
+ stream.set_parameters(&encoder);
+ stream.set_time_base((1, sample_rate as i32));
+
+ Self {
+ output,
+ context: encoder,
+ stream_index,
+ sample_rate,
+ sample_number: 0,
+ }
+ }
+
+ pub fn encode_frame(&mut self, mut frame: ffmpeg::frame::Audio) {
+ frame.set_pts(Some(self.sample_number as i64));
+ self.context.send_frame(&frame).unwrap();
+ self.sample_number += frame.samples() as i64;
+
+ self.receive_and_process_packets();
+ }
+
+ fn receive_and_process_packets(&mut self) {
+ let mut encoded = ffmpeg::Packet::empty();
+ while self.context.receive_packet(&mut encoded).is_ok() {
+ encoded.set_stream(self.stream_index);
+ encoded.set_time_base(self.output.stream(self.stream_index).unwrap().time_base());
+
+ encoded.write(&mut self.output).unwrap();
+ }
+ }
+}
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index cce34a33d..f854bff8e 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -1,9 +1,11 @@
mod audio;
mod auth;
mod camera;
+mod capture;
mod display;
mod editor;
mod editor_instance;
+mod encoder;
mod hotkeys;
mod macos;
mod permissions;
@@ -13,10 +15,13 @@ mod recording;
mod tray;
mod upload;
+use audio::AppSounds;
use auth::AuthStore;
use camera::{create_camera_window, list_cameras};
use cap_ffmpeg::FFmpeg;
-use cap_project::{ProjectConfiguration, RecordingMeta, SharingMeta};
+use cap_project::{
+ ProjectConfiguration, RecordingMeta, SharingMeta, TimelineConfiguration, TimelineSegment,
+};
use cap_rendering::ProjectUniforms;
use cap_utils::create_named_pipe;
use display::{list_capture_windows, Bounds, CaptureTarget, FPS};
@@ -36,6 +41,7 @@ use specta::Type;
use std::fs::File;
use std::io::BufWriter;
use std::io::{BufReader, Write};
+use std::time::{SystemTime, UNIX_EPOCH};
use std::{
collections::HashMap, marker::PhantomData, path::PathBuf, process::Command, sync::Arc,
time::Duration,
@@ -60,6 +66,16 @@ pub struct RecordingOptions {
audio_input_name: Option<String>,
}
+impl RecordingOptions {
+ fn camera_label(&self) -> Option<&str> {
+ self.camera_label.as_deref()
+ }
+
+ fn audio_input_name(&self) -> Option<&str> {
+ self.audio_input_name.as_deref()
+ }
+}
+
#[derive(specta::Type, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct App {
@@ -284,13 +300,47 @@ async fn start_recording(app: AppHandle, state: MutableState<'_, App>) -> Result
window.eval("window.location.reload()").unwrap();
window.show().unwrap();
- audio::play_audio(include_bytes!("../sounds/start-recording.ogg"));
+ AppSounds::StartRecording.play();
RecordingStarted.emit(&app).ok();
Ok(())
}
+#[tauri::command]
+#[specta::specta]
+async fn pause_recording(state: MutableState<'_, App>) -> Result<(), String> {
+ let mut state = state.write().await;
+
+ if let Some(recording) = &mut state.current_recording {
+ recording.pause().await?;
+ recording.segments.push(
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64(),
+ );
+ }
+ Ok(())
+}
+
+#[tauri::command]
+#[specta::specta]
+async fn resume_recording(state: MutableState<'_, App>) -> Result<(), String> {
+ let mut state = state.write().await;
+
+ if let Some(recording) = &mut state.current_recording {
+ recording.resume().await?;
+ recording.segments.push(
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64(),
+ );
+ }
+ Ok(())
+}
+
fn create_in_progress_recording_window(app: &AppHandle) {
let monitor = app.primary_monitor().unwrap().unwrap();
@@ -332,7 +382,14 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
return Err("Recording not in progress".to_string());
};
- current_recording.stop().await;
+ current_recording.segments.push(
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64(),
+ );
+
+ current_recording.stop();
let window = app
.get_webview_window(IN_PROGRESS_RECORDINGS_LABEL)
@@ -388,7 +445,36 @@ async fn stop_recording(app: AppHandle, state: MutableState<'_, App>) -> Result<
.emit(&app)
.ok();
- audio::play_audio(include_bytes!("../sounds/stop-recording.ogg"));
+ let config = {
+ let mut segments = vec![];
+
+ let mut passed_duration = 0.0;
+
+ for i in (0..current_recording.segments.len()).step_by(2) {
+ let start = passed_duration;
+
+ passed_duration += current_recording.segments[i + 1] - current_recording.segments[i];
+
+ segments.push(TimelineSegment {
+ start,
+ end: passed_duration,
+ timescale: 1.0,
+ });
+ }
+
+ ProjectConfiguration {
+ timeline: Some(TimelineConfiguration { segments }),
+ ..Default::default()
+ }
+ };
+
+ std::fs::write(
+ current_recording.recording_dir.join("project-config.json"),
+ serde_json::to_string_pretty(&json!(&config)).unwrap(),
+ )
+ .unwrap();
+
+ AppSounds::StopRecording.play();
Ok(())
}
@@ -563,7 +649,6 @@ async fn render_to_file_impl(
sample_format: "f64le".to_string(),
sample_rate: audio.sample_rate,
channels: 1,
- wallclock: false,
});
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel::<Vec<f64>>();
@@ -1623,7 +1708,7 @@ async fn take_screenshot(app: AppHandle, state: MutableState<'_, App>) -> Result
.write_image_data(&rgba_data)
.map_err(|e| e.to_string())?;
- audio::play_audio(include_bytes!("../sounds/screenshot.ogg"));
+ AppSounds::Screenshot.play();
if let Some(window) = app.get_webview_window("main") {
window.show().ok();
@@ -1646,6 +1731,7 @@ async fn take_screenshot(app: AppHandle, state: MutableState<'_, App>) -> Result
},
camera: None,
audio: None,
+ segments: vec![],
}
.save_for_project();
@@ -1760,6 +1846,8 @@ pub fn run() {
create_camera_window,
start_recording,
stop_recording,
+ pause_recording,
+ resume_recording,
take_screenshot,
list_cameras,
list_capture_windows,
diff --git a/apps/desktop/src-tauri/src/playback.rs b/apps/desktop/src-tauri/src/playback.rs
index 7650b6347..46a12cc2b 100644
--- a/apps/desktop/src-tauri/src/playback.rs
+++ b/apps/desktop/src-tauri/src/playback.rs
@@ -77,9 +77,7 @@ impl Playback {
};
let time = if let Some(timeline) = self.project.timeline() {
- match timeline.get_recording_time(
- start.elapsed().as_secs_f64() + self.start_frame_number as f64 / FPS as f64, /* frame_number as f64 / FPS as f64 */
- ) {
+ match timeline.get_recording_time(frame_number as f64 / FPS as f64) {
Some(time) => time,
None => break,
}
@@ -87,12 +85,13 @@ impl Playback {
frame_number as f64 / FPS as f64
};
+ let debug = Instant::now();
tokio::select! {
_ = stop_rx.changed() => {
break;
},
Some((screen_frame, camera_frame)) = self.decoders.get_frames((time * FPS as f64) as u32) => {
- tokio::time::sleep_until(start + (frame_number - self.start_frame_number) * Duration::from_secs_f32(1.0 / FPS as f32)).await;
+ // println!("decoded frame in {:?}", debug.elapsed());
self
.renderer
@@ -104,8 +103,9 @@ impl Playback {
)
.await;
- event_tx.send(PlaybackEvent::Frame(frame_number)).ok();
+ tokio::time::sleep_until(start + (frame_number - self.start_frame_number) * Duration::from_secs_f32(1.0 / FPS as f32)).await;
+ event_tx.send(PlaybackEvent::Frame(frame_number)).ok();
frame_number += 1;
}
diff --git a/apps/desktop/src-tauri/src/recording.rs b/apps/desktop/src-tauri/src/recording.rs
index 88e62e9e1..f143c5678 100644
--- a/apps/desktop/src-tauri/src/recording.rs
+++ b/apps/desktop/src-tauri/src/recording.rs
@@ -1,26 +1,29 @@
-use device_query::{DeviceQuery, DeviceState, MouseState};
-use nokhwa::utils::CameraFormat;
-use serde::{Deserialize, Serialize};
+use crate::audio::AudioCapturer;
+use crate::capture::CaptureController;
+use cap_ffmpeg::{FFmpeg, FFmpegInput, FFmpegProcess, FFmpegRawAudioInput};
+use device_query::{DeviceQuery, DeviceState};
+use futures::future::OptionFuture;
+use serde::Deserialize;
+use serde::Serialize;
use specta::Type;
-use std::sync::{Arc, Mutex};
-use std::time::Instant;
-use std::{fs::File, io::Write, path::PathBuf, time::Duration};
+use std::time::{Instant, SystemTime, UNIX_EPOCH};
+use std::{
+ fs::File,
+ sync::{Arc, Mutex},
+};
+use std::{path::PathBuf, time::Duration};
use tokio::sync::watch;
use objc::rc::autoreleasepool;
use objc::runtime::{Class, Object, Sel, BOOL, NO, YES};
use objc::*;
-use tauri_nspanel::objc_foundation::{INSString, NSString};
use crate::{
- audio::{self, AudioCapturer},
- camera,
+ audio, camera,
display::{self, get_window_bounds, CaptureTarget},
Bounds, RecordingOptions,
};
-use cap_ffmpeg::*;
-
#[derive(Clone, Type, Serialize)]
#[serde(rename_all = "camelCase", tag = "variant")]
pub enum DisplaySource {
@@ -46,12 +49,13 @@ pub struct InProgressRecording {
#[serde(skip)]
pub ffmpeg_process: FFmpegProcess,
#[serde(skip)]
- pub display: FFmpegCaptureOutput<FFmpegRawVideoInput>,
+ pub display: CaptureController,
pub display_source: DisplaySource,
#[serde(skip)]
- pub camera: Option<FFmpegCaptureOutput<FFmpegRawVideoInput>>,
+ pub camera: Option<CaptureController>,
#[serde(skip)]
pub audio: Option<(FFmpegCaptureOutput<FFmpegRawAudioInput>, AudioCapturer)>,
+ pub segments: Vec<f64>,
#[serde(skip)]
pub mouse_moves: Arc<Mutex<Vec<MouseEvent>>>,
#[serde(skip)]
@@ -64,39 +68,9 @@ unsafe impl Send for InProgressRecording {}
unsafe impl Sync for InProgressRecording {}
impl InProgressRecording {
- pub async fn stop(&mut self) {
- // Signal the mouse event tracking to stop
- *self.stop_signal.lock().unwrap() = true;
-
- self.ffmpeg_process.stop();
-
- if let Err(e) = self.ffmpeg_process.wait() {
- eprintln!("Failed to wait for ffmpeg process: {:?}", e);
- }
-
- self.display.capture.stop();
- if let Some(camera) = &self.camera {
- camera.capture.stop();
- }
- if let Some(audio) = &mut self.audio {
- audio.1.stop().ok();
- }
-
- // Save mouse events to files
- let mouse_moves_path = self.recording_dir.join("mousemoves.json");
- let mouse_clicks_path = self.recording_dir.join("mouseclicks.json");
-
- let mouse_moves = self.mouse_moves.lock().unwrap();
- let mouse_clicks = self.mouse_clicks.lock().unwrap();
-
- let mut mouse_moves_file = File::create(mouse_moves_path).unwrap();
- let mut mouse_clicks_file = File::create(mouse_clicks_path).unwrap();
-
- serde_json::to_writer(&mut mouse_moves_file, &*mouse_moves).unwrap();
- serde_json::to_writer(&mut mouse_clicks_file, &*mouse_clicks).unwrap();
-
+ pub fn stop(&mut self) {
use cap_project::*;
- RecordingMeta {
+ let meta = RecordingMeta {
project_path: self.recording_dir.clone(),
sharing: None,
pretty_name: format!(
@@ -118,23 +92,103 @@ impl InProgressRecording {
.unwrap()
.to_owned(),
}),
- audio: self.audio.as_ref().map(|(audio, _)| AudioMeta {
+ audio: self.audio.as_ref().map(|audio| AudioMeta {
path: audio
+ .0
.output_path
.strip_prefix(&self.recording_dir)
.unwrap()
.to_owned(),
}),
+ segments: {
+ let relative_segments = self
+ .segments
+ .iter()
+ .map(|s| s - self.segments[0])
+ .collect::<Vec<_>>();
+
+ let mut segments = vec![];
+
+ let mut diff = 0.0;
+
+ for (i, chunk) in relative_segments.chunks_exact(2).enumerate() {
+ if i < relative_segments.len() / 2 {
+ segments.push(RecordingSegment {
+ start: diff,
+ end: chunk[1] - chunk[0] + diff,
+ });
+ }
+
+ diff += chunk[1] - chunk[0];
+ }
+
+ segments
+ },
+ };
+
+ // Signal the mouse event tracking to stop
+ *self.stop_signal.lock().unwrap() = true;
+
+ self.display.stop();
+ if let Some(camera) = &self.camera {
+ camera.stop();
+ }
+
+ self.ffmpeg_process.stop();
+ if let Err(e) = self.ffmpeg_process.wait() {
+ eprintln!("Failed to wait for ffmpeg process: {:?}", e);
}
- .save_for_project();
+ if let Some(audio) = self.audio.take() {
+ audio.0.capture.stop();
+ drop(audio);
+ }
+
+ // Save mouse events to files
+ let mouse_moves_path = self.recording_dir.join("mousemoves.json");
+ let mouse_clicks_path = self.recording_dir.join("mouseclicks.json");
+
+ let mouse_moves = self.mouse_moves.lock().unwrap();
+ let mouse_clicks = self.mouse_clicks.lock().unwrap();
+
+ let mut mouse_moves_file = File::create(mouse_moves_path).unwrap();
+ let mut mouse_clicks_file = File::create(mouse_clicks_path).unwrap();
+
+ serde_json::to_writer(&mut mouse_moves_file, &*mouse_moves).unwrap();
+ serde_json::to_writer(&mut mouse_clicks_file, &*mouse_clicks).unwrap();
+
+ meta.save_for_project();
+ }
+
+ pub async fn pause(&mut self) -> Result<(), String> {
+ self.display.pause();
+ if let Some(camera) = &mut self.camera {
+ camera.pause();
+ }
+ if let Some(audio) = &mut self.audio {
+ audio.0.capture.pause();
+ }
+ println!("Sent pause command to FFmpeg");
+ Ok(())
+ }
+
+ pub async fn resume(&mut self) -> Result<(), String> {
+ self.display.resume();
+ if let Some(camera) = &mut self.camera {
+ camera.resume();
+ }
+ if let Some(audio) = &mut self.audio {
+ audio.0.capture.resume();
+ }
+
+ println!("Sent resume command to FFmpeg");
+ Ok(())
}
}
pub struct FFmpegCaptureOutput<T> {
pub input: FFmpegInput<T>,
- pub capture: NamedPipeCapture,
+ pub capture: CaptureController,
pub output_path: PathBuf,
- pub start_time: Instant,
}
pub async fn start(
@@ -149,120 +203,52 @@ pub async fn start(
let (start_writing_tx, start_writing_rx) = watch::channel(false);
+ let audio_pipe_path = content_dir.join("audio-input.pipe");
+
let (display, camera, audio) = tokio::join!(
- start_display_recording(&content_dir, recording_options, start_writing_rx.clone()),
- start_camera_recording(&content_dir, recording_options, start_writing_rx.clone()),
- start_audio_recording(&content_dir, recording_options, start_writing_rx.clone())
+ display::start_capturing(
+ content_dir.join("display.mp4"),
+ &recording_options.capture_target,
+ start_writing_rx.clone(),
+ ),
+ OptionFuture::from(
+ recording_options
+ .camera_label()
+ .and_then(camera::find_camera_by_label)
+ .map(|camera_info| {
+ camera::start_capturing(
+ content_dir.join("camera.mp4"),
+ camera_info,
+ start_writing_rx.clone(),
+ )
+ }),
+ ),
+ OptionFuture::from(
+ recording_options
+ .audio_input_name()
+ .and_then(audio::AudioCapturer::init)
+ .map(|capturer| {
+ audio::start_capturing(capturer, audio_pipe_path.clone(), start_writing_rx)
+ }),
+ )
);
- let display = {
- let ((width, height), capture, start_time) = display;
-
- let output_path = content_dir.join("display.mp4");
-
- let ffmpeg_input = ffmpeg.add_input(FFmpegRawVideoInput {
- input: capture.path().clone().into_os_string(),
- width,
- height,
- fps: 0,
- pix_fmt: "bgra",
- ..Default::default()
- });
-
- let keyframe_interval_secs = 2;
- let keyframe_interval = keyframe_interval_secs * display::FPS;
- let keyframe_interval_str = keyframe_interval.to_string();
-
- ffmpeg
- .command
- .args(["-f", "mp4", "-map", &format!("{}:v", ffmpeg_input.index)])
- .args(["-codec:v", "libx264", "-preset", "ultrafast"])
- .args(["-g", &keyframe_interval_str])
- .args(["-keyint_min", &keyframe_interval_str])
- .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
- .args([
- "-vf",
- &format!("fps={},scale=in_range=full:out_range=limited", display::FPS),
- ])
- .arg(&output_path);
-
- FFmpegCaptureOutput {
- input: ffmpeg_input,
- capture,
- output_path,
- start_time,
- }
- };
-
- let camera = if let Some((format, capture, start_time)) = camera {
- use nokhwa::utils::FrameFormat;
-
- let output_path = content_dir.join("camera.mp4");
-
- let fps = 30;
-
- let ffmpeg_input = ffmpeg.add_input(FFmpegRawVideoInput {
- input: capture.path().clone().into_os_string(),
- width: format.resolution().width(),
- height: format.resolution().height(),
- fps,
- pix_fmt: match format.format() {
- FrameFormat::YUYV => "uyvy422",
- FrameFormat::RAWRGB => "rgb24",
- FrameFormat::NV12 => "nv12",
- _ => panic!("unimplemented"),
- },
- });
-
- let keyframe_interval_secs = 2;
- let keyframe_interval = keyframe_interval_secs * fps;
- let keyframe_interval_str = keyframe_interval.to_string();
-
- ffmpeg
- .command
- .args(["-f", "mp4", "-map", &format!("{}:v", ffmpeg_input.index)])
- .args(["-codec:v", "libx264", "-preset", "ultrafast"])
- .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
- .args(["-vsync", "1", "-force_key_frames", "expr:gte(t,n_forced*3)"])
- .args(["-movflags", "frag_keyframe+empty_moov"])
- .args(["-g", &keyframe_interval_str])
- .args(["-keyint_min", &keyframe_interval_str])
- .args([
- "-vf",
- &format!(
- "fps={},scale=in_range=full:out_range=limited",
- ffmpeg_input.fps
- ),
- ])
- .arg(&output_path);
-
- Some(FFmpegCaptureOutput {
- input: ffmpeg_input,
- capture,
- output_path,
- start_time,
- })
- } else {
- None
- };
-
- let audio = if let Some((capture, start_time, capturer)) = audio {
+ let audio = if let Some((controller, capturer)) = audio {
let output_path = content_dir.join("audio-input.mp3");
dbg!(&capturer.config);
let ffmpeg_input = ffmpeg.add_input(FFmpegRawAudioInput {
- input: capture.path().clone().into_os_string(),
+ input: audio_pipe_path.into_os_string(),
sample_format: capturer.sample_format().to_string(),
sample_rate: capturer.sample_rate(),
channels: capturer.channels(),
- wallclock: true,
});
ffmpeg
.command
.args(["-f", "mp3", "-map", &format!("{}:a", ffmpeg_input.index)])
- .args(["-b:a", "192k"])
+ .args(["-b:a", "128k"])
.args(["-ar", &capturer.sample_rate().to_string()])
.args(["-ac", &capturer.channels().to_string(), "-async", "1"])
.args([
@@ -274,9 +260,8 @@ pub async fn start(
Some((
FFmpegCaptureOutput {
input: ffmpeg_input,
- capture,
+ capture: controller,
output_path,
- start_time,
},
capturer,
))
@@ -286,7 +271,7 @@ pub async fn start(
let ffmpeg_process = ffmpeg.start();
- tokio::time::sleep(Duration::from_secs(1)).await;
+ tokio::time::sleep(Duration::from_secs(3)).await;
println!("Starting writing to named pipes");
@@ -343,6 +328,10 @@ pub async fn start(
});
InProgressRecording {
+ segments: vec![SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs_f64()],
recording_dir,
ffmpeg_process,
display,
@@ -414,56 +403,3 @@ fn get_cursor_id() -> String {
}
})
}
-
-async fn start_camera_recording(
- content_path: &PathBuf,
- recording_options: &RecordingOptions,
- start_writing_rx: watch::Receiver<bool>,
-) -> Option<(CameraFormat, NamedPipeCapture, Instant)> {
- let Some(camera_info) = recording_options
- .camera_label
- .as_ref()
- .and_then(|camera_label| camera::find_camera_by_label(camera_label))
- else {
- return None;
- };
-
- let pipe_path = content_path.join("camera.pipe");
-
- Some(camera::start_capturing(pipe_path.clone(), camera_info, start_writing_rx).await)
-}
-
-async fn start_display_recording(
- content_path: &PathBuf,
- recording_options: &RecordingOptions,
- start_writing_rx: watch::Receiver<bool>,
-) -> ((u32, u32), NamedPipeCapture, Instant) {
- let pipe_path = content_path.join("display.pipe");
- display::start_capturing(
- pipe_path.clone(),
- &recording_options.capture_target,
- start_writing_rx,
- )
- .await
-}
-
-async fn start_audio_recording(
- content_path: &PathBuf,
- recording_options: &RecordingOptions,
- start_writing_rx: watch::Receiver<bool>,
-) -> Option<(NamedPipeCapture, Instant, AudioCapturer)> {
- let Some(mut capturer) = recording_options
- .audio_input_name
- .as_ref()
- .and_then(|name| audio::AudioCapturer::init(name))
- else {
- return None;
- };
-
- let pipe_path = content_path.join("audio-input.pipe");
-
- let (capture, start_time) =
- audio::start_capturing(&mut capturer, pipe_path.clone(), start_writing_rx).await;
-
- Some((capture, start_time, capturer))
-}
diff --git a/apps/desktop/src/routes/in-progress-recording.tsx b/apps/desktop/src/routes/in-progress-recording.tsx
index 32b07d693..88b2d034b 100644
--- a/apps/desktop/src/routes/in-progress-recording.tsx
+++ b/apps/desktop/src/routes/in-progress-recording.tsx
@@ -7,11 +7,12 @@ import { createMutation } from "@tanstack/solid-query";
export default function () {
const start = Date.now();
const [time, setTime] = createSignal(Date.now());
- let stopped = false;
+ const [isPaused, setIsPaused] = createSignal(false);
+ const [stopped, setStopped] = createSignal(false);
createTimer(
() => {
- if (stopped) return;
+ if (stopped() || isPaused()) return;
setTime(Date.now());
},
100,
@@ -19,17 +20,28 @@ export default function () {
);
createEffect(() => {
- stopped = false;
setTime(Date.now());
});
const stopRecording = createMutation(() => ({
mutationFn: async () => {
- stopped = true;
+ setStopped(true);
await commands.stopRecording();
},
}));
+ const togglePause = createMutation(() => ({
+ mutationFn: async () => {
+ if (isPaused()) {
+ await commands.resumeRecording();
+ setIsPaused(false);
+ } else {
+ await commands.pauseRecording();
+ setIsPaused(true);
+ }
+ },
+ }));
+
return (
<div
class="text-gray-400 flex flex-row items-stretch bg-gray-500 rounded-[0.75rem] w-full h-full animate-in fade-in"
@@ -47,18 +59,15 @@ export default function () {
{formatTime((time() - start) / 1000)}
</span>
</button>
- {/* <ActionButton disabled>
- <IconCapPauseCircle />
- </ActionButton>
- <ActionButton disabled>
- <IconCapRestart />
+ <ActionButton
+ disabled={togglePause.isPending}
+ onClick={() => togglePause.mutate()}
+ >
+ {isPaused() ? <IconCapPlayCircle /> : <IconCapPauseCircle />}
</ActionButton>
- <ActionButton disabled>
- <IconCapTrash />
- </ActionButton> */}
</div>
<div
- class="bg-white-transparent-5 cursor-move flex items-center justify-center p-[0.25rem] border-l border-white-transparent-5"
+ class="bg-white-transparent-5 cursor-move flex items-center justify-center p-[0.25rem] border-l border-white-transparent-5"
data-tauri-drag-region
>
<IconCapMoreVertical data-tauri-drag-region />
diff --git a/apps/desktop/src/utils/tauri.ts b/apps/desktop/src/utils/tauri.ts
index 72c8c4274..c87f36f3f 100644
--- a/apps/desktop/src/utils/tauri.ts
+++ b/apps/desktop/src/utils/tauri.ts
@@ -40,6 +40,22 @@ async stopRecording() : Promise<Result<null, string>> {
else return { status: "error", error: e as any };
}
},
+async pauseRecording() : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("pause_recording") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
+async resumeRecording() : Promise<Result<null, string>> {
+ try {
+ return { status: "ok", data: await TAURI_INVOKE("resume_recording") };
+} catch (e) {
+ if(e instanceof Error) throw e;
+ else return { status: "error", error: e as any };
+}
+},
async takeScreenshot() : Promise<Result<null, string>> {
try {
return { status: "ok", data: await TAURI_INVOKE("take_screenshot") };
@@ -295,7 +311,7 @@ export type Hotkey = { code: string; meta: boolean; ctrl: boolean; alt: boolean;
export type HotkeyAction = "startRecording" | "stopRecording"
export type HotkeysConfiguration = { show: boolean }
export type HotkeysStore = { hotkeys: { [key in HotkeyAction]: Hotkey } }
-export type InProgressRecording = { recordingDir: string; displaySource: DisplaySource }
+export type InProgressRecording = { recordingDir: string; displaySource: DisplaySource; segments: number[] }
export type JsonValue<T> = [T]
export type NewRecordingAdded = { path: string }
export type NewScreenshotAdded = { path: string }
@@ -304,10 +320,11 @@ export type OSPermissionStatus = "notNeeded" | "empty" | "granted" | "denied"
export type OSPermissionsCheck = { screenRecording: OSPermissionStatus; microphone: OSPermissionStatus; camera: OSPermissionStatus; accessibility: OSPermissionStatus }
export type ProjectConfiguration = { aspectRatio: AspectRatio | null; background: BackgroundConfiguration; camera: CameraConfiguration; audio: AudioConfiguration; cursor: CursorConfiguration; hotkeys: HotkeysConfiguration; timeline?: TimelineConfiguration | null }
export type ProjectRecordings = { display: Video; camera: Video | null; audio: Audio | null }
-export type RecordingMeta = { pretty_name: string; sharing?: SharingMeta | null; display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null }
+export type RecordingMeta = { pretty_name: string; sharing?: SharingMeta | null; display: Display; camera?: CameraMeta | null; audio?: AudioMeta | null; segments?: RecordingSegment[] }
export type RecordingMetaChanged = { id: string }
export type RecordingOptions = { captureTarget: CaptureTarget; cameraLabel: string | null; audioInputName: string | null }
export type RecordingOptionsChanged = null
+export type RecordingSegment = { start: number; end: number }
export type RecordingStarted = null
export type RecordingStopped = { path: string }
export type RenderFrameEvent = { frame_number: number; project: ProjectConfiguration }
diff --git a/crates/ffmpeg/Cargo.toml b/crates/ffmpeg/Cargo.toml
index e2fea2a4a..774671010 100644
--- a/crates/ffmpeg/Cargo.toml
+++ b/crates/ffmpeg/Cargo.toml
@@ -8,3 +8,4 @@ ffmpeg-sidecar = "1.1.0"
cap-utils = { path = "../utils" }
tauri = { workspace = true }
tauri-plugin-shell = "2.0.0-rc"
+nix = { version = "0.29.0", features = ["signal"] }
diff --git a/crates/ffmpeg/src/lib.rs b/crates/ffmpeg/src/lib.rs
index 867ef29f5..d1dff9cfa 100644
--- a/crates/ffmpeg/src/lib.rs
+++ b/crates/ffmpeg/src/lib.rs
@@ -1,14 +1,9 @@
-use cap_utils::create_named_pipe;
use std::{
ffi::OsString,
io::{Read, Write},
ops::Deref,
path::{Path, PathBuf},
process::{Child, ChildStdin, Command, Stdio},
- sync::{
- atomic::{AtomicBool, Ordering},
- Arc,
- },
};
use tauri::utils::platform;
@@ -39,6 +34,7 @@ impl FFmpegProcess {
pub fn stop(&mut self) {
self.ffmpeg_stdin.write_all(b"q").ok();
+ self.ffmpeg_stdin.flush().ok();
println!("Sent stop command to FFmpeg");
}
@@ -105,34 +101,27 @@ impl FFmpegProcess {
self.ffmpeg_stdin.flush()?;
Ok(())
}
-}
-
-pub struct NamedPipeCapture {
- path: PathBuf,
- is_stopped: Arc<AtomicBool>,
-}
-
-impl NamedPipeCapture {
- pub fn new(path: &PathBuf) -> (Self, Arc<AtomicBool>) {
- create_named_pipe(path).unwrap();
-
- let stop = Arc::new(AtomicBool::new(false));
-
- (
- Self {
- path: path.clone(),
- is_stopped: stop.clone(),
- },
- stop.clone(),
- )
- }
- pub fn path(&self) -> &PathBuf {
- &self.path
+ pub fn pause(&mut self) -> std::io::Result<()> {
+ #[cfg(unix)]
+ {
+ use nix::sys::signal::{kill, Signal};
+ use nix::unistd::Pid;
+ kill(Pid::from_raw(self.cmd.id() as i32), Signal::SIGSTOP)?;
+ println!("Sent SIGSTOP to FFmpeg");
+ }
+ Ok(())
}
- pub fn stop(&self) {
- self.is_stopped.store(true, Ordering::Relaxed);
+ pub fn resume(&mut self) -> std::io::Result<()> {
+ #[cfg(unix)]
+ {
+ use nix::sys::signal::{kill, Signal};
+ use nix::unistd::Pid;
+ kill(Pid::from_raw(self.cmd.id() as i32), Signal::SIGCONT)?;
+ println!("Sent SIGCONT to FFmpeg");
+ }
+ Ok(())
}
}
@@ -210,7 +199,6 @@ pub struct FFmpegRawAudioInput {
pub sample_rate: u32,
pub channels: u16,
pub input: OsString,
- pub wallclock: bool, // pub offset: f64,
}
impl ApplyFFmpegArgs for FFmpegRawAudioInput {
@@ -221,10 +209,6 @@ impl ApplyFFmpegArgs for FFmpegRawAudioInput {
.args(["-ar", &self.sample_rate.to_string()])
.args(["-ac", &self.channels.to_string()]);
- if self.wallclock {
- command.args(["-use_wallclock_as_timestamps", "1"]);
- }
-
// if self.offset != 0.0 {
// command.args(["-itsoffset", &self.offset.to_string()]);
// }
diff --git a/crates/project/src/configuration.rs b/crates/project/src/configuration.rs
index 9082de364..3d679e652 100644
--- a/crates/project/src/configuration.rs
+++ b/crates/project/src/configuration.rs
@@ -25,7 +25,9 @@ pub enum BackgroundSource {
impl Default for BackgroundSource {
fn default() -> Self {
- BackgroundSource::Color { value: [255, 0, 0] }
+ BackgroundSource::Color {
+ value: [71, 133, 255],
+ }
}
}
@@ -126,9 +128,9 @@ pub struct HotkeysConfiguration {
#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
#[serde(rename_all = "camelCase")]
pub struct TimelineSegment {
- timescale: f64,
- start: f64,
- end: f64,
+ pub timescale: f64,
+ pub start: f64,
+ pub end: f64,
}
impl TimelineSegment {
@@ -171,7 +173,7 @@ impl TimelineConfiguration {
}
}
-#[derive(Type, Serialize, Deserialize, Clone, Debug, Default)]
+#[derive(Type, Serialize, Deserialize, Clone, Debug)]
#[serde(rename_all = "camelCase")]
pub struct ProjectConfiguration {
pub aspect_ratio: Option<AspectRatio>,
@@ -189,3 +191,26 @@ impl ProjectConfiguration {
self.timeline.as_ref()
}
}
+
+impl Default for ProjectConfiguration {
+ fn default() -> Self {
+ ProjectConfiguration {
+ aspect_ratio: None,
+ background: BackgroundConfiguration {
+ source: BackgroundSource::default(),
+ ..Default::default()
+ },
+ camera: CameraConfiguration {
+ position: CameraPosition {
+ x: CameraXPosition::Right,
+ y: CameraYPosition::Bottom,
+ },
+ ..Default::default()
+ },
+ audio: AudioConfiguration::default(),
+ cursor: CursorConfiguration::default(),
+ hotkeys: HotkeysConfiguration::default(),
+ timeline: None,
+ }
+ }
+}
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
index c52022418..9d131bcef 100644
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@ -27,6 +27,12 @@ pub struct SharingMeta {
pub link: String,
}
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+pub struct RecordingSegment {
+ pub start: f64,
+ pub end: f64,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct RecordingMeta {
// this field is just for convenience, it shouldn't be persisted
@@ -40,6 +46,8 @@ pub struct RecordingMeta {
pub camera: Option<CameraMeta>,
#[serde(default)]
pub audio: Option<AudioMeta>,
+ #[serde(default)]
+ pub segments: Vec<RecordingSegment>,
}
impl RecordingMeta {
diff --git a/crates/rendering/src/decoder.rs b/crates/rendering/src/decoder.rs
index 3726f73f9..91e5e2865 100644
--- a/crates/rendering/src/decoder.rs
+++ b/crates/rendering/src/decoder.rs
@@ -53,7 +53,7 @@ impl AsyncVideoDecoder {
let mut context = codec::context::Context::new_with_codec(decoder_codec);
context.set_parameters(input_stream.parameters()).unwrap();
- let hw_device = {
+ let hw_device: Option<HwDevice> = {
#[cfg(target_os = "macos")]
{
context
@@ -112,15 +112,19 @@ impl AsyncVideoDecoder {
let mut peekable_requests = PeekableReceiver { rx, peeked: None };
- let mut packet_stuff = PacketStuff {
- packets: input.packets(),
- skipped_packet: None,
- };
+ let mut packets = input.packets();
+ // let mut packet_stuff = PacketStuff {
+ // packets: input.packets(),
+ // skipped_packet: None,
+ // };
while let Ok(r) = peekable_requests.recv() {
match r {
VideoDecoderMessage::GetFrame(frame_number, sender) => {
+ // println!("retrieving frame {frame_number}");
+
let mut sender = if let Some(cached) = cache.get(&frame_number) {
+ // println!("sending frame {frame_number} from cache");
sender.send(Some(cached.clone())).ok();
continue;
} else {
@@ -144,57 +148,47 @@ impl AsyncVideoDecoder {
* 1_000_000.0) as i64;
let position = timestamp_us.rescale((1, 1_000_000), rescale::TIME_BASE);
- // println!("seeking to {position} for frame {frame_number}");
-
- drop(packet_stuff);
+ println!("seeking to {position} for frame {frame_number}");
decoder.flush();
input.seek(position, ..position).unwrap();
cache.clear();
last_decoded_frame = None;
- packet_stuff = PacketStuff {
- packets: input.packets(),
- skipped_packet: None,
- };
+ packets = input.packets();
}
last_active_frame = Some(frame_number);
loop {
- let Some((stream, packet)) = packet_stuff
- .skipped_packet
- .take()
- .or_else(|| packet_stuff.packets.next())
- else {
- break;
- };
-
- let current_frame =
- ts_to_frame(packet.pts().unwrap(), time_base, frame_rate);
-
- let too_great_for_cache_bounds = current_frame > cache_max;
- let too_small_for_cache_bounds = current_frame < cache_min;
-
if peekable_requests.peek().is_some() {
- // println!("skipping packet for frame {current_frame} as new request is available");
- packet_stuff.skipped_packet = Some((stream, packet));
-
break;
}
+ let Some((stream, packet)) = packets.next() else {
+ break;
+ };
if stream.index() == input_stream_index {
- if too_great_for_cache_bounds {
- // println!("skipping packet for frame {current_frame} as it's out of cache bounds");
- packet_stuff.skipped_packet = Some((stream, packet));
- break;
- }
+ let packet_frame =
+ ts_to_frame(packet.pts().unwrap(), time_base, frame_rate);
+ // println!("sending frame {packet_frame} packet");
- decoder.send_packet(&packet).unwrap();
+ decoder.send_packet(&packet).ok(); // decode failures are ok, we just fail to return a frame
- last_decoded_frame = Some(current_frame);
+ let mut exit = false;
while decoder.receive_frame(&mut temp_frame).is_ok() {
+ let current_frame = ts_to_frame(
+ temp_frame.pts().unwrap(),
+ time_base,
+ frame_rate,
+ );
+ // println!("processing frame {current_frame}");
+ last_decoded_frame = Some(current_frame);
+
+ let exceeds_cache_bounds = current_frame > cache_max;
+ let too_small_for_cache_bounds = current_frame < cache_min;
+
let hw_frame =
hw_device.as_ref().and_then(|d| d.get_hwframe(&temp_frame));
@@ -216,7 +210,7 @@ impl AsyncVideoDecoder {
}
let mut rgb_frame = frame::Video::empty();
- scaler.run(&frame, &mut rgb_frame).unwrap();
+ scaler.run(frame, &mut rgb_frame).unwrap();
let width = rgb_frame.width() as usize;
let height = rgb_frame.height() as usize;
@@ -240,7 +234,7 @@ impl AsyncVideoDecoder {
}
}
- if !too_small_for_cache_bounds && !too_great_for_cache_bounds {
+ if !too_small_for_cache_bounds {
if cache.len() >= FRAME_CACHE_SIZE {
if let Some(last_active_frame) = &last_active_frame {
let frame = if frame_number > *last_active_frame {
@@ -258,17 +252,20 @@ impl AsyncVideoDecoder {
}
};
- // println!("removing frame {frame} from cache");
cache.remove(&frame);
} else {
- // println!("clearing cache");
cache.clear()
}
}
- // println!("caching frame {current_frame}");
cache.insert(current_frame, frame);
}
+
+ exit = exit || exceeds_cache_bounds;
+ }
+
+ if exit {
+ break;
}
}
}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 627e77260..d06833acb 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -117,17 +117,17 @@ pub async fn render_video_to_channel(
let background = Background::from(project.background.source.clone());
loop {
- if frame_number as f64 > 30 as f64 * duration {
+ if frame_number as f64 > 30_f64 * duration {
break;
};
let time = if let Some(timeline) = project.timeline() {
- match timeline.get_recording_time(frame_number as f64 / 30 as f64) {
+ match timeline.get_recording_time(frame_number as f64 / 30_f64) {
Some(time) => time,
None => break,
}
} else {
- frame_number as f64 / 30 as f64
+ frame_number as f64 / 30_f64
};
let Some((screen_frame, camera_frame)) =
@@ -304,7 +304,7 @@ impl ProjectUniforms {
crop_bounds[2] - crop_bounds[0],
crop_bounds[3] - crop_bounds[1],
];
- let cropped_aspect = cropped_size[0] as f32 / cropped_size[1] as f32;
+ let cropped_aspect = cropped_size[0] / cropped_size[1];
let padding = Self::get_padding(options, project);
let is_height_constrained = cropped_aspect <= output_aspect;
diff --git a/packages/ui-solid/src/auto-imports.d.ts b/packages/ui-solid/src/auto-imports.d.ts
index a8171ea3a..3d2b7b708 100644
--- a/packages/ui-solid/src/auto-imports.d.ts
+++ b/packages/ui-solid/src/auto-imports.d.ts
@@ -35,6 +35,7 @@ declare global {
const IconCapMicrophone: typeof import('~icons/cap/microphone.jsx')['default']
const IconCapMoreVertical: typeof import('~icons/cap/more-vertical.jsx')['default']
const IconCapPadding: typeof import('~icons/cap/padding.jsx')['default']
+ const IconCapPauseCircle: typeof import('~icons/cap/pause-circle.jsx')['default']
const IconCapPlayCircle: typeof import('~icons/cap/play-circle.jsx')['default']
const IconCapPresets: typeof import('~icons/cap/presets.jsx')['default']
const IconCapRedo: typeof import('~icons/cap/redo.jsx')['default']