forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBdff7d84Tahinli3 months ago58 commits

export.rs522 lines, 19.3 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 let audio =
163 AudioSession::copy_multi_segments(sources, &project.segments_from(0, meta.frame_rate))?;
164 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
165 freq_index: track.freq_index,
166 chan_conf: track.chan_conf,
167 });
168
169 let mut encoder = Enc::open(meta, settings)?;
170 let mut muxer = None;
171 let mut done = 0u32;
172 let black = Black::new(meta);
173 // Spans, not clips: a gap in the video lane is part of the timeline and
174 // gets encoded too, as black frames. The picture count is therefore
175 // `timeline_frames` however the lane is arranged.
176 for span in project.spans_from(Lane::Video, 0) {
177 // Every clip reopens its own source file at its own in point; the
178 // encoder is *not* reopened, so the export is one continuous stream
179 // whose GOP boundaries need not line up with the cuts -- nor with the
180 // file boundaries, which are just cuts that change the path.
181 let mut pictures = match span.from {
182 Some((source, in_frame)) => {
183 let path = sources
184 .get(source)
185 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
186 Some(ClipDecoder::open(path, in_frame)?)
187 }
188 None => None,
189 };
190 for _ in 0..span.len {
191 cancelled(shared)?;
192 let picture = match &mut pictures {
193 Some(pictures) => pictures.next()?,
194 None => Some(black.picture()),
195 };
196 let Some((y, u, v, width, height)) = picture else {
197 break; // source ran out early; the clip list outlives the file
198 };
199 if let Some(au) = encoder.encode(y, u, v, width, height)? {
200 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
201 }
202 done += 1;
203 shared
204 .progress
205 .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);
206 }
207 }
208 while let Some(au) = encoder.drain()? {
209 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
210 }
211 // Progress reads 100% from here on, but nothing is published yet: draining,
212 // the audio pass and `finish` are all still cancellable.
213 cancelled(shared)?;
214
215 let Some(mut muxer) = muxer else {
216 return Err("export produced no coded pictures".into());
217 };
218 if let Some((_, packets)) = audio {
219 for packet in packets {
220 muxer.write_audio_packet(&packet.bytes)?;
221 }
222 }
223 cancelled(shared)?;
224 muxer.finish()?;
225 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
226 Ok(())
227}
228
229/// The I420 planes of one black picture, allocated once for a whole export: a
230/// gap in the video lane is encoded, not skipped, or every frame after it would
231/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention
232/// [`crate::convert`] decodes with.
233struct Black {
234 y: Vec<u8>,
235 uv: Vec<u8>,
236 width: u32,
237 height: u32,
238}
239
240impl Black {
241 fn new(meta: &VideoMeta) -> Self {
242 let (w, h) = (meta.width as usize, meta.height as usize);
243 Self {
244 y: vec![16; w * h],
245 uv: vec![128; w.div_ceil(2) * h.div_ceil(2)],
246 width: meta.width,
247 height: meta.height,
248 }
249 }
250
251 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
252 (&self.y, &self.uv, &self.uv, self.width, self.height)
253 }
254}
255
256/// `Err` once a cancel has been asked for. Called at every point where the work
257/// left is more than an instant, so an `esc` at 99.9% still stops the export
258/// instead of quietly completing it.
259fn cancelled(shared: &Shared) -> crate::Result<()> {
260 if shared.cancel.load(Ordering::Relaxed) {
261 return Err("export cancelled".into());
262 }
263 Ok(())
264}
265
266/// Writes one access unit, creating the file on the first one -- the parameter
267/// sets for `avcC` only exist once the encoder has coded something. Units with
268/// no coded slice are skipped: a software encoder may hand back an empty buffer
269/// while it buffers, and the muxer rejects a sample that would carry no picture.
270fn write_video(
271 muxer: &mut Option<Mp4Muxer>,
272 out: &Path,
273 meta: &VideoMeta,
274 audio: Option<&AudioParams>,
275 au: &[u8],
276) -> crate::Result<()> {
277 if !crate::mux::has_coded_slice(au) {
278 return Ok(());
279 }
280 let muxer = match muxer {
281 Some(muxer) => muxer,
282 none => {
283 let (sps, pps) = crate::mux::parameter_sets(au)
284 .ok_or("the first coded picture carries no SPS/PPS")?;
285 none.insert(Mp4Muxer::create(
286 out,
287 &VideoParams {
288 width: meta.width,
289 height: meta.height,
290 frame_rate: meta.frame_rate,
291 sps,
292 pps,
293 },
294 audio,
295 )?)
296 }
297 };
298 muxer.write_video_au(au)
299}
300
301fn bitrate_for(meta: &VideoMeta) -> u64 {
302 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;
303 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)
304}
305
306fn forced(var: &str) -> bool {
307 std::env::var_os(var).is_some_and(|v| v == "1")
308}
309
310/// Hardware where it is available, software everywhere else -- chosen once for
311/// the whole export, so the stream never changes encoder mid-file.
312enum Enc {
313 Hw(HwEncoder),
314 Sw {
315 encoder: Encoder,
316 /// The last access unit; owned because `rusty_h264` hands back a `Vec`
317 /// while the plugin lends a slice, and the two have to look alike here.
318 au: Vec<u8>,
319 flushed: bool,
320 },
321}
322
323impl Enc {
324 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
325 // A caller's number goes through the same clamp as the computed one: a
326 // zero bitrate switches the software encoder's lookahead on, which would
327 // break the one-picture-per-call contract `encode` documents below.
328 let bitrate = settings
329 .bitrate
330 .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE));
331 // The plugin wants an exact rational; a thousandth of a frame per second
332 // is finer than any container fps we can read back.
333 let fps_num = (meta.frame_rate * 1_000.0).round().max(1.0) as u32;
334 if !settings.force_sw
335 && !forced("VE_SW_ENC")
336 && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, 1_000, bitrate)
337 {
338 eprintln!("export encoder: hardware (VA-API plugin)");
339 return Ok(Self::Hw(hw));
340 }
341 eprintln!("export encoder: software (rusty_h264)");
342 let mut cfg = EncoderConfig::new(meta.width as usize, meta.height as usize);
343 cfg.framerate = meta.frame_rate as f32;
344 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;
345 // Two seconds between key frames, and no B-frames on either path: the
346 // muxer times everything by duration alone, which reordering would break.
347 cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32;
348 cfg.bframes = 0;
349 // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same
350 // bitrate, so Fast is what a fallback should be.
351 cfg.preset = Preset::Fast;
352 let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?;
353 Ok(Self::Sw {
354 encoder,
355 au: Vec::new(),
356 flushed: false,
357 })
358 }
359
360 /// One picture in, at most one access unit out.
361 ///
362 /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer
363 /// when its lookahead is active, which would make this "one access unit"
364 /// a lie and every sample duration with it. It is inactive here because
365 /// lookahead needs a zero bitrate and this path is always CBR; a future
366 /// constant-QP mode has to split the buffer per access unit first.
367 fn encode(
368 &mut self,
369 y: &[u8],
370 u: &[u8],
371 v: &[u8],
372 width: u32,
373 height: u32,
374 ) -> crate::Result<Option<&[u8]>> {
375 match self {
376 Self::Hw(hw) => hw.encode(y, u, v, width, height, false),
377 Self::Sw { encoder, au, .. } => {
378 let frame = YuvFrame {
379 width: width as usize,
380 height: height as usize,
381 y: y.to_vec(),
382 u: u.to_vec(),
383 v: v.to_vec(),
384 };
385 *au = encoder
386 .try_encode(&frame)
387 .map_err(|e| format!("software encode: {e}"))?;
388 Ok(Some(&au[..]).filter(|au| !au.is_empty()))
389 }
390 }
391 }
392
393 /// End of stream; call until it returns `None`.
394 fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
395 match self {
396 Self::Hw(hw) => hw.drain(),
397 Self::Sw {
398 encoder,
399 au,
400 flushed,
401 } => {
402 if *flushed {
403 return Ok(None);
404 }
405 *flushed = true;
406 *au = encoder
407 .try_flush()
408 .map_err(|e| format!("software encoder flush: {e}"))?;
409 Ok(Some(&au[..]).filter(|au| !au.is_empty()))
410 }
411 }
412 }
413}
414
415/// I420 straight out of the decoder: the export never converts to BGRA and back,
416/// which would cost two conversions and a generation of colour precision.
417///
418/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`,
419/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to
420/// software: a hardware decode that fails after the first picture fails the
421/// export, which then deletes the half-written file.
422enum ClipDecoder {
423 Hw(HwSession),
424 Sw(SwDecoder),
425}
426
427impl ClipDecoder {
428 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
429 if !forced("VE_SW")
430 && let Some(hw) = HwSession::open_at(path, start_frame)
431 {
432 return Ok(Self::Hw(hw));
433 }
434 Ok(Self::Sw(SwDecoder::open(path, start_frame)?))
435 }
436
437 /// The next picture as tightly packed I420, borrowed until the call after.
438 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
439 match self {
440 Self::Hw(hw) => hw.next_frame(),
441 Self::Sw(sw) => {
442 if !sw.advance()? {
443 return Ok(None);
444 }
445 let frame = sw.frame.as_ref().expect("advance stored a picture");
446 Ok(Some((
447 &frame.y,
448 &frame.u,
449 &frame.v,
450 frame.width as u32,
451 frame.height as u32,
452 )))
453 }
454 }
455 }
456}
457
458struct SwDecoder {
459 demuxer: Demuxer,
460 decoder: Decoder,
461 /// Display index of the next picture the decoder will produce.
462 index: u32,
463 start: u32,
464 frame: Option<YuvFrame>,
465}
466
467impl SwDecoder {
468 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
469 let (_, mut demuxer) = Demuxer::open(path)?;
470 // Decoding restarts at a sync sample, so pictures between it and the in
471 // point are decoded (the target references them) and then dropped.
472 // Sample ids are 1-based, frame indices 0-based.
473 let sync = demuxer.seek_to_sync_at_or_before(start_frame.saturating_add(1));
474 Ok(Self {
475 demuxer,
476 decoder: Decoder::new(),
477 index: sync - 1,
478 start: start_frame,
479 frame: None,
480 })
481 }
482
483 /// Decodes up to and including the next picture at or after the in point,
484 /// leaving it in `frame`. `false` at end of stream.
485 fn advance(&mut self) -> crate::Result<bool> {
486 loop {
487 let Some(au) = self.demuxer.next_access_unit()? else {
488 return Ok(false);
489 };
490 let decoded = self
491 .decoder
492 .decode(&au)
493 .map_err(|e| format!("decode at picture {}: {e}", self.index))?;
494 let Some(yuv) = decoded else { continue };
495 let wanted = self.index >= self.start;
496 self.index += 1;
497 if wanted {
498 self.frame = Some(yuv);
499 return Ok(true);
500 }
501 }
502 }
503}
504
505#[cfg(test)]
506mod tests {
507 use super::*;
508
509 #[test]
510 fn bitrate_clamps_at_both_ends() {
511 let meta = |width, height, frame_rate| VideoMeta {
512 width,
513 height,
514 frame_rate,
515 frame_count: 1,
516 };
517 // 1280 * 720 * 30 * 0.1
518 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
519 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny");
520 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
521 }
522}