Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix audio sync in export

Brendan Allan63822535b100
diff --git a/Cargo.lock b/Cargo.lock
index 6a080a40c..9a78967c5 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -903,6 +903,7 @@ name = "cap-project"
version = "0.1.0"
dependencies = [
"serde",
+ "serde_json",
"specta",
]
diff --git a/apps/desktop-solid/src-tauri/src/audio.rs b/apps/desktop-solid/src-tauri/src/audio.rs
index f5cc2b08a..59405af70 100644
--- a/apps/desktop-solid/src-tauri/src/audio.rs
+++ b/apps/desktop-solid/src-tauri/src/audio.rs
@@ -1,21 +1,24 @@
use cap_ffmpeg::NamedPipeCapture;
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
-use cpal::{Device, SampleFormat, SizedSample, Stream, SupportedStreamConfig};
+use cpal::{Device, SampleFormat, SizedSample, Stream, StreamConfig, SupportedStreamConfig};
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;
-use tokio::{fs::File, io::AsyncWriteExt, sync::mpsc};
+use tokio::sync::{oneshot, watch};
type SampleReceiver = mpsc::Receiver<Arc<Vec<u8>>>;
pub struct AudioCapturer {
device: Device,
pub device_name: String,
- config: SupportedStreamConfig,
+ pub supported_config: SupportedStreamConfig,
+ pub config: StreamConfig,
sample_receiver: Option<SampleReceiver>,
stream: Option<Stream>,
}
@@ -23,27 +26,27 @@ unsafe impl Send for AudioCapturer {}
unsafe impl Sync for AudioCapturer {}
impl AudioCapturer {
- pub fn init(custom_device: &str) -> Option<Self> {
- tracing::debug!("Custom device: {:?}", custom_device);
-
- let mut devices = get_input_devices();
-
- let maybe_device = {
- let maybe_name = devices.first().map(|(name, _)| name.clone());
- maybe_name.and_then(|device_name| devices.swap_remove_entry(&device_name))
- };
-
- maybe_device.map(|(name, (device, config))| {
- tracing::info!("Using audio device: {}", name);
-
- Self {
- config,
- device,
- device_name: name,
- sample_receiver: None,
- stream: None,
- }
- })
+ pub fn init(name: &str) -> Option<Self> {
+ println!("Custom device: {}", name);
+
+ get_input_devices()
+ .swap_remove(name)
+ .map(|(device, supported_config)| {
+ println!("Using audio device: {}", name);
+
+ let mut config = supported_config.config();
+
+ config.channels = config.channels.min(2);
+
+ Self {
+ config,
+ supported_config,
+ device,
+ device_name: name.to_string(),
+ sample_receiver: None,
+ stream: None,
+ }
+ })
}
pub fn log_info(&self) {
@@ -55,7 +58,7 @@ impl AudioCapturer {
pub fn start(&mut self, start_time_tx: oneshot::Sender<Instant>) -> Result<(), String> {
tracing::trace!("Building input stream...");
- let (receiver, stream) = (match self.config.sample_format() {
+ 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),
@@ -100,16 +103,16 @@ impl AudioCapturer {
}
pub fn sample_rate(&self) -> u32 {
- self.config.sample_rate().0
+ self.config.sample_rate.0
}
pub fn channels(&self) -> u16 {
- self.config.channels()
+ self.config.channels
}
// Returns ffmpeg sample format ID and sample size in bytes
pub fn sample_format(&self) -> &str {
- match self.config.sample_format() {
+ match self.supported_config.sample_format() {
SampleFormat::I8 => "s8",
SampleFormat::I16 => "s16le",
SampleFormat::I32 => "s32le",
@@ -222,10 +225,14 @@ pub fn get_input_devices() -> IndexMap<String, (Device, SupportedStreamConfig)>
device_map
}
-pub fn start_capturing(capturer: &mut AudioCapturer, pipe_path: PathBuf) -> NamedPipeCapture {
+pub async fn start_capturing(
+ capturer: &mut AudioCapturer,
+ pipe_path: PathBuf,
+ start_writing_rx: watch::Receiver<bool>,
+) -> (NamedPipeCapture, Instant) {
let (capture, is_stopped) = NamedPipeCapture::new(&pipe_path);
- let (tx, _) = oneshot::channel();
+ let (tx, rx) = oneshot::channel();
capturer.start(tx).unwrap();
@@ -236,7 +243,9 @@ pub fn start_capturing(capturer: &mut AudioCapturer, pipe_path: PathBuf) -> Name
.expect("Audio sample collection already started!");
tokio::spawn(async move {
- let mut pipe = File::create(&pipe_path).await.unwrap();
+ println!("Opening audio pipe...");
+ let mut pipe = File::create(&pipe_path).unwrap();
+ println!("Audio pipe opened");
while let Some(bytes) = receiver.recv().await {
if is_stopped.load(Ordering::Relaxed) {
@@ -244,13 +253,17 @@ pub fn start_capturing(capturer: &mut AudioCapturer, pipe_path: PathBuf) -> Name
return;
}
- pipe.write_all(&bytes).await.unwrap();
+ if !*start_writing_rx.borrow() {
+ continue;
+ }
+
+ pipe.write_all(&bytes).unwrap();
}
println!("Done receiving audio frames");
- let _ = pipe.sync_all().await;
+ pipe.sync_all().ok();
});
- capture
+ (capture, rx.await.unwrap())
}
diff --git a/apps/desktop-solid/src-tauri/src/camera.rs b/apps/desktop-solid/src-tauri/src/camera.rs
index 85b86e99a..0588160d1 100644
--- a/apps/desktop-solid/src-tauri/src/camera.rs
+++ b/apps/desktop-solid/src-tauri/src/camera.rs
@@ -1,8 +1,8 @@
use nokhwa::utils::CameraFormat;
use serde::Serialize;
use specta::Type;
-use std::{io::Write, path::PathBuf, sync::atomic::Ordering};
-use tokio::sync::oneshot;
+use std::{fs::File, io::Write, path::PathBuf, sync::atomic::Ordering, time::Instant};
+use tokio::sync::{oneshot, watch};
use tauri::{AppHandle, Manager, WebviewUrl};
@@ -75,14 +75,20 @@ pub struct CameraInfo {
pub description: String,
}
+struct CaptureStarted {}
+
pub async fn start_capturing(
pipe_path: PathBuf,
camera_info: nokhwa::utils::CameraInfo,
-) -> (CameraFormat, NamedPipeCapture) {
+ 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);
+ 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::*, *};
@@ -102,20 +108,42 @@ pub async fn start_capturing(
camera.open_stream().unwrap();
- println!("Opening pipe");
- let mut file = std::fs::File::create(&pipe_path).unwrap();
- println!("Pipe opened");
+ let mut start_tx = Some(start_tx);
- println!("Receiving frames");
loop {
if is_stopped.load(Ordering::Relaxed) {
println!("Stopping receiving camera frames");
return;
}
let frame = camera.frame().unwrap();
- file.write_all(frame.buffer()).ok();
+
+ if let Some(start_tx) = start_tx.take() {
+ start_tx.send(Instant::now()).unwrap();
+ }
+
+ if *start_writing_rx.borrow_and_update() {
+ frame_tx.send(Some(frame)).ok();
+ }
+ }
+ });
+
+ tokio::spawn(async move {
+ frame_rx.borrow_and_update();
+
+ let mut file = File::create(&pipe_path).unwrap();
+
+ loop {
+ frame_rx.changed().await.unwrap();
+
+ if let Some(frame) = &*frame_rx.borrow() {
+ file.write_all(frame.buffer()).ok();
+ }
}
});
- (video_info_rx.await.unwrap(), capture)
+ (
+ video_info_rx.await.unwrap(),
+ capture,
+ start_rx.await.unwrap(),
+ )
}
diff --git a/apps/desktop-solid/src-tauri/src/display.rs b/apps/desktop-solid/src-tauri/src/display.rs
index 50aa5795e..c4092e87e 100644
--- a/apps/desktop-solid/src-tauri/src/display.rs
+++ b/apps/desktop-solid/src-tauri/src/display.rs
@@ -1,4 +1,5 @@
use std::{
+ fs::File,
io::{BufWriter, Write},
path::PathBuf,
sync::atomic::Ordering,
@@ -12,6 +13,10 @@ use scap::{
};
use serde::{Deserialize, Serialize};
use specta::Type;
+use tokio::{
+ io::AsyncWriteExt,
+ sync::{oneshot, watch},
+};
use crate::macos;
use cap_ffmpeg::NamedPipeCapture;
@@ -65,10 +70,11 @@ pub fn list_capture_windows() -> Vec<CaptureWindow> {
pub const FPS: u32 = 30;
-pub fn start_capturing(
+pub async fn start_capturing(
pipe_path: PathBuf,
capture_target: &CaptureTarget,
-) -> ((u32, u32), NamedPipeCapture) {
+ start_writing_rx: watch::Receiver<bool>,
+) -> ((u32, u32), NamedPipeCapture, Instant) {
dbg!(capture_target);
let mut capturer = {
let crop_area = match capture_target {
@@ -103,11 +109,14 @@ pub fn start_capturing(
let (capture, is_stopped) = NamedPipeCapture::new(&pipe_path);
+ let (tx, rx) = oneshot::channel();
+
+ let (frame_tx, mut frame_rx) = watch::channel(vec![]);
+
std::thread::spawn(move || {
capturer.start_capture();
- let mut file = std::fs::File::create(&pipe_path).unwrap();
-
+ let mut start_time = Some(tx);
loop {
if is_stopped.load(Ordering::Relaxed) {
println!("Stopping receiving capture frames");
@@ -115,18 +124,38 @@ pub fn start_capturing(
}
let frame = capturer.get_next_frame();
+
+ if let Some(tx) = start_time.take() {
+ tx.send(Instant::now()).ok();
+ }
+
+ if !*start_writing_rx.borrow() {
+ continue;
+ }
+
match frame {
Ok(Frame::BGRA(frame)) => {
- file.write_all(&frame.data).ok();
+ frame_tx.send(frame.data).ok();
}
_ => println!("Failed to get frame"),
}
}
});
- tokio::spawn(async move {});
+ tokio::spawn(async move {
+ frame_rx.borrow_and_update();
+
+ let mut file = File::create(&pipe_path).unwrap();
+
+ loop {
+ frame_rx.changed().await.unwrap();
+
+ let frame = frame_rx.borrow();
+ file.write_all(&frame).ok();
+ }
+ });
- ((width, height), capture)
+ ((width, height), capture, rx.await.unwrap())
}
pub fn get_window_bounds(window_number: u32) -> Option<Bounds> {
diff --git a/apps/desktop-solid/src-tauri/src/lib.rs b/apps/desktop-solid/src-tauri/src/lib.rs
index c6eddee03..692150b31 100644
--- a/apps/desktop-solid/src-tauri/src/lib.rs
+++ b/apps/desktop-solid/src-tauri/src/lib.rs
@@ -286,7 +286,7 @@ async fn render_to_file_impl(
screen_recording_decoder: VideoDecoderActor,
camera_recording_decoder: Option<VideoDecoderActor>,
on_progress: impl Fn(u32) + Send + 'static,
- audio: Option<Arc<Vec<f64>>>,
+ audio: Option<AudioData>,
) -> Result<PathBuf, String> {
let (tx_image_data, mut rx_image_data) = tokio::sync::mpsc::unbounded_channel::<Vec<u8>>();
@@ -306,6 +306,7 @@ async fn render_to_file_impl(
file.write_all(
audio
+ .buffer
.iter()
.flat_map(|f| f.to_le_bytes())
.collect::<Vec<_>>()
@@ -317,7 +318,7 @@ async fn render_to_file_impl(
input: file_path.clone().into_os_string(),
sample_format: "f64le".to_string(),
sample_rate: 44100,
- channels: 2,
+ channels: 1,
});
Some((file_path, file, dir))
@@ -328,7 +329,7 @@ async fn render_to_file_impl(
ffmpeg.add_input(cap_ffmpeg::FFmpegRawVideoInput {
width: options.output_size.0,
height: options.output_size.1,
- fps: 60,
+ fps: 30,
pix_fmt: "rgba",
input: "pipe:0".into(),
});
@@ -408,12 +409,18 @@ impl EditorStateChanged {
}
}
+#[derive(Clone)]
+struct AudioData {
+ pub buffer: Arc<Vec<f64>>,
+ pub sample_rate: u32,
+}
+
struct EditorInstance {
app: AppHandle,
pub path: PathBuf,
pub screen_decoder: VideoDecoderActor,
pub camera_decoder: Option<VideoDecoderActor>,
- pub audio: Option<Arc<Vec<f64>>>,
+ pub audio: Option<AudioData>,
pub ws_port: u16,
pub renderer: Arc<editor::RendererHandle>,
pub render_constants: Arc<RenderVideoConstants>,
@@ -422,57 +429,58 @@ struct EditorInstance {
impl EditorInstance {
pub async fn new(app: &AppHandle, video_id: String) -> Self {
- let path = app
+ let project_path = app
.path()
.app_data_dir()
.unwrap()
.join("recordings")
.join(format!("{video_id}.cap"));
- if !path.exists() {
- println!("Video path {} not found!", path.display());
+ if !project_path.exists() {
+ println!("Video path {} not found!", project_path.display());
// return Err(format!("Video path {} not found!", path.display()));
- panic!("Video path {} not found!", path.display());
+ panic!("Video path {} not found!", project_path.display());
}
- let meta: cap_project::RecordingMeta = serde_json::from_str(
- &std::fs::read_to_string(path.join("recording-meta.json")).unwrap(),
- )
- .unwrap();
+ let meta = cap_project::RecordingMeta::load_for_project(&project_path);
const OUTPUT_SIZE: (u32, u32) = (1920, 1080);
let render_options = RenderOptions {
screen_size: (meta.display.width, meta.display.height),
- camera_size: meta.camera.map(|c| (c.width, c.height)), //.unwrap_or((0, 0)),
+ camera_size: meta.camera.as_ref().map(|c| (c.width, c.height)), //.unwrap_or((0, 0)),
output_size: OUTPUT_SIZE,
};
- let screen_decoder = VideoDecoderActor::new(path.join("content/display.mp4").clone());
+ let screen_decoder = VideoDecoderActor::new(project_path.join(meta.display.path).clone());
let camera_decoder = meta
.camera
- .map(|_| VideoDecoderActor::new(path.join("content/camera.mp4").clone()));
+ .map(|camera| VideoDecoderActor::new(project_path.join(camera.path).clone()));
- let audio = meta.has_audio.then(|| {
- let audio_path = path.join("content/audio-input.mp3");
+ let audio = meta.audio.map(|audio| {
+ let audio_path = project_path.join(audio.path);
let stdout = Command::new("ffmpeg")
.arg("-i")
.arg(audio_path)
.args(["-f", "f64le", "-acodec", "pcm_f64le"])
- .args(["-ar", "44100", "-ac", "2", "-"])
+ .args(["-ar", &audio.sample_rate.to_string()])
+ .args(["-ac", &audio.channels.to_string(), "-"])
.output()
.unwrap()
.stdout;
- let audio = stdout
+ let buffer = stdout
.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]]))
.collect::<Vec<_>>();
- println!("audio buffer length: {}", audio.len());
+ println!("audio buffer length: {}", buffer.len());
- Arc::new(audio)
+ AudioData {
+ buffer: Arc::new(buffer),
+ sample_rate: audio.sample_rate,
+ }
});
let (frame_tx, rx) = tokio::sync::mpsc::unbounded_channel();
@@ -586,7 +594,7 @@ impl EditorInstance {
Self {
app: app.clone(),
- path,
+ path: project_path,
screen_decoder,
camera_decoder,
ws_port,
@@ -649,7 +657,7 @@ async fn start_playback(app: AppHandle, video_id: String, project: ProjectConfig
std::thread::spawn({
let mut stop_rx = stop_rx.clone();
move || {
- let Some(data) = audio else {
+ let Some(audio) = audio else {
return;
};
@@ -660,44 +668,60 @@ async fn start_playback(app: AppHandle, video_id: String, project: ProjectConfig
.expect("Failed to get default output format");
let config = supported_config.config();
- let i = data.len() as f32 * (start_frame_number as f32 / (fps * duration));
+ let data = audio.buffer.clone();
- macro_rules! convert {
- ($t:ty) => {
- |f| (f * <$t>::MAX as f64) as $t
- };
- }
- let shared_data = (&device, &config, data, i as usize);
+ let mut clock =
+ data.len() as f64 * (start_frame_number as f64 / (fps * duration) as f64);
+
+ let resample_ratio = audio.sample_rate as f64 / config.sample_rate.0 as f64;
+
+ let next_sample = move || {
+ clock = clock + resample_ratio;
+
+ if clock >= data.len() as f64 {
+ return None;
+ }
+
+ // Simple linear interpolation
+ let index = clock as usize;
+ let frac = clock.fract();
+ let current = data[index];
+ let next = data[(index + 1) % data.len()];
+ Some(current * (1.0 - frac) + next * frac)
+ };
+
+ let shared_data = (&device, &config, next_sample);
let stream = match supported_config.sample_format() {
- SampleFormat::I8 => create_stream::<i8>(shared_data, convert!(i8)),
- SampleFormat::I16 => create_stream::<i16>(shared_data, convert!(i16)),
- SampleFormat::I32 => create_stream::<i32>(shared_data, convert!(i32)),
- SampleFormat::I64 => create_stream::<i64>(shared_data, convert!(i64)),
- SampleFormat::U8 => create_stream::<u8>(shared_data, convert!(u8)),
- SampleFormat::U16 => create_stream::<u16>(shared_data, convert!(u16)),
- SampleFormat::U32 => create_stream::<u32>(shared_data, convert!(u32)),
- SampleFormat::U64 => create_stream::<u64>(shared_data, convert!(u64)),
- SampleFormat::F32 => create_stream::<f32>(shared_data, |f| f as f32),
- SampleFormat::F64 => create_stream::<f64>(shared_data, |f| f),
+ SampleFormat::I8 => create_stream::<i8>(shared_data),
+ SampleFormat::I16 => create_stream::<i16>(shared_data),
+ SampleFormat::I32 => create_stream::<i32>(shared_data),
+ SampleFormat::I64 => create_stream::<i64>(shared_data),
+ SampleFormat::U8 => create_stream::<u8>(shared_data),
+ SampleFormat::U16 => create_stream::<u16>(shared_data),
+ SampleFormat::U32 => create_stream::<u32>(shared_data),
+ SampleFormat::U64 => create_stream::<u64>(shared_data),
+ SampleFormat::F32 => create_stream::<f32>(shared_data),
+ SampleFormat::F64 => create_stream::<f64>(shared_data),
_ => unimplemented!(),
};
- fn create_stream<T: SizedSample + 'static>(
- (device, config, data, mut i): (
+ fn create_stream<T: SizedSample + cpal::FromSample<f64> + 'static>(
+ (device, config, mut next_sample): (
&cpal::Device,
&cpal::StreamConfig,
- Arc<Vec<f64>>,
- usize,
+ impl FnMut() -> Option<f64> + Send + 'static,
),
- convert: fn(f64) -> T,
) -> cpal::Stream {
device
.build_output_stream(
config,
- move |buffer, _info| {
+ move |buffer: &mut [T], _info| {
for sample in buffer.iter_mut() {
- *sample = convert(data.get(i).cloned().unwrap_or(0.0));
- i += 1;
+ let Some(s) = next_sample() else {
+ continue;
+ };
+ let value = cpal::Sample::from_sample::<f64>(s);
+ *sample = value;
}
},
|_| {},
diff --git a/apps/desktop-solid/src-tauri/src/recording.rs b/apps/desktop-solid/src-tauri/src/recording.rs
index 7d4277931..a628aaab4 100644
--- a/apps/desktop-solid/src-tauri/src/recording.rs
+++ b/apps/desktop-solid/src-tauri/src/recording.rs
@@ -1,6 +1,9 @@
+use nokhwa::utils::CameraFormat;
use serde::Serialize;
use specta::Type;
-use std::path::PathBuf;
+use std::time::Instant;
+use std::{path::PathBuf, time::Duration};
+use tokio::sync::watch;
use crate::{
audio::{self, AudioCapturer},
@@ -68,25 +71,180 @@ pub async fn start(
std::fs::create_dir_all(&content_dir).unwrap();
+ let now = Instant::now();
+
let mut ffmpeg = FFmpeg::new();
- let camera = start_camera_recording(&content_dir, recording_options, &mut ffmpeg).await;
- let display = start_display_recording(&content_dir, recording_options, &mut ffmpeg).await;
- let audio = start_audio_recording(&content_dir, recording_options, &mut ffmpeg).await;
+ let (start_writing_tx, start_writing_rx) = watch::channel(false);
+
+ 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())
+ );
+
+ // let latest_start_time = std::cmp::max(
+ // display.2,
+ // std::cmp::max(
+ // camera.as_ref().map(|c| c.2).unwrap_or(now),
+ // audio.as_ref().map(|a| a.1).unwrap_or(now),
+ // ),
+ // );
+
+ 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: 30,
+ pix_fmt: "bgra",
+ // offset: start_time.duration_since(latest_start_time).as_secs_f64(),
+ ..Default::default()
+ });
+
+ 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([
+ "-vf",
+ &format!("fps={},scale=in_range=full:out_range=limited", display::FPS),
+ ])
+ .arg(&output_path);
+
+ FFmpegCaptureOutput {
+ input: ffmpeg_input,
+ capture,
+ output_path,
+ }
+ };
+
+ let camera = if let Some((format, capture, start_time)) = camera {
+ use nokhwa::utils::FrameFormat;
+
+ let output_path = content_dir.join("camera.mp4");
+
+ let ffmpeg_input = ffmpeg.add_input(FFmpegRawVideoInput {
+ input: capture.path().clone().into_os_string(),
+ width: format.resolution().width(),
+ height: format.resolution().height(),
+ fps: 30,
+ // fps: format.frame_rate(),
+ pix_fmt: match format.format() {
+ FrameFormat::YUYV => "uyvy422",
+ FrameFormat::RAWRGB => "rgb24",
+ FrameFormat::NV12 => "nv12",
+ _ => panic!("unimplemented"),
+ },
+ // offset: start_time.duration_since(latest_start_time).as_secs_f64(),
+ });
+
+ 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([
+ "-vf",
+ &format!(
+ "fps={},scale=in_range=full:out_range=limited",
+ ffmpeg_input.fps
+ ),
+ ])
+ .arg(&output_path);
+
+ Some(FFmpegCaptureOutput {
+ input: ffmpeg_input,
+ capture,
+ output_path,
+ })
+ } else {
+ None
+ };
+
+ let audio = if let Some((capture, start_time, 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(),
+ sample_format: capturer.sample_format().to_string(),
+ sample_rate: capturer.sample_rate(),
+ channels: capturer.channels(),
+ // offset: start_time.duration_since(latest_start_time).as_secs_f64(),
+ });
+
+ ffmpeg
+ .command
+ .args(["-f", "mp3", "-map", &format!("{}:a", ffmpeg_input.index)])
+ .args(["-b:a", "192k"])
+ .args(["-ar", &capturer.sample_rate().to_string()])
+ .args(["-ac", &capturer.channels().to_string(), "-async", "1"])
+ .args([
+ "-af",
+ "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
+ ])
+ .arg(&output_path);
+
+ Some((
+ FFmpegCaptureOutput {
+ input: ffmpeg_input,
+ capture,
+ output_path,
+ },
+ capturer,
+ ))
+ } else {
+ None
+ };
let ffmpeg_process = ffmpeg.start();
+ tokio::time::sleep(Duration::from_secs(2)).await;
+
+ println!("Starting writing to named pipes");
+
+ start_writing_tx.send(true).unwrap();
+
use cap_project::*;
let meta = RecordingMeta {
display: Display {
+ path: display
+ .output_path
+ .strip_prefix(&recording_dir)
+ .unwrap()
+ .to_owned(),
width: display.input.width,
height: display.input.height,
},
camera: camera.as_ref().map(|camera| Camera {
+ path: camera
+ .output_path
+ .strip_prefix(&recording_dir)
+ .unwrap()
+ .to_owned(),
width: camera.input.width,
height: camera.input.height,
}),
- has_audio: audio.is_some(),
+ audio: audio.as_ref().map(|(audio, _)| Audio {
+ path: audio
+ .output_path
+ .strip_prefix(&recording_dir)
+ .unwrap()
+ .to_owned(),
+ sample_rate: audio.input.sample_rate,
+ channels: audio.input.channels,
+ }),
};
std::fs::write(
@@ -113,8 +271,8 @@ pub async fn start(
async fn start_camera_recording(
content_path: &PathBuf,
recording_options: &RecordingOptions,
- ffmpeg: &mut FFmpeg,
-) -> Option<FFmpegCaptureOutput<FFmpegRawVideoInput>> {
+ start_writing_rx: watch::Receiver<bool>,
+) -> Option<(CameraFormat, NamedPipeCapture, Instant)> {
let Some(camera_info) = recording_options
.camera_label
.as_ref()
@@ -124,92 +282,29 @@ async fn start_camera_recording(
};
let pipe_path = content_path.join("camera.pipe");
- let output_path = content_path.join("camera.mp4");
-
- let (format, capture) = camera::start_capturing(pipe_path.clone(), camera_info).await;
-
- use nokhwa::utils::FrameFormat;
-
- let ffmpeg_input = ffmpeg.add_input(FFmpegRawVideoInput {
- input: pipe_path.into_os_string(),
- width: format.resolution().width(),
- height: format.resolution().height(),
- fps: format.frame_rate(),
- pix_fmt: match format.format() {
- FrameFormat::YUYV => "uyvy422",
- FrameFormat::RAWRGB => "rgb24",
- FrameFormat::NV12 => "nv12",
- _ => panic!("unimplemented"),
- },
- });
-
- 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([
- "-vf",
- &format!(
- "fps={},scale=in_range=full:out_range=limited",
- ffmpeg_input.fps
- ),
- ])
- .arg(&output_path);
-
- Some(FFmpegCaptureOutput {
- input: ffmpeg_input,
- capture,
- output_path,
- })
+
+ Some(camera::start_capturing(pipe_path.clone(), camera_info, start_writing_rx).await)
}
async fn start_display_recording(
content_path: &PathBuf,
recording_options: &RecordingOptions,
- ffmpeg: &mut FFmpeg,
-) -> FFmpegCaptureOutput<FFmpegRawVideoInput> {
+ start_writing_rx: watch::Receiver<bool>,
+) -> ((u32, u32), NamedPipeCapture, Instant) {
let pipe_path = content_path.join("display.pipe");
- let output_path = content_path.join("display.mp4");
-
- let ((width, height), capture) =
- display::start_capturing(pipe_path.clone(), &recording_options.capture_target);
-
- let ffmpeg_input = ffmpeg.add_input(FFmpegRawVideoInput {
- input: pipe_path.into_os_string(),
- width,
- height,
- fps: 0,
- pix_fmt: "bgra",
- });
-
- 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([
- "-vf",
- &format!("fps={},scale=in_range=full:out_range=limited", display::FPS),
- ])
- .arg(&output_path);
-
- FFmpegCaptureOutput {
- input: ffmpeg_input,
- capture,
- output_path,
- }
+ 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,
- ffmpeg: &mut FFmpeg,
-) -> Option<(FFmpegCaptureOutput<FFmpegRawAudioInput>, AudioCapturer)> {
+ start_writing_rx: watch::Receiver<bool>,
+) -> Option<(NamedPipeCapture, Instant, AudioCapturer)> {
let Some(mut capturer) = recording_options
.audio_input_name
.as_ref()
@@ -219,33 +314,9 @@ async fn start_audio_recording(
};
let pipe_path = content_path.join("audio-input.pipe");
- let output_path = content_path.join("audio-input.mp3");
-
- let capture = audio::start_capturing(&mut capturer, pipe_path.clone());
-
- let ffmpeg_input = ffmpeg.add_input(FFmpegRawAudioInput {
- input: pipe_path.into_os_string(),
- sample_format: capturer.sample_format().to_string(),
- sample_rate: capturer.sample_rate(),
- channels: capturer.channels(),
- });
-
- ffmpeg
- .command
- .args(["-f", "mp3", "-map", &format!("{}:a", ffmpeg_input.index)])
- .args(["-b:a", "128k", "-async", "1", "-vn"])
- .args([
- "-af",
- "aresample=async=1:min_hard_comp=0.100000:first_pts=0",
- ])
- .arg(&output_path);
-
- Some((
- FFmpegCaptureOutput {
- input: ffmpeg_input,
- capture,
- output_path,
- },
- capturer,
- ))
+
+ let (capture, start_time) =
+ audio::start_capturing(&mut capturer, pipe_path.clone(), start_writing_rx).await;
+
+ Some((capture, start_time, capturer))
}
diff --git a/crates/ffmpeg/src/lib.rs b/crates/ffmpeg/src/lib.rs
index 89f5a600d..1ddecf6e1 100644
--- a/crates/ffmpeg/src/lib.rs
+++ b/crates/ffmpeg/src/lib.rs
@@ -177,16 +177,19 @@ pub trait ApplyFFmpegArgs {
fn apply_ffmpeg_args(&self, command: &mut Command);
}
+#[derive(Debug, Default)]
pub struct FFmpegRawVideoInput {
pub width: u32,
pub height: u32,
pub fps: u32,
pub pix_fmt: &'static str,
pub input: OsString,
+ // pub offset: f64,
}
impl ApplyFFmpegArgs for FFmpegRawVideoInput {
fn apply_ffmpeg_args(&self, command: &mut Command) {
+ dbg!(&self);
let size = format!("{}x{}", self.width, self.height);
command
@@ -199,27 +202,40 @@ impl ApplyFFmpegArgs for FFmpegRawVideoInput {
command.args(["-r", &self.fps.to_string()]);
}
+ // if self.offset != 0.0 {
+ // command.args(["-itsoffset", &self.offset.to_string()]);
+ // }
+
command
.args(["-thread_queue_size", "4096", "-i"])
.arg(&self.input);
}
}
+#[derive(Debug, Default)]
pub struct FFmpegRawAudioInput {
pub sample_format: String,
pub sample_rate: u32,
pub channels: u16,
pub input: OsString,
+ // pub offset: f64,
}
impl ApplyFFmpegArgs for FFmpegRawAudioInput {
fn apply_ffmpeg_args(&self, command: &mut Command) {
+ dbg!(&self);
command
.args(["-f", &self.sample_format])
.args(["-ar", &self.sample_rate.to_string()])
.args(["-ac", &self.channels.to_string()])
- .args(["-thread_queue_size", "4096", "-i"])
- .arg(&self.input);
+ .args(["-use_wallclock_as_timestamps", "1"])
+ .args(["-thread_queue_size", "4096", "-i"]);
+
+ // if self.offset != 0.0 {
+ // command.args(["-itsoffset", &self.offset.to_string()]);
+ // }
+
+ command.arg(&self.input);
}
}
diff --git a/crates/project/Cargo.toml b/crates/project/Cargo.toml
index 39546f43b..31bf17d3a 100644
--- a/crates/project/Cargo.toml
+++ b/crates/project/Cargo.toml
@@ -6,3 +6,4 @@ edition = "2021"
[dependencies]
specta = { version = "=2.0.0-rc.19", features = ["derive"] }
serde = { version = "1.0.209", features = ["derive"] }
+serde_json = "1.0.127"
diff --git a/crates/project/src/lib.rs b/crates/project/src/lib.rs
index 030499191..7e55aaaa1 100644
--- a/crates/project/src/lib.rs
+++ b/crates/project/src/lib.rs
@@ -1,25 +1,45 @@
mod configuration;
+use std::path::PathBuf;
+
pub use configuration::*;
use serde::{Deserialize, Serialize};
use specta::Type;
-#[derive(Debug, Clone, Serialize, Deserialize, Type, Copy)]
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct Display {
+ pub path: PathBuf,
pub width: u32,
pub height: u32,
}
-#[derive(Debug, Clone, Serialize, Deserialize, Type, Copy)]
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct Camera {
+ pub path: PathBuf,
pub width: u32,
pub height: u32,
}
-#[derive(Debug, Clone, Serialize, Deserialize, Type, Copy)]
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
+pub struct Audio {
+ pub path: PathBuf,
+ pub channels: u16,
+ pub sample_rate: u32,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, Type)]
pub struct RecordingMeta {
pub display: Display,
+ #[serde(default)]
pub camera: Option<Camera>,
#[serde(default)]
- pub has_audio: bool,
+ pub audio: Option<Audio>,
+}
+
+impl RecordingMeta {
+ pub fn load_for_project(project_path: &PathBuf) -> Self {
+ let meta_path = project_path.join("recording-meta.json");
+ let meta = std::fs::read_to_string(meta_path).unwrap();
+ serde_json::from_str(&meta).unwrap()
+ }
}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index ee3784033..0be534f4d 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -125,7 +125,6 @@ pub async fn render_video_to_channel(
) -> Result<(), String> {
let constants = RenderVideoConstants::new(options).await?;
-
println!("Setting up FFmpeg input for screen recording...");
ffmpeg_next::init().unwrap();
@@ -626,8 +625,6 @@ pub async fn produce_frame(
let texture_view = texture.create_view(&wgpu::TextureViewDescriptor::default());
- println!("camera frame size: {}", camera_frame.len());
-
queue.write_texture(
wgpu::ImageCopyTexture {
texture: &texture,