forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB9eac4beTahinli3 months ago20 commits

export.rs416 lines, 14.6 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: cancel and every error path delete the
9//! output file. A killed *process* still leaves it — only in-process cleanup is
10//! promised.
11
12use std::path::Path;
13use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
14use std::sync::{Arc, Mutex};
15use std::thread;
16
17use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame};
18
19use crate::audio::AudioSession;
20use crate::demux::{Demuxer, VideoMeta};
21use crate::hw::{HwEncoder, HwSession};
22use crate::mux::{AudioParams, Mp4Muxer, VideoParams};
23use 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.
27const 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%.
31const BITS_PER_PIXEL: f64 = 0.1;
32const MIN_BITRATE: u64 = 1_000_000;
33const MAX_BITRATE: u64 = 20_000_000;
34
35struct 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.
46pub struct ExportHandle {
47 shared: Arc<Shared>,
48}
49
50impl 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.
75pub(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
99fn 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
105fn 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.
170fn 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
201fn 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
206fn 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.
212enum 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
223impl 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.
316enum ClipDecoder {
317 Hw(HwSession),
318 Sw(SwDecoder),
319}
320
321impl 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
352struct 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
361impl 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)]
400mod 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}