forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB951c3fcTahinli3 months ago113 commits

export.rs807 lines, 32.7 KiBHistoryRawDownload
1//! Export: the edit list rendered back out as one mp4 — or, picture left
2//! behind, as one WAV or FLAC of the timeline's audio alone.
3//!
4//! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it
5//! is impossible — while audio is copied packet for packet, because there is no
6//! pure-Rust AAC encoder to re-encode with. The audio-only formats have no such
7//! trouble: `hound` writes PCM and `flacenc` encodes FLAC, both pure Rust, so
8//! those are *decoded* out of the timeline instead of copied. The worker owns
9//! everything: the caller gets an [`ExportHandle`] and polls it from its render
10//! loop.
11//!
12//! Nothing partial survives a failure: the worker writes to `<out>.part` and
13//! renames it onto `out` only once the file is closed and complete, so the
14//! output either does not exist or is finished — there is no window where a
15//! half-written `.export.mp4` is sitting there looking playable. Cancel and
16//! every error path delete the `.part`. A killed *process* leaves the `.part`
17//! behind (only in-process cleanup is promised), which is an orphan a user can
18//! delete rather than a file that plays for two seconds and stops.
19
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
22use std::sync::{Arc, Mutex};
23use std::thread;
24
25use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame};
26
27use flacenc::component::BitRepr;
28use flacenc::error::Verify;
29
30use crate::audio::{AudioMeta, AudioSession};
31use crate::demux::{Demuxer, VideoMeta};
32use crate::hw::{HwEncoder, HwSession};
33use crate::mux::{AudioParams, Mp4Muxer, VideoParams};
34use crate::project::Project;
35use crate::scale::Composer;
36
37/// Progress is reported in permille: an atomic integer the render loop can read
38/// without a lock, fine enough for any progress bar.
39const PROGRESS_SCALE: u32 = 1_000;
40
41/// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
42/// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%.
43const BITS_PER_PIXEL: f64 = 0.1;
44const MIN_BITRATE: u64 = 1_000_000;
45const MAX_BITRATE: u64 = 20_000_000;
46
47/// What an export writes. Three, not more: H.264-in-mp4 is the only *video*
48/// pair with both an encoder and a decoder under this project's no-install
49/// rule, and WAV and FLAC are the only audio formats with a pure-Rust encoder
50/// at all. MP3 has one (`shine-rs`) under LGPL-2.0, which is a licensing
51/// decision this project has not taken; Vorbis, Opus and AAC have none. A
52/// front-end says so rather than hiding the rows.
53#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
54pub enum Format {
55 /// Picture and sound: video re-encoded, AAC copied. Copied, so it carries
56 /// **one** audio lane: a timeline whose sound is spread over two is refused
57 /// by name here and mixed by the other two formats, which decode.
58 #[default]
59 Mp4,
60 /// The audio lane alone, 16-bit PCM.
61 Wav,
62 /// The audio lane alone, losslessly compressed.
63 Flac,
64}
65
66impl Format {
67 /// The extension a file of this format is named with -- a front-end builds
68 /// the destination path from it, so the name never disagrees with the bytes.
69 pub fn ext(self) -> &'static str {
70 match self {
71 Self::Mp4 => "mp4",
72 Self::Wav => "wav",
73 Self::Flac => "flac",
74 }
75 }
76
77 /// Whether this format carries the picture. The bitrate settings are video
78 /// settings and mean nothing to the other two.
79 pub fn has_video(self) -> bool {
80 matches!(self, Self::Mp4)
81 }
82}
83
84/// What the caller gets to decide about the output. The codec is not among it:
85/// [`Format`] names a container *and* what goes in it, because every pair we
86/// can write is a pair we can also read back.
87#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
88pub struct ExportSettings {
89 /// Bits per second, clamped to the same sane range the automatic value uses.
90 /// `None` picks it from the picture size and frame rate. Video only.
91 pub bitrate: Option<u64>,
92 /// Skip the hardware encoder even where it is available -- an escape hatch
93 /// for a driver that encodes badly, matching the `VE_SW_ENC` env pin.
94 pub force_sw: bool,
95 /// The file to write. Defaults to [`Format::Mp4`], which is what every
96 /// caller wrote before there was a choice.
97 pub format: Format,
98}
99
100struct Shared {
101 progress: AtomicU32,
102 cancel: AtomicBool,
103 finished: AtomicBool,
104 outcome: Mutex<Option<crate::Result<()>>>,
105}
106
107/// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
108/// rendered frame and take the [`result`](ExportHandle::result) when it flips;
109/// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel)
110/// does.
111pub struct ExportHandle {
112 shared: Arc<Shared>,
113}
114
115impl ExportHandle {
116 /// Fraction of the timeline written, `0.0..=1.0`.
117 pub fn progress(&self) -> f32 {
118 self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32
119 }
120
121 /// Asks the worker to stop at its next checkpoint and delete the partial
122 /// file. The outcome then reports the cancellation as an error. Checkpoints
123 /// run to the last instant before the rename, so even a cancel at full
124 /// progress leaves no output.
125 pub fn cancel(&self) {
126 self.shared.cancel.store(true, Ordering::Relaxed);
127 }
128
129 pub fn is_finished(&self) -> bool {
130 self.shared.finished.load(Ordering::Acquire)
131 }
132
133 /// The outcome, once — taken out of the handle, so a caller that already
134 /// reported it sees `None` afterwards. `None` while the export is running.
135 pub fn result(&self) -> Option<crate::Result<()>> {
136 self.shared.outcome.lock().unwrap().take()
137 }
138}
139
140/// Starts the worker. Failures are reported through the handle rather than
141/// returned, so a caller has exactly one place to look. The files to read are
142/// the project's own [`sources`](Project::sources) -- every clip names one --
143/// so nothing but the edit list decides what is decoded.
144pub fn start(
145 project: Project,
146 meta: VideoMeta,
147 out: &Path,
148 settings: &ExportSettings,
149) -> ExportHandle {
150 let settings = *settings;
151 let shared = Arc::new(Shared {
152 progress: AtomicU32::new(0),
153 cancel: AtomicBool::new(false),
154 finished: AtomicBool::new(false),
155 outcome: Mutex::new(None),
156 });
157 let worker = Arc::clone(&shared);
158 let out = out.to_path_buf();
159 // `<out>.part`, appended rather than substituted: the temporary of
160 // `a.export.mp4` is `a.export.mp4.part`, which no other export claims.
161 let mut part = out.clone().into_os_string();
162 part.push(".part");
163 let part = PathBuf::from(part);
164 let spawned = thread::Builder::new().name("export".into()).spawn(move || {
165 // The rename is the last step and the only one that publishes a file
166 // under the name the caller asked for; it stays on the same directory,
167 // so it is atomic.
168 let written = match settings.format {
169 Format::Mp4 => run(&project, &meta, &part, &worker, &settings),
170 format => run_audio(&project, &meta, &part, &worker, format),
171 };
172 let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
173 if result.is_err() {
174 // The muxer -- and with it the file handle -- died with `run`.
175 let _ = std::fs::remove_file(&part);
176 }
177 settle(&worker, result);
178 });
179 if let Err(e) = spawned {
180 settle(&shared, Err(e.into()));
181 }
182 ExportHandle { shared }
183}
184
185fn settle(shared: &Shared, result: crate::Result<()>) {
186 *shared.outcome.lock().unwrap() = Some(result);
187 // Published last: a caller that sees the flag is guaranteed the outcome.
188 shared.finished.store(true, Ordering::Release);
189}
190
191fn run(
192 project: &Project,
193 meta: &VideoMeta,
194 out: &Path,
195 shared: &Shared,
196 settings: &ExportSettings,
197) -> crate::Result<()> {
198 let total = project.timeline_frames();
199 let sources = project.sources();
200 // Audio first: a track has to be declared when the muxer is created, which
201 // happens as soon as the first coded picture arrives.
202 //
203 // ponytail: this holds the whole exported AAC track in memory (~3 kB per
204 // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
205 // `copy_segments` that yields packets instead of collecting them.
206 //
207 // The segments name their source, and the copy carries its packet-rounding
208 // debt across a source join exactly as across a cut, so a timeline spanning
209 // files stays in sync. A source whose AAC parameters disagree with the
210 // first one is an `Err` from there -- import refuses those up front, this
211 // is the backstop -- and the caller deletes the `.part`.
212 //
213 // The stream each source is copied from is the one it plays: `audio_sources`
214 // is the same list `PlaybackSession::seek` hands the decoder, so an export
215 // of a timeline playing a file's second audio track carries *that* track.
216 //
217 // One lane, because this path *copies* AAC packets and a mix is not a copy:
218 // summing two lanes means decoding both and encoding the result, and there
219 // is no AAC encoder here to encode it with. Refused by name rather than
220 // silently exporting the first lane -- a file missing half its sound is the
221 // one failure a user would not notice.
222 //
223 // *Which* lane is the same question `audio_segments_from` answers for
224 // playback, and it is asked here rather than assumed: the lane that holds
225 // the sound need not be `A1` (a project may leave `A1` empty and place
226 // everything on `A2`), and copying `A1`'s list in that case would write a
227 // file with no audio track at all -- silently, which is the failure this
228 // whole comment is about.
229 let lanes = project.audio_segments_from(0, meta.frame_rate);
230 let [segments] = &lanes[..] else {
231 return Err(format!(
232 "this timeline has {} audio lanes and an mp4 export copies one: \
233 there is no AAC encoder here to mix them with. Export WAV or FLAC, \
234 which are mixed, or put the sound on one lane",
235 lanes.len()
236 )
237 .into());
238 };
239 // ...and the same list decides which clips this would be copying, which is
240 // the only way to ask whether any of them carries an equalizer. An EQ is
241 // sample math and a copy never decodes: exporting it here would write the
242 // clip flat, silently -- the same failure a missing audio track is. Named by
243 // where it sits on the timeline, because "some clip" is not a thing a user
244 // can go and fix.
245 let lane = project.audio_lanes()[0];
246 if let Some((at, _)) = project
247 .lane(lane)
248 .iter()
249 .enumerate()
250 .find(|(idx, _)| project.eq_of(lane, *idx).is_some_and(|eq| !eq.is_identity()))
251 .map(|(idx, clip)| (clip.start, idx))
252 {
253 return Err(format!(
254 "the clip at {} has an equalizer and an mp4 export copies AAC packets, \
255 which no filter can reach: export WAV or FLAC, which are decoded and \
256 mixed, or clear the equalizer",
257 timecode(at, meta.frame_rate)
258 )
259 .into());
260 }
261 let audio = AudioSession::copy_multi_streams(&project.audio_sources(), segments)?;
262 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
263 freq_index: track.freq_index,
264 chan_conf: track.chan_conf,
265 });
266
267 let mut encoder = Enc::open(meta, settings)?;
268 let mut muxer = None;
269 let mut done = 0u32;
270 let black = Black::new(meta);
271 // Spans, not clips: a gap in the video is part of the timeline and gets
272 // encoded too, as black frames. The picture count is therefore
273 // `timeline_frames` however the lanes are arranged -- and *which* lane a
274 // span comes from is `composite_spans_from`'s answer, the same one playback
275 // shows, so an export is what was watched.
276 for span in project.composite_spans_from(0) {
277 // Every clip reopens its own source file at its own in point; the
278 // encoder is *not* reopened, so the export is one continuous stream
279 // whose GOP boundaries need not line up with the cuts -- nor with the
280 // file boundaries, which are just cuts that change the path.
281 let mut pictures = match span.from {
282 Some((source, in_frame)) => {
283 let entry = sources
284 .get(source)
285 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
286 Some(ClipDecoder::open(&entry.path, in_frame)?)
287 }
288 None => None,
289 };
290 // What this span is graded by -- the same answer playback's decoder
291 // carries, so the export is the picture that was watched. `None` for a
292 // gap and for an ungraded clip, and that is the path where not a byte
293 // is touched. Scratch outside the frame loop: it is refilled per frame
294 // and its allocation survives the whole span.
295 let grade = project.composite_color_at(span.start).copied();
296 let mut graded = (Vec::new(), Vec::new(), Vec::new());
297 // ...and the canvas it is placed on, which is where a source of another
298 // resolution becomes a picture at the project's. The same `Composer`
299 // playback composes with, given the same policy, so an export is what
300 // was watched down to the letterbox; a clip already the project's size
301 // passes through it untouched.
302 let mut canvas = Composer::new(
303 meta.width,
304 meta.height,
305 project.composite_fit_at(span.start),
306 );
307 for _ in 0..span.len {
308 cancelled(shared)?;
309 let picture = match &mut pictures {
310 Some(pictures) => pictures.next()?,
311 None => Some(black.picture()),
312 };
313 let Some((y, u, v, width, height)) = picture else {
314 break; // source ran out early; the clip list outlives the file
315 };
316 // The planes are borrowed from the decoder (and `Black::picture`
317 // hands the same slice as both u and v), so a grade cannot be
318 // applied in place: it goes onto a copy, which the encoder then
319 // reads instead.
320 let (y, u, v) = match grade.filter(|p| !p.is_identity()) {
321 Some(params) => {
322 let (gy, gu, gv) = &mut graded;
323 gy.clear();
324 gy.extend_from_slice(y);
325 gu.clear();
326 gu.extend_from_slice(u);
327 gv.clear();
328 gv.extend_from_slice(v);
329 crate::color::apply_yuv(&params, gy, gu, gv);
330 (&gy[..], &gu[..], &gv[..])
331 }
332 None => (y, u, v),
333 };
334 // Grade first, place second: the grade is the clip's own pixels
335 // and the bars around them are not the clip (see `scale::Composer`).
336 let (y, u, v, width, height) = canvas.place(y, u, v, width, height);
337 if let Some(au) = encoder.encode(y, u, v, width, height)? {
338 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
339 }
340 done += 1;
341 shared
342 .progress
343 .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);
344 }
345 }
346 while let Some(au) = encoder.drain()? {
347 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
348 }
349 // Progress reads 100% from here on, but nothing is published yet: draining,
350 // the audio pass and `finish` are all still cancellable.
351 cancelled(shared)?;
352
353 let Some(mut muxer) = muxer else {
354 return Err("export produced no coded pictures".into());
355 };
356 if let Some((_, packets)) = audio {
357 for packet in packets {
358 muxer.write_audio_packet(&packet.bytes)?;
359 }
360 }
361 cancelled(shared)?;
362 muxer.finish()?;
363 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
364 Ok(())
365}
366
367/// Where a clip sits on the timeline as a person reads it: `mm:ss`, short
368/// enough to sit inside a refusal and exact enough to go and find the clip.
369/// Not the app's frame-accurate timecode -- an engine refusal is prose, and a
370/// `00:00:12:07` in the middle of a sentence is a serial number.
371fn timecode(frame: u32, fps: f64) -> String {
372 let secs = match fps.is_finite() && fps > 0.0 {
373 true => (f64::from(frame) / fps) as u32,
374 false => 0,
375 };
376 format!("{:02}:{:02}", secs / 60, secs % 60)
377}
378
379/// The audio lanes alone, summed, as a WAV or a FLAC.
380///
381/// Nothing here re-derives the edit: the play lists are
382/// [`Project::audio_segments_from`] and they are handed to the very
383/// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written
384/// is what was heard -- every lane, mixed the same way, gaps included, which
385/// arrive as real silence from that choke point rather than as a hole this would
386/// have to invent.
387///
388/// The length is the *timeline's*: each segment resolves its window to whole
389/// samples on its own, so the sum can miss the timeline by a sample or two, and
390/// a source that runs out early would leave the file short. Both are settled by
391/// one `resize` at the end -- padding with silence, trimming what overshot --
392/// so an exported file is exactly as long as what was edited.
393fn run_audio(
394 project: &Project,
395 meta: &VideoMeta,
396 out: &Path,
397 shared: &Shared,
398 format: Format,
399) -> crate::Result<()> {
400 let sources = project.audio_sources();
401 let segs = project.audio_segments_from(0, meta.frame_rate);
402 // The equalizers with them, so what is written is what is heard down to the
403 // filter: the worker applies them per segment before the lanes are summed
404 // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point
405 // playback's feeder reads from -- there is no second place here that could
406 // apply them differently.
407 let eqs = project.audio_eqs_from(0, meta.frame_rate);
408 let Some((audio, chunks)) = AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs)? else {
409 return Err("this timeline has no audio to export".into());
410 };
411 let channels = usize::from(audio.channels);
412 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate
413 * f64::from(audio.sample_rate))
414 .round() as u64;
415 let total = frames as usize * channels;
416 // ponytail: the whole export sits in memory (4 bytes a sample, so ~23 MB
417 // per minute of 48 kHz stereo). `flacenc::MemSource` wants it that way and
418 // the mp4 path already collects its copied AAC track the same. Upgrade path
419 // is hound's incremental writer plus flacenc's `Source` trait.
420 let mut samples: Vec<i32> = Vec::with_capacity(total);
421 for chunk in chunks {
422 cancelled(shared)?;
423 // Already equalized: the chunks come out of the per-lane workers, which
424 // filter each segment before the mix (`open_mixed_streams_eq` above).
425 samples.extend(
426 chunk
427 .samples
428 .iter()
429 .map(|s| (s.clamp(-1.0, 1.0) * f32::from(i16::MAX)).round() as i32),
430 );
431 let done = samples.len().min(total) * PROGRESS_SCALE as usize / total.max(1);
432 shared.progress.store(done as u32, Ordering::Relaxed);
433 }
434 samples.resize(total, 0);
435 // Written in one go and still cancellable up to here, exactly as the mp4
436 // path is up to its `finish`: the `.part` is what either gets renamed or
437 // deleted.
438 cancelled(shared)?;
439 match format {
440 Format::Wav => write_wav(out, &samples, &audio)?,
441 Format::Flac => write_flac(out, &samples, &audio)?,
442 Format::Mp4 => unreachable!("the mp4 path is `run`"),
443 }
444 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
445 Ok(())
446}
447
448/// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in
449/// this engine, so what the decoder handed over is what the header says.
450fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
451 let mut writer = hound::WavWriter::create(
452 out,
453 hound::WavSpec {
454 channels: audio.channels,
455 sample_rate: audio.sample_rate,
456 bits_per_sample: 16,
457 sample_format: hound::SampleFormat::Int,
458 },
459 )?;
460 for &sample in samples {
461 writer.write_sample(sample as i16)?;
462 }
463 // Not `drop`: this is what rewrites the RIFF sizes in the header, and its
464 // failure is the difference between a finished file and a truncated one.
465 writer.finalize()?;
466 Ok(())
467}
468
469/// The same samples, losslessly compressed. `flacenc`'s errors are flattened to
470/// text: they are not `Send + Sync`, and every one of them fails the export the
471/// same way.
472fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
473 let config = flacenc::config::Encoder::default()
474 .into_verified()
475 .map_err(|(_, e)| format!("flac encoder config: {e}"))?;
476 let source = flacenc::source::MemSource::from_samples(
477 samples,
478 usize::from(audio.channels),
479 16,
480 audio.sample_rate as usize,
481 );
482 let mut stream = flacenc::encode_with_fixed_block_size(&config, source, config.block_size)
483 .map_err(|e| format!("flac encode: {e}"))?;
484 // The block sizes are stated fixed, which is what the frames themselves say
485 // (they are numbered, not sample-addressed). flacenc's single-threaded path
486 // instead writes the *last* frame's length as the minimum, and a short final
487 // frame is the normal case -- a stream whose `streaminfo` then disagrees
488 // with its own blocking strategy. ffmpeg shrugs and plays it; symphonia,
489 // which is this engine's own reader, rejects every frame header and reads
490 // to EOF looking for a good one. Written this way the file reopens here,
491 // which is the only test of an export that counts. (Same value flacenc's
492 // own `par` path writes; the reference encoder does it too.)
493 stream
494 .stream_info_mut()
495 .set_block_sizes(config.block_size, config.block_size)
496 .map_err(|e| format!("flac block size: {e}"))?;
497 let mut sink = flacenc::bitsink::ByteSink::new();
498 stream
499 .write(&mut sink)
500 .map_err(|e| format!("flac write: {e}"))?;
501 std::fs::write(out, sink.as_slice())?;
502 Ok(())
503}
504
505/// The I420 planes of one black picture, allocated once for a whole export: a
506/// gap in the video lane is encoded, not skipped, or every frame after it would
507/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention
508/// [`crate::convert`] decodes with.
509struct Black {
510 y: Vec<u8>,
511 uv: Vec<u8>,
512 width: u32,
513 height: u32,
514}
515
516impl Black {
517 fn new(meta: &VideoMeta) -> Self {
518 let (w, h) = (meta.width as usize, meta.height as usize);
519 Self {
520 y: vec![16; w * h],
521 uv: vec![128; w.div_ceil(2) * h.div_ceil(2)],
522 width: meta.width,
523 height: meta.height,
524 }
525 }
526
527 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
528 (&self.y, &self.uv, &self.uv, self.width, self.height)
529 }
530}
531
532/// `Err` once a cancel has been asked for. Called at every point where the work
533/// left is more than an instant, so an `esc` at 99.9% still stops the export
534/// instead of quietly completing it.
535fn cancelled(shared: &Shared) -> crate::Result<()> {
536 if shared.cancel.load(Ordering::Relaxed) {
537 return Err("export cancelled".into());
538 }
539 Ok(())
540}
541
542/// Writes one access unit, creating the file on the first one -- the parameter
543/// sets for `avcC` only exist once the encoder has coded something. Units with
544/// no coded slice are skipped: a software encoder may hand back an empty buffer
545/// while it buffers, and the muxer rejects a sample that would carry no picture.
546fn write_video(
547 muxer: &mut Option<Mp4Muxer>,
548 out: &Path,
549 meta: &VideoMeta,
550 audio: Option<&AudioParams>,
551 au: &[u8],
552) -> crate::Result<()> {
553 if !crate::mux::has_coded_slice(au) {
554 return Ok(());
555 }
556 let muxer = match muxer {
557 Some(muxer) => muxer,
558 none => {
559 let (sps, pps) = crate::mux::parameter_sets(au)
560 .ok_or("the first coded picture carries no SPS/PPS")?;
561 none.insert(Mp4Muxer::create(
562 out,
563 &VideoParams {
564 width: meta.width,
565 height: meta.height,
566 frame_rate: meta.frame_rate,
567 sps,
568 pps,
569 },
570 audio,
571 )?)
572 }
573 };
574 muxer.write_video_au(au)
575}
576
577fn bitrate_for(meta: &VideoMeta) -> u64 {
578 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;
579 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)
580}
581
582fn forced(var: &str) -> bool {
583 std::env::var_os(var).is_some_and(|v| v == "1")
584}
585
586/// Hardware where it is available, software everywhere else -- chosen once for
587/// the whole export, so the stream never changes encoder mid-file.
588enum Enc {
589 Hw(HwEncoder),
590 Sw {
591 encoder: Encoder,
592 /// The last access unit; owned because `rusty_h264` hands back a `Vec`
593 /// while the plugin lends a slice, and the two have to look alike here.
594 au: Vec<u8>,
595 flushed: bool,
596 },
597}
598
599impl Enc {
600 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
601 // A caller's number goes through the same clamp as the computed one: a
602 // zero bitrate switches the software encoder's lookahead on, which would
603 // break the one-picture-per-call contract `encode` documents below.
604 let bitrate = settings
605 .bitrate
606 .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE));
607 // The plugin wants an exact rational, and the muxer already picks one
608 // that is exact at every rate we can read -- `fps * 1000 / 1000` would
609 // hand 24000/1001 over as a rounded 23.976, which is the same
610 // truncation the container timing had.
611 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
612 if !settings.force_sw
613 && !forced("VE_SW_ENC")
614 && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate)
615 {
616 eprintln!("export encoder: hardware (VA-API plugin)");
617 return Ok(Self::Hw(hw));
618 }
619 eprintln!("export encoder: software (rusty_h264)");
620 let mut cfg = EncoderConfig::new(meta.width as usize, meta.height as usize);
621 cfg.framerate = meta.frame_rate as f32;
622 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;
623 // Two seconds between key frames, and no B-frames on either path: the
624 // muxer times everything by duration alone, which reordering would break.
625 cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32;
626 cfg.bframes = 0;
627 // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same
628 // bitrate, so Fast is what a fallback should be.
629 cfg.preset = Preset::Fast;
630 let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?;
631 Ok(Self::Sw {
632 encoder,
633 au: Vec::new(),
634 flushed: false,
635 })
636 }
637
638 /// One picture in, at most one access unit out.
639 ///
640 /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer
641 /// when its lookahead is active, which would make this "one access unit"
642 /// a lie and every sample duration with it. It is inactive here because
643 /// lookahead needs a zero bitrate and this path is always CBR; a future
644 /// constant-QP mode has to split the buffer per access unit first.
645 fn encode(
646 &mut self,
647 y: &[u8],
648 u: &[u8],
649 v: &[u8],
650 width: u32,
651 height: u32,
652 ) -> crate::Result<Option<&[u8]>> {
653 match self {
654 Self::Hw(hw) => hw.encode(y, u, v, width, height, false),
655 Self::Sw { encoder, au, .. } => {
656 let frame = YuvFrame {
657 width: width as usize,
658 height: height as usize,
659 y: y.to_vec(),
660 u: u.to_vec(),
661 v: v.to_vec(),
662 };
663 *au = encoder
664 .try_encode(&frame)
665 .map_err(|e| format!("software encode: {e}"))?;
666 Ok(Some(&au[..]).filter(|au| !au.is_empty()))
667 }
668 }
669 }
670
671 /// End of stream; call until it returns `None`.
672 fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
673 match self {
674 Self::Hw(hw) => hw.drain(),
675 Self::Sw {
676 encoder,
677 au,
678 flushed,
679 } => {
680 if *flushed {
681 return Ok(None);
682 }
683 *flushed = true;
684 *au = encoder
685 .try_flush()
686 .map_err(|e| format!("software encoder flush: {e}"))?;
687 Ok(Some(&au[..]).filter(|au| !au.is_empty()))
688 }
689 }
690 }
691}
692
693/// I420 straight out of the decoder: the export never converts to BGRA and back,
694/// which would cost two conversions and a generation of colour precision.
695///
696/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`,
697/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to
698/// software: a hardware decode that fails after the first picture fails the
699/// export, which then deletes the half-written file.
700enum ClipDecoder {
701 Hw(HwSession),
702 Sw(SwDecoder),
703}
704
705impl ClipDecoder {
706 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
707 if !forced("VE_SW")
708 && let Some(hw) = HwSession::open_at(path, start_frame)
709 {
710 return Ok(Self::Hw(hw));
711 }
712 Ok(Self::Sw(SwDecoder::open(path, start_frame)?))
713 }
714
715 /// The next picture as tightly packed I420, borrowed until the call after.
716 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
717 match self {
718 Self::Hw(hw) => hw.next_frame(),
719 Self::Sw(sw) => {
720 if !sw.advance()? {
721 return Ok(None);
722 }
723 let frame = sw.frame.as_ref().expect("advance stored a picture");
724 Ok(Some((
725 &frame.y,
726 &frame.u,
727 &frame.v,
728 frame.width as u32,
729 frame.height as u32,
730 )))
731 }
732 }
733 }
734}
735
736struct SwDecoder {
737 demuxer: Demuxer,
738 decoder: Decoder,
739 /// Display index of the next picture the decoder will produce. Signed: a
740 /// sync sample inside what the edit list trims is before frame 0.
741 index: i64,
742 start: u32,
743 frame: Option<YuvFrame>,
744}
745
746impl SwDecoder {
747 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
748 let (meta, mut demuxer) = Demuxer::open(path)?;
749 // The software decoder is H.264-only; an HEVC or VP9 source that got
750 // this far means the plugin refused it, and the export says so instead
751 // of handing those bytes to `rusty_h264`.
752 if meta.codec != crate::demux::Codec::H264 {
753 return Err(meta.codec.needs_plugin().into());
754 }
755 // Decoding restarts at a sync sample, so pictures between it and the in
756 // point are decoded (the target references them) and then dropped.
757 let index = demuxer.seek_to_sync_at_or_before(start_frame);
758 Ok(Self {
759 demuxer,
760 decoder: Decoder::new(),
761 index,
762 start: start_frame,
763 frame: None,
764 })
765 }
766
767 /// Decodes up to and including the next picture at or after the in point,
768 /// leaving it in `frame`. `false` at end of stream.
769 fn advance(&mut self) -> crate::Result<bool> {
770 loop {
771 let Some(au) = self.demuxer.next_access_unit()? else {
772 return Ok(false);
773 };
774 let decoded = self
775 .decoder
776 .decode(&au)
777 .map_err(|e| format!("decode at picture {}: {e}", self.index))?;
778 let Some(yuv) = decoded else { continue };
779 let wanted = self.index >= i64::from(self.start);
780 self.index += 1;
781 if wanted {
782 self.frame = Some(yuv);
783 return Ok(true);
784 }
785 }
786 }
787}
788
789#[cfg(test)]
790mod tests {
791 use super::*;
792
793 #[test]
794 fn bitrate_clamps_at_both_ends() {
795 let meta = |width, height, frame_rate| VideoMeta {
796 width,
797 height,
798 frame_rate,
799 frame_count: 1,
800 codec: crate::demux::Codec::H264,
801 };
802 // 1280 * 720 * 30 * 0.1
803 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
804 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny");
805 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
806 }
807}