Export — edit list to mp4, HW encode with SW fallback
Browse files at this commit86d5c151fe88efa0a6be8e8138d927e006c5a9deParent: b75c83e- feat
- export — edit list to mp4, HW encode with SW fallback
5 changed files +770 -2
- crates/engine/src/export.rs +416 -0
- crates/engine/src/lib.rs +3 -1
- crates/engine/src/mux.rs +16 -1
- crates/engine/src/playback.rs +11 -0
- crates/engine/tests/export.rs +324 -0
crates/engine/src/export.rsadded+416 -0
| @@ -0,0 +1,416 @@ | |||
| 1 | +//! Export: the edit list rendered back out as one mp4. | ||
| 2 | +//! | ||
| 3 | +//! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it | ||
| 4 | +//! is impossible — while audio is copied packet for packet, because there is no | ||
| 5 | +//! pure-Rust AAC encoder to re-encode with. The worker owns everything: the | ||
| 6 | +//! caller gets an [`ExportHandle`] and polls it from its render loop. | ||
| 7 | +//! | ||
| 8 | +//! Nothing partial survives a failure: cancel and every error path delete the | ||
| 9 | +//! output file. A killed *process* still leaves it — only in-process cleanup is | ||
| 10 | +//! promised. | ||
| 11 | + | ||
| 12 | +use std::path::Path; | ||
| 13 | +use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; | ||
| 14 | +use std::sync::{Arc, Mutex}; | ||
| 15 | +use std::thread; | ||
| 16 | + | ||
| 17 | +use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame}; | ||
| 18 | + | ||
| 19 | +use crate::audio::AudioSession; | ||
| 20 | +use crate::demux::{Demuxer, VideoMeta}; | ||
| 21 | +use crate::hw::{HwEncoder, HwSession}; | ||
| 22 | +use crate::mux::{AudioParams, Mp4Muxer, VideoParams}; | ||
| 23 | +use crate::project::Project; | ||
| 24 | + | ||
| 25 | +/// Progress is reported in permille: an atomic integer the render loop can read | ||
| 26 | +/// without a lock, fine enough for any progress bar. | ||
| 27 | +const PROGRESS_SCALE: u32 = 1_000; | ||
| 28 | + | ||
| 29 | +/// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands | ||
| 30 | +/// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%. | ||
| 31 | +const BITS_PER_PIXEL: f64 = 0.1; | ||
| 32 | +const MIN_BITRATE: u64 = 1_000_000; | ||
| 33 | +const MAX_BITRATE: u64 = 20_000_000; | ||
| 34 | + | ||
| 35 | +struct Shared { | ||
| 36 | + progress: AtomicU32, | ||
| 37 | + cancel: AtomicBool, | ||
| 38 | + finished: AtomicBool, | ||
| 39 | + outcome: Mutex<Option<crate::Result<()>>>, | ||
| 40 | +} | ||
| 41 | + | ||
| 42 | +/// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per | ||
| 43 | +/// rendered frame and take the [`result`](ExportHandle::result) when it flips; | ||
| 44 | +/// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel) | ||
| 45 | +/// does. | ||
| 46 | +pub struct ExportHandle { | ||
| 47 | + shared: Arc<Shared>, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +impl ExportHandle { | ||
| 51 | + /// Fraction of the timeline written, `0.0..=1.0`. | ||
| 52 | + pub fn progress(&self) -> f32 { | ||
| 53 | + self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32 | ||
| 54 | + } | ||
| 55 | + | ||
| 56 | + /// Asks the worker to stop at its next frame and delete the partial file. | ||
| 57 | + /// The outcome then reports the cancellation as an error. | ||
| 58 | + pub fn cancel(&self) { | ||
| 59 | + self.shared.cancel.store(true, Ordering::Relaxed); | ||
| 60 | + } | ||
| 61 | + | ||
| 62 | + pub fn is_finished(&self) -> bool { | ||
| 63 | + self.shared.finished.load(Ordering::Acquire) | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + /// The outcome, once — taken out of the handle, so a caller that already | ||
| 67 | + /// reported it sees `None` afterwards. `None` while the export is running. | ||
| 68 | + pub fn result(&self) -> Option<crate::Result<()>> { | ||
| 69 | + self.shared.outcome.lock().unwrap().take() | ||
| 70 | + } | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// Starts the worker. Failures are reported through the handle rather than | ||
| 74 | +/// returned, so a caller has exactly one place to look. | ||
| 75 | +pub(crate) fn start(source: &Path, project: Project, meta: VideoMeta, out: &Path) -> ExportHandle { | ||
| 76 | + let shared = Arc::new(Shared { | ||
| 77 | + progress: AtomicU32::new(0), | ||
| 78 | + cancel: AtomicBool::new(false), | ||
| 79 | + finished: AtomicBool::new(false), | ||
| 80 | + outcome: Mutex::new(None), | ||
| 81 | + }); | ||
| 82 | + let worker = Arc::clone(&shared); | ||
| 83 | + let source = source.to_path_buf(); | ||
| 84 | + let out = out.to_path_buf(); | ||
| 85 | + let spawned = thread::Builder::new().name("export".into()).spawn(move || { | ||
| 86 | + let result = run(&source, &project, &meta, &out, &worker); | ||
| 87 | + if result.is_err() { | ||
| 88 | + // The muxer -- and with it the file handle -- died with `run`. | ||
| 89 | + let _ = std::fs::remove_file(&out); | ||
| 90 | + } | ||
| 91 | + settle(&worker, result); | ||
| 92 | + }); | ||
| 93 | + if let Err(e) = spawned { | ||
| 94 | + settle(&shared, Err(e.into())); | ||
| 95 | + } | ||
| 96 | + ExportHandle { shared } | ||
| 97 | +} | ||
| 98 | + | ||
| 99 | +fn settle(shared: &Shared, result: crate::Result<()>) { | ||
| 100 | + *shared.outcome.lock().unwrap() = Some(result); | ||
| 101 | + // Published last: a caller that sees the flag is guaranteed the outcome. | ||
| 102 | + shared.finished.store(true, Ordering::Release); | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +fn run( | ||
| 106 | + source: &Path, | ||
| 107 | + project: &Project, | ||
| 108 | + meta: &VideoMeta, | ||
| 109 | + out: &Path, | ||
| 110 | + shared: &Shared, | ||
| 111 | +) -> crate::Result<()> { | ||
| 112 | + let total = project.timeline_frames(); | ||
| 113 | + // Audio first: a track has to be declared when the muxer is created, which | ||
| 114 | + // happens as soon as the first coded picture arrives. | ||
| 115 | + // | ||
| 116 | + // ponytail: this holds the whole exported AAC track in memory (~3 kB per | ||
| 117 | + // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming | ||
| 118 | + // `copy_segments` that yields packets instead of collecting them. | ||
| 119 | + let audio = AudioSession::copy_segments(source, &project.segments_from(0, meta.frame_rate))?; | ||
| 120 | + let audio_params = audio.as_ref().map(|(track, _)| AudioParams { | ||
| 121 | + freq_index: track.freq_index, | ||
| 122 | + chan_conf: track.chan_conf, | ||
| 123 | + }); | ||
| 124 | + | ||
| 125 | + let mut encoder = Enc::open(meta)?; | ||
| 126 | + let mut muxer = None; | ||
| 127 | + let mut done = 0u32; | ||
| 128 | + for clip in project.clips() { | ||
| 129 | + // Every clip reopens the file at its own in point; the encoder is *not* | ||
| 130 | + // reopened, so the export is one continuous stream whose GOP boundaries | ||
| 131 | + // need not line up with the cuts. | ||
| 132 | + let mut pictures = ClipDecoder::open(source, clip.in_frame)?; | ||
| 133 | + for _ in 0..clip.len() { | ||
| 134 | + if shared.cancel.load(Ordering::Relaxed) { | ||
| 135 | + return Err("export cancelled".into()); | ||
| 136 | + } | ||
| 137 | + let Some((y, u, v, width, height)) = pictures.next()? else { | ||
| 138 | + break; // source ran out early; the clip list outlives the file | ||
| 139 | + }; | ||
| 140 | + if let Some(au) = encoder.encode(y, u, v, width, height)? { | ||
| 141 | + write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?; | ||
| 142 | + } | ||
| 143 | + done += 1; | ||
| 144 | + shared | ||
| 145 | + .progress | ||
| 146 | + .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed); | ||
| 147 | + } | ||
| 148 | + } | ||
| 149 | + while let Some(au) = encoder.drain()? { | ||
| 150 | + write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?; | ||
| 151 | + } | ||
| 152 | + | ||
| 153 | + let Some(mut muxer) = muxer else { | ||
| 154 | + return Err("export produced no coded pictures".into()); | ||
| 155 | + }; | ||
| 156 | + if let Some((_, packets)) = audio { | ||
| 157 | + for packet in packets { | ||
| 158 | + muxer.write_audio_packet(&packet.bytes)?; | ||
| 159 | + } | ||
| 160 | + } | ||
| 161 | + muxer.finish()?; | ||
| 162 | + shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); | ||
| 163 | + Ok(()) | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +/// Writes one access unit, creating the file on the first one -- the parameter | ||
| 167 | +/// sets for `avcC` only exist once the encoder has coded something. Units with | ||
| 168 | +/// no coded slice are skipped: a software encoder may hand back an empty buffer | ||
| 169 | +/// while it buffers, and the muxer rejects a sample that would carry no picture. | ||
| 170 | +fn write_video( | ||
| 171 | + muxer: &mut Option<Mp4Muxer>, | ||
| 172 | + out: &Path, | ||
| 173 | + meta: &VideoMeta, | ||
| 174 | + audio: Option<&AudioParams>, | ||
| 175 | + au: &[u8], | ||
| 176 | +) -> crate::Result<()> { | ||
| 177 | + if !crate::mux::has_coded_slice(au) { | ||
| 178 | + return Ok(()); | ||
| 179 | + } | ||
| 180 | + let muxer = match muxer { | ||
| 181 | + Some(muxer) => muxer, | ||
| 182 | + none => { | ||
| 183 | + let (sps, pps) = crate::mux::parameter_sets(au) | ||
| 184 | + .ok_or("the first coded picture carries no SPS/PPS")?; | ||
| 185 | + none.insert(Mp4Muxer::create( | ||
| 186 | + out, | ||
| 187 | + &VideoParams { | ||
| 188 | + width: meta.width, | ||
| 189 | + height: meta.height, | ||
| 190 | + frame_rate: meta.frame_rate, | ||
| 191 | + sps, | ||
| 192 | + pps, | ||
| 193 | + }, | ||
| 194 | + audio, | ||
| 195 | + )?) | ||
| 196 | + } | ||
| 197 | + }; | ||
| 198 | + muxer.write_video_au(au) | ||
| 199 | +} | ||
| 200 | + | ||
| 201 | +fn bitrate_for(meta: &VideoMeta) -> u64 { | ||
| 202 | + let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL; | ||
| 203 | + (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE) | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +fn forced(var: &str) -> bool { | ||
| 207 | + std::env::var_os(var).is_some_and(|v| v == "1") | ||
| 208 | +} | ||
| 209 | + | ||
| 210 | +/// Hardware where it is available, software everywhere else -- chosen once for | ||
| 211 | +/// the whole export, so the stream never changes encoder mid-file. | ||
| 212 | +enum Enc { | ||
| 213 | + Hw(HwEncoder), | ||
| 214 | + Sw { | ||
| 215 | + encoder: Encoder, | ||
| 216 | + /// The last access unit; owned because `rusty_h264` hands back a `Vec` | ||
| 217 | + /// while the plugin lends a slice, and the two have to look alike here. | ||
| 218 | + au: Vec<u8>, | ||
| 219 | + flushed: bool, | ||
| 220 | + }, | ||
| 221 | +} | ||
| 222 | + | ||
| 223 | +impl Enc { | ||
| 224 | + fn open(meta: &VideoMeta) -> crate::Result<Self> { | ||
| 225 | + let bitrate = bitrate_for(meta); | ||
| 226 | + // The plugin wants an exact rational; a thousandth of a frame per second | ||
| 227 | + // is finer than any container fps we can read back. | ||
| 228 | + let fps_num = (meta.frame_rate * 1_000.0).round().max(1.0) as u32; | ||
| 229 | + if !forced("VE_SW_ENC") | ||
| 230 | + && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, 1_000, bitrate) | ||
| 231 | + { | ||
| 232 | + eprintln!("export encoder: hardware (VA-API plugin)"); | ||
| 233 | + return Ok(Self::Hw(hw)); | ||
| 234 | + } | ||
| 235 | + eprintln!("export encoder: software (rusty_h264)"); | ||
| 236 | + let mut cfg = EncoderConfig::new(meta.width as usize, meta.height as usize); | ||
| 237 | + cfg.framerate = meta.frame_rate as f32; | ||
| 238 | + cfg.bitrate = bitrate.min(u32::MAX as u64) as u32; | ||
| 239 | + // Two seconds between key frames, and no B-frames on either path: the | ||
| 240 | + // muxer times everything by duration alone, which reordering would break. | ||
| 241 | + cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32; | ||
| 242 | + cfg.bframes = 0; | ||
| 243 | + // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same | ||
| 244 | + // bitrate, so Fast is what a fallback should be. | ||
| 245 | + cfg.preset = Preset::Fast; | ||
| 246 | + let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?; | ||
| 247 | + Ok(Self::Sw { | ||
| 248 | + encoder, | ||
| 249 | + au: Vec::new(), | ||
| 250 | + flushed: false, | ||
| 251 | + }) | ||
| 252 | + } | ||
| 253 | + | ||
| 254 | + /// One picture in, at most one access unit out. | ||
| 255 | + /// | ||
| 256 | + /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer | ||
| 257 | + /// when its lookahead is active, which would make this "one access unit" | ||
| 258 | + /// a lie and every sample duration with it. It is inactive here because | ||
| 259 | + /// lookahead needs a zero bitrate and this path is always CBR; a future | ||
| 260 | + /// constant-QP mode has to split the buffer per access unit first. | ||
| 261 | + fn encode( | ||
| 262 | + &mut self, | ||
| 263 | + y: &[u8], | ||
| 264 | + u: &[u8], | ||
| 265 | + v: &[u8], | ||
| 266 | + width: u32, | ||
| 267 | + height: u32, | ||
| 268 | + ) -> crate::Result<Option<&[u8]>> { | ||
| 269 | + match self { | ||
| 270 | + Self::Hw(hw) => hw.encode(y, u, v, width, height, false), | ||
| 271 | + Self::Sw { encoder, au, .. } => { | ||
| 272 | + let frame = YuvFrame { | ||
| 273 | + width: width as usize, | ||
| 274 | + height: height as usize, | ||
| 275 | + y: y.to_vec(), | ||
| 276 | + u: u.to_vec(), | ||
| 277 | + v: v.to_vec(), | ||
| 278 | + }; | ||
| 279 | + *au = encoder | ||
| 280 | + .try_encode(&frame) | ||
| 281 | + .map_err(|e| format!("software encode: {e}"))?; | ||
| 282 | + Ok(Some(&au[..]).filter(|au| !au.is_empty())) | ||
| 283 | + } | ||
| 284 | + } | ||
| 285 | + } | ||
| 286 | + | ||
| 287 | + /// End of stream; call until it returns `None`. | ||
| 288 | + fn drain(&mut self) -> crate::Result<Option<&[u8]>> { | ||
| 289 | + match self { | ||
| 290 | + Self::Hw(hw) => hw.drain(), | ||
| 291 | + Self::Sw { | ||
| 292 | + encoder, | ||
| 293 | + au, | ||
| 294 | + flushed, | ||
| 295 | + } => { | ||
| 296 | + if *flushed { | ||
| 297 | + return Ok(None); | ||
| 298 | + } | ||
| 299 | + *flushed = true; | ||
| 300 | + *au = encoder | ||
| 301 | + .try_flush() | ||
| 302 | + .map_err(|e| format!("software encoder flush: {e}"))?; | ||
| 303 | + Ok(Some(&au[..]).filter(|au| !au.is_empty())) | ||
| 304 | + } | ||
| 305 | + } | ||
| 306 | + } | ||
| 307 | +} | ||
| 308 | + | ||
| 309 | +/// I420 straight out of the decoder: the export never converts to BGRA and back, | ||
| 310 | +/// which would cost two conversions and a generation of colour precision. | ||
| 311 | +/// | ||
| 312 | +/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`, | ||
| 313 | +/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to | ||
| 314 | +/// software: a hardware decode that fails after the first picture fails the | ||
| 315 | +/// export, which then deletes the half-written file. | ||
| 316 | +enum ClipDecoder { | ||
| 317 | + Hw(HwSession), | ||
| 318 | + Sw(SwDecoder), | ||
| 319 | +} | ||
| 320 | + | ||
| 321 | +impl ClipDecoder { | ||
| 322 | + fn open(path: &Path, start_frame: u32) -> crate::Result<Self> { | ||
| 323 | + if !forced("VE_SW") | ||
| 324 | + && let Some(hw) = HwSession::open_at(path, start_frame) | ||
| 325 | + { | ||
| 326 | + return Ok(Self::Hw(hw)); | ||
| 327 | + } | ||
| 328 | + Ok(Self::Sw(SwDecoder::open(path, start_frame)?)) | ||
| 329 | + } | ||
| 330 | + | ||
| 331 | + /// The next picture as tightly packed I420, borrowed until the call after. | ||
| 332 | + fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> { | ||
| 333 | + match self { | ||
| 334 | + Self::Hw(hw) => hw.next_frame(), | ||
| 335 | + Self::Sw(sw) => { | ||
| 336 | + if !sw.advance()? { | ||
| 337 | + return Ok(None); | ||
| 338 | + } | ||
| 339 | + let frame = sw.frame.as_ref().expect("advance stored a picture"); | ||
| 340 | + Ok(Some(( | ||
| 341 | + &frame.y, | ||
| 342 | + &frame.u, | ||
| 343 | + &frame.v, | ||
| 344 | + frame.width as u32, | ||
| 345 | + frame.height as u32, | ||
| 346 | + ))) | ||
| 347 | + } | ||
| 348 | + } | ||
| 349 | + } | ||
| 350 | +} | ||
| 351 | + | ||
| 352 | +struct SwDecoder { | ||
| 353 | + demuxer: Demuxer, | ||
| 354 | + decoder: Decoder, | ||
| 355 | + /// Display index of the next picture the decoder will produce. | ||
| 356 | + index: u32, | ||
| 357 | + start: u32, | ||
| 358 | + frame: Option<YuvFrame>, | ||
| 359 | +} | ||
| 360 | + | ||
| 361 | +impl SwDecoder { | ||
| 362 | + fn open(path: &Path, start_frame: u32) -> crate::Result<Self> { | ||
| 363 | + let (_, mut demuxer) = Demuxer::open(path)?; | ||
| 364 | + // Decoding restarts at a sync sample, so pictures between it and the in | ||
| 365 | + // point are decoded (the target references them) and then dropped. | ||
| 366 | + // Sample ids are 1-based, frame indices 0-based. | ||
| 367 | + let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1)); | ||
| 368 | + Ok(Self { | ||
| 369 | + demuxer, | ||
| 370 | + decoder: Decoder::new(), | ||
| 371 | + index: sync - 1, | ||
| 372 | + start: start_frame, | ||
| 373 | + frame: None, | ||
| 374 | + }) | ||
| 375 | + } | ||
| 376 | + | ||
| 377 | + /// Decodes up to and including the next picture at or after the in point, | ||
| 378 | + /// leaving it in `frame`. `false` at end of stream. | ||
| 379 | + fn advance(&mut self) -> crate::Result<bool> { | ||
| 380 | + loop { | ||
| 381 | + let Some(au) = self.demuxer.next_access_unit()? else { | ||
| 382 | + return Ok(false); | ||
| 383 | + }; | ||
| 384 | + let decoded = self | ||
| 385 | + .decoder | ||
| 386 | + .decode(&au) | ||
| 387 | + .map_err(|e| format!("decode at picture {}: {e}", self.index))?; | ||
| 388 | + let Some(yuv) = decoded else { continue }; | ||
| 389 | + let wanted = self.index >= self.start; | ||
| 390 | + self.index += 1; | ||
| 391 | + if wanted { | ||
| 392 | + self.frame = Some(yuv); | ||
| 393 | + return Ok(true); | ||
| 394 | + } | ||
| 395 | + } | ||
| 396 | + } | ||
| 397 | +} | ||
| 398 | + | ||
| 399 | +#[cfg(test)] | ||
| 400 | +mod tests { | ||
| 401 | + use super::*; | ||
| 402 | + | ||
| 403 | + #[test] | ||
| 404 | + fn bitrate_clamps_at_both_ends() { | ||
| 405 | + let meta = |width, height, frame_rate| VideoMeta { | ||
| 406 | + width, | ||
| 407 | + height, | ||
| 408 | + frame_rate, | ||
| 409 | + frame_count: 1, | ||
| 410 | + }; | ||
| 411 | + // 1280 * 720 * 30 * 0.1 | ||
| 412 | + assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); | ||
| 413 | + assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny"); | ||
| 414 | + assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge"); | ||
| 415 | + } | ||
| 416 | +} | ||
crates/engine/src/lib.rsmodified+3 -1
| @@ -6,15 +6,17 @@ pub mod clock; | |||
| 6 | pub mod convert; | 6 | pub mod convert; |
| 7 | pub mod decode; | 7 | pub mod decode; |
| 8 | pub mod demux; | 8 | pub mod demux; |
| 9 | +pub mod export; | ||
| 9 | pub mod hw; | 10 | pub mod hw; |
| 10 | pub mod mux; | 11 | pub mod mux; |
| 11 | pub mod playback; | 12 | pub mod playback; |
| 12 | pub mod project; | 13 | pub mod project; |
| 13 | 14 | ||
| 14 | -pub use audio::{AudioChunk, AudioMeta, AudioSession}; | 15 | +pub use audio::{AacPacket, AacTrackParams, AudioChunk, AudioMeta, AudioSession}; |
| 15 | pub use clock::PlaybackClock; | 16 | pub use clock::PlaybackClock; |
| 16 | pub use decode::{DecodeSession, Frame}; | 17 | pub use decode::{DecodeSession, Frame}; |
| 17 | pub use demux::VideoMeta; | 18 | pub use demux::VideoMeta; |
| 19 | +pub use export::ExportHandle; | ||
| 18 | pub use mux::{AudioParams, Mp4Muxer, VideoParams}; | 20 | pub use mux::{AudioParams, Mp4Muxer, VideoParams}; |
| 19 | pub use playback::PlaybackSession; | 21 | pub use playback::PlaybackSession; |
| 20 | pub use project::{Clip, Project}; | 22 | pub use project::{Clip, Project}; |
crates/engine/src/mux.rsmodified+16 -1
| @@ -13,7 +13,12 @@ use mp4::{ | |||
| 13 | /// 90 kHz is the H.264 convention; frame durations round to well under a | 13 | /// 90 kHz is the H.264 convention; frame durations round to well under a |
| 14 | /// microsecond of error at every fps we care about. | 14 | /// microsecond of error at every fps we care about. |
| 15 | const VIDEO_TIMESCALE: u32 = 90_000; | 15 | const VIDEO_TIMESCALE: u32 = 90_000; |
| 16 | -const MOVIE_TIMESCALE: u32 = 1_000; | 16 | +/// The same as the video's, deliberately: `mp4` converts every sample duration |
| 17 | +/// into the movie timescale with an integer division of its own (track.rs:752), | ||
| 18 | +/// so a coarser movie clock loses a fraction of a millisecond *per frame* -- | ||
| 19 | +/// 1 kHz makes a 4.000 s export announce itself as 3.960 s. Equal timescales | ||
| 20 | +/// make the video conversion exact. | ||
| 21 | +const MOVIE_TIMESCALE: u32 = VIDEO_TIMESCALE; | ||
| 17 | /// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the | 22 | /// An AAC-LC packet is always 1024 samples, so with timescale == sample rate the |
| 18 | /// per-packet duration is this constant. | 23 | /// per-packet duration is this constant. |
| 19 | const AAC_PACKET_SAMPLES: u32 = 1024; | 24 | const AAC_PACKET_SAMPLES: u32 = 1024; |
| @@ -173,6 +178,16 @@ pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> { | |||
| 173 | Some((sps, pps)) | 178 | Some((sps, pps)) |
| 174 | } | 179 | } |
| 175 | 180 | ||
| 181 | +/// Whether the unit carries a coded picture (NAL types 1..=5). An encoder that | ||
| 182 | +/// buffered instead of coding hands back an empty buffer, and one that emitted | ||
| 183 | +/// only parameter sets has no sample to write -- both are for the caller to skip | ||
| 184 | +/// rather than for [`Mp4Muxer::write_video_au`] to reject. | ||
| 185 | +pub(crate) fn has_coded_slice(annex_b: &[u8]) -> bool { | ||
| 186 | + split_annex_b(annex_b) | ||
| 187 | + .iter() | ||
| 188 | + .any(|nal| (1..=NAL_IDR).contains(&nal_type(nal))) | ||
| 189 | +} | ||
| 190 | + | ||
| 176 | /// Exact inverse of `demux::append_annex_b`: 4-byte length prefixes (the only | 191 | /// Exact inverse of `demux::append_annex_b`: 4-byte length prefixes (the only |
| 177 | /// prefix size `mp4` writes, avc1.rs hardcodes `length_size_minus_one = 3`). | 192 | /// prefix size `mp4` writes, avc1.rs hardcodes `length_size_minus_one = 3`). |
| 178 | /// Parameter sets, access unit delimiters and SEI are stripped — the first two | 193 | /// Parameter sets, access unit delimiters and SEI are stripped — the first two |
crates/engine/src/playback.rsmodified+11 -0
| @@ -389,6 +389,17 @@ impl PlaybackSession { | |||
| 389 | } | 389 | } |
| 390 | } | 390 | } |
| 391 | 391 | ||
| 392 | + /// Renders the edited timeline to `out` on a worker thread. The session is | ||
| 393 | + /// untouched -- the export decodes the source file for itself -- but a | ||
| 394 | + /// caller should still [`pause`](PlaybackSession::pause) first, because | ||
| 395 | + /// playback and export otherwise fight over the same decoder hardware. | ||
| 396 | + /// | ||
| 397 | + /// Later edits do not reach a running export: it works from a snapshot of | ||
| 398 | + /// the edit list taken here. | ||
| 399 | + pub fn export_to(&self, out: &Path) -> crate::ExportHandle { | ||
| 400 | + crate::export::start(&self.path, self.project.clone(), self.meta, out) | ||
| 401 | + } | ||
| 402 | + | ||
| 392 | /// Moves the clock forward; the caller runs this once per rendered frame. | 403 | /// Moves the clock forward; the caller runs this once per rendered frame. |
| 393 | /// Costs an atomic load, and once per session a mode switch. | 404 | /// Costs an atomic load, and once per session a mode switch. |
| 394 | pub fn tick(&mut self) { | 405 | pub fn tick(&mut self) { |
crates/engine/tests/export.rsadded+324 -0
| @@ -0,0 +1,324 @@ | |||
| 1 | +//! Export round trips: an edited timeline out to mp4 and straight back in | ||
| 2 | +//! through our own demuxer and decoder. | ||
| 3 | +//! | ||
| 4 | +//! The software test is the default one and needs nothing installed. The | ||
| 5 | +//! hardware twins need a built `libengine_hw.so` plus a VA-API driver with an | ||
| 6 | +//! H.264 encode entrypoint, so they are `#[ignore]`d: | ||
| 7 | +//! | ||
| 8 | +//! ```text | ||
| 9 | +//! cargo build -p engine -p engine-hw --release | ||
| 10 | +//! LD_LIBRARY_PATH=target/release \ | ||
| 11 | +//! cargo test -p engine --release --test export -- --ignored --nocapture --test-threads=1 | ||
| 12 | +//! ``` | ||
| 13 | +//! | ||
| 14 | +//! Both env pins are process-wide, hence `--test-threads=1` for the ignored run. | ||
| 15 | + | ||
| 16 | +use std::fs::File; | ||
| 17 | +use std::io::BufReader; | ||
| 18 | +use std::path::{Path, PathBuf}; | ||
| 19 | +use std::sync::Once; | ||
| 20 | +use std::time::{Duration, Instant}; | ||
| 21 | + | ||
| 22 | +use engine::hw::HwEncoder; | ||
| 23 | +use engine::mux::{Mp4Muxer, VideoParams, parameter_sets}; | ||
| 24 | +use engine::{DecodeSession, ExportHandle, PlaybackSession}; | ||
| 25 | + | ||
| 26 | +const FPS: f64 = 30.0; | ||
| 27 | + | ||
| 28 | +fn asset(name: &str) -> PathBuf { | ||
| 29 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 30 | + .join("../../assets") | ||
| 31 | + .join(name) | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +fn out_path(name: &str) -> PathBuf { | ||
| 35 | + let path = std::env::temp_dir().join(format!("ve_export_{name}.mp4")); | ||
| 36 | + let _ = std::fs::remove_file(&path); | ||
| 37 | + path | ||
| 38 | +} | ||
| 39 | + | ||
| 40 | +/// Pins both paths to software for the whole test binary, so the default suite | ||
| 41 | +/// proves the fallback that every machine has. | ||
| 42 | +fn pin_software() { | ||
| 43 | + static PIN: Once = Once::new(); | ||
| 44 | + PIN.call_once(|| unsafe { | ||
| 45 | + std::env::set_var("VE_SW", "1"); | ||
| 46 | + std::env::set_var("VE_SW_ENC", "1"); | ||
| 47 | + }); | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// Removes both pins, for the hardware twins. | ||
| 51 | +fn pin_hardware() { | ||
| 52 | + static PIN: Once = Once::new(); | ||
| 53 | + PIN.call_once(|| unsafe { | ||
| 54 | + std::env::remove_var("VE_SW"); | ||
| 55 | + std::env::remove_var("VE_SW_ENC"); | ||
| 56 | + }); | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +/// `[0,30) + [60,150)` of the source: two cuts and a delete, so the export has | ||
| 60 | +/// to seek, and the join is a real discontinuity rather than a formality. | ||
| 61 | +fn edited(source: &Path) -> PlaybackSession { | ||
| 62 | + let mut session = PlaybackSession::open(source).expect("open source"); | ||
| 63 | + assert!(session.cut_at(30.0 / FPS), "cut at frame 30"); | ||
| 64 | + assert!(session.cut_at(60.0 / FPS), "cut at frame 60"); | ||
| 65 | + assert!(session.delete_clip(1), "drop the middle clip"); | ||
| 66 | + assert_eq!(session.clip_spans().len(), 2); | ||
| 67 | + session | ||
| 68 | +} | ||
| 69 | + | ||
| 70 | +fn wait(handle: &ExportHandle, limit: Duration) -> engine::Result<()> { | ||
| 71 | + let started = Instant::now(); | ||
| 72 | + while !handle.is_finished() { | ||
| 73 | + assert!( | ||
| 74 | + started.elapsed() < limit, | ||
| 75 | + "export did not finish in {limit:?}" | ||
| 76 | + ); | ||
| 77 | + std::thread::sleep(Duration::from_millis(20)); | ||
| 78 | + } | ||
| 79 | + handle.result().expect("a finished export has an outcome") | ||
| 80 | +} | ||
| 81 | + | ||
| 82 | +/// Every frame of `path`, BGRA, in timeline order. | ||
| 83 | +fn decode_all(path: &Path) -> Vec<Vec<u8>> { | ||
| 84 | + let (_, frames) = DecodeSession::open(path).expect("open export"); | ||
| 85 | + frames.into_iter().map(|frame| frame.bgra).collect() | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// One frame of `path` by absolute index. | ||
| 89 | +fn frame_at(path: &Path, index: u32) -> Vec<u8> { | ||
| 90 | + let (_, frames, _) = DecodeSession::open_at(path, index).expect("open source"); | ||
| 91 | + frames.recv().expect("frame present").bgra | ||
| 92 | +} | ||
| 93 | + | ||
| 94 | +fn mean_abs_diff(a: &[u8], b: &[u8]) -> f64 { | ||
| 95 | + assert_eq!(a.len(), b.len(), "frame sizes differ"); | ||
| 96 | + a.iter() | ||
| 97 | + .zip(b) | ||
| 98 | + .map(|(x, y)| f64::from(x.abs_diff(*y))) | ||
| 99 | + .sum::<f64>() | ||
| 100 | + / a.len() as f64 | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/// The whole point of the slice: an edited timeline survives the trip out to | ||
| 104 | +/// disk and back, frame for frame and picture for picture. | ||
| 105 | +fn round_trip(name: &str, limit: Duration) { | ||
| 106 | + let source = asset("test_baseline.mp4"); | ||
| 107 | + let mut session = edited(&source); | ||
| 108 | + session.pause(); | ||
| 109 | + let out = out_path(name); | ||
| 110 | + | ||
| 111 | + let started = Instant::now(); | ||
| 112 | + let handle = session.export_to(&out); | ||
| 113 | + wait(&handle, limit).expect("export"); | ||
| 114 | + let spent = started.elapsed(); | ||
| 115 | + println!( | ||
| 116 | + "{name}: 120 frames in {:.2} s = {:.2} ms/frame", | ||
| 117 | + spent.as_secs_f64(), | ||
| 118 | + spent.as_secs_f64() * 1000.0 / 120.0 | ||
| 119 | + ); | ||
| 120 | + assert_eq!(handle.progress(), 1.0, "finished at full progress"); | ||
| 121 | + | ||
| 122 | + let (meta, _) = engine::demux::Demuxer::open(&out).expect("reopen export"); | ||
| 123 | + assert_eq!(meta.frame_count, 120, "timeline frames written"); | ||
| 124 | + assert_eq!((meta.width, meta.height), (1280, 720)); | ||
| 125 | + assert_eq!(meta.frame_rate.round(), FPS); | ||
| 126 | + | ||
| 127 | + let file = File::open(&out).unwrap(); | ||
| 128 | + let size = file.metadata().unwrap().len(); | ||
| 129 | + let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); | ||
| 130 | + let duration = reader.duration().as_secs_f64(); | ||
| 131 | + assert!( | ||
| 132 | + (duration - 120.0 / FPS).abs() <= 1.0 / FPS, | ||
| 133 | + "duration {duration} s is more than a frame off 4.0 s" | ||
| 134 | + ); | ||
| 135 | + | ||
| 136 | + let frames = decode_all(&out); | ||
| 137 | + assert_eq!(frames.len(), 120, "every written frame decodes back"); | ||
| 138 | + | ||
| 139 | + // Timeline -> source: [0,30) maps to itself, [30,120) to [60,150). | ||
| 140 | + for (timeline, source_frame) in [(0u32, 0u32), (59, 89), (119, 149)] { | ||
| 141 | + let diff = mean_abs_diff(&frames[timeline as usize], &frame_at(&source, source_frame)); | ||
| 142 | + println!("timeline {timeline} vs source {source_frame}: mean abs diff {diff:.2}"); | ||
| 143 | + assert!( | ||
| 144 | + diff < 6.0, | ||
| 145 | + "timeline frame {timeline} drifted by {diff:.2} from source frame {source_frame}" | ||
| 146 | + ); | ||
| 147 | + } | ||
| 148 | + std::fs::remove_file(&out).unwrap(); | ||
| 149 | +} | ||
| 150 | + | ||
| 151 | +#[test] | ||
| 152 | +fn exports_an_edited_timeline_in_software() { | ||
| 153 | + pin_software(); | ||
| 154 | + round_trip("sw", Duration::from_secs(120)); | ||
| 155 | +} | ||
| 156 | + | ||
| 157 | +/// Same trip through the plugin, and the only place the end-to-end hardware | ||
| 158 | +/// cost (decode + encode + mux) is measured. | ||
| 159 | +#[test] | ||
| 160 | +#[ignore] | ||
| 161 | +fn exports_an_edited_timeline_in_hardware() { | ||
| 162 | + pin_hardware(); | ||
| 163 | + round_trip("hw", Duration::from_secs(60)); | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +/// A cancelled export leaves nothing behind -- the half-written file is the | ||
| 167 | +/// thing a user would otherwise try to play. | ||
| 168 | +#[test] | ||
| 169 | +fn cancelling_leaves_no_file() { | ||
| 170 | + pin_software(); | ||
| 171 | + let mut session = edited(&asset("test_baseline.mp4")); | ||
| 172 | + session.pause(); | ||
| 173 | + let out = out_path("cancel"); | ||
| 174 | + | ||
| 175 | + let handle = session.export_to(&out); | ||
| 176 | + let started = Instant::now(); | ||
| 177 | + while handle.progress() < 0.1 { | ||
| 178 | + assert!( | ||
| 179 | + started.elapsed() < Duration::from_secs(60), | ||
| 180 | + "export never got going" | ||
| 181 | + ); | ||
| 182 | + assert!( | ||
| 183 | + !handle.is_finished(), | ||
| 184 | + "export finished before it was cancelled" | ||
| 185 | + ); | ||
| 186 | + std::thread::sleep(Duration::from_millis(10)); | ||
| 187 | + } | ||
| 188 | + handle.cancel(); | ||
| 189 | + let result = wait(&handle, Duration::from_secs(5)); | ||
| 190 | + assert!(result.is_err(), "a cancelled export is an error"); | ||
| 191 | + assert!(!out.exists(), "no partial file survives a cancel"); | ||
| 192 | +} | ||
| 193 | + | ||
| 194 | +/// Audio: the copied AAC packets have to land in the export as a track a reader | ||
| 195 | +/// can open again, at a length the video agrees with. | ||
| 196 | +#[test] | ||
| 197 | +#[ignore] | ||
| 198 | +fn exports_audio_alongside_the_video() { | ||
| 199 | + pin_hardware(); | ||
| 200 | + let source = asset("test_av.mp4"); | ||
| 201 | + let mut session = PlaybackSession::open(&source).expect("open source"); | ||
| 202 | + // One cut: the timeline is unchanged but the audio copy now runs as two | ||
| 203 | + // segments, so the packet-boundary rounding at the join is exercised. | ||
| 204 | + assert!(session.cut_at(2.0)); | ||
| 205 | + session.pause(); | ||
| 206 | + let timeline = session.timeline_duration(); | ||
| 207 | + let out = out_path("av"); | ||
| 208 | + | ||
| 209 | + let handle = session.export_to(&out); | ||
| 210 | + wait(&handle, Duration::from_secs(120)).expect("export"); | ||
| 211 | + | ||
| 212 | + let file = File::open(&out).unwrap(); | ||
| 213 | + let size = file.metadata().unwrap().len(); | ||
| 214 | + let reader = mp4::Mp4Reader::read_header(BufReader::new(file), size).unwrap(); | ||
| 215 | + let packets = reader.sample_count(2).expect("audio track"); | ||
| 216 | + let expected = engine::AudioSession::copy_segments(&source, &[(0.0, 2.0), (2.0, 5.0)]) | ||
| 217 | + .unwrap() | ||
| 218 | + .expect("source has audio") | ||
| 219 | + .1 | ||
| 220 | + .len() as u32; | ||
| 221 | + assert_eq!(packets, expected, "every copied packet reached the file"); | ||
| 222 | + // Independently of the copier: the rounding stays inside one packet per join | ||
| 223 | + // plus the priming packet it starts with. | ||
| 224 | + let samples = f64::from(packets * 1024); | ||
| 225 | + let wanted = timeline * 44_100.0; | ||
| 226 | + println!("audio: {packets} packets = {samples} samples for {wanted} of timeline"); | ||
| 227 | + assert!( | ||
| 228 | + (samples - wanted).abs() < 3.0 * 1024.0, | ||
| 229 | + "audio length {samples} drifted from {wanted}" | ||
| 230 | + ); | ||
| 231 | + | ||
| 232 | + let (meta, chunks) = engine::AudioSession::open(&out) | ||
| 233 | + .expect("reopen export audio") | ||
| 234 | + .expect("export has an audio track"); | ||
| 235 | + assert_eq!(meta.sample_rate, 44_100); | ||
| 236 | + assert_eq!(meta.channels, 2); | ||
| 237 | + let decoded: usize = chunks.into_iter().map(|c| c.samples.len()).sum(); | ||
| 238 | + assert!( | ||
| 239 | + decoded as f64 / 2.0 > wanted - 3.0 * 1024.0, | ||
| 240 | + "only {decoded} samples decoded back out" | ||
| 241 | + ); | ||
| 242 | + | ||
| 243 | + let (video, _) = engine::demux::Demuxer::open(&out).unwrap(); | ||
| 244 | + assert_eq!(video.frame_count, 150, "video track unaffected by the cut"); | ||
| 245 | + std::fs::remove_file(&out).unwrap(); | ||
| 246 | +} | ||
| 247 | + | ||
| 248 | +/// Hardware-encoded access units had never been through the muxer before this | ||
| 249 | +/// slice: the Mesa slice-header fixup and the parameter-set placement were only | ||
| 250 | +/// ever proven against a raw decoder. | ||
| 251 | +#[test] | ||
| 252 | +#[ignore] | ||
| 253 | +fn hardware_access_units_repack_into_mp4() { | ||
| 254 | + let (w, h) = (640u32, 480u32); | ||
| 255 | + let mut encoder = | ||
| 256 | + HwEncoder::open(w, h, 30, 1, 4_000_000).expect("no hardware encode plugin/driver"); | ||
| 257 | + let out = out_path("hwmux"); | ||
| 258 | + let mut muxer: Option<Mp4Muxer> = None; | ||
| 259 | + let mut written = 0; | ||
| 260 | + for index in 0..10u32 { | ||
| 261 | + let (y, u, v) = synthetic(index, w as usize, h as usize); | ||
| 262 | + let Some(au) = encoder.encode(&y, &u, &v, w, h, false).expect("encode") else { | ||
| 263 | + continue; | ||
| 264 | + }; | ||
| 265 | + if muxer.is_none() { | ||
| 266 | + let (sps, pps) = parameter_sets(au).expect("first access unit carries SPS+PPS"); | ||
| 267 | + muxer = Some( | ||
| 268 | + Mp4Muxer::create( | ||
| 269 | + &out, | ||
| 270 | + &VideoParams { | ||
| 271 | + width: w, | ||
| 272 | + height: h, | ||
| 273 | + frame_rate: 30.0, | ||
| 274 | + sps, | ||
| 275 | + pps, | ||
| 276 | + }, | ||
| 277 | + None, | ||
| 278 | + ) | ||
| 279 | + .expect("create"), | ||
| 280 | + ); | ||
| 281 | + } | ||
| 282 | + muxer.as_mut().unwrap().write_video_au(au).expect("write"); | ||
| 283 | + written += 1; | ||
| 284 | + } | ||
| 285 | + while let Some(au) = encoder.drain().expect("drain") { | ||
| 286 | + muxer.as_mut().unwrap().write_video_au(au).expect("write"); | ||
| 287 | + written += 1; | ||
| 288 | + } | ||
| 289 | + muxer.unwrap().finish().expect("finish"); | ||
| 290 | + assert_eq!(written, 10); | ||
| 291 | + | ||
| 292 | + let (meta, mut demuxer) = engine::demux::Demuxer::open(&out).unwrap(); | ||
| 293 | + assert_eq!(meta.frame_count, 10); | ||
| 294 | + let mut decoder = rusty_h264::Decoder::new(); | ||
| 295 | + let mut decoded = 0; | ||
| 296 | + while let Some(au) = demuxer.next_access_unit().unwrap() { | ||
| 297 | + if decoder | ||
| 298 | + .decode(&au) | ||
| 299 | + .expect("software decode of the remuxed stream") | ||
| 300 | + .is_some() | ||
| 301 | + { | ||
| 302 | + decoded += 1; | ||
| 303 | + } | ||
| 304 | + } | ||
| 305 | + assert_eq!(decoded, 10, "every remuxed picture decodes again"); | ||
| 306 | + std::fs::remove_file(&out).unwrap(); | ||
| 307 | +} | ||
| 308 | + | ||
| 309 | +/// A moving diagonal gradient: something that costs bits, so the encoder cannot | ||
| 310 | +/// pass the check by emitting skip frames. | ||
| 311 | +fn synthetic(index: u32, width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) { | ||
| 312 | + let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); | ||
| 313 | + let mut y = vec![0u8; width * height]; | ||
| 314 | + for row in 0..height { | ||
| 315 | + for col in 0..width { | ||
| 316 | + y[row * width + col] = (row + col + index as usize * 5) as u8; | ||
| 317 | + } | ||
| 318 | + } | ||
| 319 | + ( | ||
| 320 | + y, | ||
| 321 | + vec![64u8.wrapping_add(index as u8); cw * ch], | ||
| 322 | + vec![192u8.wrapping_sub(index as u8); cw * ch], | ||
| 323 | + ) | ||
| 324 | +} | ||