forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

export.rs530 lines, 19.8 KiBHistoryRawDownload
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: the worker writes to `<out>.part` and
9//! renames it onto `out` only once the file is closed and complete, so the
10//! output either does not exist or is finished — there is no window where a
11//! half-written `.export.mp4` is sitting there looking playable. Cancel and
12//! every error path delete the `.part`. A killed *process* leaves the `.part`
13//! behind (only in-process cleanup is promised), which is an orphan a user can
14//! delete rather than a file that plays for two seconds and stops.
15
16use std::path::{Path, PathBuf};
17use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
18use std::sync::{Arc, Mutex};
19use std::thread;
20
21use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame};
22
23use crate::audio::AudioSession;
24use crate::demux::{Demuxer, VideoMeta};
25use crate::hw::{HwEncoder, HwSession};
26use crate::mux::{AudioParams, Mp4Muxer, VideoParams};
27use crate::project::{Lane, Project};
28
29/// Progress is reported in permille: an atomic integer the render loop can read
30/// without a lock, fine enough for any progress bar.
31const PROGRESS_SCALE: u32 = 1_000;
32
33/// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
34/// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%.
35const BITS_PER_PIXEL: f64 = 0.1;
36const MIN_BITRATE: u64 = 1_000_000;
37const MAX_BITRATE: u64 = 20_000_000;
38
39/// What the caller gets to decide about the output. The codec and container are
40/// not among it: H.264 in mp4 is the only pair with both an encoder and a
41/// decoder under this project's no-install rule, so offering a choice would be
42/// offering files we cannot read back.
43#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
44pub struct ExportSettings {
45 /// Bits per second, clamped to the same sane range the automatic value uses.
46 /// `None` picks it from the picture size and frame rate.
47 pub bitrate: Option<u64>,
48 /// Skip the hardware encoder even where it is available -- an escape hatch
49 /// for a driver that encodes badly, matching the `VE_SW_ENC` env pin.
50 pub force_sw: bool,
51}
52
53struct Shared {
54 progress: AtomicU32,
55 cancel: AtomicBool,
56 finished: AtomicBool,
57 outcome: Mutex<Option<crate::Result<()>>>,
58}
59
60/// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
61/// rendered frame and take the [`result`](ExportHandle::result) when it flips;
62/// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel)
63/// does.
64pub struct ExportHandle {
65 shared: Arc<Shared>,
66}
67
68impl ExportHandle {
69 /// Fraction of the timeline written, `0.0..=1.0`.
70 pub fn progress(&self) -> f32 {
71 self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32
72 }
73
74 /// Asks the worker to stop at its next checkpoint and delete the partial
75 /// file. The outcome then reports the cancellation as an error. Checkpoints
76 /// run to the last instant before the rename, so even a cancel at full
77 /// progress leaves no output.
78 pub fn cancel(&self) {
79 self.shared.cancel.store(true, Ordering::Relaxed);
80 }
81
82 pub fn is_finished(&self) -> bool {
83 self.shared.finished.load(Ordering::Acquire)
84 }
85
86 /// The outcome, once — taken out of the handle, so a caller that already
87 /// reported it sees `None` afterwards. `None` while the export is running.
88 pub fn result(&self) -> Option<crate::Result<()>> {
89 self.shared.outcome.lock().unwrap().take()
90 }
91}
92
93/// Starts the worker. Failures are reported through the handle rather than
94/// returned, so a caller has exactly one place to look. The files to read are
95/// the project's own [`sources`](Project::sources) -- every clip names one --
96/// so nothing but the edit list decides what is decoded.
97pub fn start(
98 project: Project,
99 meta: VideoMeta,
100 out: &Path,
101 settings: &ExportSettings,
102) -> ExportHandle {
103 let settings = *settings;
104 let shared = Arc::new(Shared {
105 progress: AtomicU32::new(0),
106 cancel: AtomicBool::new(false),
107 finished: AtomicBool::new(false),
108 outcome: Mutex::new(None),
109 });
110 let worker = Arc::clone(&shared);
111 let out = out.to_path_buf();
112 // `<out>.part`, appended rather than substituted: the temporary of
113 // `a.export.mp4` is `a.export.mp4.part`, which no other export claims.
114 let mut part = out.clone().into_os_string();
115 part.push(".part");
116 let part = PathBuf::from(part);
117 let spawned = thread::Builder::new().name("export".into()).spawn(move || {
118 // The rename is the last step and the only one that publishes a file
119 // under the name the caller asked for; it stays on the same directory,
120 // so it is atomic.
121 let result = run(&project, &meta, &part, &worker, &settings)
122 .and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
123 if result.is_err() {
124 // The muxer -- and with it the file handle -- died with `run`.
125 let _ = std::fs::remove_file(&part);
126 }
127 settle(&worker, result);
128 });
129 if let Err(e) = spawned {
130 settle(&shared, Err(e.into()));
131 }
132 ExportHandle { shared }
133}
134
135fn settle(shared: &Shared, result: crate::Result<()>) {
136 *shared.outcome.lock().unwrap() = Some(result);
137 // Published last: a caller that sees the flag is guaranteed the outcome.
138 shared.finished.store(true, Ordering::Release);
139}
140
141fn run(
142 project: &Project,
143 meta: &VideoMeta,
144 out: &Path,
145 shared: &Shared,
146 settings: &ExportSettings,
147) -> crate::Result<()> {
148 let total = project.timeline_frames();
149 let sources = project.sources();
150 // Audio first: a track has to be declared when the muxer is created, which
151 // happens as soon as the first coded picture arrives.
152 //
153 // ponytail: this holds the whole exported AAC track in memory (~3 kB per
154 // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
155 // `copy_segments` that yields packets instead of collecting them.
156 //
157 // The segments name their source, and the copy carries its packet-rounding
158 // debt across a source join exactly as across a cut, so a timeline spanning
159 // files stays in sync. A source whose AAC parameters disagree with the
160 // first one is an `Err` from there -- import refuses those up front, this
161 // is the backstop -- and the caller deletes the `.part`.
162 //
163 // The stream each source is copied from is the one it plays: `audio_sources`
164 // is the same list `PlaybackSession::seek` hands the decoder, so an export
165 // of a timeline playing a file's second audio track carries *that* track.
166 let audio = AudioSession::copy_multi_streams(
167 &project.audio_sources(),
168 &project.segments_from(0, meta.frame_rate),
169 )?;
170 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
171 freq_index: track.freq_index,
172 chan_conf: track.chan_conf,
173 });
174
175 let mut encoder = Enc::open(meta, settings)?;
176 let mut muxer = None;
177 let mut done = 0u32;
178 let black = Black::new(meta);
179 // Spans, not clips: a gap in the video lane is part of the timeline and
180 // gets encoded too, as black frames. The picture count is therefore
181 // `timeline_frames` however the lane is arranged.
182 for span in project.spans_from(Lane::Video, 0) {
183 // Every clip reopens its own source file at its own in point; the
184 // encoder is *not* reopened, so the export is one continuous stream
185 // whose GOP boundaries need not line up with the cuts -- nor with the
186 // file boundaries, which are just cuts that change the path.
187 let mut pictures = match span.from {
188 Some((source, in_frame)) => {
189 let entry = sources
190 .get(source)
191 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
192 Some(ClipDecoder::open(&entry.path, in_frame)?)
193 }
194 None => None,
195 };
196 for _ in 0..span.len {
197 cancelled(shared)?;
198 let picture = match &mut pictures {
199 Some(pictures) => pictures.next()?,
200 None => Some(black.picture()),
201 };
202 let Some((y, u, v, width, height)) = picture else {
203 break; // source ran out early; the clip list outlives the file
204 };
205 if let Some(au) = encoder.encode(y, u, v, width, height)? {
206 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
207 }
208 done += 1;
209 shared
210 .progress
211 .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);
212 }
213 }
214 while let Some(au) = encoder.drain()? {
215 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
216 }
217 // Progress reads 100% from here on, but nothing is published yet: draining,
218 // the audio pass and `finish` are all still cancellable.
219 cancelled(shared)?;
220
221 let Some(mut muxer) = muxer else {
222 return Err("export produced no coded pictures".into());
223 };
224 if let Some((_, packets)) = audio {
225 for packet in packets {
226 muxer.write_audio_packet(&packet.bytes)?;
227 }
228 }
229 cancelled(shared)?;
230 muxer.finish()?;
231 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
232 Ok(())
233}
234
235/// The I420 planes of one black picture, allocated once for a whole export: a
236/// gap in the video lane is encoded, not skipped, or every frame after it would
237/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention
238/// [`crate::convert`] decodes with.
239struct Black {
240 y: Vec<u8>,
241 uv: Vec<u8>,
242 width: u32,
243 height: u32,
244}
245
246impl Black {
247 fn new(meta: &VideoMeta) -> Self {
248 let (w, h) = (meta.width as usize, meta.height as usize);
249 Self {
250 y: vec![16; w * h],
251 uv: vec![128; w.div_ceil(2) * h.div_ceil(2)],
252 width: meta.width,
253 height: meta.height,
254 }
255 }
256
257 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
258 (&self.y, &self.uv, &self.uv, self.width, self.height)
259 }
260}
261
262/// `Err` once a cancel has been asked for. Called at every point where the work
263/// left is more than an instant, so an `esc` at 99.9% still stops the export
264/// instead of quietly completing it.
265fn cancelled(shared: &Shared) -> crate::Result<()> {
266 if shared.cancel.load(Ordering::Relaxed) {
267 return Err("export cancelled".into());
268 }
269 Ok(())
270}
271
272/// Writes one access unit, creating the file on the first one -- the parameter
273/// sets for `avcC` only exist once the encoder has coded something. Units with
274/// no coded slice are skipped: a software encoder may hand back an empty buffer
275/// while it buffers, and the muxer rejects a sample that would carry no picture.
276fn write_video(
277 muxer: &mut Option<Mp4Muxer>,
278 out: &Path,
279 meta: &VideoMeta,
280 audio: Option<&AudioParams>,
281 au: &[u8],
282) -> crate::Result<()> {
283 if !crate::mux::has_coded_slice(au) {
284 return Ok(());
285 }
286 let muxer = match muxer {
287 Some(muxer) => muxer,
288 none => {
289 let (sps, pps) = crate::mux::parameter_sets(au)
290 .ok_or("the first coded picture carries no SPS/PPS")?;
291 none.insert(Mp4Muxer::create(
292 out,
293 &VideoParams {
294 width: meta.width,
295 height: meta.height,
296 frame_rate: meta.frame_rate,
297 sps,
298 pps,
299 },
300 audio,
301 )?)
302 }
303 };
304 muxer.write_video_au(au)
305}
306
307fn bitrate_for(meta: &VideoMeta) -> u64 {
308 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;
309 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)
310}
311
312fn forced(var: &str) -> bool {
313 std::env::var_os(var).is_some_and(|v| v == "1")
314}
315
316/// Hardware where it is available, software everywhere else -- chosen once for
317/// the whole export, so the stream never changes encoder mid-file.
318enum Enc {
319 Hw(HwEncoder),
320 Sw {
321 encoder: Encoder,
322 /// The last access unit; owned because `rusty_h264` hands back a `Vec`
323 /// while the plugin lends a slice, and the two have to look alike here.
324 au: Vec<u8>,
325 flushed: bool,
326 },
327}
328
329impl Enc {
330 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
331 // A caller's number goes through the same clamp as the computed one: a
332 // zero bitrate switches the software encoder's lookahead on, which would
333 // break the one-picture-per-call contract `encode` documents below.
334 let bitrate = settings
335 .bitrate
336 .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE));
337 // The plugin wants an exact rational, and the muxer already picks one
338 // that is exact at every rate we can read -- `fps * 1000 / 1000` would
339 // hand 24000/1001 over as a rounded 23.976, which is the same
340 // truncation the container timing had.
341 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
342 if !settings.force_sw
343 && !forced("VE_SW_ENC")
344 && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate)
345 {
346 eprintln!("export encoder: hardware (VA-API plugin)");
347 return Ok(Self::Hw(hw));
348 }
349 eprintln!("export encoder: software (rusty_h264)");
350 let mut cfg = EncoderConfig::new(meta.width as usize, meta.height as usize);
351 cfg.framerate = meta.frame_rate as f32;
352 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;
353 // Two seconds between key frames, and no B-frames on either path: the
354 // muxer times everything by duration alone, which reordering would break.
355 cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32;
356 cfg.bframes = 0;
357 // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same
358 // bitrate, so Fast is what a fallback should be.
359 cfg.preset = Preset::Fast;
360 let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?;
361 Ok(Self::Sw {
362 encoder,
363 au: Vec::new(),
364 flushed: false,
365 })
366 }
367
368 /// One picture in, at most one access unit out.
369 ///
370 /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer
371 /// when its lookahead is active, which would make this "one access unit"
372 /// a lie and every sample duration with it. It is inactive here because
373 /// lookahead needs a zero bitrate and this path is always CBR; a future
374 /// constant-QP mode has to split the buffer per access unit first.
375 fn encode(
376 &mut self,
377 y: &[u8],
378 u: &[u8],
379 v: &[u8],
380 width: u32,
381 height: u32,
382 ) -> crate::Result<Option<&[u8]>> {
383 match self {
384 Self::Hw(hw) => hw.encode(y, u, v, width, height, false),
385 Self::Sw { encoder, au, .. } => {
386 let frame = YuvFrame {
387 width: width as usize,
388 height: height as usize,
389 y: y.to_vec(),
390 u: u.to_vec(),
391 v: v.to_vec(),
392 };
393 *au = encoder
394 .try_encode(&frame)
395 .map_err(|e| format!("software encode: {e}"))?;
396 Ok(Some(&au[..]).filter(|au| !au.is_empty()))
397 }
398 }
399 }
400
401 /// End of stream; call until it returns `None`.
402 fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
403 match self {
404 Self::Hw(hw) => hw.drain(),
405 Self::Sw {
406 encoder,
407 au,
408 flushed,
409 } => {
410 if *flushed {
411 return Ok(None);
412 }
413 *flushed = true;
414 *au = encoder
415 .try_flush()
416 .map_err(|e| format!("software encoder flush: {e}"))?;
417 Ok(Some(&au[..]).filter(|au| !au.is_empty()))
418 }
419 }
420 }
421}
422
423/// I420 straight out of the decoder: the export never converts to BGRA and back,
424/// which would cost two conversions and a generation of colour precision.
425///
426/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`,
427/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to
428/// software: a hardware decode that fails after the first picture fails the
429/// export, which then deletes the half-written file.
430enum ClipDecoder {
431 Hw(HwSession),
432 Sw(SwDecoder),
433}
434
435impl ClipDecoder {
436 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
437 if !forced("VE_SW")
438 && let Some(hw) = HwSession::open_at(path, start_frame)
439 {
440 return Ok(Self::Hw(hw));
441 }
442 Ok(Self::Sw(SwDecoder::open(path, start_frame)?))
443 }
444
445 /// The next picture as tightly packed I420, borrowed until the call after.
446 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
447 match self {
448 Self::Hw(hw) => hw.next_frame(),
449 Self::Sw(sw) => {
450 if !sw.advance()? {
451 return Ok(None);
452 }
453 let frame = sw.frame.as_ref().expect("advance stored a picture");
454 Ok(Some((
455 &frame.y,
456 &frame.u,
457 &frame.v,
458 frame.width as u32,
459 frame.height as u32,
460 )))
461 }
462 }
463 }
464}
465
466struct SwDecoder {
467 demuxer: Demuxer,
468 decoder: Decoder,
469 /// Display index of the next picture the decoder will produce. Signed: a
470 /// sync sample inside what the edit list trims is before frame 0.
471 index: i64,
472 start: u32,
473 frame: Option<YuvFrame>,
474}
475
476impl SwDecoder {
477 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
478 let (_, mut demuxer) = Demuxer::open(path)?;
479 // Decoding restarts at a sync sample, so pictures between it and the in
480 // point are decoded (the target references them) and then dropped.
481 let index = demuxer.seek_to_sync_at_or_before(start_frame);
482 Ok(Self {
483 demuxer,
484 decoder: Decoder::new(),
485 index,
486 start: start_frame,
487 frame: None,
488 })
489 }
490
491 /// Decodes up to and including the next picture at or after the in point,
492 /// leaving it in `frame`. `false` at end of stream.
493 fn advance(&mut self) -> crate::Result<bool> {
494 loop {
495 let Some(au) = self.demuxer.next_access_unit()? else {
496 return Ok(false);
497 };
498 let decoded = self
499 .decoder
500 .decode(&au)
501 .map_err(|e| format!("decode at picture {}: {e}", self.index))?;
502 let Some(yuv) = decoded else { continue };
503 let wanted = self.index >= i64::from(self.start);
504 self.index += 1;
505 if wanted {
506 self.frame = Some(yuv);
507 return Ok(true);
508 }
509 }
510 }
511}
512
513#[cfg(test)]
514mod tests {
515 use super::*;
516
517 #[test]
518 fn bitrate_clamps_at_both_ends() {
519 let meta = |width, height, frame_rate| VideoMeta {
520 width,
521 height,
522 frame_rate,
523 frame_count: 1,
524 };
525 // 1280 * 720 * 30 * 0.1
526 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
527 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny");
528 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
529 }
530}