From 86d5c151fe88efa0a6be8e8138d927e006c5a9de Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 9 Aug 2026 18:42:17 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(engine):=20export=20=E2=80=94?= =?UTF-8?q?=20edit=20list=20to=20mp4,=20HW=20encode=20with=20SW=20fallback?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Worker thread per export: decodes each clip straight to I420 (never through DecodeSession, which only speaks BGRA), feeds one encoder chosen once -- VA-API plugin unless VE_SW_ENC=1 or the plugin is unavailable, rusty_h264 Fast/CBR otherwise -- and muxes the access units as they come. Audio is copied packet for packet, so the file has to be opened before the first video sample is written. Cancel and every error path delete the partial file; progress is a permille atomic a render loop can read without a lock. mux: the movie timescale moves to 90 kHz. mp4 0.14 converts each sample duration into the movie timescale with its own integer division, so 1 kHz lost 0.33 ms per frame and made a 4.000 s export announce 3.960 s. --- crates/engine/src/export.rs | 416 ++++++++++++++++++++++++++++++++++ crates/engine/src/lib.rs | 4 +- crates/engine/src/mux.rs | 17 +- crates/engine/src/playback.rs | 11 + crates/engine/tests/export.rs | 324 ++++++++++++++++++++++++++ 5 files changed, 770 insertions(+), 2 deletions(-) create mode 100644 crates/engine/src/export.rs create mode 100644 crates/engine/tests/export.rs diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs new file mode 100644 index 0000000..24fa122 --- /dev/null +++ b/crates/engine/src/export.rs @@ -0,0 +1,416 @@ +//! Export: the edit list rendered back out as one mp4. +//! +//! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it +//! is impossible — while audio is copied packet for packet, because there is no +//! pure-Rust AAC encoder to re-encode with. The worker owns everything: the +//! caller gets an [`ExportHandle`] and polls it from its render loop. +//! +//! Nothing partial survives a failure: cancel and every error path delete the +//! output file. A killed *process* still leaves it — only in-process cleanup is +//! promised. + +use std::path::Path; +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; +use std::sync::{Arc, Mutex}; +use std::thread; + +use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame}; + +use crate::audio::AudioSession; +use crate::demux::{Demuxer, VideoMeta}; +use crate::hw::{HwEncoder, HwSession}; +use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; +use crate::project::Project; + +/// Progress is reported in permille: an atomic integer the render loop can read +/// without a lock, fine enough for any progress bar. +const PROGRESS_SCALE: u32 = 1_000; + +/// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands +/// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%. +const BITS_PER_PIXEL: f64 = 0.1; +const MIN_BITRATE: u64 = 1_000_000; +const MAX_BITRATE: u64 = 20_000_000; + +struct Shared { + progress: AtomicU32, + cancel: AtomicBool, + finished: AtomicBool, + outcome: Mutex>>, +} + +/// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per +/// rendered frame and take the [`result`](ExportHandle::result) when it flips; +/// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel) +/// does. +pub struct ExportHandle { + shared: Arc, +} + +impl ExportHandle { + /// Fraction of the timeline written, `0.0..=1.0`. + pub fn progress(&self) -> f32 { + self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32 + } + + /// Asks the worker to stop at its next frame and delete the partial file. + /// The outcome then reports the cancellation as an error. + pub fn cancel(&self) { + self.shared.cancel.store(true, Ordering::Relaxed); + } + + pub fn is_finished(&self) -> bool { + self.shared.finished.load(Ordering::Acquire) + } + + /// The outcome, once — taken out of the handle, so a caller that already + /// reported it sees `None` afterwards. `None` while the export is running. + pub fn result(&self) -> Option> { + self.shared.outcome.lock().unwrap().take() + } +} + +/// Starts the worker. Failures are reported through the handle rather than +/// returned, so a caller has exactly one place to look. +pub(crate) fn start(source: &Path, project: Project, meta: VideoMeta, out: &Path) -> ExportHandle { + let shared = Arc::new(Shared { + progress: AtomicU32::new(0), + cancel: AtomicBool::new(false), + finished: AtomicBool::new(false), + outcome: Mutex::new(None), + }); + let worker = Arc::clone(&shared); + let source = source.to_path_buf(); + let out = out.to_path_buf(); + let spawned = thread::Builder::new().name("export".into()).spawn(move || { + let result = run(&source, &project, &meta, &out, &worker); + if result.is_err() { + // The muxer -- and with it the file handle -- died with `run`. + let _ = std::fs::remove_file(&out); + } + settle(&worker, result); + }); + if let Err(e) = spawned { + settle(&shared, Err(e.into())); + } + ExportHandle { shared } +} + +fn settle(shared: &Shared, result: crate::Result<()>) { + *shared.outcome.lock().unwrap() = Some(result); + // Published last: a caller that sees the flag is guaranteed the outcome. + shared.finished.store(true, Ordering::Release); +} + +fn run( + source: &Path, + project: &Project, + meta: &VideoMeta, + out: &Path, + shared: &Shared, +) -> crate::Result<()> { + let total = project.timeline_frames(); + // Audio first: a track has to be declared when the muxer is created, which + // happens as soon as the first coded picture arrives. + // + // ponytail: this holds the whole exported AAC track in memory (~3 kB per + // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming + // `copy_segments` that yields packets instead of collecting them. + let audio = AudioSession::copy_segments(source, &project.segments_from(0, meta.frame_rate))?; + let audio_params = audio.as_ref().map(|(track, _)| AudioParams { + freq_index: track.freq_index, + chan_conf: track.chan_conf, + }); + + let mut encoder = Enc::open(meta)?; + let mut muxer = None; + let mut done = 0u32; + for clip in project.clips() { + // Every clip reopens the file at its own in point; the encoder is *not* + // reopened, so the export is one continuous stream whose GOP boundaries + // need not line up with the cuts. + let mut pictures = ClipDecoder::open(source, clip.in_frame)?; + for _ in 0..clip.len() { + if shared.cancel.load(Ordering::Relaxed) { + return Err("export cancelled".into()); + } + let Some((y, u, v, width, height)) = pictures.next()? else { + break; // source ran out early; the clip list outlives the file + }; + if let Some(au) = encoder.encode(y, u, v, width, height)? { + write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?; + } + done += 1; + shared + .progress + .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed); + } + } + while let Some(au) = encoder.drain()? { + write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?; + } + + let Some(mut muxer) = muxer else { + return Err("export produced no coded pictures".into()); + }; + if let Some((_, packets)) = audio { + for packet in packets { + muxer.write_audio_packet(&packet.bytes)?; + } + } + muxer.finish()?; + shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); + Ok(()) +} + +/// Writes one access unit, creating the file on the first one -- the parameter +/// sets for `avcC` only exist once the encoder has coded something. Units with +/// no coded slice are skipped: a software encoder may hand back an empty buffer +/// while it buffers, and the muxer rejects a sample that would carry no picture. +fn write_video( + muxer: &mut Option, + out: &Path, + meta: &VideoMeta, + audio: Option<&AudioParams>, + au: &[u8], +) -> crate::Result<()> { + if !crate::mux::has_coded_slice(au) { + return Ok(()); + } + let muxer = match muxer { + Some(muxer) => muxer, + none => { + let (sps, pps) = crate::mux::parameter_sets(au) + .ok_or("the first coded picture carries no SPS/PPS")?; + none.insert(Mp4Muxer::create( + out, + &VideoParams { + width: meta.width, + height: meta.height, + frame_rate: meta.frame_rate, + sps, + pps, + }, + audio, + )?) + } + }; + muxer.write_video_au(au) +} + +fn bitrate_for(meta: &VideoMeta) -> u64 { + let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL; + (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE) +} + +fn forced(var: &str) -> bool { + std::env::var_os(var).is_some_and(|v| v == "1") +} + +/// Hardware where it is available, software everywhere else -- chosen once for +/// the whole export, so the stream never changes encoder mid-file. +enum Enc { + Hw(HwEncoder), + Sw { + encoder: Encoder, + /// The last access unit; owned because `rusty_h264` hands back a `Vec` + /// while the plugin lends a slice, and the two have to look alike here. + au: Vec, + flushed: bool, + }, +} + +impl Enc { + fn open(meta: &VideoMeta) -> crate::Result { + let bitrate = bitrate_for(meta); + // The plugin wants an exact rational; a thousandth of a frame per second + // is finer than any container fps we can read back. + let fps_num = (meta.frame_rate * 1_000.0).round().max(1.0) as u32; + if !forced("VE_SW_ENC") + && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, 1_000, bitrate) + { + eprintln!("export encoder: hardware (VA-API plugin)"); + return Ok(Self::Hw(hw)); + } + eprintln!("export encoder: software (rusty_h264)"); + let mut cfg = EncoderConfig::new(meta.width as usize, meta.height as usize); + cfg.framerate = meta.frame_rate as f32; + cfg.bitrate = bitrate.min(u32::MAX as u64) as u32; + // Two seconds between key frames, and no B-frames on either path: the + // muxer times everything by duration alone, which reordering would break. + cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32; + cfg.bframes = 0; + // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same + // bitrate, so Fast is what a fallback should be. + cfg.preset = Preset::Fast; + let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?; + Ok(Self::Sw { + encoder, + au: Vec::new(), + flushed: false, + }) + } + + /// One picture in, at most one access unit out. + /// + /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer + /// when its lookahead is active, which would make this "one access unit" + /// a lie and every sample duration with it. It is inactive here because + /// lookahead needs a zero bitrate and this path is always CBR; a future + /// constant-QP mode has to split the buffer per access unit first. + fn encode( + &mut self, + y: &[u8], + u: &[u8], + v: &[u8], + width: u32, + height: u32, + ) -> crate::Result> { + match self { + Self::Hw(hw) => hw.encode(y, u, v, width, height, false), + Self::Sw { encoder, au, .. } => { + let frame = YuvFrame { + width: width as usize, + height: height as usize, + y: y.to_vec(), + u: u.to_vec(), + v: v.to_vec(), + }; + *au = encoder + .try_encode(&frame) + .map_err(|e| format!("software encode: {e}"))?; + Ok(Some(&au[..]).filter(|au| !au.is_empty())) + } + } + } + + /// End of stream; call until it returns `None`. + fn drain(&mut self) -> crate::Result> { + match self { + Self::Hw(hw) => hw.drain(), + Self::Sw { + encoder, + au, + flushed, + } => { + if *flushed { + return Ok(None); + } + *flushed = true; + *au = encoder + .try_flush() + .map_err(|e| format!("software encoder flush: {e}"))?; + Ok(Some(&au[..]).filter(|au| !au.is_empty())) + } + } + } +} + +/// I420 straight out of the decoder: the export never converts to BGRA and back, +/// which would cost two conversions and a generation of colour precision. +/// +/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`, +/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to +/// software: a hardware decode that fails after the first picture fails the +/// export, which then deletes the half-written file. +enum ClipDecoder { + Hw(HwSession), + Sw(SwDecoder), +} + +impl ClipDecoder { + fn open(path: &Path, start_frame: u32) -> crate::Result { + if !forced("VE_SW") + && let Some(hw) = HwSession::open_at(path, start_frame) + { + return Ok(Self::Hw(hw)); + } + Ok(Self::Sw(SwDecoder::open(path, start_frame)?)) + } + + /// The next picture as tightly packed I420, borrowed until the call after. + fn next(&mut self) -> crate::Result> { + match self { + Self::Hw(hw) => hw.next_frame(), + Self::Sw(sw) => { + if !sw.advance()? { + return Ok(None); + } + let frame = sw.frame.as_ref().expect("advance stored a picture"); + Ok(Some(( + &frame.y, + &frame.u, + &frame.v, + frame.width as u32, + frame.height as u32, + ))) + } + } + } +} + +struct SwDecoder { + demuxer: Demuxer, + decoder: Decoder, + /// Display index of the next picture the decoder will produce. + index: u32, + start: u32, + frame: Option, +} + +impl SwDecoder { + fn open(path: &Path, start_frame: u32) -> crate::Result { + let (_, mut demuxer) = Demuxer::open(path)?; + // Decoding restarts at a sync sample, so pictures between it and the in + // point are decoded (the target references them) and then dropped. + // Sample ids are 1-based, frame indices 0-based. + let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1)); + Ok(Self { + demuxer, + decoder: Decoder::new(), + index: sync - 1, + start: start_frame, + frame: None, + }) + } + + /// Decodes up to and including the next picture at or after the in point, + /// leaving it in `frame`. `false` at end of stream. + fn advance(&mut self) -> crate::Result { + loop { + let Some(au) = self.demuxer.next_access_unit()? else { + return Ok(false); + }; + let decoded = self + .decoder + .decode(&au) + .map_err(|e| format!("decode at picture {}: {e}", self.index))?; + let Some(yuv) = decoded else { continue }; + let wanted = self.index >= self.start; + self.index += 1; + if wanted { + self.frame = Some(yuv); + return Ok(true); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bitrate_clamps_at_both_ends() { + let meta = |width, height, frame_rate| VideoMeta { + width, + height, + frame_rate, + frame_count: 1, + }; + // 1280 * 720 * 30 * 0.1 + assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); + assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny"); + assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge"); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 83b4cc8..afdae27 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -6,15 +6,17 @@ pub mod clock; pub mod convert; pub mod decode; pub mod demux; +pub mod export; pub mod hw; pub mod mux; pub mod playback; pub mod project; -pub use audio::{AudioChunk, AudioMeta, AudioSession}; +pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioSession}; pub use clock::PlaybackClock; pub use decode::{DecodeSession, Frame}; pub use demux::VideoMeta; +pub use export::ExportHandle; pub use mux::{AudioParams, Mp4Muxer, VideoParams}; pub use playback::PlaybackSession; pub use project::{Clip, Project}; diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index 12e61a4..00ed8f1 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -13,7 +13,12 @@ use mp4::{ /// 90 kHz is the H.264 convention; frame durations round to well under a /// microsecond of error at every fps we care about. const VIDEO_TIMESCALE: u32 = 90_000; -const MOVIE_TIMESCALE: u32 = 1_000; +/// The same as the video's, deliberately: `mp4` converts every sample duration +/// into the movie timescale with an integer division of its own (track.rs:752), +/// so a coarser movie clock loses a fraction of a millisecond *per frame* -- +/// 1 kHz makes a 4.000 s export announce itself as 3.960 s. Equal timescales +/// make the video conversion exact. +const MOVIE_TIMESCALE: u32 = VIDEO_TIMESCALE; /// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the /// per-packet duration is this constant. const AAC_PACKET_SAMPLES: u32 = 1024; @@ -173,6 +178,16 @@ pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> { Some((sps, pps)) } +/// Whether the unit carries a coded picture (NAL types 1..=5). An encoder that +/// buffered instead of coding hands back an empty buffer, and one that emitted +/// only parameter sets has no sample to write -- both are for the caller to skip +/// rather than for [`Mp4Muxer::write_video_au`] to reject. +pub(crate) fn has_coded_slice(annex_b: &[u8]) -> bool { + split_annex_b(annex_b) + .iter() + .any(|nal| (1..=NAL_IDR).contains(&nal_type(nal))) +} + /// Exact inverse of `demux::append_annex_b`: 4-byte length prefixes (the only /// prefix size `mp4` writes, avc1.rs hardcodes `length_size_minus_one = 3`). /// Parameter sets, access unit delimiters and SEI are stripped — the first two diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index 6fd4929..b89a0d7 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -389,6 +389,17 @@ impl PlaybackSession { } } + /// Renders the edited timeline to `out` on a worker thread. The session is + /// untouched -- the export decodes the source file for itself -- but a + /// caller should still [`pause`](PlaybackSession::pause) first, because + /// playback and export otherwise fight over the same decoder hardware. + /// + /// Later edits do not reach a running export: it works from a snapshot of + /// the edit list taken here. + pub fn export_to(&self, out: &Path) -> crate::ExportHandle { + crate::export::start(&self.path, self.project.clone(), self.meta, out) + } + /// Moves the clock forward; the caller runs this once per rendered frame. /// Costs an atomic load, and once per session a mode switch. pub fn tick(&mut self) { diff --git a/crates/engine/tests/export.rs b/crates/engine/tests/export.rs new file mode 100644 index 0000000..f95fcb6 --- /dev/null +++ b/crates/engine/tests/export.rs @@ -0,0 +1,324 @@ +//! Export round trips: an edited timeline out to mp4 and straight back in +//! through our own demuxer and decoder. +//! +//! The software test is the default one and needs nothing installed. The +//! hardware twins need a built `libengine_hw.so` plus a VA-API driver with an +//! H.264 encode entrypoint, so they are `#[ignore]`d: +//! +//! ```text +//! cargo build -p engine -p engine-hw --release +//! LD_LIBRARY_PATH=target/release \ +//! cargo test -p engine --release --test export -- --ignored --nocapture --test-threads=1 +//! ``` +//! +//! Both env pins are process-wide, hence `--test-threads=1` for the ignored run. + +use std::fs::File; +use std::io::BufReader; +use std::path::{Path, PathBuf}; +use std::sync::Once; +use std::time::{Duration, Instant}; + +use engine::hw::HwEncoder; +use engine::mux::{Mp4Muxer, VideoParams, parameter_sets}; +use engine::{DecodeSession, ExportHandle, PlaybackSession}; + +const FPS: f64 = 30.0; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn out_path(name: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!("ve_export_{name}.mp4")); + let _ = std::fs::remove_file(&path); + path +} + +/// Pins both paths to software for the whole test binary, so the default suite +/// proves the fallback that every machine has. +fn pin_software() { + static PIN: Once = Once::new(); + PIN.call_once(|| unsafe { + std::env::set_var("VE_SW", "1"); + std::env::set_var("VE_SW_ENC", "1"); + }); +} + +/// Removes both pins, for the hardware twins. +fn pin_hardware() { + static PIN: Once = Once::new(); + PIN.call_once(|| unsafe { + std::env::remove_var("VE_SW"); + std::env::remove_var("VE_SW_ENC"); + }); +} + +/// `[0,30) + [60,150)` of the source: two cuts and a delete, so the export has +/// to seek, and the join is a real discontinuity rather than a formality. +fn edited(source: &Path) -> PlaybackSession { + let mut session = PlaybackSession::open(source).expect("open source"); + assert!(session.cut_at(30.0 / FPS), "cut at frame 30"); + assert!(session.cut_at(60.0 / FPS), "cut at frame 60"); + assert!(session.delete_clip(1), "drop the middle clip"); + assert_eq!(session.clip_spans().len(), 2); + session +} + +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < limit, + "export did not finish in {limit:?}" + ); + std::thread::sleep(Duration::from_millis(20)); + } + handle.result().expect("a finished export has an outcome") +} + +/// Every frame of `path`, BGRA, in timeline order. +fn decode_all(path: &Path) -> Vec> { + let (_, frames) = DecodeSession::open(path).expect("open export"); + frames.into_iter().map(|frame| frame.bgra).collect() +} + +/// One frame of `path` by absolute index. +fn frame_at(path: &Path, index: u32) -> Vec { + let (_, frames, _) = DecodeSession::open_at(path, index).expect("open source"); + frames.recv().expect("frame present").bgra +} + +fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { + assert_eq!(a.len(), b.len(), "frame sizes differ"); + a.iter() + .zip(b) + .map(|(x, y)| f64::from(x.abs_diff(*y))) + .sum::() + / a.len() as f64 +} + +/// The whole point of the slice: an edited timeline survives the trip out to +/// disk and back, frame for frame and picture for picture. +fn round_trip(name: &str, limit: Duration) { + let source = asset("test_baseline.mp4"); + let mut session = edited(&source); + session.pause(); + let out = out_path(name); + + let started = Instant::now(); + let handle = session.export_to(&out); + wait(&handle, limit).expect("export"); + let spent = started.elapsed(); + println!( + "{name}: 120 frames in {:.2} s = {:.2} ms/frame", + spent.as_secs_f64(), + spent.as_secs_f64() * 1000.0 / 120.0 + ); + assert_eq!(handle.progress(), 1.0, "finished at full progress"); + + let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen export"); + assert_eq!(meta.frame_count, 120, "timeline frames written"); + assert_eq!((meta.width, meta.height), (1280, 720)); + assert_eq!(meta.frame_rate.round(), FPS); + + let file = File::open(&out).unwrap(); + let size = file.metadata().unwrap().len(); + let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); + let duration = reader.duration().as_secs_f64(); + assert!( + (duration - 120.0 / FPS).abs() <= 1.0 / FPS, + "duration {duration} s is more than a frame off 4.0 s" + ); + + let frames = decode_all(&out); + assert_eq!(frames.len(), 120, "every written frame decodes back"); + + // Timeline -> source: [0,30) maps to itself, [30,120) to [60,150). + for (timeline, source_frame) in [(0u32, 0u32), (59, 89), (119, 149)] { + let diff = mean_abs_diff(&frames[timeline as usize], &frame_at(&source, source_frame)); + println!("timeline {timeline} vs source {source_frame}: mean abs diff {diff:.2}"); + assert!( + diff < 6.0, + "timeline frame {timeline} drifted by {diff:.2} from source frame {source_frame}" + ); + } + std::fs::remove_file(&out).unwrap(); +} + +#[test] +fn exports_an_edited_timeline_in_software() { + pin_software(); + round_trip("sw", Duration::from_secs(120)); +} + +/// Same trip through the plugin, and the only place the end-to-end hardware +/// cost (decode + encode + mux) is measured. +#[test] +#[ignore] +fn exports_an_edited_timeline_in_hardware() { + pin_hardware(); + round_trip("hw", Duration::from_secs(60)); +} + +/// A cancelled export leaves nothing behind -- the half-written file is the +/// thing a user would otherwise try to play. +#[test] +fn cancelling_leaves_no_file() { + pin_software(); + let mut session = edited(&asset("test_baseline.mp4")); + session.pause(); + let out = out_path("cancel"); + + let handle = session.export_to(&out); + let started = Instant::now(); + while handle.progress() < 0.1 { + assert!( + started.elapsed() < Duration::from_secs(60), + "export never got going" + ); + assert!( + !handle.is_finished(), + "export finished before it was cancelled" + ); + std::thread::sleep(Duration::from_millis(10)); + } + handle.cancel(); + let result = wait(&handle, Duration::from_secs(5)); + assert!(result.is_err(), "a cancelled export is an error"); + assert!(!out.exists(), "no partial file survives a cancel"); +} + +/// Audio: the copied AAC packets have to land in the export as a track a reader +/// can open again, at a length the video agrees with. +#[test] +#[ignore] +fn exports_audio_alongside_the_video() { + pin_hardware(); + let source = asset("test_av.mp4"); + let mut session = PlaybackSession::open(&source).expect("open source"); + // One cut: the timeline is unchanged but the audio copy now runs as two + // segments, so the packet-boundary rounding at the join is exercised. + assert!(session.cut_at(2.0)); + session.pause(); + let timeline = session.timeline_duration(); + let out = out_path("av"); + + let handle = session.export_to(&out); + wait(&handle, Duration::from_secs(120)).expect("export"); + + let file = File::open(&out).unwrap(); + let size = file.metadata().unwrap().len(); + let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); + let packets = reader.sample_count(2).expect("audio track"); + let expected = engine::AudioSession::copy_segments(&source, &[(0.0, 2.0), (2.0, 5.0)]) + .unwrap() + .expect("source has audio") + .1 + .len() as u32; + assert_eq!(packets, expected, "every copied packet reached the file"); + // Independently of the copier: the rounding stays inside one packet per join + // plus the priming packet it starts with. + let samples = f64::from(packets * 1024); + let wanted = timeline * 44_100.0; + println!("audio: {packets} packets = {samples} samples for {wanted} of timeline"); + assert!( + (samples - wanted).abs() < 3.0 * 1024.0, + "audio length {samples} drifted from {wanted}" + ); + + let (meta, chunks) = engine::AudioSession::open(&out) + .expect("reopen export audio") + .expect("export has an audio track"); + assert_eq!(meta.sample_rate, 44_100); + assert_eq!(meta.channels, 2); + let decoded: usize = chunks.into_iter().map(|c| c.samples.len()).sum(); + assert!( + decoded as f64 / 2.0 > wanted - 3.0 * 1024.0, + "only {decoded} samples decoded back out" + ); + + let (video, _) = engine::demux::Demuxer::open(&out).unwrap(); + assert_eq!(video.frame_count, 150, "video track unaffected by the cut"); + std::fs::remove_file(&out).unwrap(); +} + +/// Hardware-encoded access units had never been through the muxer before this +/// slice: the Mesa slice-header fixup and the parameter-set placement were only +/// ever proven against a raw decoder. +#[test] +#[ignore] +fn hardware_access_units_repack_into_mp4() { + let (w, h) = (640u32, 480u32); + let mut encoder = + HwEncoder::open(w, h, 30, 1, 4_000_000).expect("no hardware encode plugin/driver"); + let out = out_path("hwmux"); + let mut muxer: Option = None; + let mut written = 0; + for index in 0..10u32 { + let (y, u, v) = synthetic(index, w as usize, h as usize); + let Some(au) = encoder.encode(&y, &u, &v, w, h, false).expect("encode") else { + continue; + }; + if muxer.is_none() { + let (sps, pps) = parameter_sets(au).expect("first access unit carries SPS+PPS"); + muxer = Some( + Mp4Muxer::create( + &out, + &VideoParams { + width: w, + height: h, + frame_rate: 30.0, + sps, + pps, + }, + None, + ) + .expect("create"), + ); + } + muxer.as_mut().unwrap().write_video_au(au).expect("write"); + written += 1; + } + while let Some(au) = encoder.drain().expect("drain") { + muxer.as_mut().unwrap().write_video_au(au).expect("write"); + written += 1; + } + muxer.unwrap().finish().expect("finish"); + assert_eq!(written, 10); + + let (meta, mut demuxer) = engine::demux::Demuxer::open(&out).unwrap(); + assert_eq!(meta.frame_count, 10); + let mut decoder = rusty_h264::Decoder::new(); + let mut decoded = 0; + while let Some(au) = demuxer.next_access_unit().unwrap() { + if decoder + .decode(&au) + .expect("software decode of the remuxed stream") + .is_some() + { + decoded += 1; + } + } + assert_eq!(decoded, 10, "every remuxed picture decodes again"); + std::fs::remove_file(&out).unwrap(); +} + +/// A moving diagonal gradient: something that costs bits, so the encoder cannot +/// pass the check by emitting skip frames. +fn synthetic(index: u32, width: usize, height: usize) -> (Vec, Vec, Vec) { + let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); + let mut y = vec![0u8; width * height]; + for row in 0..height { + for col in 0..width { + y[row * width + col] = (row + col + index as usize * 5) as u8; + } + } + ( + y, + vec![64u8.wrapping_add(index as u8); cw * ch], + vec![192u8.wrapping_sub(index as u8); cw * ch], + ) +}