Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
mux mp4 without ffmpeg cli
Brendan Allanbd4e9a271b7c
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex 4f27000c1..92794580b 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -499,7 +499,7 @@ async fn create_screenshot(decoder.format(),decoder.width(),decoder.height(),- ffmpeg::format::Pixel::RGB24,+ ffmpeg::format::Pixel::YUV420P,size.map_or(decoder.width(), |s| s.0),size.map_or(decoder.height(), |s| s.1),ffmpeg::software::scaling::flag::Flags::BILINEAR,diff --git a/crates/export/src/lib.rs b/crates/export/src/lib.rsindex d555b748a..35ec5f894 100644--- a/crates/export/src/lib.rs+++ b/crates/export/src/lib.rs@@ -1,8 +1,12 @@use cap_editor::Segment;+use cap_media::data::{AudioInfo, RawVideoFormat, VideoInfo};+use cap_media::encoders::MP4Input;+use cap_media::MediaError;use image::{ImageBuffer, Rgba};use mp4::Mp4Reader;use std::path::Path;use std::{path::PathBuf, sync::Arc};+use tokio::sync::oneshot;use cap_media::feeds::AudioFrameBuffer;use cap_project::{ProjectConfiguration, RecordingMeta};@@ -13,7 +17,6 @@ use cap_rendering::{struct AudioRender {buffer: AudioFrameBuffer,- pipe_tx: tokio::sync::mpsc::Sender<Vec<u8>>,}const FPS: u32 = 30;@@ -31,6 +34,9 @@ pub enum ExportError {#[error("Rendering: {0}")]Rendering(#[from] cap_rendering::RenderingError),++ #[error("Media/{0}")]+ Media(#[from] cap_media::MediaError),}pub async fn export_video_to_file(@@ -78,30 +84,55 @@ pub async fn export_video_to_file(}).unzip();- let ffmpeg_handle = tokio::spawn({+ let (frame_tx, frame_rx) = std::sync::mpsc::sync_channel::<MP4Input>(4);+ let (done_tx, done_rx) = oneshot::channel();++ let audio_info = if audio_segments+ .get(0)+ .and_then(|d| d.as_ref().as_ref())+ .is_some()+ {+ Some(+ AudioInfo::new(+ cap_media::data::Sample::F32(cap_media::data::Type::Packed),+ 48000,+ 1,+ )+ .map_err(Into::<MediaError>::into)?,+ )+ } else {+ None+ };++ std::thread::spawn(move || {+ let mut encoder = cap_media::encoders::MP4Encoder::init(+ "output",+ VideoInfo::from_raw(RawVideoFormat::YUYV420, output_size.0, output_size.1, 30),+ audio_info,+ cap_media::encoders::Output::File(output_path.clone()),+ )+ .unwrap();++ while let Ok(frame) = frame_rx.recv() {+ println!("queueing frame");+ encoder.queue_video_frame(frame.video);+ if let Some(audio) = frame.audio {+ encoder.queue_audio_frame(audio);+ }+ }++ encoder.finish();++ done_tx.send(output_path).ok();+ });++ tokio::spawn({let project = project.clone();let project_path = project_path.clone();async move {println!("Starting FFmpeg output process...");- let mut ffmpeg = cap_ffmpeg_cli::FFmpeg::new();-- let audio_dir = tempfile::tempdir().unwrap();- let video_dir = tempfile::tempdir().unwrap();- let mut audio = if let Some(audio_data) =- audio_segments.get(0).and_then(|d| d.as_ref().as_ref())+ let mut audio = if let Some(_) = 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"));-- 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(audio_segments@@ -109,104 +140,73 @@ pub async fn export_video_to_file(.map(|s| s.as_ref().as_ref().unwrap().clone()).collect(),),- pipe_tx: tx,})} else {None};- let video_tx = {- let (tx, rx) = tokio::sync::mpsc::channel::<Vec<u8>>(30);-- let pipe_path =- cap_utils::create_channel_named_pipe(rx, video_dir.path().join("video.pipe"));-- ffmpeg.add_input(cap_ffmpeg_cli::FFmpegRawVideoInput {- width: output_size.0,- height: output_size.1,- fps: 30,- pix_fmt: "rgba",- input: pipe_path,- });-- tx- };-- ffmpeg- .command- .args(["-f", "mp4"])- .args(["-codec:v", "libx264", "-codec:a", "aac"])- .args(["-preset", "ultrafast"])- .args(["-pix_fmt", "yuv420p", "-tune", "zerolatency"])- .arg("-y")- .arg(&output_path);-- let mut ffmpeg_process = ffmpeg.start();-let mut frame_count = 0;let mut first_frame = None;- 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())- ))- }- }- }?;+ while let Some(frame) = rx_image_data.recv().await {+ on_progress(frame_count);++ if frame_count == 0 {+ first_frame = Some(frame.clone());+ }++ let audio_frame = if let Some(audio) = &mut audio {+ if frame_count == 0 {+ audio.buffer.set_playhead(0., project.timeline());}- frame = rx_image_data.recv() => {- match frame {- Some(frame) => {- 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;- }- }++ 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())+ {+ // 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,+ );+ frame.set_pts(Some(1_000_000 / 30 * (frame_count as i64)));+ Some(frame)+ } else {+ None}- }+ } else {+ None+ };++ let mut video_frame =+ VideoInfo::from_raw(RawVideoFormat::Rgba, output_size.0, output_size.1, 30)+ .wrap_frame(&frame, 0);+ video_frame.set_pts(Some(frame_count as i64));++ frame_tx+ .send(MP4Input {+ audio: audio_frame,+ video: video_frame,+ })+ .ok();++ frame_count += 1;}- ffmpeg_process.stop().await;-// Save the first frame as a screenshot and thumbnailif let Some(frame_data) = first_frame {let width = output_size.0;@@ -248,7 +248,7 @@ pub async fn export_video_to_file(eprintln!("No frames were processed, cannot save screenshot or thumbnail");}- Ok::<_, ExportError>(output_path)+ Ok::<_, ExportError>(())}});@@ -263,49 +263,7 @@ pub async fn export_video_to_file().await?;- let output_path = ffmpeg_handle.await??;-- println!("Copying file to {:?}", project_path);- let result_path = project_path.join("output").join("result.mp4");- // Function to check if the file is a valid MP4- fn is_valid_mp4(path: &std::path::Path) -> bool {- if let Ok(file) = std::fs::File::open(path) {- let file_size = match file.metadata() {- Ok(metadata) => metadata.len(),- Err(_) => return false,- };- let reader = std::io::BufReader::new(file);- Mp4Reader::read_header(reader, file_size).is_ok()- } else {- false- }- }-- if output_path != result_path {- println!("Waiting for valid MP4 file at {:?}", output_path);- // Wait for the file to become a valid MP4- let mut attempts = 0;- while attempts < 10 {- // Wait for up to 60 seconds- if is_valid_mp4(&output_path) {- println!("Valid MP4 file detected after {} seconds", attempts);- match std::fs::copy(&output_path, &result_path) {- Ok(bytes) => {- println!("Successfully copied {} bytes to {:?}", bytes, result_path)- }- Err(e) => eprintln!("Failed to copy file: {:?}", e),- }- break;- }- println!("Attempt {}: File not yet valid, waiting...", attempts + 1);- std::thread::sleep(std::time::Duration::from_secs(1));- attempts += 1;- }-- if attempts == 10 {- eprintln!("Timeout: Failed to detect a valid MP4 file after 60 seconds");- }- }+ let output_path = done_rx.await.unwrap();Ok(output_path)}diff --git a/crates/ffmpeg-cli/src/lib.rs b/crates/ffmpeg-cli/src/lib.rsindex 6a8bc532e..6673e3589 100644--- a/crates/ffmpeg-cli/src/lib.rs+++ b/crates/ffmpeg-cli/src/lib.rs@@ -13,7 +13,7 @@ use tokio::{pub struct FFmpegProcess {pub ffmpeg_stdin: ChildStdin,- pub ffmpeg_stderr: ChildStderr,+ // pub ffmpeg_stderr: ChildStderr,cmd: Child,}@@ -28,7 +28,7 @@ impl FFmpegProcess {let mut cmd = command.stdin(Stdio::piped())- .stderr(Stdio::piped())+ // .stderr(Stdio::piped()).spawn().unwrap_or_else(|e| {println!("Failed to start FFmpeg: {}", e);@@ -41,14 +41,14 @@ impl FFmpegProcess {panic!("Failed to capture FFmpeg stdin");});- let ffmpeg_stderr = cmd.stderr.take().unwrap_or_else(|| {- println!("Failed to capture FFmpeg stderr");- panic!("Failed to capture FFmpeg stderr");- });+ // let ffmpeg_stderr = cmd.stderr.take().unwrap_or_else(|| {+ // println!("Failed to capture FFmpeg stderr");+ // panic!("Failed to capture FFmpeg stderr");+ // });Self {ffmpeg_stdin,- ffmpeg_stderr,+ // ffmpeg_stderr,cmd,}}@@ -69,7 +69,7 @@ impl FFmpegProcess {pub async fn read_stderr(&mut self) -> std::io::Result<String> {let mut err = String::new();- self.ffmpeg_stderr.read_to_string(&mut err).await?;+ // self.ffmpeg_stderr.read_to_string(&mut err).await?;Ok(err)}diff --git a/crates/gpu-converters/src/rgba_uyvy/shader.wgsl b/crates/gpu-converters/src/rgba_uyvy/shader.wgslnew file mode 100644index 000000000..dbdb7000c--- /dev/null+++ b/crates/gpu-converters/src/rgba_uyvy/shader.wgsl@@ -0,0 +1,33 @@+@group(0) @binding(0)+var rgba_input: texture_2d<f32>;++@group(0) @binding(1)+var uyvy_output: texture_storage_2d<rgba8unorm, write>;++@compute+@workgroup_size(8, 8)+fn main(@builtin(global_invocation_id) global_id: vec3<u32>) {+ let coords = global_id.xy;++ // Get two adjacent RGBA pixels+ let input_coords = coords * vec2<u32>(2, 1);+ let rgba1 = textureLoad(rgba_input, input_coords, 0);+ let rgba2 = textureLoad(rgba_input, input_coords + vec2<u32>(1, 0), 0);++ // Convert RGB to YUV for first pixel+ let y1 = 0.299 * rgba1.r + 0.587 * rgba1.g + 0.114 * rgba1.b;+ let u1 = -0.147 * rgba1.r - 0.289 * rgba1.g + 0.436 * rgba1.b + 0.5;+ let v1 = 0.615 * rgba1.r - 0.515 * rgba1.g - 0.100 * rgba1.b + 0.5;++ // Convert RGB to YUV for second pixel+ let y2 = 0.299 * rgba2.r + 0.587 * rgba2.g + 0.114 * rgba2.b;+ let u2 = -0.147 * rgba2.r - 0.289 * rgba2.g + 0.436 * rgba2.b + 0.5;+ let v2 = 0.615 * rgba2.r - 0.515 * rgba2.g - 0.100 * rgba2.b + 0.5;++ // Average the U and V values+ let u = (u1 + u2) * 0.5;+ let v = (v1 + v2) * 0.5;++ // Store as UYVY+ textureStore(uyvy_output, coords, vec4<f32>(u, y1, v, y2));+}diff --git a/crates/media/src/data.rs b/crates/media/src/data.rsindex 1c807429c..b87203a08 100644--- a/crates/media/src/data.rs+++ b/crates/media/src/data.rs@@ -177,6 +177,13 @@ impl AudioInfo {frame.set_pts(Some(timestamp));frame.set_rate(self.sample_rate);+ // dbg!(+ // samples,+ // sample_size,+ // frame.plane::<f64>(0).len(),+ // data.len()+ // );+match self.channels {0 => unreachable!(),1 => frame.plane_data_mut(0)[0..data.len()].copy_from_slice(data),diff --git a/crates/media/src/encoders/mod.rs b/crates/media/src/encoders/mod.rsindex 27d9ba0cd..b47d29dbe 100644--- a/crates/media/src/encoders/mod.rs+++ b/crates/media/src/encoders/mod.rs@@ -4,11 +4,13 @@ mod h264;#[cfg(target_os = "macos")]mod h264_avassetwriter;mod mp3;+mod mp4;pub use h264::*;#[cfg(target_os = "macos")]pub use h264_avassetwriter::*;pub use mp3::*;+pub use mp4::*;pub enum Output {File(PathBuf),diff --git a/crates/media/src/encoders/mp3.rs b/crates/media/src/encoders/mp3.rsindex 7ac4036ac..a7d0cefe8 100644--- a/crates/media/src/encoders/mp3.rs+++ b/crates/media/src/encoders/mp3.rs@@ -7,7 +7,7 @@ use std::collections::VecDeque;use crate::{data::{AudioInfo, FFAudio, FFPacket, FFRational, PlanarData},- pipeline::task::PipelineSinkTask,+ pipeline::{audio_buffer::AudioBuffer, task::PipelineSinkTask},MediaError,};@@ -119,70 +119,3 @@ impl PipelineSinkTask for MP3Encoder {println!("Shutting down {} audio encoding thread", self.tag);}}--#[derive(Debug)]-struct AudioBuffer {- current_pts: i64,- data: Vec<VecDeque<u8>>,- frame_size: usize,- config: AudioInfo,-}--impl AudioBuffer {- fn new(config: AudioInfo, encoder: &encoder::Audio) -> Self {- let sample_size = config.sample_size();- let frame_buffer_size = usize::try_from(config.buffer_size).unwrap() * sample_size;-- Self {- current_pts: 0,- data: vec![VecDeque::with_capacity(frame_buffer_size); config.channels],- frame_size: encoder.frame_size().try_into().unwrap(),- config,- }- }-- fn is_empty(&self) -> bool {- self.data[0].is_empty()- }-- fn len(&self) -> usize {- self.data[0].len()- }-- 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;- // }- 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));- }- }-- fn next_frame(&mut self) -> Option<FFAudio> {- if self.is_empty() {- return None;- }-- let frame_size = self.frame_size * self.config.sample_size();-- if self.len() < frame_size {- return None;- }-- let mut frame = self.config.empty_frame(self.frame_size);- frame.set_pts(Some(self.current_pts));-- for channel in 0..self.config.channels {- for (index, byte) in self.data[channel].drain(0..frame_size).enumerate() {- frame.plane_data_mut(channel)[index] = byte;- }- }-- self.current_pts += i64::try_from(frame_size / self.config.sample_size()).unwrap();- Some(frame)- }-}diff --git a/crates/media/src/encoders/mp4.rs b/crates/media/src/encoders/mp4.rsnew file mode 100644index 000000000..c47a5c030--- /dev/null+++ b/crates/media/src/encoders/mp4.rs@@ -0,0 +1,280 @@+use crate::{+ data::{AudioInfo, FFAudio, FFPacket, FFRational, FFVideo, PlanarData, VideoInfo},+ pipeline::{audio_buffer::AudioBuffer, task::PipelineSinkTask},+ MediaError,+};+use ffmpeg::{+ codec::{codec::Codec, context, encoder},+ format::{self},+ threading::Config,+ Dictionary,+};++use super::Output;++pub struct MP4Encoder {+ tag: &'static str,+ video_encoder: encoder::Video,+ audio_encoder: Option<encoder::Audio>,+ output_ctx: format::context::Output,+ audio_buffer: Option<AudioBuffer>,+ last_video_pts: Option<i64>,+ video_config: VideoInfo,+ audio_config: Option<AudioInfo>,+}++impl MP4Encoder {+ const AUDIO_BITRATE: usize = 128 * 1000; // 128k++ pub fn init(+ tag: &'static str,+ video_config: VideoInfo,+ audio_config: Option<AudioInfo>,+ output: Output,+ ) -> Result<Self, MediaError> {+ dbg!(&audio_config, video_config);++ let Output::File(destination) = output;+ let mut output_ctx = format::output(&destination)?;++ // Setup video encoder+ let (video_codec, video_options) = get_video_codec_and_options(&video_config)?;+ let mut video_ctx = context::Context::new_with_codec(video_codec);+ video_ctx.set_threading(Config::count(4));+ let mut video_enc = video_ctx.encoder().video()?;++ 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_frame_rate(Some(video_config.frame_rate));++ dbg!(video_enc.time_base());++ if video_codec.name() == "h264_videotoolbox" {+ video_enc.set_bit_rate(1_200_000);+ video_enc.set_max_bit_rate(120_000);+ } else {+ video_enc.set_bit_rate(8_000_000);+ video_enc.set_max_bit_rate(8_000_000);+ }++ let video_encoder = video_enc.open_with(video_options)?;++ let audio = if let Some(audio_config) = audio_config {+ // Setup audio encoder+ let audio_codec = encoder::find(ffmpeg::codec::Id::AAC)+ .ok_or(MediaError::TaskLaunch("Could not find AAC codec".into()))?;+ let mut audio_ctx = context::Context::new_with_codec(audio_codec);+ audio_ctx.set_threading(Config::count(4));+ let mut audio_enc = audio_ctx.encoder().audio()?;++ if !audio_codec+ .audio()+ .unwrap()+ .rates()+ .into_iter()+ .flatten()+ .any(|r| r == audio_config.rate())+ {+ return Err(MediaError::TaskLaunch(format!(+ "AAC Codec does not support sample rate {}",+ audio_config.rate()+ )));+ }++ audio_enc.set_bit_rate(Self::AUDIO_BITRATE);+ audio_enc.set_rate(audio_config.rate());+ audio_enc.set_format(audio_config.sample_format);+ audio_enc.set_channel_layout(audio_config.channel_layout());+ audio_enc.set_time_base(audio_config.time_base);++ Some((audio_enc.open()?, audio_codec, audio_config))+ } else {+ None+ };++ // 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_parameters(&video_encoder);++ dbg!(video_stream.time_base());++ let (audio_encoder, audio_buffer) =+ if let Some((audio_encoder, audio_codec, audio_config)) = audio {+ let mut audio_stream = output_ctx.add_stream(audio_codec)?;+ audio_stream.set_time_base(FFRational(1, audio_config.rate()));+ audio_stream.set_parameters(&audio_encoder);++ let audio_buffer = AudioBuffer::new(audio_config, &audio_encoder);++ Some((audio_encoder, audio_buffer))+ } else {+ None+ }+ .unzip();++ output_ctx.write_header()?;++ Ok(Self {+ tag,+ video_encoder,+ audio_encoder,+ output_ctx,+ audio_buffer,+ last_video_pts: None,+ video_config,+ audio_config,+ })+ }++ pub fn queue_video_frame(&mut self, frame: FFVideo) {+ let mut scaler = ffmpeg::software::converter(+ (frame.width(), frame.height()),+ frame.format(),+ self.video_config.pixel_format,+ )+ .unwrap();++ let mut output = FFVideo::empty();++ scaler.run(&frame, &mut output).unwrap();++ output.set_pts(frame.pts());++ self.video_encoder.send_frame(&output).unwrap();+ self.process_video_packets();+ }++ pub fn queue_audio_frame(&mut self, frame: FFAudio) {+ if self.audio_buffer.is_none() || self.audio_encoder.is_none() {+ return;+ }++ self.audio_buffer.as_mut().unwrap().consume(frame);+ while let Some(buffered_frame) = self.audio_buffer.as_mut().unwrap().next_frame() {+ self.audio_encoder+ .as_mut()+ .unwrap()+ .send_frame(&buffered_frame)+ .unwrap();+ self.process_audio_packets();+ }+ }++ fn process_video_packets(&mut self) {+ let mut encoded_packet = FFPacket::empty();++ while self+ .video_encoder+ .receive_packet(&mut encoded_packet)+ .is_ok()+ {+ 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(),+ );+ encoded_packet+ .write_interleaved(&mut self.output_ctx)+ .unwrap();+ }+ }++ fn process_audio_packets(&mut self) {+ let mut encoded_packet = FFPacket::empty();++ if let Some(audio_encoder) = self.audio_encoder.as_mut() {+ while audio_encoder.receive_packet(&mut encoded_packet).is_ok() {+ encoded_packet.set_stream(1); // Audio is stream 1+ encoded_packet.set_time_base(self.output_ctx.stream(1).unwrap().time_base());+ encoded_packet.rescale_ts(+ encoded_packet.time_base(),+ self.output_ctx.stream(1).unwrap().time_base(),+ );+ encoded_packet+ .write_interleaved(&mut self.output_ctx)+ .unwrap();+ }+ }+ }++ pub fn finish(&mut self) {+ self.video_encoder.send_eof().unwrap();+ self.process_video_packets();++ if let Some(audio_encoder) = self.audio_encoder.as_mut() {+ audio_encoder.send_eof().unwrap();+ self.process_audio_packets();+ }++ self.output_ctx.write_trailer().unwrap();+ }+}++// Implementation of AudioBuffer and get_video_codec_and_options remains the same+// ... [Previous AudioBuffer implementation]+// ... [Previous get_video_codec_and_options implementation]++// You'll need to implement a new task trait for handling both audio and video inputs+pub struct MP4Input {+ pub video: FFVideo,+ pub audio: Option<FFAudio>,+}++impl PipelineSinkTask for MP4Encoder {+ type Input = MP4Input;++ fn run(+ &mut self,+ ready_signal: crate::pipeline::task::PipelineReadySignal,+ input: flume::Receiver<Self::Input>,+ ) {+ println!("Starting {} MP4 encoding thread", self.tag);+ ready_signal.send(Ok(())).unwrap();++ while let Ok(frame) = input.recv() {+ self.queue_video_frame(frame.video);+ if let Some(audio) = frame.audio {+ self.queue_audio_frame(audio);+ }+ }++ println!("Received last {} frame. Finishing up encoding.", self.tag);+ self.finish();++ println!("Shutting down {} MP4 encoding thread", self.tag);+ }+}++fn get_video_codec_and_options(config: &VideoInfo) -> Result<(Codec, Dictionary), MediaError> {+ let encoder_name = {+ if cfg!(target_os = "macos") {+ "libx264"+ // looks terrible rn :(+ // "h264_videotoolbox"+ } else {+ "libx264"+ }+ };+ if let Some(codec) = encoder::find_by_name(encoder_name) {+ let mut options = Dictionary::new();++ if encoder_name == "h264_videotoolbox" {+ // options.set("constant_bit_rate", "true");+ options.set("realtime", "true");+ } else {+ let keyframe_interval_secs = 2;+ let keyframe_interval = keyframe_interval_secs * config.frame_rate.numerator();+ let keyframe_interval_str = keyframe_interval.to_string();++ options.set("preset", "ultrafast");+ options.set("tune", "zerolatency");+ }++ return Ok((codec, options));+ }++ Err(MediaError::MissingCodec("H264 video"))+}diff --git a/crates/media/src/pipeline/audio_buffer.rs b/crates/media/src/pipeline/audio_buffer.rsnew file mode 100644index 000000000..54d65f8c4--- /dev/null+++ b/crates/media/src/pipeline/audio_buffer.rs@@ -0,0 +1,73 @@+use std::collections::VecDeque;++use ffmpeg::encoder;+pub use ffmpeg::util::frame::Audio as FFAudio;++use crate::data::{AudioInfo, PlanarData};++#[derive(Debug)]+pub struct AudioBuffer {+ current_pts: i64,+ data: Vec<VecDeque<u8>>,+ frame_size: usize,+ config: AudioInfo,+}++impl AudioBuffer {+ pub fn new(config: AudioInfo, encoder: &encoder::Audio) -> Self {+ let sample_size = config.sample_size();+ let frame_buffer_size = usize::try_from(config.buffer_size).unwrap() * sample_size;++ Self {+ current_pts: 0,+ data: vec![VecDeque::with_capacity(frame_buffer_size); config.channels],+ frame_size: encoder.frame_size().try_into().unwrap(),+ config,+ }+ }++ fn is_empty(&self) -> bool {+ self.data[0].is_empty()+ }++ fn len(&self) -> usize {+ self.data[0].len()+ }++ 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;+ // }+ 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));+ }+ }++ pub fn next_frame(&mut self) -> Option<FFAudio> {+ if self.is_empty() {+ return None;+ }++ let frame_size = self.frame_size * self.config.sample_size();++ if self.len() < frame_size {+ return None;+ }++ let mut frame = self.config.empty_frame(self.frame_size);+ frame.set_pts(Some(self.current_pts));++ for channel in 0..self.config.channels {+ for (index, byte) in self.data[channel].drain(0..frame_size).enumerate() {+ frame.plane_data_mut(channel)[index] = byte;+ }+ }++ self.current_pts += i64::try_from(frame_size / self.config.sample_size()).unwrap();+ Some(frame)+ }+}diff --git a/crates/media/src/pipeline/mod.rs b/crates/media/src/pipeline/mod.rsindex 685aa6af1..d3a94da58 100644--- a/crates/media/src/pipeline/mod.rs+++ b/crates/media/src/pipeline/mod.rs@@ -1,6 +1,7 @@use indexmap::IndexMap;use std::thread::JoinHandle;+pub mod audio_buffer;pub mod builder;pub mod clock;pub mod control;