Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: Camera frame shader issue + removal of ffmpeg CLI from editor

Richie McIlroy265812718f71
diff --git a/Cargo.lock b/Cargo.lock
index ea66481aa..7c0fe9f8e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -824,7 +824,6 @@ name = "cap-export"
version = "0.1.0"
dependencies = [
"cap-editor",
- "cap-ffmpeg-cli",
"cap-flags",
"cap-media",
"cap-project",
@@ -877,6 +876,7 @@ dependencies = [
"core-graphics 0.24.0",
"cpal 0.15.3 (git+https://github.com/RustAudio/cpal?rev=f43d36e55494993bbbde3299af0c53e5cdf4d4cf)",
"ffmpeg-next",
+ "ffmpeg-sys-next",
"flume 0.11.0",
"futures",
"indexmap 2.5.0",
diff --git a/apps/desktop/src-tauri/src/export.rs b/apps/desktop/src-tauri/src/export.rs
index abcfb7b35..f99e41251 100644
--- a/apps/desktop/src-tauri/src/export.rs
+++ b/apps/desktop/src-tauri/src/export.rs
@@ -94,7 +94,7 @@ pub async fn export_video(
let result = if use_custom_muxer {
exporter.export_with_custom_muxer().await
} else {
- exporter.export_with_ffmpeg_cli().await
+ exporter.export_with_mp4_encoder().await
};
match result {
diff --git a/crates/export/Cargo.toml b/crates/export/Cargo.toml
index 1711b488f..5ff659f4e 100644
--- a/crates/export/Cargo.toml
+++ b/crates/export/Cargo.toml
@@ -7,7 +7,6 @@ edition = "2021"
cap-utils = { path = "../utils" }
cap-project = { path = "../project" }
cap-rendering = { path = "../rendering" }
-cap-ffmpeg-cli = { path = "../ffmpeg-cli" }
cap-editor = { path = "../editor" }
cap-media = { path = "../media" }
cap-flags = { path = "../flags" }
diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rs
index 8f9247de4..fb7f90590 100644
--- a/crates/export/src/lib.rs
+++ b/crates/export/src/lib.rs
@@ -112,7 +112,6 @@ where
}
let (tx_image_data, mut rx_image_data) = tokio::sync::mpsc::channel::<RenderedFrame>(4);
-
let (frame_tx, frame_rx) = std::sync::mpsc::sync_channel::<MP4Input>(4);
let audio_info = match self.audio_segments.get(0).and_then(|d| d.as_ref().as_ref()) {
@@ -188,29 +187,25 @@ where
}
let audio_info = audio.buffer.info();
- // dbg!(&audio_info);
let estimated_samples_per_frame =
f64::from(audio_info.sample_rate) / f64::from(FPS);
let samples = estimated_samples_per_frame.ceil() as usize;
- if let Some((_, frame_data)) =
- audio.buffer.next_frame_data(samples, project.timeline())
+ if let Some((_, frame_data)) = audio
+ .buffer
+ .next_frame_data(samples, project.timeline.as_ref().map(|t| t))
{
- // dbg!(&audio_info);
- let mut frame = audio_info.wrap_frame(
- &frame_data
- .to_vec()
- .chunks(8)
- .flat_map(|v| {
- (f64::from_le_bytes([
- v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7],
- ]) as f32)
- .to_le_bytes()
- })
- .collect::<Vec<_>>(),
- 0,
+ let mut frame = audio_info.wrap_frame(&frame_data, 0);
+ let pts = (frame_count as f64 * f64::from(audio_info.sample_rate) / f64::from(FPS)) as i64;
+ frame.set_pts(Some(pts));
+ frame.set_duration(Some(samples as i64));
+ println!(
+ "Export: Sending audio frame {} with PTS: {:?}, samples: {}, data size: {}",
+ frame_count,
+ frame.pts(),
+ samples,
+ frame_data.len()
);
- frame.set_pts(Some(1_000_000 / 30 * (frame_count as i64)));
Some(frame)
} else {
None
@@ -219,6 +214,11 @@ where
None
};
+ println!(
+ "Export: Processing frame {} (size: {}x{}, padded_bytes_per_row: {})",
+ frame_count, frame.width, frame.height, frame.padded_bytes_per_row
+ );
+
let mut video_frame = VideoInfo::from_raw(
RawVideoFormat::Rgba,
self.output_size.0,
@@ -232,6 +232,12 @@ where
);
video_frame.set_pts(Some(frame_count as i64));
+ println!(
+ "Export: Sending frame {} to encoder (PTS: {:?})",
+ frame_count,
+ video_frame.pts()
+ );
+
frame_tx
.send(MP4Input {
audio: audio_frame,
@@ -265,18 +271,6 @@ where
rgb_img.save(&screenshot_path).unwrap_or_else(|e| {
eprintln!("Failed to save screenshot: {:?}", e);
});
-
- // // Create and save thumbnail
- // let thumbnail = image::imageops::resize(
- // &rgb_img,
- // 100,
- // 100,
- // image::imageops::FilterType::Lanczos3,
- // );
- // let thumbnail_path = screenshots_dir.join("thumbnail.png");
- // thumbnail.save(&thumbnail_path).unwrap_or_else(|e| {
- // eprintln!("Failed to save thumbnail: {:?}", e);
- // });
} else {
eprintln!("No frames were processed, cannot save screenshot or thumbnail");
}
@@ -302,172 +296,137 @@ where
Ok(output_path)
}
- pub async fn export_with_ffmpeg_cli(self) -> Result<PathBuf, ExportError> {
+ pub async fn export_with_mp4_encoder(self) -> Result<PathBuf, ExportError> {
struct AudioRender {
buffer: AudioFrameBuffer,
- pipe_tx: tokio::sync::mpsc::Sender<Vec<u8>>,
}
let (tx_image_data, mut rx_image_data) = tokio::sync::mpsc::channel::<RenderedFrame>(4);
- let ffmpeg_handle = tokio::spawn({
+ let encoder_handle = tokio::spawn({
let project = self.project.clone();
let project_path = self.project_path.clone();
async move {
- println!("Starting FFmpeg output process...");
- let mut ffmpeg = cap_ffmpeg_cli::FFmpeg::new();
+ println!("Starting MP4 encoding process...");
- let audio_dir = tempfile::tempdir().unwrap();
- let video_dir = tempfile::tempdir().unwrap();
- let mut audio = if let Some(audio_data) =
+ let audio_info = if let Some(audio_data) =
self.audio_segments.get(0).and_then(|d| d.as_ref().as_ref())
{
- let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(30);
-
- let pipe_path = cap_utils::create_channel_named_pipe(
- rx,
- audio_dir.path().join("audio.pipe"),
- {
- let mut done = false;
- move |value| {
- if done {
- None
- } else {
- done = true;
- Some(&value)
- }
- }
- },
- );
-
- ffmpeg.add_input(cap_ffmpeg_cli::FFmpegRawAudioInput {
- input: pipe_path,
- sample_format: "f64le".to_string(),
- sample_rate: audio_data.info.sample_rate,
- channels: audio_data.info.channels as u16,
- });
-
- Some(AudioRender {
- buffer: AudioFrameBuffer::new(
- self.audio_segments
- .iter()
- .map(|s| s.as_ref().as_ref().unwrap().clone())
- .collect(),
- ),
- pipe_tx: tx,
- })
+ Some(
+ AudioInfo::new(
+ audio_data.info.sample_format,
+ audio_data.info.sample_rate,
+ audio_data.info.channels as u16,
+ )
+ .map_err(Into::<MediaError>::into)?,
+ )
} else {
None
};
- let video_tx = {
- let (tx, rx) = tokio::sync::mpsc::channel::<RenderedFrame>(30);
+ let mut encoder = cap_media::encoders::MP4Encoder::init(
+ "output",
+ VideoInfo::from_raw(
+ MP4Encoder::video_format(),
+ self.output_size.0,
+ self.output_size.1,
+ 30,
+ ),
+ audio_info,
+ cap_media::encoders::Output::File(self.output_path.clone()),
+ )?;
- let pipe_path = cap_utils::create_channel_named_pipe(
- rx,
- video_dir.path().join("video.pipe"),
- {
- let mut i = 0;
-
- move |frame| {
- if i < frame.data.len() as u32 {
- let value =
- &frame.data[i as usize..(i + frame.width * 4) as usize];
-
- i += frame.padded_bytes_per_row;
- Some(value)
- } else {
- None
- }
- }
- },
- );
+ let mut audio =
+ if let Some(_) = self.audio_segments.get(0).and_then(|d| d.as_ref().as_ref()) {
+ Some(AudioRender {
+ buffer: AudioFrameBuffer::new(
+ self.audio_segments
+ .iter()
+ .map(|s| s.as_ref().as_ref().unwrap().clone())
+ .collect(),
+ ),
+ })
+ } else {
+ None
+ };
- ffmpeg.add_input(cap_ffmpeg_cli::FFmpegRawVideoInput {
- width: self.output_size.0,
- height: self.output_size.1,
- fps: 30,
- pix_fmt: "rgba",
- input: pipe_path,
- });
+ let mut frame_count = 0;
+ let mut first_frame = None;
- tx
- };
+ while let Some(frame) = rx_image_data.recv().await {
+ (self.on_progress)(frame_count);
- ffmpeg
- .command
- .args(["-f", "mp4"])
- .args(["-codec:v", "libx264", "-codec:a", "aac"])
- .args(["-preset", "ultrafast"])
- .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])
- .arg("-y")
- .arg(&self.output_path);
+ if frame_count == 0 {
+ first_frame = Some(frame.clone());
+ }
- let mut ffmpeg_process = ffmpeg.start();
+ if let Some(audio) = &mut audio {
+ if frame_count == 0 {
+ audio.buffer.set_playhead(0., project.timeline());
+ }
- let mut frame_count = 0;
- let mut first_frame = None;
+ let audio_info = audio.buffer.info();
+ let estimated_samples_per_frame =
+ f64::from(audio_info.sample_rate) / f64::from(FPS);
+ let samples = estimated_samples_per_frame.ceil() as usize;
- loop {
- tokio::select! {
- result = ffmpeg_process.wait() => {
- match result {
- Err(e) => Err(ExportError::FFmpeg(e.to_string())),
- Ok(status) => {
- if status.success() {
- Ok(())
- } else {
- Err(ExportError::FFmpeg(
- ffmpeg_process
- .read_stderr()
- .await
- .unwrap_or_else(|_| "Failed to read FFmpegg error".to_string())
- ))
- }
- }
- }?;
- }
- frame = rx_image_data.recv() => {
- match frame {
- Some(frame) => {
- (self.on_progress)(frame_count);
-
- if frame_count == 0 {
- first_frame = Some(frame.clone());
- }
-
- if let Some(audio) = &mut audio {
- if frame_count == 0 {
- audio.buffer.set_playhead(0., project.timeline());
- }
-
- let audio_info = audio.buffer.info();
- let estimated_samples_per_frame =
- f64::from(audio_info.sample_rate) / f64::from(FPS);
- let samples = estimated_samples_per_frame.ceil() as usize;
-
- if let Some((_, frame_data)) =
- audio.buffer.next_frame_data(samples, project.timeline())
- {
- let frame_samples = frame_data.to_vec();
- audio.pipe_tx.send(frame_samples).await.unwrap();
- }
- }
-
- video_tx.send(frame).await.unwrap();
-
- frame_count += 1;
- }
- None => {
- println!("All frames sent to FFmpeg");
- break;
- }
- }
+ if let Some((_, frame_data)) =
+ audio.buffer.next_frame_data(samples, project.timeline())
+ {
+ let mut frame = audio_info.wrap_frame(
+ &frame_data
+ .to_vec()
+ .chunks(8)
+ .flat_map(|v| {
+ (f64::from_le_bytes([
+ v[0], v[1], v[2], v[3], v[4], v[5], v[6], v[7],
+ ]) as f32)
+ .to_le_bytes()
+ })
+ .collect::<Vec<_>>(),
+ 0,
+ );
+ let pts = i64::from(frame_count) * i64::try_from(samples).unwrap();
+ frame.set_pts(Some(pts));
+ println!(
+ "Export: Sending audio frame {} with PTS: {:?}, samples: {}",
+ frame_count,
+ frame.pts(),
+ samples
+ );
+ encoder.queue_audio_frame(frame);
}
}
+
+ println!(
+ "Export: Processing frame {} (size: {}x{}, padded_bytes_per_row: {})",
+ frame_count, frame.width, frame.height, frame.padded_bytes_per_row
+ );
+
+ let mut video_frame = VideoInfo::from_raw(
+ RawVideoFormat::Rgba,
+ self.output_size.0,
+ self.output_size.1,
+ 30,
+ )
+ .wrap_frame(
+ &frame.data,
+ 0,
+ frame.padded_bytes_per_row as usize,
+ );
+ video_frame.set_pts(Some(frame_count as i64));
+
+ println!(
+ "Export: Sending frame {} to encoder (PTS: {:?})",
+ frame_count,
+ video_frame.pts()
+ );
+
+ encoder.queue_video_frame(video_frame);
+ frame_count += 1;
}
- ffmpeg_process.stop().await;
+ encoder.finish();
// Save the first frame as a screenshot and thumbnail
if let Some(frame) = first_frame {
@@ -492,18 +451,6 @@ where
rgb_img.save(&screenshot_path).unwrap_or_else(|e| {
eprintln!("Failed to save screenshot: {:?}", e);
});
-
- // // Create and save thumbnail
- // let thumbnail = image::imageops::resize(
- // &rgb_img,
- // 100,
- // 100,
- // image::imageops::FilterType::Lanczos3,
- // );
- // let thumbnail_path = screenshots_dir.join("thumbnail.png");
- // thumbnail.save(&thumbnail_path).unwrap_or_else(|e| {
- // eprintln!("Failed to save thumbnail: {:?}", e);
- // });
} else {
eprintln!("No frames were processed, cannot save screenshot or thumbnail");
}
@@ -523,7 +470,7 @@ where
)
.await?;
- let output_path = ffmpeg_handle.await??;
+ let output_path = encoder_handle.await??;
Ok(output_path)
}
diff --git a/crates/gpu-converters/src/yuyv_rgba/shader.wgsl b/crates/gpu-converters/src/yuyv_rgba/shader.wgsl
index 192050ac6..378bf244c 100644
--- a/crates/gpu-converters/src/yuyv_rgba/shader.wgsl
+++ b/crates/gpu-converters/src/yuyv_rgba/shader.wgsl
@@ -1,3 +1,54 @@
+@group(0) @binding(0)
+var yuyv_input: texture_2d<u32>;
+
+@group(0) @binding(1)
+var rgba_output: texture_storage_2d<rgba8unorm, write>;
+
+// We use 8x8 workgroups to cover the entire input texture
+@compute
+@workgroup_size(8, 8)
+fn main(@builtin(global_invocation_id) gid: vec3<u32>) {
+ let dims = textureDimensions(yuyv_input);
+ if (gid.x >= dims.x || gid.y >= dims.y) {
+ return;
+ }
+
+ // Each texel in Rgba8Uint has .r, .g, .b, .a (each 8 bits).
+ // In standard YUYV: R=Y0, G=U, B=Y1, A=V.
+ // Some cameras mislabel and actually deliver YVYU or UYVY, so see below if color is off.
+
+ let packed = textureLoad(yuyv_input, gid.xy, 0);
+
+ // --- Standard “YUYV” interpretation (no offsets) ---
+ let y0 = f32(packed.r) / 255.0;
+ let v = f32(packed.g) / 255.0;
+ let y1 = f32(packed.b) / 255.0;
+ let u = f32(packed.a) / 255.0;
+
+ // If you still see green/magenta, try swapping U<->V here:
+ // let y0 = f32(packed.r) / 255.0;
+ // let v = f32(packed.g) / 255.0; // swapped
+ // let y1 = f32(packed.b) / 255.0;
+ // let u = f32(packed.a) / 255.0; // swapped
+
+ // ---- Full-Range YUV->RGB (0..255 for Y, U, V) ----
+ // R = Y + 1.402 * (V - 0.5)
+ // G = Y - 0.344136 * (U - 0.5) - 0.714136 * (V - 0.5)
+ // B = Y + 1.772 * (U - 0.5)
+ let r1 = clamp(y0 + 1.402 * (v - 0.5), 0.0, 1.0);
+ let g1 = clamp(y0
+ - 0.344136 * (u - 0.5)
+ - 0.714136 * (v - 0.5),
+ 0.0, 1.0);
+ let b1 = clamp(y0 + 1.772 * (u - 0.5), 0.0, 1.0);
+
+ let r2 = clamp(y1 + 1.402 * (v - 0.5), 0.0, 1.0);
+ let g2 = clamp(y1
+ - 0.344136 * (u - 0.5)
+ - 0.714136 * (v - 0.5),
+ 0.0, 1.0);
+ let b2 = clamp(y1 + 1.772 * (u - 0.5), 0.0, 1.0);
+
// Each texel stores two Y’s => two output RGBA pixels.
let out_coords = gid.xy * vec2<u32>(2, 1);
diff --git a/crates/media/Cargo.toml b/crates/media/Cargo.toml
index 85612a07b..4b7f60649 100644
--- a/crates/media/Cargo.toml
+++ b/crates/media/Cargo.toml
@@ -7,7 +7,7 @@ rust-version = "1.80"
[features]
default = []
-debug-logging = [] # Feature flag to control debug logging
+debug-logging = [] # Feature flag to control debug logging
[dependencies]
cap-project = { path = "../project" }
@@ -15,6 +15,7 @@ cap-flags = { path = "../flags" }
cap-gpu-converters = { path = "../gpu-converters" }
cpal.workspace = true
ffmpeg.workspace = true
+ffmpeg-sys-next.workspace = true
flume.workspace = true
indexmap = "2.5.0"
nokhwa = { workspace = true, features = ["input-native", "serialize"] }
diff --git a/crates/media/src/encoders/h264.rs b/crates/media/src/encoders/h264.rs
index 659645725..2b09ebb64 100644
--- a/crates/media/src/encoders/h264.rs
+++ b/crates/media/src/encoders/h264.rs
@@ -7,8 +7,9 @@ use ffmpeg::{
codec::{codec::Codec, context, encoder},
format::{self},
threading::Config,
- Dictionary,
+ Dictionary, Rescale,
};
+use ffmpeg_sys_next as sys;
use super::Output;
@@ -18,6 +19,7 @@ pub struct H264Encoder {
output_ctx: format::context::Output,
last_pts: Option<i64>,
config: VideoInfo,
+ frame_count: i64,
}
impl H264Encoder {
@@ -52,8 +54,8 @@ impl H264Encoder {
let mut output_stream = output_ctx.add_stream(codec)?;
output_stream.set_time_base(config.frame_rate.invert());
+ output_stream.set_rate(config.frame_rate);
output_stream.set_parameters(&video_encoder);
- // TODO: Move this to after pipeline start maybe?
output_ctx.write_header()?;
Ok(Self {
@@ -62,24 +64,25 @@ impl H264Encoder {
output_ctx,
last_pts: None,
config,
+ frame_count: 0,
})
}
- fn queue_frame(&mut self, frame: FFVideo) {
+ fn queue_frame(&mut self, mut frame: FFVideo) {
+ frame.set_pts(Some(self.frame_count));
+ self.frame_count += 1;
self.encoder.send_frame(&frame).unwrap();
}
fn process_frame(&mut self) {
let mut encoded_packet = FFPacket::empty();
- // TODO: Handle errors that are not EGAIN/"needs more data"
while self.encoder.receive_packet(&mut encoded_packet).is_ok() {
encoded_packet.set_stream(0);
encoded_packet.rescale_ts(
self.encoder.time_base(),
self.output_ctx.stream(0).unwrap().time_base(),
);
- // TODO: Possibly move writing to disk to its own file, to increase encoding throughput?
encoded_packet
.write_interleaved(&mut self.output_ctx)
.unwrap();
@@ -89,6 +92,23 @@ impl H264Encoder {
fn finish(&mut self) {
self.encoder.send_eof().unwrap();
self.process_frame();
+
+ // Set the duration in the output container's stream
+ if let Some(stream) = self.output_ctx.stream(0) {
+ let duration = self
+ .frame_count
+ .rescale(self.config.frame_rate.invert(), stream.time_base());
+ unsafe {
+ let stream_ptr = stream.as_ptr() as *mut sys::AVStream;
+ (*stream_ptr).duration = duration;
+ (*stream_ptr).time_base = stream.time_base().into();
+ (*stream_ptr).nb_frames = self.frame_count;
+ (*stream_ptr).start_time = 0;
+ (*stream_ptr).r_frame_rate = self.config.frame_rate.into();
+ (*stream_ptr).avg_frame_rate = self.config.frame_rate.into();
+ }
+ }
+
self.output_ctx.write_trailer().unwrap();
}
}
diff --git a/crates/media/src/encoders/mp4.rs b/crates/media/src/encoders/mp4.rs
index d6034b373..19460d3aa 100644
--- a/crates/media/src/encoders/mp4.rs
+++ b/crates/media/src/encoders/mp4.rs
@@ -7,11 +7,12 @@ use crate::{
};
use ffmpeg::{
codec::{codec::Codec, context, encoder},
- format::{self},
+ format::{self, sample::Sample},
software,
threading::Config,
- Dictionary,
+ Dictionary, Rescale,
};
+use ffmpeg_sys_next as sys;
use super::Output;
@@ -25,6 +26,7 @@ struct Audio {
struct Video {
encoder: ffmpeg::encoder::Video,
config: VideoInfo,
+ frame_count: i64,
}
pub struct MP4Encoder {
@@ -57,7 +59,7 @@ impl MP4Encoder {
video_enc.set_width(video_config.width);
video_enc.set_height(video_config.height);
video_enc.set_format(video_config.pixel_format);
- video_enc.set_time_base(video_config.frame_rate.invert());
+ video_enc.set_time_base(FFRational(1, video_config.frame_rate.numerator()));
video_enc.set_frame_rate(Some(video_config.frame_rate));
if video_codec.name() == "h264_videotoolbox" {
@@ -73,6 +75,7 @@ impl MP4Encoder {
let video = Video {
encoder: video_encoder,
config: video_config,
+ frame_count: 0,
};
let audio = if let Some(audio_config) = audio_config {
@@ -97,17 +100,17 @@ impl MP4Encoder {
)));
}
- let output_format = ffmpeg::format::Sample::F32(format::sample::Type::Packed);
+ let output_format = ffmpeg::format::Sample::F32(format::sample::Type::Planar);
audio_enc.set_bit_rate(Self::AUDIO_BITRATE);
audio_enc.set_rate(audio_config.rate());
audio_enc.set_format(output_format);
audio_enc.set_channel_layout(audio_config.channel_layout());
- audio_enc.set_time_base(audio_config.time_base);
+ audio_enc.set_time_base(FFRational(1, audio_config.rate()));
let resampler = software::resampler(
(
- audio_config.sample_format,
+ Sample::F64(format::sample::Type::Packed),
audio_config.channel_layout(),
audio_config.sample_rate,
),
@@ -125,7 +128,7 @@ impl MP4Encoder {
// Setup output streams
let mut video_stream = output_ctx.add_stream(video_codec)?;
- video_stream.set_time_base(video_config.frame_rate.invert());
+ video_stream.set_time_base(FFRational(1, video_config.frame_rate.numerator()));
video_stream.set_parameters(&video.encoder);
let audio = if let Some((encoder, codec, input_config, resampler)) = audio {
@@ -159,7 +162,12 @@ impl MP4Encoder {
RawVideoFormat::YUYV420
}
- pub fn queue_video_frame(&mut self, frame: FFVideo) {
+ pub fn queue_video_frame(&mut self, mut frame: FFVideo) {
+ println!(
+ "MP4Encoder: Processing frame {} (input PTS: {:?})",
+ self.video.frame_count,
+ frame.pts()
+ );
let mut scaler = ffmpeg::software::converter(
(frame.width(), frame.height()),
frame.format(),
@@ -168,29 +176,75 @@ impl MP4Encoder {
.unwrap();
let mut output = FFVideo::empty();
-
scaler.run(&frame, &mut output).unwrap();
- output.set_pts(frame.pts());
+ // Set PTS in microseconds (1/1_000_000 second units)
+ let pts = frame.pts().unwrap_or_else(|| self.video.frame_count);
+ output.set_pts(Some(pts));
+ println!(
+ "MP4Encoder: Setting frame {} PTS to {}",
+ self.video.frame_count, pts
+ );
+ self.video.frame_count += 1;
self.video.encoder.send_frame(&output).unwrap();
self.process_video_packets();
}
pub fn queue_audio_frame(&mut self, frame: FFAudio) {
- if let Some(buffer) = self.audio.as_mut().map(|a| &mut a.buffer) {
- buffer.consume(frame);
- }
+ let Some(audio) = &mut self.audio else {
+ return;
+ };
+
+ println!(
+ "MP4Encoder: Queueing audio frame with PTS: {:?}, samples: {}",
+ frame.pts(),
+ frame.samples()
+ );
+
+ audio.buffer.consume(frame);
+
+ // Process all buffered frames
+ loop {
+ let Some(buffered_frame) = audio.buffer.next_frame() else {
+ break;
+ };
- while let Some((buffered_frame, audio)) = self
- .audio
- .as_mut()
- .and_then(|a| Some((a.buffer.next_frame()?, a)))
- {
let mut output = ffmpeg::util::frame::Audio::empty();
audio.resampler.run(&buffered_frame, &mut output).unwrap();
+
+ // Preserve PTS from input frame
+ if let Some(pts) = buffered_frame.pts() {
+ output.set_pts(Some(pts));
+ }
+
+ println!(
+ "MP4Encoder: Sending audio frame with PTS: {:?}, samples: {}",
+ output.pts(),
+ output.samples()
+ );
+
+ // Send frame to encoder
audio.encoder.send_frame(&output).unwrap();
- self.process_audio_packets();
+
+ // Process any encoded packets
+ let mut encoded_packet = FFPacket::empty();
+ while audio.encoder.receive_packet(&mut encoded_packet).is_ok() {
+ println!(
+ "MP4Encoder: Writing audio packet with PTS: {:?}, size: {}",
+ encoded_packet.pts(),
+ encoded_packet.size()
+ );
+
+ encoded_packet.set_stream(1);
+ encoded_packet.rescale_ts(
+ audio.encoder.time_base(),
+ self.output_ctx.stream(1).unwrap().time_base(),
+ );
+ encoded_packet
+ .write_interleaved(&mut self.output_ctx)
+ .unwrap();
+ }
}
}
@@ -203,11 +257,21 @@ impl MP4Encoder {
.receive_packet(&mut encoded_packet)
.is_ok()
{
+ println!(
+ "MP4Encoder: Got encoded packet with PTS: {:?}, DTS: {:?}",
+ encoded_packet.pts(),
+ encoded_packet.dts()
+ );
encoded_packet.set_stream(0); // Video is stream 0
encoded_packet.rescale_ts(
self.video.encoder.time_base(),
self.output_ctx.stream(0).unwrap().time_base(),
);
+ println!(
+ "MP4Encoder: Writing packet with rescaled PTS: {:?}, DTS: {:?}",
+ encoded_packet.pts(),
+ encoded_packet.dts()
+ );
encoded_packet
.write_interleaved(&mut self.output_ctx)
.unwrap();
@@ -215,30 +279,84 @@ impl MP4Encoder {
}
fn process_audio_packets(&mut self) {
- let mut packet = FFPacket::empty();
-
if let Some(audio) = self.audio.as_mut() {
- while audio.encoder.receive_packet(&mut packet).is_ok() {
- packet.set_stream(1); // Audio is stream 1
- packet.set_time_base(self.output_ctx.stream(1).unwrap().time_base());
- packet.rescale_ts(
- packet.time_base(),
+ let mut encoded_packet = FFPacket::empty();
+
+ while audio.encoder.receive_packet(&mut encoded_packet).is_ok() {
+ println!(
+ "MP4Encoder: Writing audio packet with PTS: {:?}, size: {}",
+ encoded_packet.pts(),
+ encoded_packet.size()
+ );
+
+ // Set stream index for audio (stream 1)
+ encoded_packet.set_stream(1);
+
+ // Rescale timestamps to output timebase
+ encoded_packet.rescale_ts(
+ audio.encoder.time_base(),
self.output_ctx.stream(1).unwrap().time_base(),
);
- packet.write_interleaved(&mut self.output_ctx).unwrap();
+
+ encoded_packet
+ .write_interleaved(&mut self.output_ctx)
+ .unwrap();
}
}
}
pub fn finish(&mut self) {
+ println!("MP4Encoder: Finishing encoding");
+
+ // Flush video encoder
self.video.encoder.send_eof().unwrap();
self.process_video_packets();
- if let Some(audio) = self.audio.as_mut() {
+ // Flush audio encoder
+ if let Some(audio) = &mut self.audio {
+ println!("MP4Encoder: Flushing audio encoder");
+
+ // Process any remaining frames in the buffer
+ while let Some(buffered_frame) = audio.buffer.next_frame() {
+ let mut output = ffmpeg::util::frame::Audio::empty();
+ audio.resampler.run(&buffered_frame, &mut output).unwrap();
+
+ if let Some(pts) = buffered_frame.pts() {
+ output.set_pts(Some(pts));
+ }
+
+ audio.encoder.send_frame(&output).unwrap();
+
+ // Process packets after each frame
+ let mut encoded_packet = FFPacket::empty();
+ while audio.encoder.receive_packet(&mut encoded_packet).is_ok() {
+ encoded_packet.set_stream(1);
+ encoded_packet.rescale_ts(
+ audio.encoder.time_base(),
+ self.output_ctx.stream(1).unwrap().time_base(),
+ );
+ encoded_packet
+ .write_interleaved(&mut self.output_ctx)
+ .unwrap();
+ }
+ }
+
+ // Send EOF to audio encoder and process final packets
audio.encoder.send_eof().unwrap();
- self.process_audio_packets();
+ let mut encoded_packet = FFPacket::empty();
+ while audio.encoder.receive_packet(&mut encoded_packet).is_ok() {
+ encoded_packet.set_stream(1);
+ encoded_packet.rescale_ts(
+ audio.encoder.time_base(),
+ self.output_ctx.stream(1).unwrap().time_base(),
+ );
+ encoded_packet
+ .write_interleaved(&mut self.output_ctx)
+ .unwrap();
+ }
}
+ println!("MP4Encoder: Writing trailer");
self.output_ctx.write_trailer().unwrap();
}
}
diff --git a/crates/media/src/pipeline/audio_buffer.rs b/crates/media/src/pipeline/audio_buffer.rs
index 54d65f8c4..d698a16f4 100644
--- a/crates/media/src/pipeline/audio_buffer.rs
+++ b/crates/media/src/pipeline/audio_buffer.rs
@@ -4,6 +4,7 @@ use ffmpeg::encoder;
pub use ffmpeg::util::frame::Audio as FFAudio;
use crate::data::{AudioInfo, PlanarData};
+use cap_project::TimelineConfiguration;
#[derive(Debug)]
pub struct AudioBuffer {
@@ -35,14 +36,10 @@ impl AudioBuffer {
}
pub fn consume(&mut self, frame: FFAudio) {
- // TODO: Set PTS from frame with ffmpeg::sys::av_rescale_q??
- // if let Some(pts) = frame.pts() {
- // self.current_pts = pts;
- // }
+ if let Some(pts) = frame.pts() {
+ self.current_pts = pts;
+ }
for channel in 0..self.config.channels {
- // if self.current_pts == 0 {
- // println!("Data in channel {channel}: {:?}", frame.data(channel));
- // }
self.data[channel].extend(frame.plane_data(channel));
}
}
@@ -67,7 +64,33 @@ impl AudioBuffer {
}
}
- self.current_pts += i64::try_from(frame_size / self.config.sample_size()).unwrap();
+ self.current_pts += i64::try_from(self.frame_size).unwrap();
Some(frame)
}
+
+ pub fn next_frame_data(
+ &mut self,
+ samples: usize,
+ timeline: Option<&TimelineConfiguration>,
+ ) -> Option<(f64, Vec<u8>)> {
+ if self.is_empty() {
+ return None;
+ }
+
+ let frame_size = samples * self.config.sample_size();
+
+ if self.len() < frame_size {
+ return None;
+ }
+
+ let mut frame_data = Vec::with_capacity(frame_size * self.config.channels);
+ for channel in 0..self.config.channels {
+ frame_data.extend(self.data[channel].drain(0..frame_size));
+ }
+
+ let current_time = self.current_pts as f64 / f64::from(self.config.sample_rate);
+ self.current_pts += i64::try_from(samples).unwrap();
+
+ Some((current_time, frame_data))
+ }
}
diff --git a/crates/rendering/src/lib.rs b/crates/rendering/src/lib.rs
index 06bd5575d..9124f11e0 100644
--- a/crates/rendering/src/lib.rs
+++ b/crates/rendering/src/lib.rs
@@ -211,16 +211,6 @@ pub async fn render_video_to_channel(
duration, total_frames
);
- // Send initial frame to communicate total frames
- let initial_frame = RenderedFrame {
- data: vec![],
- width: 0,
- height: 0,
- padded_bytes_per_row: 0,
- total_frames: Some(total_frames),
- };
- sender.send(initial_frame).await?;
-
let mut frame_number = 0;
let background = Background::from(project.background.source.clone());
@@ -233,99 +223,27 @@ pub async fn render_video_to_channel(
println!("Processing frame {frame_number}/{total_frames}");
let (time, segment_i) = if let Some(timeline) = &project.timeline {
- println!("Getting time from timeline for frame {}", frame_number);
match timeline.get_recording_time(frame_number as f64 / 30_f64) {
- Some(value) => {
- println!(
- "Timeline returned time: {}, segment: {:?}",
- value.0, value.1
- );
- value
- }
- None => {
- println!(
- "Timeline returned None for frame {} (time: {})",
- frame_number,
- frame_number as f64 / 30_f64
- );
- println!(
- "Timeline segments: {:?}",
- timeline
- .segments
- .iter()
- .map(|s| (s.start, s.end))
- .collect::<Vec<_>>()
- );
- break;
- }
+ Some(value) => (value.0, value.1),
+ None => (frame_number as f64 / 30_f64, Some(0u32)),
}
} else {
- let time = frame_number as f64 / 30_f64;
- println!("No timeline, using direct time calculation: {}", time);
- (time, None)
+ (frame_number as f64 / 30_f64, Some(0u32))
};
- let segment_index = segment_i.unwrap_or(0) as usize;
- println!("Using segment {} for frame {}", segment_index, frame_number);
- let segment = &segments[segment_index];
- let uniforms = ProjectUniforms::new(&constants, &project, time as f32);
-
- println!("Getting frames for time: {} (frame {})", time, frame_number);
- // Get frames or use last valid frames if past duration
- let (screen_frame, camera_frame) =
- match segment.decoders.get_frames((time * 30.0) as u32).await {
- Some((screen, camera)) => {
- println!(
- "Successfully got frames for time {} (frame {})",
- time, frame_number
- );
- (screen, camera)
- }
- None => {
- println!(
- "No frames from decoder at time {} (frame {}), using last valid frames",
- time, frame_number
- );
- // Get the last valid frame from each decoder
- let screen = segment
- .decoders
- .screen
- .get_frame((time * 30.0) as u32)
- .await
- .unwrap_or_else(|| {
- println!("Using empty frame for screen");
- Arc::new(vec![
- 0;
- (constants.options.screen_size.x
- * constants.options.screen_size.y
- * 4) as usize
- ])
- });
-
- let camera = match &segment.decoders.camera {
- Some(camera_decoder) => {
- println!("Getting camera frame at time {}", time);
- Some(
- camera_decoder
- .get_frame((time * 30.0) as u32)
- .await
- .unwrap_or_else(|| {
- println!("Using empty frame for camera");
- Arc::new(match constants.options.camera_size {
- Some(size) => vec![0; (size.x * size.y * 4) as usize],
- None => vec![0; 0],
- })
- }),
- )
- }
- None => None,
- };
+ let segment = &segments[segment_i.unwrap() as usize];
+ let frame_time = frame_number;
+ let Some((screen_frame, camera_frame)) = segment.decoders.get_frames(frame_time).await
+ else {
+ println!(
+ "No frames available for time {} (frame {})",
+ time, frame_time
+ );
+ break;
+ };
- (screen, camera)
- }
- };
+ let uniforms = ProjectUniforms::new(&constants, &project, time as f32);
- println!("Producing frame {frame_number}");
let frame = produce_frame(
&constants,
&screen_frame,
@@ -337,20 +255,21 @@ pub async fn render_video_to_channel(
)
.await?;
- println!("Sending frame {frame_number}");
- if let Err(e) = sender.send(frame).await {
- println!("Failed to send frame: {e}");
- break;
+ if frame.width == 0 || frame.height == 0 {
+ println!("Skipping frame with zero dimensions");
+ continue;
}
+ println!(
+ "Rendering: Sending frame {} (size: {}x{}, time: {}, segment: {})",
+ frame_number,
+ frame.width,
+ frame.height,
+ time,
+ segment_i.unwrap()
+ );
+ sender.send(frame).await?;
frame_number += 1;
- if frame_number % 60 == 0 {
- let elapsed = start_time.elapsed();
- println!(
- "Rendered {frame_number}/{total_frames} frames in {:?} seconds",
- elapsed.as_secs_f32()
- );
- }
}
println!("Render loop exited at frame {frame_number}/{total_frames}");