forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB3fc6753Tahinli3 months ago345 commits

export.rs3659 lines, 169.6 KiBHistoryRawDownload
1//! Export: the edit list rendered back out as one mp4 (H.264, AV1 or HEVC) or
2//! one Matroska file (AV1 or HEVC) — or, picture left behind, as one WAV, FLAC,
3//! MP3 or Ogg Vorbis of the timeline's audio alone.
4//!
5//! The HEVC pair is **intra-only**, and says so wherever it is offered: every
6//! frame is a self-contained IDR from the vendored `oxideav-h265`, which is the
7//! only shape of a pure-Rust HEVC encode fast enough to wait for (its inter
8//! modes code 1080p at 0.81 fps across 12 cores against the intra path's 4.30).
9//! That makes it an intraframe master in the family of ProRes and DNxHD — large
10//! files, every frame a cut point — and not a delivery codec.
11//!
12//! Picture and sound are both **copied wherever a copy says exactly what the
13//! timeline says** — a copy is exact, free and never a generation of loss. For
14//! the sound that is packet for packet ([`copy_audio`]); for the picture it is
15//! block for block out of a Matroska source into a Matroska file ([`CopyPlan`]),
16//! which is what makes a cut in a two-hour film cost the reading of it rather
17//! than the re-encoding of it. The picture's copy is all-or-nothing per export,
18//! because a copied span and an encoded one cannot share one track: what it
19//! needs of a cut is that it lands on a sync point, and everything else — a
20//! grade, a speed, a gap, a source of another size or codec, an mp4 — goes
21//! through the encoder exactly as it always did. Where the *sound* cannot be
22//! copied — a second audio lane to mix in, a speeded clip, an
23//! equalized one, a source that is not AAC inside an mp4's own sample table —
24//! the sound is decoded, mixed and encoded again with `rusty_aac`
25//! ([`encode_audio`]). The audio-only formats have no such split: `hound` writes
26//! PCM, `flacenc` encodes FLAC, `rusty_mp3` encodes MP3 and `rusty_vorbis`
27//! encodes Vorbis, so those are always *decoded* out of the timeline. The worker owns everything: the caller gets an
28//! [`ExportHandle`] and polls it from its render loop.
29//!
30//! **Every video format here carries the timeline's sound**, in whichever
31//! container: the mp4 muxer writes an AAC track and so does the Matroska one.
32//! Nothing is written picture-only and nothing is left silent without saying so
33//! — the only sound that does not come out is sound this engine cannot decode at
34//! all (Opus and AC-3 inside a Matroska file), and that is an error by name.
35//!
36//! A **speeded** clip splits along the same line, and for the same reason. The
37//! picture is re-encoded, so the frame walk honours a rate: it takes the source
38//! frame each timeline frame shows ([`crate::project::Speed::source_at`], the
39//! very frame preview holds there) and encodes a held one again rather than
40//! decoding it twice. A clip whose *file* was shot at another rate than the
41//! timeline goes through the same walk with one more conversion on the end
42//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at.
43//! The sound is *copied* unless something forces a decode, and a packet carries
44//! no rate — so a speeded lane is one of the things that forces one
45//! ([`copy_audio`]) rather than being written out at 1.00x under a re-timed
46//! picture. The audio-only formats are decoded and resampled, so they honour a
47//! rate like the picture does.
48//!
49//! Nothing partial survives a failure: the worker writes to `<out>.part` and
50//! renames it onto `out` only once the file is closed and complete, so the
51//! output either does not exist or is finished — there is no window where a
52//! half-written `.export.mp4` is sitting there looking playable. Cancel and
53//! every error path delete the `.part`. A killed *process* leaves the `.part`
54//! behind (only in-process cleanup is promised), which is an orphan a user can
55//! delete rather than a file that plays for two seconds and stops.
56
57use std::fs::File;
58use std::io::{BufWriter, Write};
59use std::path::{Path, PathBuf};
60use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
61use std::sync::{Arc, Mutex};
62use std::thread;
63
64use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame};
65
66use flacenc::component::BitRepr;
67use flacenc::error::Verify;
68// The trait the Ogg muxer's `write_header` / `write_packet` / `write_trailer`
69// live on -- `oxideav_ogg::mux::open_concrete` hands back the concrete muxer
70// (the only way to reach `set_page_target_bytes`), so the trait has to be here.
71use oxideav_core::Muxer as _;
72
73use crate::audio::{AudioMeta, AudioSession};
74use crate::colorspace::{ColorDescription, Matrix, Transfer};
75use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta};
76use crate::hw::{HwEncoder, HwSession};
77use crate::mux::{
78 AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams,
79};
80use crate::project::{LaneKind, Project, Rate};
81use crate::scale::Composer;
82use crate::subtitle::{Cue, SubtitleTrack};
83use crate::tonemap::{self, ToneMapper};
84
85/// Progress is reported in permille: an atomic integer the render loop can read
86/// without a lock, fine enough for any progress bar.
87const PROGRESS_SCALE: u32 = 1_000;
88
89/// The head of the bar the *sound* owns, before a picture is written at all.
90/// The mix is decoded, encoded and measured before the muxer exists ([`run`]
91/// says why), and on a feature film that is a minute or two in which a bar
92/// pinned at zero is the only thing on screen -- which reads as an export that
93/// has hung. Small, because the picture is still nearly all of the work.
94const AUDIO_BAND: u32 = PROGRESS_SCALE / 20;
95
96/// Where the bar stands with `done` of `total` pictures written: the sound's
97/// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is
98/// left rather than starting again from zero.
99fn picture_progress(done: u32, total: u32) -> u32 {
100 AUDIO_BAND + done.min(total) * (PROGRESS_SCALE - AUDIO_BAND) / total.max(1)
101}
102
103/// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
104/// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%.
105const BITS_PER_PIXEL: f64 = 0.1;
106const MIN_BITRATE: u64 = 1_000_000;
107const MAX_BITRATE: u64 = 20_000_000;
108
109/// The rates the sound may be coded at, smallest first -- what a front-end
110/// offers and what [`ExportSettings::audio_kbps`] is clamped into. Every one of
111/// them is a legal MPEG-1 Layer III value, so the MP3 path writes the figure it
112/// was given rather than the nearest one `rusty_mp3` snaps to.
113pub const AUDIO_KBPS: [u32; 4] = [128, 192, 256, 320];
114
115/// What the sound is coded at when nobody picked: the rate this project wrote
116/// before the choice existed. 256 and not the encoders' own 128, because an
117/// export is a master a person edits from again and this is a second lossy
118/// generation over sources that may already have been one -- measured on the
119/// suite's fixtures, an untouched clip re-encoded moves 0.15 dB here against
120/// 0.46 dB at 128, and 32 KB/s beside a 2.76 Mbps picture is not a size anyone
121/// is counting.
122pub const DEFAULT_AUDIO_KBPS: u32 = 256;
123
124/// `rav1e`'s fastest preset. Anything slower is minutes per second of timeline
125/// on a build with no assembly, which is what this one is.
126const AV1_SPEED: u8 = 10;
127
128/// The HEVC coding tree block this encoder is fixed at: the coded picture is a
129/// whole number of them, which is what the conformance window crops back.
130const CTB: usize = 16;
131/// How many frames the intra HEVC encoder codes at once. Twelve is where the
132/// 2026-08-11 bench stopped scaling on this box (4.30 fps at 1080p); more lanes
133/// only holds more decoded frames in memory.
134const HEVC_LANES: usize = 12;
135/// Bits per pixel the intra encoder spends at QP 27, measured on the same bench:
136/// 0.607 at 720p and 0.586 at 1080p. What [`hevc_qp`] maps a bitrate row through.
137const HEVC_BPP_AT_27: f64 = 0.6;
138/// The band [`hevc_qp`] is clamped into, for the reason stated there.
139const HEVC_QP_MIN: i32 = 22;
140const HEVC_QP_MAX: i32 = 40;
141
142/// What an export writes. H.264-in-mp4, AV1 and HEVC -- each of the last two in
143/// Matroska or in mp4, the user's pick of container -- are the *video* pairs
144/// with both an encoder and a decoder under this project's no-install rule, and
145/// WAV, FLAC, MP3 and Ogg Vorbis are the standalone audio formats with a
146/// pure-Rust encoder: `hound`, `flacenc`, `rusty_mp3` and `rusty_vorbis`. Opus
147/// still has none -- `oxideav-opus` encodes CELT alone, which is half a codec.
148/// (AAC has one too -- `rusty_aac`, which is what a re-encoded video track's
149/// sound leaves through -- but AAC is a container's own audio, never a file of
150/// its own here.) VP9 is the
151/// one codec left that comes in through the plugin and stops there, HEVC having
152/// gained an encoder (an intra-only one, which the rows say). A front-end says
153/// so rather than hiding the row.
154///
155/// **Every video format carries sound.** Which way it carries it is the only
156/// difference: copied packet for packet where a copy can say what the timeline
157/// says, decoded and encoded again ([`encode_audio`]) where it cannot.
158#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
159pub enum Format {
160 /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too,
161 /// where a copy could not carry the edit (a second audio lane to mix in, a
162 /// speeded clip, an equalized one, a source no mp4 sample table holds).
163 #[default]
164 Mp4,
165 /// AV1 in Matroska, with the timeline's AAC beside it: this engine's
166 /// Matroska writer carries an audio track ([`crate::mux::MkvMuxer`]) and its
167 /// reader reads one back, symphonia's `mkv` reader being what
168 /// `audio::Track::open` opens it with.
169 Av1,
170 /// The same AV1 stream in an mp4, for everything that plays mp4 and not
171 /// Matroska. The sample entry `mp4 0.14` cannot write is written by hand
172 /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own,
173 /// unchanged.
174 Av1Mp4,
175 /// HEVC in Matroska, **intra-only**: every frame is a self-contained IDR
176 /// picture ([`Enc::open_hevc`]), which is what makes a pure-Rust HEVC
177 /// encoder fast enough to be an export at all. An intraframe master, like
178 /// ProRes or DNxHD -- large files, and every frame a cut point.
179 Hevc,
180 /// The same HEVC stream in an mp4 (`hvc1`), for everything that plays mp4
181 /// and not Matroska -- the AV1 pair's split, for the same reason.
182 HevcMp4,
183 /// The audio lanes alone, 16-bit PCM.
184 Wav,
185 /// The audio lanes alone, losslessly compressed.
186 Flac,
187 /// The audio lanes alone, MPEG-1 Layer III CBR (`rusty_mp3`) at the rate
188 /// [`ExportSettings::audio_kbps`] asks for.
189 Mp3,
190 /// The audio lanes alone, Vorbis I in an Ogg container -- `rusty_vorbis`
191 /// encoding, `oxideav-ogg` paging. Quality-coded and not rate-coded, which
192 /// is why [`audio_rate_refusal`] takes the Sound row away here: see
193 /// [`VORBIS_QUALITY`] for the operating point and how it was measured.
194 Ogg,
195}
196
197impl Format {
198 /// The extension a file of this format is named with -- a front-end builds
199 /// the destination path from it, so the name never disagrees with the bytes.
200 pub fn ext(self) -> &'static str {
201 match self {
202 Self::Mp4 | Self::Av1Mp4 | Self::HevcMp4 => "mp4",
203 Self::Av1 | Self::Hevc => "mkv",
204 Self::Wav => "wav",
205 Self::Flac => "flac",
206 Self::Mp3 => "mp3",
207 Self::Ogg => "ogg",
208 }
209 }
210
211 /// Whether this format carries the picture. The bitrate settings are video
212 /// settings and mean nothing to the audio-only ones.
213 pub fn has_video(self) -> bool {
214 matches!(
215 self,
216 Self::Mp4 | Self::Av1 | Self::Av1Mp4 | Self::Hevc | Self::HevcMp4
217 )
218 }
219
220 /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs
221 /// and which of the two AV1 containers is being written are separate
222 /// questions, and this is the first.
223 fn is_av1(self) -> bool {
224 matches!(self, Self::Av1 | Self::Av1Mp4)
225 }
226
227 /// The same question for HEVC, and the same answer for both its containers:
228 /// one encoder, two boxes to put its stream in.
229 fn is_hevc(self) -> bool {
230 matches!(self, Self::Hevc | Self::HevcMp4)
231 }
232
233 /// Whether the file is a Matroska one. Only that container carries this
234 /// project's Opus track ([`encode_opus`]): an mp4 may hold Opus by spec, but
235 /// the crate that writes the mp4s here has no sample entry for it, so the
236 /// mp4 formats stay on AAC and say so.
237 fn is_mkv(self) -> bool {
238 matches!(self, Self::Av1 | Self::Hevc)
239 }
240
241 /// What the format is called where a refusal names it.
242 pub fn name(self) -> &'static str {
243 match self {
244 Self::Mp4 => "an mp4",
245 Self::Av1 => "an AV1 Matroska",
246 Self::Av1Mp4 => "an AV1 mp4",
247 Self::Hevc => "an HEVC Matroska",
248 Self::HevcMp4 => "an HEVC mp4",
249 Self::Wav => "a WAV",
250 Self::Flac => "a FLAC",
251 Self::Mp3 => "an MP3",
252 Self::Ogg => "an Ogg Vorbis",
253 }
254 }
255}
256
257/// What the caller gets to decide about the output. The codec is not among it:
258/// [`Format`] names a container *and* what goes in it, because every pair we
259/// can write is a pair we can also read back.
260#[derive(Debug, Clone, Default, PartialEq, Eq)]
261pub struct ExportSettings {
262 /// Bits per second, clamped to the same sane range the automatic value uses.
263 /// `None` picks it from the picture size and frame rate. Video only.
264 pub bitrate: Option<u64>,
265 /// Skip the hardware encoder even where it is available -- an escape hatch
266 /// for a driver that encodes badly, matching the `VE_SW_ENC` env pin.
267 pub force_sw: bool,
268 /// The file to write. Defaults to [`Format::Mp4`], which is what every
269 /// caller wrote before there was a choice.
270 pub format: Format,
271 /// What the *sound* is coded at, in kbps, wherever an encoder writes it --
272 /// the AAC of a video export as much as an MP3. `None` is
273 /// [`DEFAULT_AUDIO_KBPS`], which is what every caller wrote before there
274 /// was a choice, so a settings value nobody touched writes the same bytes
275 /// it used to. Means nothing to WAV and FLAC, which code no rate, and
276 /// nothing to a *copied* AAC track, which carries its source's.
277 pub audio_kbps: Option<u32>,
278 /// Which of the project's subtitle tracks travel with the file: indices into
279 /// [`Project::subtitles`], which is the same list a front-end picks rows of.
280 /// As many as the timeline holds, in the order given -- the file declares
281 /// them in that order and a player's subtitle menu lists them in it. Empty
282 /// writes none -- what every caller wrote before there was a choice, so an
283 /// export of a timeline without subtitles is the file it always was, byte
284 /// for byte.
285 ///
286 /// Every container that carries picture carries them: Matroska as
287 /// `S_TEXT/UTF8` blocks, an mp4 as a `tx3g` timed-text track
288 /// ([`crate::mux::Mp4Muxer::write_subtitles`]). A Matroska block names its
289 /// track in one byte, so a Matroska file carries at most
290 /// [`crate::mux::MAX_SUB_TRACKS`] of them and asking for more is refused by
291 /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has
292 /// no such ceiling.
293 pub subtitles: Vec<usize>,
294}
295
296struct Shared {
297 progress: AtomicU32,
298 cancel: AtomicBool,
299 finished: AtomicBool,
300 outcome: Mutex<Option<crate::Result<()>>>,
301 /// The encoders this job really opened, published the moment they are
302 /// chosen and never changed after -- one seat for the whole file, which is
303 /// what [`Enc`] states. `None` until then.
304 encoders: Mutex<Option<String>>,
305}
306
307/// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
308/// rendered frame and take the [`result`](ExportHandle::result) when it flips;
309/// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel)
310/// does.
311pub struct ExportHandle {
312 shared: Arc<Shared>,
313}
314
315impl ExportHandle {
316 /// Fraction of the timeline written, `0.0..=1.0`.
317 pub fn progress(&self) -> f32 {
318 self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32
319 }
320
321 /// Asks the worker to stop at its next checkpoint and delete the partial
322 /// file. The outcome then reports the cancellation as an error. Checkpoints
323 /// run to the last instant before the rename, so even a cancel at full
324 /// progress leaves no output.
325 pub fn cancel(&self) {
326 self.shared.cancel.store(true, Ordering::Relaxed);
327 }
328
329 pub fn is_finished(&self) -> bool {
330 self.shared.finished.load(Ordering::Acquire)
331 }
332
333 /// What this export is encoding with -- the video seat and what the sound
334 /// is doing -- as the worker chose them, hardware fallback included.
335 /// `None` for the first instants of a job, before the encoder is open.
336 pub fn encoders(&self) -> Option<String> {
337 self.shared.encoders.lock().unwrap().clone()
338 }
339
340 /// The outcome, once — taken out of the handle, so a caller that already
341 /// reported it sees `None` afterwards. `None` while the export is running.
342 pub fn result(&self) -> Option<crate::Result<()>> {
343 self.shared.outcome.lock().unwrap().take()
344 }
345}
346
347/// Starts the worker. Failures are reported through the handle rather than
348/// returned, so a caller has exactly one place to look. The files to read are
349/// the project's own [`sources`](Project::sources) -- every clip names one --
350/// so nothing but the edit list decides what is decoded.
351pub fn start(
352 project: Project,
353 meta: VideoMeta,
354 out: &Path,
355 settings: &ExportSettings,
356) -> ExportHandle {
357 let settings = settings.clone();
358 let shared = Arc::new(Shared {
359 progress: AtomicU32::new(0),
360 cancel: AtomicBool::new(false),
361 finished: AtomicBool::new(false),
362 outcome: Mutex::new(None),
363 encoders: Mutex::new(None),
364 });
365 let worker = Arc::clone(&shared);
366 let out = out.to_path_buf();
367 // `<out>.part`, appended rather than substituted: the temporary of
368 // `a.export.mp4` is `a.export.mp4.part`, which no other export claims.
369 let mut part = out.clone().into_os_string();
370 part.push(".part");
371 let part = PathBuf::from(part);
372 let spawned = thread::Builder::new().name("export".into()).spawn(move || {
373 // The rename is the last step and the only one that publishes a file
374 // under the name the caller asked for; it stays on the same directory,
375 // so it is atomic.
376 //
377 // An emptied timeline is a legal project and an illegal file: no
378 // picture, no sound, and a muxer that is never created because no coded
379 // frame arrives. Refused by name here -- before the format is even
380 // looked at, so an mp4 and a WAV refuse in the same words -- rather than
381 // left to write a file of no frames that nothing opens. Every caller of
382 // `start` comes through this, the app's own door
383 // (`PlaybackSession::is_empty`) being only the first fence.
384 //
385 // An audio-only timeline is the other legal project no mp4 can be made
386 // of: every frame of it is a gap, so the file would be black picture
387 // over the sound -- minutes of encoding for a video of nothing. Refused
388 // by name, with the two formats that *are* that timeline, rather than
389 // written; the app says the same on the format row before a destination
390 // is even picked (`mp4_refusal`).
391 let written = match settings.format {
392 _ if project.timeline_frames() == 0 => {
393 Err("the timeline is empty: there is nothing to export".into())
394 }
395 format if format.has_video() && !has_picture(&project) => Err(format!(
396 "the timeline has no picture: {} would be black. Export WAV, \
397 FLAC or MP3, which are the sound itself",
398 format.name()
399 )
400 .into()),
401 format if format.has_video() => run(&project, &meta, &part, &worker, &settings),
402 _ => run_audio(&project, &meta, &part, &worker, &settings),
403 };
404 let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
405 if result.is_err() {
406 // The muxer -- and with it the file handle -- died with `run`.
407 let _ = std::fs::remove_file(&part);
408 }
409 settle(&worker, result);
410 });
411 if let Err(e) = spawned {
412 settle(&shared, Err(e.into()));
413 }
414 ExportHandle { shared }
415}
416
417/// Whether any video lane holds anything at all -- what tells an audio-only
418/// timeline from one that merely opens on a gap. Asked of the *lanes* rather
419/// than of the sources, because a project may name a video file no clip plays
420/// from any more.
421fn has_picture(project: &Project) -> bool {
422 project
423 .lanes()
424 .into_iter()
425 .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty())
426}
427
428/// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a
429/// timeline whose export will carry sound from one whose file has none.
430fn has_sound(project: &Project) -> bool {
431 project
432 .lanes()
433 .into_iter()
434 .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty())
435}
436
437/// Whether any equalizer on the sound is doing something -- the one edit a
438/// packet copy cannot carry, so an mp4 whose lane has one is decoded and
439/// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane:
440/// the copy path has exactly one by the time it asks, and [`planned_audio`] is
441/// asked before that is settled.
442fn equalized(project: &Project) -> bool {
443 project.audio_lanes().into_iter().any(|lane| {
444 (0..project.lane(lane).len())
445 .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity()))
446 })
447}
448
449/// Whether the *mix* is doing something -- a lane turned off unity, or a
450/// limiter in circuit. [`equalized`]'s pair, and a copy cannot carry either of
451/// them: both live where the lanes are summed
452/// ([`AudioSession::open_mixed_streams_master`]), and a copied packet was never
453/// summed at all. An mp4 whose timeline is mixed is decoded and re-encoded.
454fn mastered(project: &Project) -> bool {
455 project.limiter().is_active() || project.audio_gains().iter().any(|&g| g != 1.0)
456}
457
458/// The bitrate an export codes at: the caller's number through the same clamp
459/// as the computed one, for the reason [`Enc::open`] states.
460fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 {
461 settings
462 .bitrate
463 .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE))
464}
465
466/// The rate the sound codes at: the caller's pick clamped into the offered
467/// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused,
468/// for [`bitrate_of`]'s reason -- a number out of range is a caller's slip and
469/// not a file worth failing.
470fn audio_kbps_of(settings: &ExportSettings) -> u32 {
471 settings.audio_kbps.map_or(DEFAULT_AUDIO_KBPS, |k| {
472 k.clamp(AUDIO_KBPS[0], AUDIO_KBPS[3])
473 })
474}
475
476/// The hardware seat for these settings, opened exactly as the export opens it
477/// -- the same pins, the same AV1 opt-in, the same dimensions a driver may
478/// refuse -- or `None` where the software encoder takes the file. The single
479/// place that choice is made, which is what lets [`planned_video`] *measure* it
480/// instead of promising it.
481fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
482 if settings.force_sw || forced("VE_SW_ENC") {
483 return None;
484 }
485 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
486 let bitrate = bitrate_of(meta, settings);
487 match settings.format {
488 // The HEVC pair is software only, and not for want of a GPU: the plugin
489 // has no HEVC *encode* entry point at all (`hw::HwEncoder` opens H.264
490 // and AV1), so there is no seat to probe. Said here rather than left to
491 // a failed open, which would read as a driver refusal.
492 format if format.is_hevc() => None,
493 // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both
494 // AV1 formats sit on it: the container is not the encoder's business.
495 format if format.is_av1() && !forced("VE_HW_AV1") => None,
496 format if format.is_av1() => {
497 HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate)
498 }
499 _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate),
500 }
501}
502
503/// How a front-end names a video seat: which of the two encoders has the file,
504/// and which library that is. Not the codec -- a caller shows this beside the
505/// format it picked, and `rav1e` names AV1 as `rusty_h264` names H.264. One
506/// place, so what a card says before an export and what its progress line says
507/// during one cannot drift apart.
508fn video_label(format: Format, hw: bool) -> &'static str {
509 match (format, hw) {
510 (_, true) => "HW encode (VA-API)",
511 (Format::Hevc | Format::HevcMp4, false) => "SW encode (oxideav-h265 intra)",
512 (Format::Av1 | Format::Av1Mp4, false) => "SW encode (rav1e)",
513 (_, false) => "SW encode (rusty_h264)",
514 }
515}
516
517/// The cheap half of "does this timeline's sound have to be re-encoded": what
518/// the *edit* says, with no file opened. Two lanes are a mix and a mix is not a
519/// copy; a speeded lane is resampled; an equalizer is sample math. The other
520/// half -- whether the sources can be copied out of at all -- costs a file open
521/// each and belongs to [`copy_audio`], which may re-encode where this says copy.
522fn forces_encode(project: &Project) -> bool {
523 let lanes: Vec<_> = project
524 .audio_lanes()
525 .into_iter()
526 .filter(|&lane| !project.lane(lane).is_empty())
527 .collect();
528 lanes.len() > 1
529 || lanes
530 .iter()
531 .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal()))
532 || equalized(project)
533 || mastered(project)
534}
535
536/// What the sound is written by. Every audio encoder here is software -- there
537/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and
538/// whether a container escapes encoding altogether by copying the packets it was
539/// given. Both AV1 formats are in it like the mp4: an AV1 export carries the
540/// timeline's sound too, so leaving it unnamed would be the old lie.
541///
542/// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a
543/// card asking before the export has no way to know (a source that cannot be
544/// copied out of is only found by opening it). `None` predicts from the edit
545/// alone.
546fn audio_label(
547 project: &Project,
548 format: Format,
549 sound: bool,
550 copied: Option<bool>,
551) -> &'static str {
552 if !sound {
553 return "no sound to write";
554 }
555 match format {
556 Format::Wav => "PCM · SW (hound)",
557 Format::Flac => "FLAC · SW (flacenc)",
558 Format::Mp3 => "MP3 · SW (rusty_mp3)",
559 Format::Ogg => "Vorbis · SW (rusty_vorbis)",
560 _ => match copied.unwrap_or(!forces_encode(project)) {
561 true => "AAC copy",
562 // A Matroska file gets Opus where the mix allows it -- 48 kHz and
563 // stereo, which is every Opus source and most of everything else --
564 // and AAC where it does not ([`encode_audio`]). Which of the two it
565 // will be cannot be known here: both answers need a source opened,
566 // and this function may be asked per repaint. So the card names the
567 // codec it will nearly always be, as a prediction like the copy above
568 // it, and the line the export publishes while it runs is the measured
569 // one ([`run`]) -- it says AAC when the fallback took it, so the
570 // fallback is visible rather than silent.
571 //
572 // It is one line and 76 characters wide (`summary_head` in the app
573 // has the test), which is why the condition is in this comment
574 // instead of in the string.
575 false if format.is_mkv() => "Opus · SW encode (opus-rs)",
576 false => "AAC · SW encode (rusty_aac)",
577 },
578 }
579}
580
581/// What [`start`] would write this timeline's sound with, before one is
582/// started. Pure: no probe and no file opened, so a card may ask it per repaint.
583pub fn planned_audio(project: &Project, format: Format) -> &'static str {
584 audio_label(project, format, has_sound(project), None)
585}
586
587/// Why the sound's rate is nothing this timeline can be asked about in this
588/// format, or `None` where it is a real choice: there is no sound to write, the
589/// format codes the samples themselves, or the packets are the source's own and
590/// carry the rate *it* was coded at. Pure, like [`planned_audio`], and a
591/// prediction in the same way -- a copy that turns out impossible (a source no
592/// mp4 sample table holds) falls through to [`encode_audio`], which codes at
593/// [`ExportSettings::audio_kbps`] like every other encode. So the value travels
594/// even where this refuses; what it cannot do is silently write a rate nobody
595/// picked.
596pub fn audio_rate_refusal(project: &Project, format: Format) -> Option<&'static str> {
597 match format {
598 _ if !has_sound(project) => Some("no sound to write"),
599 Format::Wav | Format::Flac => Some("lossless — the samples themselves, at no rate"),
600 // Vorbis has a quality knob and no rate knob, and the two are not the
601 // same control wearing different words: measured across this suite's
602 // fixtures, the whole usable quality band lands between 55 and 175 kbps
603 // ([`VORBIS_QUALITY`]), so two of the four rates on offer here are not
604 // rates it can reach at all. A live row would print a figure the file
605 // does not hold, which is the one thing this card is built not to do.
606 Format::Ogg => Some("quality-coded — Vorbis holds no rate to pick"),
607 Format::Mp3 => None,
608 _ if forces_encode(project) => None,
609 _ => Some("the source's own packets are copied — at the rate they hold"),
610 }
611}
612
613/// The tracks an export carries, in the order they were picked, and empty where
614/// it carries none: no pick, a pick nothing answers, a track that could not be
615/// read, one with no cue left on the exported timeline -- and every format that
616/// is the sound alone, which has nowhere to put them. Filtered *per track*, so
617/// one unusable pick costs its own row and not the others.
618///
619/// Both containers, since the mp4 muxer gained its `tx3g` track: what the two
620/// do with the very same [`SubParams`] is theirs to say
621/// ([`crate::mux::Mp4Muxer::write_subtitles`], [`MkvMuxer`]), and nothing here
622/// asks which one is being written.
623fn export_subtitles(
624 project: &Project,
625 meta: &VideoMeta,
626 settings: &ExportSettings,
627) -> Vec<SubParams> {
628 if !settings.format.has_video() {
629 return Vec::new();
630 }
631 settings
632 .subtitles
633 .iter()
634 .filter_map(|&pick| {
635 let track = project.subtitles().get(pick)?;
636 // A picture is not a line: the muxer writes an `S_TEXT/UTF8` track
637 // and a PGS cue has no words to put in one. `planned_subtitles` says
638 // so before the button is pressed rather than the file coming out
639 // short.
640 if track.refused.is_some() || track.is_bitmap() {
641 return None;
642 }
643 let cues = timeline_cues(project, track, meta.frame_rate);
644 // The container's own two fields, carried as two
645 // ([`SubtitleTrack::language`]): a `TrackEntry` with no `Language`
646 // means `eng` by spec, so a French track that arrives here as one
647 // flattened string leaves as an English one.
648 (!cues.is_empty()).then(|| SubParams {
649 language: track.language.clone(),
650 name: track.name.clone(),
651 cues,
652 })
653 })
654 .collect()
655}
656
657/// The track's cues where the *exported* timeline puts them, which is the only
658/// clock the file has: the export writes timeline frame 0 onwards and nothing
659/// else, exactly as the sound is mixed from frame 0 and resized to the
660/// timeline's own length ([`encode_audio`]).
661///
662/// Which clock the cues arrive in is what the track itself says:
663///
664/// * a track out of a *file* (`SubtitleTrack::track`) is timed against that
665/// file, so each cue is carried through the spans that play it -- a cue over
666/// a stretch that was cut out is gone, one straddling a cut keeps the half
667/// that is still there, and one after a rippled delete moves back with the
668/// picture it belongs to. The *edges* a cut clips to are frames -- that is
669/// what a cut is -- but a cue nothing clipped keeps its own microseconds, so
670/// an untouched timeline exports the times the source states.
671/// * a *standalone* file (`subs.srt`) is timed against nothing else -- there is
672/// no clip to hang it on and no offset in the project to shift it by -- so it
673/// is the timeline's own clock, which is where it was drawn while editing
674/// (`Player::subtitle_overlay`). Clipped to the exported length and no more.
675///
676/// This is also what the *preview* draws: the plate over the picture and the
677/// timeline strip both ask it through
678/// [`PlaybackSession::timeline_cues`](crate::PlaybackSession::timeline_cues), so
679/// what a rippled timeline shows and what its export writes are one answer by
680/// construction rather than two maps kept in step by hand.
681///
682/// Pure and cheap enough to ask per repaint (a walk of the spans and of the
683/// cues, no file opened), which is how a front-end asks it.
684pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<Cue> {
685 let frames = project.timeline_frames();
686 let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64;
687 let end = us(frames);
688 // The file the cues are timed against, when there is one on this timeline.
689 // A track whose media has since been dropped from the project has no span
690 // to be carried through and falls back to the timeline's clock, which is
691 // what it was drawn on.
692 //
693 // Through the same `canonical` a source is indexed by, or the two spellings
694 // of one file (an argv `../assets/film.mkv`, a symlinked folder) would read
695 // as two files and the cues would quietly fall back to the timeline's clock.
696 let source = track.track.and_then(|_| {
697 let path = crate::project::canonical(&track.path);
698 project.sources().iter().position(|s| s.path == path)
699 });
700 let Some(source) = source else {
701 return track
702 .cues
703 .iter()
704 .filter_map(|cue| {
705 let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end));
706 (end_us > start_us).then(|| Cue {
707 start_us,
708 end_us,
709 text: cue.text.clone(),
710 image: cue.image.clone(),
711 })
712 })
713 .collect();
714 };
715 let mut out = Vec::new();
716 for span in project.composite_spans_from(0) {
717 let Some((_, in_frame)) = span.from.filter(|&(from, _)| from == source) else {
718 continue;
719 };
720 // What of the file this span plays, as *time in the file*: a clip counts
721 // the timeline's frames whatever its file was shot at ([`Rate`]), which
722 // is what makes those frames the same seconds a cue is timed in.
723 let (first, last) = (us(in_frame), us(in_frame + span.source_len()));
724 // Where that lands, and how fast: a cue is carried by the same factor
725 // the pictures under it are, so a slowed clip stretches its subtitles
726 // with it instead of leaving them behind.
727 let start = us(span.start);
728 let onto = |t: i64| start + ((t - first) as f64 / span.speed.as_f64()).round() as i64;
729 for cue in &track.cues {
730 let (a, b) = (cue.start_us.max(first), cue.end_us.min(last));
731 if b <= a {
732 continue; // wholly outside what this span kept
733 }
734 out.push(Cue {
735 start_us: onto(a),
736 end_us: onto(b).min(end),
737 text: cue.text.clone(),
738 image: cue.image.clone(),
739 });
740 }
741 }
742 // The spans come in timeline order but a cue's *own* order across them does
743 // not: a Matroska muxer writes blocks as they come up.
744 out.sort_by_key(|cue| cue.start_us);
745 out
746}
747
748/// What [`start`] would do about the subtitles, in the words a card shows: what
749/// travels, and the reason beside every pick that does not. Pure, like
750/// [`planned_audio`]: no file is opened, so it may be asked per repaint.
751///
752/// `picks` is any run of indices into [`Project::subtitles`] -- an
753/// [`ExportSettings::subtitles`] list (`picks.iter().copied()`) as much as a
754/// single `Some(row)`, which is what a front-end holding one row still hands it.
755pub fn planned_subtitles(
756 project: &Project,
757 format: Format,
758 picks: impl IntoIterator<Item = usize>,
759) -> String {
760 let mut embedded: Vec<&str> = Vec::new();
761 let mut dropped: Vec<String> = Vec::new();
762 let picks: Vec<usize> = picks.into_iter().collect();
763 // One statement about the *file*, said before any about a track: a format
764 // that is the sound alone has nowhere to put a single one of them, and the
765 // reason a pick would not have travelled anyway (a picture track, no cues)
766 // is not the reason it does not travel here. Nothing picked is "none" --
767 // there is nothing to say a container cannot carry.
768 if !picks.is_empty() && !format.has_video() {
769 return "none — this format is the sound alone".into();
770 }
771 for pick in picks {
772 // A pick the project has no row for: a caller holding an index the list
773 // no longer has (a removed row shifts every later one down). Every other
774 // reason a pick does not travel is named on this card, so this one is
775 // too -- a bug that says nothing is a bug found in the finished file.
776 let Some(track) = project.subtitles().get(pick) else {
777 dropped.push(format!("#{pick} — no such track"));
778 continue;
779 };
780 if let Some(why) = &track.refused {
781 dropped.push(format!("{} — {why}", track.label));
782 } else if track.is_bitmap() {
783 // Drawn over the picture, written into no file: the exported track
784 // is text and these cues are bitmaps. Said whatever the format,
785 // because it is the track and not the container that cannot be
786 // carried.
787 dropped.push(format!("{} — pictures; drawn, not written", track.label));
788 } else if track.cues.is_empty() {
789 dropped.push(format!("{} — no cues", track.label));
790 } else {
791 // Whichever container: a Matroska carries the track as
792 // `S_TEXT/UTF8` blocks and an mp4 as a `tx3g` timed-text track, and
793 // a pick travels either way. There is no container refusal left on
794 // this card -- the sound-alone one above is about the *file* and the
795 // ones beside it about the *track*.
796 embedded.push(&track.label);
797 }
798 }
799 let mut parts = match embedded.len() {
800 0 => Vec::new(),
801 1 => vec![format!("{} → embedded", embedded[0])],
802 n => vec![format!("{n} tracks → embedded ({})", embedded.join(", "))],
803 };
804 parts.extend(dropped);
805 match parts.is_empty() {
806 true => "none".into(),
807 false => parts.join("; "),
808 }
809}
810
811/// What [`start`] would encode the picture with, probed the way the export
812/// probes it -- the very encoder is opened and closed again -- so this is a
813/// measurement and not a promise. `None` for a format that carries no picture.
814///
815/// Costs that open (~100 ms here): ask it off a render thread and keep the
816/// answer until the format, the resolution or the bitrate changes.
817pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> {
818 settings
819 .format
820 .has_video()
821 .then(|| video_label(settings.format, hw_seat(meta, settings).is_some()))
822}
823
824/// What [`start`] would open for *this* timeline: the picture's seat -- or the
825/// copy that means there is no encoder at all -- and the sound's, asked of the
826/// very gates the export asks ([`CopyPlan::of`] and [`copy_audio`]'s) rather
827/// than of the format alone.
828///
829/// This exists because the card and the running export used to disagree in both
830/// directions on the same file: the card named a software HEVC encode for a cut
831/// the engine copied, and named an AAC copy for a Matroska source whose sound
832/// no sample table holds and which therefore always re-encodes. A prediction
833/// that is not the decision is worse than no prediction, because a person plans
834/// their evening around it.
835///
836/// Costs what [`planned_video`] costs (an encoder opened and closed) plus a
837/// header read per source and, once per file, its cluster walk: ask it off a
838/// render thread and keep the answer until the timeline or the settings change.
839pub fn planned_seats(
840 project: &Project,
841 meta: &VideoMeta,
842 settings: &ExportSettings,
843) -> (Option<&'static str>, &'static str) {
844 let video = settings.format.has_video().then(|| {
845 match CopyPlan::of(project, meta, settings).is_some() {
846 true => "copy (source packets)",
847 false => video_label(settings.format, hw_seat(meta, settings).is_some()),
848 }
849 });
850 // The half [`audio_label`] cannot know from the format: a copy is a *sample
851 // table's* packets ([`copy_audio`] hands them to `copy_multi_streams`), and
852 // a Matroska file has none -- so every mkv source re-encodes, however
853 // untouched its lane is. Extension only, which is what `is_matroska`
854 // reads, so this costs nothing beyond what is already open.
855 let copyable = !forces_encode(project)
856 && !project
857 .sources()
858 .iter()
859 .any(|source| crate::demux::is_matroska(&source.path));
860 (
861 video,
862 audio_label(project, settings.format, has_sound(project), Some(copyable)),
863 )
864}
865
866fn settle(shared: &Shared, result: crate::Result<()>) {
867 *shared.outcome.lock().unwrap() = Some(result);
868 // Published last: a caller that sees the flag is guaranteed the outcome.
869 shared.finished.store(true, Ordering::Release);
870}
871
872/// The audio track an export writes, and how it was made -- a copy is the
873/// source's own packets, bit for bit, and anything else is this project's
874/// encoder over the decoded mix. [`run`] publishes which of the two really
875/// happened, so the encoder line a user reads is measured and not promised.
876pub(crate) struct ExportAudio {
877 pub params: crate::AacTrackParams,
878 pub packets: Vec<crate::AacPacket>,
879 /// Whether those packets are the source's, untouched.
880 pub copied: bool,
881 /// The track's pre-skip in samples where those packets are **Opus** and not
882 /// AAC ([`encode_opus`]), which is what the Matroska track entry states in
883 /// its `OpusHead` and its `CodecDelay`. `None` is an AAC track, which is
884 /// every copy and every mp4.
885 pub opus_pre_skip: Option<u16>,
886}
887
888/// The timeline's audio track for a file that carries picture: copied packet for
889/// packet where a copy says exactly what the timeline says, and decoded, mixed
890/// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane,
891/// a speeded clip, an equalizer, a source that is not AAC inside an mp4 sample
892/// table. Nothing is refused for being uncopyable any more; the only refusals
893/// left below the copy are about sound this engine cannot *decode* either, and
894/// those come out of the decode path by name.
895///
896/// The copy is still the default and still bit-exact: a timeline nobody has
897/// touched leaves as the very packets its source holds.
898///
899/// ponytail: this holds the whole exported AAC track in memory (~3 kB per
900/// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
901/// `copy_segments` that yields packets instead of collecting them.
902fn copy_audio(
903 project: &Project,
904 meta: &VideoMeta,
905 kbps: u32,
906 mkv: bool,
907 shared: &Shared,
908) -> crate::Result<Option<ExportAudio>> {
909 // The segments name their source, and the copy carries its packet-rounding
910 // debt across a source join exactly as across a cut, so a timeline spanning
911 // files stays in sync. A source whose AAC parameters disagree with the
912 // first one is an `Err` from there -- import refuses those up front, this
913 // is the backstop -- and the caller deletes the `.part`.
914 //
915 // The stream each source is copied from is the one it plays: `audio_sources`
916 // is the same list `PlaybackSession::seek` hands the decoder, so an export
917 // of a timeline playing a file's second audio track carries *that* track.
918 //
919 // One lane is the only shape a *copy* has: summing two means decoding both,
920 // and a sum is not a copy. Two or more go to [`encode_audio`], which is the
921 // very mix the WAV path writes -- it used to be a refusal, and a refusal is
922 // what a file missing half its sound deserves, not what a mix does.
923 //
924 // *Which* lane is the same question `audio_segments_from` answers for
925 // playback, and it is asked here rather than assumed: the lane that holds
926 // the sound need not be `A1` (a project may leave `A1` empty and place
927 // everything on `A2`), and copying `A1`'s list in that case would write a
928 // file with no audio track at all -- silently, which is the failure this
929 // whole comment is about.
930 let lanes = project.audio_segments_from(0, meta.frame_rate);
931 let [segments] = &lanes[..] else {
932 return encode_audio(project, meta, kbps, mkv, shared);
933 };
934 // ...and the same list names *which* lane those clips sit on, which is the
935 // only way to ask what has been done to them.
936 let lane = project.audio_lanes()[0];
937 // ...and the same list decides whether any clip this would copy plays at a
938 // rate other than the one it was recorded at. A copy hands the muxer the
939 // very AAC packets the source holds and there is no rate inside a packet to
940 // change: the picture would come out re-timed (the walk in [`run`] honours
941 // it) over sound at 1.00x, which is the drift a person finds only after the
942 // file has gone somewhere. Decoded and resampled instead, by the same worker
943 // playback feeds from.
944 //
945 // ...and whether any clip on it carries an equalizer, which is sample math a
946 // copy never reaches: copying such a lane would write the clip *flat*,
947 // silently.
948 //
949 // A frame *rate* of its own is not one of those, and that is deliberate: do
950 // not "fix" this into a re-encode. A clip counts the **timeline's** frames
951 // whatever its file was shot at ([`crate::project::Rate`]), so the window
952 // this copy trims a source's sound to is `start..end` in whole timeline
953 // frames -- exactly the seconds the picture covers -- and the file is read
954 // at the pitch it was recorded at, which is what playing at the rate it was
955 // shot at means. There is no per-clip stretch to express, so the packets are
956 // already the right sound in the right place; re-encoding a conformed lane
957 // would buy nothing and cost a generation of loss on every mixed-rate export
958 // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot`
959 // measures the copied sound against the picture). A *speed* is different
960 // because it resamples, which is why it leaves through the re-encode above.
961 //
962 // Only these: a timeline nobody has touched still leaves through the copy
963 // below, packet for packet, so no passthrough quietly becomes a generation
964 // of loss.
965 // ...and whether the mix itself does anything a packet never went through:
966 // a lane volume is applied at the sum and a limiter over it, so copying
967 // such a lane would write it at unity and unlimited, silently.
968 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
969 if speeded || equalized(project) || mastered(project) {
970 return encode_audio(project, meta, kbps, mkv, shared);
971 }
972 // What is left is a copy the *sources* may still not be able to give: AAC
973 // inside a Matroska file (readable, but not out of a sample table this walks
974 // -- there is none), an mp3 or a wav on the timeline, an AC-3 track, two
975 // sources whose AAC parameters disagree. Every one of them decodes, and what
976 // decodes can be encoded again, so the copy's refusal is now a route: the
977 // error a *decode* cannot get past -- Opus or AC-3 inside a Matroska file,
978 // which symphonia has no decoder for at any version -- is the one that comes
979 // back, by name, from [`encode_audio`].
980 match AudioSession::copy_multi_streams(&project.audio_sources(), segments) {
981 Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio {
982 params,
983 packets,
984 copied: true,
985 // A copy is the source's own AAC packets: there is no Opus copy
986 // path here, since the packets an mkv source holds never reach this
987 // (they are not in a sample table) and every one of them re-encodes.
988 opus_pre_skip: None,
989 })),
990 Err(_) => encode_audio(project, meta, kbps, mkv, shared),
991 }
992}
993
994/// The picture's half of [`copy_audio`]: a Matroska export whose every span is
995/// its source's own coded blocks, written back out without a decoder or an
996/// encoder anywhere in the path.
997///
998/// **When.** A copy is entered only where it says *exactly* what the timeline
999/// says, which is the audio gate's rule and not a looser one: the file this
1000/// export writes is Matroska, the source's codec is the one that file would
1001/// carry ([`Format::Hevc`] over HEVC, [`Format::Av1`] over AV1), and nothing on
1002/// the way has touched a sample -- no grade, no speed, no rate conversion, no
1003/// gap to fill with black, no source of another size to place on the canvas,
1004/// no `ContentEncodings` packing to undo. Anything else re-encodes exactly as
1005/// it always did; there is no half-copied file.
1006///
1007/// **All or nothing, per export.** A copied span and an encoded one cannot
1008/// share one track: this project's encoders write 8-bit SDR streams whose
1009/// parameter sets are their own, so splicing them into (say) a Main 10 HDR
1010/// source would change bit depth and colour mid-track, and a container states
1011/// its configuration record once. So the head and tail fragments of a cut that
1012/// lands mid-GOP are *not* re-encoded into the copy -- they are what makes the
1013/// whole export fall back to the encoder. What a copy needs instead is that
1014/// every span begins on a sync point and ends where the next one begins, which
1015/// is what a cut placed on a keyframe gives it.
1016///
1017/// **What a cut costs.** An open-GOP source (x265's default) writes leading
1018/// pictures after a sync point that are shown *before* it and reference the
1019/// group before it. At the start of a copied region those references are not in
1020/// the file, so they are dropped -- the picture before the cut is held for those
1021/// few frames (four at this film's B-depth, a sixth of a second) rather than
1022/// being written as pictures that cannot decode. The region still starts at the
1023/// timeline frame it owns, so the sound never drifts.
1024///
1025/// ponytail: mp4 is not copied (its `hvc1` sample entry forbids in-band
1026/// parameter sets, and the mp4 muxer here writes its sample table from a frame
1027/// counter), and neither is H.264, which this project only writes into mp4. The
1028/// upgrade path for both is a sample-table writer that takes explicit
1029/// timestamps, which is what [`MkvMuxer::write_block`] already is for Matroska.
1030struct CopyPlan {
1031 /// Every source a region reads, by the index the project names it with;
1032 /// `None` for a source no clip plays from.
1033 sources: Vec<Option<MkvDemuxer>>,
1034 regions: Vec<CopyRegion>,
1035 codec_id: &'static [u8],
1036 /// The `CodecPrivate` every region's source agrees on -- a track is declared
1037 /// once, so two sources that disagree about their parameter sets are not one
1038 /// copy.
1039 private: Vec<u8>,
1040 colour: ColorDescription,
1041 width: u32,
1042 height: u32,
1043}
1044
1045/// A run of source blocks copied in one piece: what a cut leaves behind, and
1046/// what two spans that continue each other in the same file merge back into.
1047struct CopyRegion {
1048 source: usize,
1049 /// Blocks of that source, in the file's own decode order.
1050 blocks: std::ops::Range<usize>,
1051 /// The timeline frame the region's first picture is shown at.
1052 start: u32,
1053}
1054
1055impl CopyPlan {
1056 /// The plan for this timeline, or `None` where anything at all makes a copy
1057 /// say something other than what the timeline says -- in which case the
1058 /// caller encodes, which is what it always did.
1059 fn of(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<Self> {
1060 let (codec_id, codec): (&'static [u8], Codec) = match settings.format {
1061 Format::Hevc => (b"V_MPEGH/ISO/HEVC", Codec::Hevc),
1062 Format::Av1 => (b"V_AV1", Codec::Av1),
1063 _ => return None,
1064 };
1065 let entries = project.sources();
1066 let mut sources: Vec<Option<MkvDemuxer>> = (0..entries.len()).map(|_| None).collect();
1067 let mut declared: Option<(Vec<u8>, ColorDescription)> = None;
1068 let mut regions: Vec<CopyRegion> = Vec::new();
1069 for span in project.composite_spans_from(0) {
1070 // A gap is black frames, which only an encoder makes.
1071 let (source, in_frame) = span.from?;
1072 if !span.speed.is_normal() {
1073 return None;
1074 }
1075 // The grade playback shows, which a copied packet never went
1076 // through. `None` and the identity are the same untouched picture.
1077 if project
1078 .composite_color_at(span.start)
1079 .is_some_and(|params| !params.is_identity())
1080 {
1081 return None;
1082 }
1083 let path = &entries.get(source)?.path;
1084 if sources.get(source)?.is_none() {
1085 if !crate::demux::is_matroska(path) {
1086 return None;
1087 }
1088 let (source_meta, demuxer) = Demuxer::open(path).ok()?;
1089 let Demuxer::Mkv(demuxer) = demuxer else {
1090 return None;
1091 };
1092 // The stream this file would carry, at the size and the rate the
1093 // timeline is in: anything else is a picture that has to be
1094 // coded again to become this file's.
1095 if source_meta.codec != codec
1096 || source_meta.width != meta.width
1097 || source_meta.height != meta.height
1098 || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()?
1099 != Rate::REAL_TIME
1100 || !demuxer.plain_blocks()
1101 {
1102 return None;
1103 }
1104 // One track, one configuration record and one `Colour`: two
1105 // sources that disagree about either are two streams, and this
1106 // writes one.
1107 let declares = (demuxer.codec_private().to_vec(), source_meta.color);
1108 if declared.get_or_insert(declares.clone()) != &declares {
1109 return None;
1110 }
1111 sources[source] = Some(demuxer);
1112 }
1113 let demuxer = sources.get_mut(source)?.as_mut()?;
1114 // The window this span reads, in the blocks the whole engine counts
1115 // a source's frames in. It has to *be* whole groups of pictures: a
1116 // copy that began between two sync points would hand a decoder
1117 // pictures whose references are not in the file, and one that ended
1118 // between them would drop a reference the pictures before it need.
1119 let (start, end) = (in_frame as usize, in_frame as usize + span.len as usize);
1120 if end > demuxer.block_count()
1121 || !demuxer.is_sync(start)
1122 || (end < demuxer.block_count() && !demuxer.is_sync(end))
1123 {
1124 return None;
1125 }
1126 // Two spans that continue each other in one file are one region:
1127 // nothing was cut between them, so the leading pictures across that
1128 // boundary still have every reference they need.
1129 match regions.last_mut() {
1130 Some(last)
1131 if last.source == source
1132 && last.blocks.end == start
1133 && last.start + (last.blocks.end - last.blocks.start) as u32
1134 == span.start =>
1135 {
1136 last.blocks.end = end;
1137 }
1138 _ => regions.push(CopyRegion {
1139 source,
1140 blocks: start..end,
1141 start: span.start,
1142 }),
1143 }
1144 }
1145 let (private, colour) = declared?;
1146 Some(Self {
1147 sources,
1148 regions,
1149 codec_id,
1150 private,
1151 colour,
1152 width: meta.width,
1153 height: meta.height,
1154 })
1155 }
1156
1157 /// The file itself: one Matroska muxer, every region's blocks through it in
1158 /// the order and at the timing their source states.
1159 fn run(
1160 mut self,
1161 out: &Path,
1162 meta: &VideoMeta,
1163 shared: &Shared,
1164 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
1165 subs: Vec<SubParams>,
1166 total: u32,
1167 ) -> crate::Result<()> {
1168 let mut muxer = MkvMuxer::create_copy(
1169 out,
1170 &CopyParams {
1171 width: self.width,
1172 height: self.height,
1173 frame_rate: meta.frame_rate,
1174 codec_id: self.codec_id,
1175 codec_private: &self.private,
1176 colour: self.colour,
1177 },
1178 audio,
1179 subs,
1180 )?;
1181 // Nanoseconds a timeline frame lasts, which is what a region's own
1182 // position on the timeline is measured in.
1183 let frame_ns = 1e9 / meta.frame_rate;
1184 let mut done = 0u32;
1185 for region in &self.regions {
1186 let demuxer = self.sources[region.source]
1187 .as_mut()
1188 .ok_or("a copied region names a source that was never opened")?;
1189 let base = (f64::from(region.start) * frame_ns).round() as i64;
1190 // When the region's first picture is shown on its source's clock;
1191 // everything after it is written that far along from `base`.
1192 let mut origin: Option<i64> = None;
1193 for index in region.blocks.clone() {
1194 cancelled(shared)?;
1195 let Some(block) = demuxer.coded_block(index)? else {
1196 break;
1197 };
1198 let origin = *origin.get_or_insert(block.ts_ns);
1199 // The leading pictures of the group this region opens on: shown
1200 // before it, coded against the group before it, and that group
1201 // is not in this file. Dropped rather than written as pictures
1202 // no decoder can put back together.
1203 if block.ts_ns < origin {
1204 continue;
1205 }
1206 muxer.write_block(block.bytes, block.key, base + block.ts_ns - origin)?;
1207 done += 1;
1208 shared
1209 .progress
1210 .store(picture_progress(done, total), Ordering::Relaxed);
1211 }
1212 }
1213 // Everything up to here is still cancellable, exactly as the encoded
1214 // path is up to its own `finish`.
1215 cancelled(shared)?;
1216 muxer.finish()?;
1217 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
1218 Ok(())
1219 }
1220}
1221
1222/// The same lane, *decoded*: what a packet copy cannot carry comes out here as
1223/// AAC written by this project's own encoder.
1224///
1225/// The samples are the very ones [`run_audio`] would put in a WAV -- the same
1226/// opener with the same equalizers, the same rates and the same resize onto the
1227/// timeline's own length -- so an mp4 and a WAV of one timeline are one mix,
1228/// not two that could disagree.
1229///
1230/// AAC-LC's encoder delay is one 1024-frame block, which is exactly the priming
1231/// a reader drops when the file carries no edit list (`audio::DEFAULT_PRIMING`,
1232/// and [`crate::mux::Mp4Muxer`] writes none): the first packet is that delay, so
1233/// the sound starts at timeline frame 0 as a copied track's does.
1234///
1235/// ponytail: the mix sits in memory as f32 before it is encoded (~46 MB a
1236/// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers
1237/// the whole stream anyway, since it encodes its frames in parallel. Upgrade
1238/// path is a chunked push once that encoder streams.
1239fn encode_audio(
1240 project: &Project,
1241 meta: &VideoMeta,
1242 kbps: u32,
1243 mkv: bool,
1244 shared: &Shared,
1245) -> crate::Result<Option<ExportAudio>> {
1246 let sources = project.audio_sources();
1247 let segs = project.audio_segments_from(0, meta.frame_rate);
1248 let eqs = project.audio_eqs_from(0, meta.frame_rate);
1249 let speeds = project.audio_speeds_from(0, meta.frame_rate);
1250 // Coarse stage timers, in the same voice as `export video: copy` below: an
1251 // export of a feature film spends minutes in here before a byte of picture
1252 // is written, and which minutes went where is the first question asked of a
1253 // slow export. Three lines an export, so they stay on.
1254 let mixed = std::time::Instant::now();
1255 let Some((audio, chunks)) = AudioSession::open_mixed_streams_master(
1256 &sources,
1257 &segs,
1258 &eqs,
1259 &speeds,
1260 &project.audio_gains(),
1261 project.limiter(),
1262 )?
1263 else {
1264 return Ok(None); // no audio to write, exactly as a copy of nothing is
1265 };
1266 let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| {
1267 format!(
1268 "{} Hz is not an AAC sample rate: export WAV, FLAC, MP3 or OGG, which write it as \
1269 it is",
1270 audio.sample_rate
1271 )
1272 })?;
1273 let channels = usize::from(audio.channels.max(1));
1274 // The timeline's length, not the mix's: a segment resolves its window to
1275 // whole samples on its own, so the sum can miss by a sample or two and a
1276 // source that ran out early would leave the track short under a picture
1277 // that is not. One resize settles both, as [`run_audio`]'s does.
1278 let total = (f64::from(project.timeline_frames()) / meta.frame_rate
1279 * f64::from(audio.sample_rate))
1280 .round() as usize
1281 * channels;
1282 let mut samples: Vec<f32> = Vec::with_capacity(total);
1283 for chunk in chunks {
1284 samples.extend(chunk.samples);
1285 // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of
1286 // the three stages and the only one that can be counted as it goes.
1287 shared.progress.store(
1288 (samples.len().min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32,
1289 Ordering::Relaxed,
1290 );
1291 }
1292 samples.resize(total, 0.0);
1293 eprintln!(
1294 "export audio: mixed {:.1} s of sound in {:.1} s",
1295 total as f64 / f64::from(audio.sample_rate.max(1)) / channels as f64,
1296 mixed.elapsed().as_secs_f64()
1297 );
1298
1299 // Opus where the container carries it and the mix is inside the envelope
1300 // this encoder was *measured* correct in ([`encode_opus`]): a Matroska file,
1301 // 48 kHz, stereo. An Opus source edited into an mkv export therefore leaves
1302 // as Opus instead of being turned into AAC on the way out, which is the one
1303 // generation of loss an all-Opus timeline used to pay for being cut.
1304 //
1305 // Everything else falls through to the AAC below and is unchanged by this:
1306 // every mp4, a mono mix, a 44.1 kHz timeline. The rate is the mix's own --
1307 // there is no resampler on this path, and inventing one to reach 48 kHz
1308 // would resample a whole timeline to satisfy a codec, which is a bigger
1309 // change to the sound than the codec is.
1310 if mkv
1311 && audio.sample_rate == OPUS_RATE
1312 && channels == 2
1313 && let Some((packets, pre_skip)) = encode_opus(&samples, kbps)?
1314 {
1315 return Ok(Some(ExportAudio {
1316 params: crate::AacTrackParams {
1317 freq_index,
1318 chan_conf: 2,
1319 sample_rate: OPUS_RATE,
1320 },
1321 packets,
1322 copied: false,
1323 opus_pre_skip: Some(pre_skip),
1324 }));
1325 }
1326
1327 // The caller's rate, never the encoder's own 128 default -- see
1328 // [`DEFAULT_AUDIO_KBPS`] for why the untouched figure is 256.
1329 let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig {
1330 bitrate_bps: kbps * 1_000,
1331 ..Default::default()
1332 });
1333 encoder.push_pcm(&samples, audio.channels.max(1), audio.sample_rate)?;
1334 encoder.finish();
1335 let mut packets = Vec::new();
1336 // `next_packet` after `finish` yields packets until `Eof` and nothing else,
1337 // so the loop ends on the only error it can see.
1338 while let Ok(packet) = encoder.next_packet() {
1339 packets.push(crate::AacPacket {
1340 bytes: packet.data,
1341 samples: packet.duration,
1342 });
1343 }
1344 Ok(Some(ExportAudio {
1345 params: crate::AacTrackParams {
1346 freq_index,
1347 // 1 and 2 are the ISO channel configurations for mono and stereo,
1348 // and what the opener hands the timeline is one of those whatever
1349 // the source carried ([`crate::audio::downmix`]).
1350 chan_conf: audio.channels.max(1) as u8,
1351 sample_rate: audio.sample_rate,
1352 },
1353 packets,
1354 copied: false,
1355 opus_pre_skip: None,
1356 }))
1357}
1358
1359/// The one rate Opus codes at. The container may state another one in its
1360/// `OpusHead` and every decoder still runs at 48 kHz (RFC 7845 §5.1), so a
1361/// timeline at any other rate is not "encoded at its own rate" here -- it is
1362/// resampled or it is not Opus, and [`encode_audio`] picks the second.
1363pub(crate) const OPUS_RATE: u32 = 48_000;
1364
1365/// 20 ms at [`OPUS_RATE`], the frame every Opus muxer in the wild writes:
1366/// long enough that the per-packet overhead is nothing, short enough that a
1367/// Matroska block timestamp in whole milliseconds is exact.
1368const OPUS_FRAME: usize = 960;
1369
1370/// The most this project asks of `opus-rs`, in kbps, and why it is a cap rather
1371/// than the four rates the Sound row offers: this encoder falls off a cliff at a
1372/// rate that depends on the *content*, and above it a conformant decoder gets
1373/// noise back. Measured on three one-second spans of a real 5.1 Opus film,
1374/// encoded here and decoded with `ruopus` -- which is not the suspect, since it
1375/// decodes ffmpeg's own libopus at 256 kbps to correlation 1.00000 on the same
1376/// material:
1377///
1378/// ```text
1379/// kbps 120 128 136 144 152 160
1380/// span A 0.945 0.937 0.452 0.206 0.223 0.163
1381/// span B 0.986 0.989 0.697 0.153 0.114 0.149
1382/// span C 0.999 0.994 0.951 0.335 0.266 0.326
1383/// libopus 0.997 0.998 -- -- -- 0.996 (same spans, control)
1384/// ```
1385///
1386/// So: usable to 128, ruined by 136 on real film sound, and the pure-tone
1387/// fixtures that first suggested a 165 kbps ceiling were simply easy material.
1388/// 128 kbps stereo Opus is around transparency anyway (libopus scores 0.998
1389/// there on the worst of those spans), so the cap costs nothing a listener has.
1390/// It is still not *trusted*: every track is decoded again and measured before
1391/// it is written ([`opus_fidelity`]), because a cliff whose edge moves with the
1392/// material is not something a constant can be safe against on its own.
1393///
1394/// ponytail: the ceiling is this encoder's, not the format's. Upgrade path is a
1395/// released `opus-rs` that survives its own high rates -- the unit test pins the
1396/// failure, so it fails the day the bug is fixed and this can be raised.
1397pub(crate) const OPUS_MAX_KBPS: u32 = 128;
1398
1399/// How well a track has to survive its own round trip to be written as Opus:
1400/// the correlation between the mix and the decode of what was encoded from it.
1401/// A good encoder scores 0.98-0.999 on this material (libopus, measured above);
1402/// the failure mode is not subtle at all, scoring 0.1-0.7. 0.95 sits in the gap
1403/// with room on both sides, and what fails it is written as AAC -- the export's
1404/// own encoder line then says AAC, so the fallback is visible rather than
1405/// silent.
1406const OPUS_MIN_FIDELITY: f64 = 0.95;
1407
1408/// The encoder's lookahead at [`OPUS_RATE`] in the mode this envelope always
1409/// selects (CELT-only: 2.5 ms). The pre-skip a file states is this *plus* the
1410/// warm-up frame [`encode_opus`] throws away. Measured by
1411/// cross-correlating the decode against the source, not taken from the crate --
1412/// it exposes no lookahead getter -- and asserted at both ends of the rate band
1413/// in `tests/opus_export.rs`, which is what catches a version that changes it.
1414const OPUS_PRE_SKIP: u16 = 120;
1415
1416/// The mix as Opus packets, one per [`OPUS_FRAME`], plus the pre-skip that has
1417/// to be declared in front of them. Stereo and [`OPUS_RATE`] only -- the caller
1418/// checks both, because outside that pair this encoder is not one this project
1419/// is willing to write files with ([`OPUS_MAX_KBPS`]).
1420///
1421/// The tail frame is padded with silence rather than dropped: Opus codes whole
1422/// frames and a track a few milliseconds short under a picture that is not is
1423/// the drift every other path here is written to avoid. The pre-skip trims the
1424/// front; the container's duration trims the back.
1425fn encode_opus(samples: &[f32], kbps: u32) -> crate::Result<Option<(Vec<crate::AacPacket>, u16)>> {
1426 let mut encoder = opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio)
1427 .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}"))?;
1428 encoder.bitrate_bps = (kbps.min(OPUS_MAX_KBPS) * 1_000) as i32;
1429 encoder.complexity = 10;
1430 let mut packets = Vec::new();
1431 let mut frame = vec![0f32; OPUS_FRAME * 2];
1432 // 1275 bytes is the most one Opus frame may weigh (RFC 6716 §3.2); this is
1433 // that with room for the TOC and a padded frame, so `encode` never has to
1434 // refuse for want of a buffer.
1435 let mut out = vec![0u8; 1500];
1436 // The head, coded **twice**. An encoder's very first frame has no history
1437 // behind it and comes out ramped and out of phase -- measured on a 440 Hz
1438 // fixture, the first 20 ms of the export correlated 0.09 with the source
1439 // where every later window correlated 0.9997 -- and 20 ms of wrong sound at
1440 // the head of a file is the kind of thing nobody hears in a test and
1441 // everybody hears in the first frame of a cut. So the first frame is fed in
1442 // once to warm the encoder, and thrown away again by the pre-skip: exactly
1443 // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet.
1444 let coded = std::time::Instant::now();
1445 let warm = samples.len().min(OPUS_FRAME * 2);
1446 // ...and one silent frame after the sound, for the same delay seen from the
1447 // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so
1448 // without a frame to push them out the last 2.5 ms of the timeline stay
1449 // inside it and the track ends short under a picture that does not.
1450 let blocks = std::iter::once(&samples[..warm])
1451 .chain(samples.chunks(OPUS_FRAME * 2))
1452 .chain(std::iter::once(&samples[..0]));
1453 for block in blocks {
1454 frame[..block.len()].copy_from_slice(block);
1455 frame[block.len()..].fill(0.0);
1456 let len = encoder
1457 .encode(&frame, OPUS_FRAME, &mut out)
1458 .map_err(|e| format!("Opus encode failed: {e}"))?;
1459 packets.push(crate::AacPacket {
1460 bytes: out[..len].to_vec(),
1461 samples: OPUS_FRAME as u32,
1462 });
1463 }
1464 // ...and now the part that is not optimism: what was just written is
1465 // decoded again and measured against what went in, and a track that does
1466 // not come back is not written at all ([`OPUS_MIN_FIDELITY`]). The caller
1467 // falls through to AAC, which is exactly where it stood before this seat
1468 // existed -- a worse codec is a fair trade for a track that is the sound.
1469 //
1470 // ponytail: this costs one Opus decode of the whole track (a minute of
1471 // sound in a few hundred milliseconds, against a video encode that is
1472 // minutes). Upgrade path is deleting it, the day this encoder can be
1473 // trusted at the rate it is asked for.
1474 let encoded = coded.elapsed().as_secs_f64();
1475 let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16;
1476 let measured = std::time::Instant::now();
1477 let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip));
1478 eprintln!(
1479 "export audio: Opus encode {encoded:.1} s, fidelity {fidelity:.4} measured in {:.1} s",
1480 measured.elapsed().as_secs_f64()
1481 );
1482 Ok((fidelity >= OPUS_MIN_FIDELITY).then_some((packets, pre_skip)))
1483}
1484
1485/// Packets one sampled window listens to: 5 s at [`OPUS_FRAME`].
1486const FIDELITY_WINDOW: usize = 250;
1487
1488/// How many of them a long track is judged on -- a minute of sound, wherever
1489/// the track's length puts them, and a constant cost rather than one that grows
1490/// with the film ([`opus_fidelity`]).
1491const FIDELITY_WINDOWS: usize = 12;
1492
1493/// Packets decoded into a window and thrown away before it is measured. CELT
1494/// predicts across frames, so a decoder started cold mid-stream is behind its
1495/// own history for a few frames; 100 ms is far more than it needs and is not
1496/// worth counting.
1497const FIDELITY_WARMUP: usize = 5;
1498
1499/// How much sound a window must carry before its correlation means anything:
1500/// mean square per sample. A window of digital silence -- the head of a film,
1501/// the gap between a feature and its credits -- correlates with nothing, and
1502/// failing a track for it would send perfectly good sound to AAC.
1503const FIDELITY_FLOOR: f64 = 1e-9;
1504
1505/// The correlation between `samples` and the decode of `packets` with the first
1506/// `pre_skip` frames dropped: 1.0 is the same waveform, and this codec's failure
1507/// mode lands near 0.1. Streamed packet by packet -- the decode is never held,
1508/// only three running sums -- because the mix behind it is already the biggest
1509/// thing in an export ([`encode_audio`]'s ponytail).
1510///
1511/// A packet the decoder refuses is 0.0 and no argument: a track this project
1512/// cannot read is exactly what this is here to catch.
1513///
1514/// **Sampled, above a minute of sound, and the worst window is the answer.**
1515/// This decode is the whole cost of exporting a feature film: `ruopus` runs its
1516/// inverse MDCT at 0.2x real time here (measured, 24.2 s for 121.5 s of stereo),
1517/// so judging every packet of a two-and-a-half-hour film costs half an hour
1518/// before a byte of picture is written -- which is what it did, and what made a
1519/// copy export that has no encoding to do at all sit at zero for twenty minutes.
1520/// [`FIDELITY_WINDOWS`] windows spread evenly across the track cost the same
1521/// minute of decode whatever the film's length, and what they are looking for
1522/// survives sampling: [`OPUS_MAX_KBPS`]'s cliff is a *rate* the encoder falls
1523/// off, measured over one-second spans, not a defect of one bar of music. It is
1524/// also strictly harsher per window than the old whole-track sum, which let a
1525/// ruined minute average away against two good hours -- the answer here is the
1526/// worst window, not the mean.
1527fn opus_fidelity(packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize) -> f64 {
1528 // Short enough to hear all of: every fixture, every unit test, and any
1529 // track under a minute. There is nothing to sample from.
1530 let all = FIDELITY_WINDOW * FIDELITY_WINDOWS;
1531 if packets.len() <= all {
1532 return window_fidelity(packets, samples, pre_skip, 0, 0, packets.len()).unwrap_or(1.0);
1533 }
1534 // Evenly spread, first window at the head: the head is where an encoder's
1535 // own warm-up would show, and the last starts a window short of the end so
1536 // no window runs past the packets.
1537 let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);
1538 let mut worst: Option<f64> = None;
1539 for w in 0..FIDELITY_WINDOWS {
1540 let at = w * step;
1541 let from = at.saturating_sub(FIDELITY_WARMUP);
1542 let Some(fidelity) =
1543 window_fidelity(packets, samples, pre_skip, from, at, at + FIDELITY_WINDOW)
1544 else {
1545 continue; // silence: nothing to correlate, and not a failure
1546 };
1547 worst = Some(worst.map_or(fidelity, |w: f64| w.min(fidelity)));
1548 }
1549 // Every window silent is a silent track, which this codec writes as silence.
1550 worst.unwrap_or(1.0)
1551}
1552
1553/// [`opus_fidelity`] over `packets[measure..to]`, with `packets[from..measure]`
1554/// -- the warm-up -- decoded for its state and thrown away. `None` where the
1555/// source window carries no sound worth correlating ([`FIDELITY_FLOOR`]).
1556fn window_fidelity(
1557 packets: &[crate::AacPacket],
1558 samples: &[f32],
1559 pre_skip: usize,
1560 from: usize,
1561 measure: usize,
1562 to: usize,
1563) -> Option<f64> {
1564 let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);
1565 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
1566 // Where in the mix this window's first decoded sample lands: every packet
1567 // is [`OPUS_FRAME`] long, and the pre-skip is what the front of the stream
1568 // owes before the first of them is the timeline's frame 0.
1569 let mut at = (from * OPUS_FRAME * 2).saturating_sub(pre_skip * 2);
1570 let mut drop = (pre_skip * 2).saturating_sub(from * OPUS_FRAME * 2);
1571 let mut counted = 0usize;
1572 for (index, packet) in packets.iter().enumerate().take(to).skip(from) {
1573 let Ok(pcm) = decoder.decode_packet(&packet.bytes) else {
1574 return Some(0.0);
1575 };
1576 let pcm = &pcm[drop.min(pcm.len())..];
1577 drop = drop.saturating_sub(packet.samples as usize * 2);
1578 // The warm-up is decoded for its state and not for its numbers.
1579 if index < measure {
1580 at += pcm.len();
1581 continue;
1582 }
1583 for (want, got) in samples[at.min(samples.len())..].iter().zip(pcm) {
1584 let (x, y) = (f64::from(*want), f64::from(*got));
1585 num += x * y;
1586 da += x * x;
1587 db += y * y;
1588 at += 1;
1589 counted += 1;
1590 }
1591 }
1592 (da / counted.max(1) as f64 > FIDELITY_FLOOR).then(|| num / (da.sqrt() * db.sqrt()).max(1e-12))
1593}
1594
1595fn run(
1596 project: &Project,
1597 meta: &VideoMeta,
1598 out: &Path,
1599 shared: &Shared,
1600 settings: &ExportSettings,
1601) -> crate::Result<()> {
1602 let total = project.timeline_frames();
1603 let sources = project.sources();
1604 // The picture's decision first, before a sample of sound is touched: it is
1605 // the answer that decides what the whole export *is*, it costs one header
1606 // read per source, and it is what the line on screen has been missing --
1607 // an export that copies its picture used to say nothing at all for as long
1608 // as its sound took, which on a feature film was minutes. Half a line now,
1609 // completed by the measured codec once the sound is known below: what is
1610 // published is never a codec that did not run.
1611 let plan = CopyPlan::of(project, meta, settings);
1612 if plan.is_some() {
1613 eprintln!("export video: copy (source packets)");
1614 *shared.encoders.lock().unwrap() = Some("copy · working out the sound…".into());
1615 }
1616 // ...then the audio: a track has to be declared when the muxer is created,
1617 // which happens as soon as the first coded picture arrives -- and the
1618 // Matroska muxer wants the packets themselves that early too, because it
1619 // interleaves them into the clusters as it writes. Every video format gets
1620 // the same track: none of them is picture-only any more.
1621 let audio = copy_audio(
1622 project,
1623 meta,
1624 audio_kbps_of(settings),
1625 settings.format.is_mkv(),
1626 shared,
1627 )?;
1628 let audio_params = audio.as_ref().map(|track| AudioParams {
1629 freq_index: track.params.freq_index,
1630 chan_conf: track.params.chan_conf,
1631 sample_rate: track.params.sample_rate,
1632 opus_pre_skip: track.opus_pre_skip,
1633 });
1634 // What the track *is*, kept before the packets are handed to a muxer: the
1635 // encoder line names a copy or an encode and only `copy_audio` knows which.
1636 let sound = audio.as_ref().map(|track| track.copied);
1637 // ...and *which* encoder, for the same line: the card predicts Opus from the
1638 // format alone and cannot know the mix's rate or width ([`audio_label`]),
1639 // while this is after the mix was opened, so it is the measured answer.
1640 let opus = audio
1641 .as_ref()
1642 .is_some_and(|track| track.opus_pre_skip.is_some());
1643 // Taken by the Matroska muxer at creation; the mp4 one writes its track
1644 // after the picture, so for that path this is still `Some` at the end.
1645 let mut packets = audio.map(|track| track.packets);
1646 // ...and the cues with them, for the same reason: the subtitle track is
1647 // declared in the header and its blocks are interleaved into the clusters,
1648 // so the muxer needs the lot before the first picture is written.
1649 let mut subs = export_subtitles(project, meta, settings);
1650 // The sound is done, whichever way it went: the bar stands at the head of
1651 // the picture's own share ([`AUDIO_BAND`]).
1652 shared.progress.store(AUDIO_BAND, Ordering::Relaxed);
1653
1654 // Before an encoder is opened at all: a timeline nobody has touched, whose
1655 // sources this file can hold as they are, is written by copying their coded
1656 // blocks -- the picture's half of what `copy_audio` just did for the sound,
1657 // and the difference between an export bounded by the *edited* spans and one
1658 // that re-encodes a whole film to change a cut. [`CopyPlan`] states the
1659 // whole rule; anything at all outside it falls through to the walk below.
1660 if let Some(plan) = plan {
1661 *shared.encoders.lock().unwrap() = Some(format!(
1662 "copy · {}",
1663 // The measured codec, exactly as the encoder path below publishes
1664 // it: the mix has been opened by now, so a line that fell back to
1665 // AAC says AAC. Naming the prediction here would make the fallback
1666 // invisible on precisely the exports that are over in seconds.
1667 match opus {
1668 true => "Opus · SW encode (opus-rs)",
1669 false => audio_label(project, settings.format, sound.is_some(), sound),
1670 }
1671 ));
1672 return plan.run(
1673 out,
1674 meta,
1675 shared,
1676 audio_params.as_ref().zip(packets.take()),
1677 std::mem::take(&mut subs),
1678 total,
1679 );
1680 }
1681
1682 // One header parse per source, before any of them is decoded: what rate
1683 // each file was shot at against the timeline's ([`Rate`]), which is how the
1684 // clip's timeline frames below become frames of the file, and what its
1685 // samples *mean* ([`ColorDescription`]), which is what decides whether they
1686 // are remapped on the way in. Real time for a still, a song and a
1687 // single-rate project, where every conversion below is the identity.
1688 let rates: Vec<(Rate, ColorDescription, Option<f32>)> = sources
1689 .iter()
1690 .map(|source| source_rate(&source.path, meta.frame_rate))
1691 .collect();
1692 // ...and, for a source on an HDR curve, the tone map that brings its samples
1693 // down to the SDR this file is written in ([`crate::tonemap`]). Once per
1694 // source stream: the table costs a couple of milliseconds to build and a
1695 // span reopens its file, so building it here rather than in the loop below
1696 // is the difference between paying that once and paying it per cut. An SDR
1697 // source -- the whole of an ordinary project -- builds no table at all.
1698 //
1699 // Through the project's own preset ([`tonemap::Preset`]) and each source's
1700 // own declared peak, which is the pair playback's decode funnel builds its
1701 // tables with: preview and export are the same rendition of the same film
1702 // because they are told the same two things, not because two numbers happen
1703 // to agree.
1704 let preset = project.tone();
1705 let tone: Vec<Option<ToneMapper>> = rates
1706 .iter()
1707 .map(|(_, color, peak)| match color.transfer {
1708 Transfer::Sdr => None,
1709 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)),
1710 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)),
1711 })
1712 .collect();
1713 // ...and the one space they are all written in, the same rule a reader with
1714 // no tags to read would apply to this file's height.
1715 let out_color = ColorDescription::output(meta.height);
1716
1717 let mut encoder = Enc::open(meta, settings)?;
1718 // What this file is really being written by, for a progress line to name.
1719 // Published *after* the seat is open, so a hardware encoder the driver
1720 // refused reads as the software one that took over rather than as the hope
1721 // it replaced -- and the sound says whether it was copied or encoded, which
1722 // `copy_audio` decided a few lines up.
1723 *shared.encoders.lock().unwrap() = Some(format!(
1724 "{} · {}",
1725 encoder.label(),
1726 match opus {
1727 true => "Opus · SW encode (opus-rs)",
1728 false => audio_label(project, settings.format, sound.is_some(), sound),
1729 }
1730 ));
1731 let mut muxer = None;
1732 let mut done = 0u32;
1733 let black = Black::new(meta);
1734 // Spans, not clips: a gap in the video is part of the timeline and gets
1735 // encoded too, as black frames. The picture count is therefore
1736 // `timeline_frames` however the lanes are arranged -- and *which* lane a
1737 // span comes from is `composite_spans_from`'s answer, the same one playback
1738 // shows, so an export is what was watched.
1739 for span in project.composite_spans_from(0) {
1740 // Every clip reopens its own source file at its own in point; the
1741 // encoder is *not* reopened, so the export is one continuous stream
1742 // whose GOP boundaries need not line up with the cuts -- nor with the
1743 // file boundaries, which are just cuts that change the path.
1744 let (mut pictures, rate, in_frame, color, mapper) = match span.from {
1745 Some((source, in_frame)) => {
1746 let entry = sources
1747 .get(source)
1748 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
1749 let (rate, color, _peak) = rates[source];
1750 // Opened at the file's own frame, which is the only place the
1751 // file's numbering is used -- the span's are the timeline's.
1752 let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?;
1753 (
1754 Some(pictures),
1755 rate,
1756 in_frame,
1757 Some(color),
1758 tone[source].as_ref(),
1759 )
1760 }
1761 // A gap's black is 16/128/128, which is black in every matrix here
1762 // and on every curve: nothing to remap and nothing to tone-map,
1763 // which is what `None` says.
1764 None => (None, Rate::REAL_TIME, 0, None, None),
1765 };
1766 // Mixed spaces on one timeline: a clip coded against another matrix than
1767 // the one this file declares is rewritten into it, *after* the grade --
1768 // playback grades in the source's own space and converts for the screen
1769 // ([`crate::decode`]), so a grade applied to remapped samples is a
1770 // different picture than the one the canvas showed. Same-space clips --
1771 // the whole of an ordinary project -- take `None` and not a byte is
1772 // touched.
1773 //
1774 // ...and what the samples mean when that remap sees them is not always
1775 // what the file said, which is [`remap_into`]'s whole question.
1776 let remap = remap_into(color, mapper.is_some(), out_color.matrix);
1777 // What this span is graded by -- the same answer playback's decoder
1778 // carries, so the export is the picture that was watched. `None` for a
1779 // gap and for an ungraded clip, and that is the path where not a byte
1780 // is touched. Scratch outside the frame loop: it is refilled per frame
1781 // and its allocation survives the whole span.
1782 let grade = project.composite_color_at(span.start).copied();
1783 let mut graded = (Vec::new(), Vec::new(), Vec::new());
1784 // ...and the canvas it is placed on, which is where a source of another
1785 // resolution becomes a picture at the project's. The same `Composer`
1786 // playback composes with, given the same policy, so an export is what
1787 // was watched down to the letterbox; a clip already the project's size
1788 // passes through it untouched.
1789 let mut canvas = Composer::new(
1790 meta.width,
1791 meta.height,
1792 project.composite_fit_at(span.start),
1793 );
1794 // Timeline frames, taken a *source* frame at a time: at a rate other
1795 // than real time the two are not the same count, and the span says which
1796 // source frame each timeline frame shows ([`Speed::source_at`]) -- the
1797 // very frame playback is holding there, because the two conversions are
1798 // one floor/ceil pair (`speed_maps_both_ways`). A speed-up decodes the
1799 // frames it skips and drops them, because the pictures after them
1800 // reference those; a slow-down encodes the picture it is holding again
1801 // rather than decoding it twice. At real time `repeats` is 1 and `want`
1802 // advances by one, which is the loop this always ran.
1803 let mut done_here = 0u32;
1804 // Source frames already taken out of this span's decoder.
1805 let mut taken = 0u32;
1806 // The whole of the mapping, in the order it composes: the speed says
1807 // which of the clip's (timeline-rate) frames a timeline frame shows,
1808 // and the rate says which frame of the *file* that is -- counted from
1809 // the one the decoder was opened at. At real time and at the timeline's
1810 // own rate this is `Speed::source_at` and nothing else, which is the
1811 // walk a single-rate project has always taken.
1812 let opened_at = rate.source_at(in_frame);
1813 let source_at =
1814 |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at;
1815 while done_here < span.len {
1816 cancelled(shared)?;
1817 let want = source_at(done_here);
1818 // How many timeline frames from here show that same picture: one at
1819 // real time, more when the clip is slowed or its file is slower
1820 // than the timeline. Encoded again rather than decoded twice.
1821 let repeats = (done_here..span.len)
1822 .take_while(|&offset| source_at(offset) == want)
1823 .count() as u32;
1824 let picture = match &mut pictures {
1825 Some(pictures) => {
1826 let mut ran_out = false;
1827 while taken < want && !ran_out {
1828 ran_out = pictures.next()?.is_none();
1829 taken += 1;
1830 }
1831 match ran_out {
1832 true => None,
1833 false => {
1834 taken += 1;
1835 pictures.next()?
1836 }
1837 }
1838 }
1839 None => Some(black.picture()),
1840 };
1841 let Some((y, u, v, width, height)) = picture else {
1842 break; // source ran out early; the clip list outlives the file
1843 };
1844 // The planes are borrowed from the decoder (and `Black::picture`
1845 // hands the same slice as both u and v), so a grade cannot be
1846 // applied in place: it goes onto a copy, which the encoder then
1847 // reads instead.
1848 let params = grade.filter(|p| !p.is_identity());
1849 let (y, u, v) = match (params, remap, mapper) {
1850 (None, None, None) => (y, u, v),
1851 (params, remap, mapper) => {
1852 let (gy, gu, gv) = &mut graded;
1853 gy.clear();
1854 gy.extend_from_slice(y);
1855 gu.clear();
1856 gu.extend_from_slice(u);
1857 gv.clear();
1858 gv.extend_from_slice(v);
1859 // Tone-map first, so the grade is applied to the SDR picture
1860 // the canvas showed and not to HDR codes; then remap the
1861 // graded result. The order playback renders in, and the
1862 // only order in which preview and export agree.
1863 if let Some(mapper) = mapper {
1864 mapper.map(gy, gu, gv, width as usize, height as usize);
1865 }
1866 if let Some(params) = params {
1867 crate::color::apply_yuv(&params, gy, gu, gv);
1868 }
1869 if let Some((from, to)) = remap {
1870 crate::colorspace::remap(from, to, gy, gu, gv, width as usize);
1871 }
1872 (&gy[..], &gu[..], &gv[..])
1873 }
1874 };
1875 // Grade first, place second: the grade is the clip's own pixels
1876 // and the bars around them are not the clip (see `scale::Composer`).
1877 let (y, u, v, width, height) = canvas.place(y, u, v, width, height);
1878 // Once per timeline frame this source frame covers: one at real time
1879 // and faster, more when the clip is slowed -- the picture is already
1880 // graded and placed, so a held frame costs an encode and no decode.
1881 for _ in 0..repeats {
1882 if let Some((au, key)) = encoder.encode(y, u, v, width, height)? {
1883 write_video(
1884 &mut muxer,
1885 out,
1886 meta,
1887 settings,
1888 audio_params.as_ref(),
1889 &mut packets,
1890 &mut subs,
1891 au,
1892 key,
1893 )?;
1894 }
1895 done += 1;
1896 shared
1897 .progress
1898 .store(picture_progress(done, total), Ordering::Relaxed);
1899 }
1900 done_here += repeats;
1901 }
1902 }
1903 while let Some((au, key)) = encoder.drain()? {
1904 write_video(
1905 &mut muxer,
1906 out,
1907 meta,
1908 settings,
1909 audio_params.as_ref(),
1910 &mut packets,
1911 &mut subs,
1912 au,
1913 key,
1914 )?;
1915 }
1916 // Progress reads 100% from here on, but nothing is published yet: draining,
1917 // the audio pass and `finish` are all still cancellable.
1918 cancelled(shared)?;
1919
1920 let Some(muxer) = muxer else {
1921 return Err("export produced no coded pictures".into());
1922 };
1923 // The mp4's audio and subtitle tracks after its picture -- the Matroska one
1924 // interleaved its own as it went and left `packets` and `subs` empty behind
1925 // it. The text last, so its samples are written knowing how long the picture
1926 // turned out to be.
1927 let muxer = match muxer {
1928 Muxer::Mp4(mut mp4) => {
1929 for packet in packets.into_iter().flatten() {
1930 mp4.write_audio_packet(&packet.bytes)?;
1931 }
1932 mp4.write_subtitles(&subs)?;
1933 Muxer::Mp4(mp4)
1934 }
1935 muxer => muxer,
1936 };
1937 cancelled(shared)?;
1938 muxer.finish()?;
1939 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
1940 Ok(())
1941}
1942
1943/// Which matrix pair a span's samples are rewritten by on the way into a file
1944/// whose own matrix is `out` -- `None` when they are already coded against it,
1945/// and for a gap, whose 16/128/128 black is black in every matrix here.
1946///
1947/// `toned` says the tone map ran on this span: it hands back BT.709 SDR whatever
1948/// the source was coded as, so an HDR clip is never *also* given the matrix
1949/// treatment its BT.2020 tag would ask for -- one conversion or the other, never
1950/// both on one frame -- while a tone-mapped clip on a canvas below 720 lines
1951/// still takes its 709 -> 601 step.
1952fn remap_into(
1953 color: Option<ColorDescription>,
1954 toned: bool,
1955 out: Matrix,
1956) -> Option<(Matrix, Matrix)> {
1957 let from = match toned {
1958 true => Matrix::Bt709,
1959 false => color?.matrix,
1960 };
1961 (from != out).then_some((from, out))
1962}
1963
1964/// What rate `path` was shot at against a timeline at `timeline_fps`
1965/// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own
1966/// -- a still, a song -- and for one that will not open here: the decoder is
1967/// opened a few lines later and fails the export by name, which is a better
1968/// error than this one could raise.
1969fn source_rate(path: &Path, timeline_fps: f64) -> (Rate, ColorDescription, Option<f32>) {
1970 if crate::is_image(path) || crate::is_audio(path) {
1971 // A still is BT.601 by construction whatever it was authored as:
1972 // `decode::rgb_to_i420` is the one matrix that turns its pixels into
1973 // planes. A song has no picture and the answer is never read.
1974 return (Rate::REAL_TIME, ColorDescription::default(), None);
1975 }
1976 match Demuxer::open(path) {
1977 // ...and one whose rate cannot be named against the timeline's, which
1978 // `matches_timeline` refuses at import, so nothing on a timeline is on
1979 // this arm either.
1980 //
1981 // The declared peak comes off the same open the space does, which is
1982 // what keeps export on the number playback's decode funnel read: one
1983 // header parse, both answers.
1984 Ok((meta, demuxer)) => (
1985 Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME),
1986 meta.color,
1987 demuxer.light().peak(),
1988 ),
1989 // Unreadable here means unreadable below too, where the span dies with a
1990 // real message; the file's own space is the least of that.
1991 Err(_) => (Rate::REAL_TIME, ColorDescription::default(), None),
1992 }
1993}
1994
1995/// The audio lanes alone, summed, as a WAV or a FLAC.
1996///
1997/// Nothing here re-derives the edit: the play lists are
1998/// [`Project::audio_segments_from`] and they are handed to the very
1999/// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written
2000/// is what was heard -- every lane, mixed the same way, gaps included, which
2001/// arrive as real silence from that choke point rather than as a hole this would
2002/// have to invent.
2003///
2004/// The length is the *timeline's*: each segment resolves its window to whole
2005/// samples on its own, so the sum can miss the timeline by a sample or two, and
2006/// a source that runs out early would leave the file short. Both are settled by
2007/// one `resize` at the end -- padding with silence, trimming what overshot --
2008/// so an exported file is exactly as long as what was edited.
2009fn run_audio(
2010 project: &Project,
2011 meta: &VideoMeta,
2012 out: &Path,
2013 shared: &Shared,
2014 settings: &ExportSettings,
2015) -> crate::Result<()> {
2016 let format = settings.format;
2017 let sources = project.audio_sources();
2018 let segs = project.audio_segments_from(0, meta.frame_rate);
2019 // The equalizers with them, so what is written is what is heard down to the
2020 // filter: the worker applies them per segment before the lanes are summed
2021 // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point
2022 // playback's feeder reads from -- there is no second place here that could
2023 // apply them differently.
2024 let eqs = project.audio_eqs_from(0, meta.frame_rate);
2025 // ...and the rates with them, for exactly the same reason: a speeded clip is
2026 // resampled inside the worker playback feeds from, so a WAV of a timeline at
2027 // 2x is half as long and holds the samples that were heard -- not a
2028 // second pass here that could disagree with what the ear got.
2029 let speeds = project.audio_speeds_from(0, meta.frame_rate);
2030 // ...and the mix over both: each lane's volume into the sum, the master
2031 // limiter out of it. The same opener playback's feeder reads from, so a
2032 // file is written at the levels it was heard at -- there is no second
2033 // place here that could mix it differently.
2034 let Some((audio, chunks)) = AudioSession::open_mixed_streams_master(
2035 &sources,
2036 &segs,
2037 &eqs,
2038 &speeds,
2039 &project.audio_gains(),
2040 project.limiter(),
2041 )?
2042 else {
2043 return Err("this timeline has no audio to export".into());
2044 };
2045 // The picture path's line, for a file that is sound alone: there is sound
2046 // by the line above, so this names the encoder writing it.
2047 *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string());
2048 let channels = usize::from(audio.channels);
2049 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate
2050 * f64::from(audio.sample_rate))
2051 .round() as u64;
2052 let total = frames as usize * channels;
2053 // ponytail: the whole export sits in memory (4 bytes a sample, so ~23 MB
2054 // per minute of 48 kHz stereo). `flacenc::MemSource` wants it that way and
2055 // the mp4 path already collects its copied AAC track the same. Upgrade path
2056 // is hound's incremental writer plus flacenc's `Source` trait.
2057 let mut samples: Vec<i32> = Vec::with_capacity(total);
2058 for chunk in chunks {
2059 cancelled(shared)?;
2060 // Already equalized: the chunks come out of the per-lane workers, which
2061 // filter each segment before the mix (`open_mixed_streams_eq` above).
2062 samples.extend(
2063 chunk
2064 .samples
2065 .iter()
2066 .map(|s| (s.clamp(-1.0, 1.0) * f32::from(i16::MAX)).round() as i32),
2067 );
2068 let done = samples.len().min(total) * PROGRESS_SCALE as usize / total.max(1);
2069 shared.progress.store(done as u32, Ordering::Relaxed);
2070 }
2071 samples.resize(total, 0);
2072 // Written in one go and still cancellable up to here, exactly as the mp4
2073 // path is up to its `finish`: the `.part` is what either gets renamed or
2074 // deleted.
2075 cancelled(shared)?;
2076 match format {
2077 Format::Wav => write_wav(out, &samples, &audio)?,
2078 Format::Flac => write_flac(out, &samples, &audio)?,
2079 Format::Mp3 => write_mp3(out, &samples, &audio, audio_kbps_of(settings))?,
2080 Format::Ogg => write_ogg(out, &samples, &audio)?,
2081 _ => unreachable!("the picture formats are `run`"),
2082 }
2083 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
2084 Ok(())
2085}
2086
2087/// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in
2088/// this engine, so what the decoder handed over is what the header says.
2089fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
2090 let mut writer = hound::WavWriter::create(
2091 out,
2092 hound::WavSpec {
2093 channels: audio.channels,
2094 sample_rate: audio.sample_rate,
2095 bits_per_sample: 16,
2096 sample_format: hound::SampleFormat::Int,
2097 },
2098 )?;
2099 for &sample in samples {
2100 writer.write_sample(sample as i16)?;
2101 }
2102 // Not `drop`: this is what rewrites the RIFF sizes in the header, and its
2103 // failure is the difference between a finished file and a truncated one.
2104 writer.finalize()?;
2105 Ok(())
2106}
2107
2108/// The same samples as MPEG-1 Layer III, `rusty_mp3` doing the encoding -- pure
2109/// Rust like every other encoder here, and the reason this format is a row at
2110/// all: the LGPL `shine-rs` was the only one when it was not.
2111///
2112/// CBR at the caller's rate, [`DEFAULT_AUDIO_KBPS`] where there was none. Every
2113/// offered rate is already a legal Layer III value, so the encoder's snap is a
2114/// backstop and not a silent substitution; a sample rate MPEG has no frame for
2115/// (anything but 8-48 kHz) is refused there by name rather than written as
2116/// something else.
2117///
2118/// ponytail: CBR only -- the card offers rates and not a quality index. Upgrade
2119/// path is `Mp3EncoderConfig::vbr_quality` behind a setting of its own.
2120fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta, kbps: u32) -> crate::Result<()> {
2121 let mut encoder = rusty_mp3::Mp3Encoder::new(rusty_mp3::Mp3EncoderConfig {
2122 bitrate_kbps: kbps,
2123 vbr_quality: None,
2124 });
2125 // The samples are the 16-bit ones a WAV of this timeline holds, so the two
2126 // files are one mix -- and `push_pcm_s16` divides by 32768 exactly as this
2127 // engine's own decoders do.
2128 let pcm: Vec<i16> = samples.iter().map(|&s| s as i16).collect();
2129 encoder
2130 .push_pcm_s16(&pcm, audio.channels, audio.sample_rate)
2131 .map_err(|e| format!("mp3 encode: {e}"))?;
2132 encoder.finish();
2133 let mut file = BufWriter::new(File::create(out)?);
2134 // `next_packet` after `finish` yields frames until `Eof`, the Xing/Info
2135 // header first: the loop ends on the only error it can see.
2136 while let Ok(frame) = encoder.next_packet() {
2137 file.write_all(&frame)?;
2138 }
2139 file.flush()?;
2140 Ok(())
2141}
2142
2143/// The Vorbis quality every `.ogg` this program writes is coded at, on
2144/// `rusty_vorbis`'s normalised `[0, 1]` scale -- about `-q 8.35` on the scale
2145/// Vorbis itself is spoken in (`quality01_from_vorbis_q`).
2146///
2147/// A measured number, not a taste. The 2026-08-11 bench encoded three of this
2148/// suite's fixtures (`test_tone_48k.wav`, `test_av.mp4`, `test_tone.mp3`) at
2149/// every quality from 0.40 to 0.95 and decoded each back with **symphonia** --
2150/// an independent decoder, and the very one [`crate::audio`] reopens an export
2151/// with. Two things came out of it:
2152///
2153/// * **Below 0.50 the encoder is quiet, not just coarse.** The decoded RMS
2154/// against the source's runs 0.83-0.94 at quality 0.40 (a 1 to 1.6 dB level
2155/// error), and at 0.10 and below the file decodes to near-silence -- the same
2156/// class of failure the AC-3 mono downmix has in `crate::audio`. From 0.55 up
2157/// the level sits at 1.000-1.009, which is what a lossy codec should do.
2158/// * **The band tops out well under the rates the Sound row offers.** Quality
2159/// 0.85 measured 176, 144 and 148 kbps on the three fixtures; 0.95 only
2160/// reaches ~200. That is why [`audio_rate_refusal`] takes the row away rather
2161/// than mapping 128/192/256/320 onto quality steps: the top two are numbers
2162/// this encoder cannot produce, and a card that printed them would be lying.
2163///
2164/// 0.85 is the top of the band where every fixture still decoded to *exactly*
2165/// its own length (0.95 overshot one by 820 samples), which is the property
2166/// [`write_ogg`] is built around.
2167const VORBIS_QUALITY: f32 = 0.85;
2168
2169/// The Vorbis block hop, and the size of the pre-roll [`write_ogg`] feeds the
2170/// encoder. `rusty_vorbis` emits long blocks only (`N = 2048`, hop `N/2`).
2171const VORBIS_HOP: usize = 1024;
2172
2173/// The same samples as Vorbis I in an Ogg container: `rusty_vorbis` encodes,
2174/// `oxideav-ogg` pages. Pure Rust on both halves, like every other encoder here.
2175///
2176/// Two corrections stand between that library pair and a file this project would
2177/// ship, and both are measured rather than guessed (2026-08-11, decoded back
2178/// with symphonia every time):
2179///
2180/// 1. **One hop of pre-roll.** `rusty_vorbis` advances the granule by a full hop
2181/// on its *first* audio packet, which its own doc comment says decodes to
2182/// zero samples. Written straight through, every sample lands ~1024 early:
2183/// a marker signal whose only energy was its first and last 1024 samples came
2184/// back with the head at 36% of its amplitude and a full-scale burst 1500
2185/// samples *before* the real one, in what should have been silence. Feeding
2186/// [`VORBIS_HOP`] samples of silence ahead of the mix and subtracting the same
2187/// from every granule puts it back: head 0.86 against an input peak of 0.80,
2188/// the phantom burst down to 0.04, the real burst at its own place. The
2189/// decoder drops the pre-roll itself -- a first page whose granule is under
2190/// what its packets decode to is exactly how Ogg says "skip this much".
2191/// 2. **The tail is declared, not encoded.** The block grid overshoots the last
2192/// sample, so the stream is padded out and the *last* page's granule is set
2193/// to the timeline's own frame count. A decoder trims to it, which is what
2194/// makes an `.ogg` here exactly as long as the WAV of the same timeline --
2195/// the promise [`run_audio`] makes for every other audio format.
2196///
2197/// **Stereo, always.** The embedded setup header `rusty_vorbis` ships is a
2198/// stereo profile: a mono push is refused outright ("bad coupling channels"),
2199/// and so is anything wider. A mono mix is therefore written as dual mono, both
2200/// channels bit-identical (measured: `max|L-R|` is exactly 0, and Vorbis's own
2201/// channel coupling codes the empty side channel for almost nothing). Wider than
2202/// stereo cannot reach here -- [`crate::audio`] folds 5.1 to stereo when the
2203/// source is opened -- but it is refused by name rather than left to the
2204/// library's own message.
2205///
2206/// ponytail: one quality, [`VORBIS_QUALITY`], with no user control -- the Sound
2207/// row is refused for this format because the rates it offers are not rates
2208/// Vorbis reaches. Upgrade path is a quality picker of its own, worth building
2209/// the day the card has a control that speaks in quality rather than kbps.
2210fn write_ogg(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
2211 if audio.channels > 2 {
2212 return Err(format!(
2213 "Ogg Vorbis is written in stereo here and this mix has {} channels",
2214 audio.channels
2215 )
2216 .into());
2217 }
2218 // The mp3 path's conversion, so the two files are one mix, plus the pre-roll
2219 // and (for a mono mix) the dual-mono widening: the same sample in both
2220 // channels is the same signal, not a widening of it, so what a player folds
2221 // back down is what was mixed.
2222 let mut pcm: Vec<i16> = vec![0; VORBIS_HOP * 2];
2223 match audio.channels < 2 {
2224 true => pcm.extend(samples.iter().flat_map(|&s| [s as i16, s as i16])),
2225 false => pcm.extend(samples.iter().map(|&s| s as i16)),
2226 }
2227 // The block grid has to run past the last real sample or the tail is never
2228 // coded at all; the granule below is what trims the padding back off.
2229 let frames = samples.len() / usize::from(audio.channels).max(1);
2230 pcm.resize(pcm.len() + VORBIS_HOP * 4 * 2, 0);
2231
2232 let mut encoder = rusty_vorbis::VorbisEncoder::new(rusty_vorbis::VorbisEncoderConfig {
2233 bitrate_bps: rusty_vorbis::BITRATE_NOMINAL,
2234 quality: VORBIS_QUALITY,
2235 });
2236 encoder
2237 .push_pcm_s16(&pcm, 2, audio.sample_rate)
2238 .map_err(|e| format!("vorbis encode: {e}"))?;
2239 encoder.finish();
2240 let mut packets = Vec::new();
2241 loop {
2242 match encoder.next_packet() {
2243 Ok(packet) => packets.push(packet),
2244 Err(rusty_vorbis::Error::Eof) => break,
2245 Err(e) => return Err(format!("vorbis encode: {e}").into()),
2246 }
2247 }
2248 // Identification, comment and setup, then at least one audio packet: fewer
2249 // than four and there is no stream to page.
2250 if packets.len() < 4 {
2251 return Err(format!("vorbis encode: {} packets is not a stream", packets.len()).into());
2252 }
2253 let headers = [
2254 &packets[0].data[..],
2255 &packets[1].data[..],
2256 &packets[2].data[..],
2257 ];
2258 let extradata = oxideav_ogg::mux::xiph_lace(&headers)
2259 .ok_or("vorbis encode: the three headers would not lace")?;
2260
2261 let time_base = oxideav_core::TimeBase::new(1, i64::from(audio.sample_rate));
2262 let mut params = oxideav_core::CodecParameters::audio(oxideav_core::CodecId::new("vorbis"));
2263 params.sample_rate = Some(audio.sample_rate);
2264 params.channels = Some(2);
2265 params.extradata = extradata;
2266 let stream = oxideav_core::StreamInfo {
2267 index: 0,
2268 time_base,
2269 duration: Some(frames as i64),
2270 start_time: Some(0),
2271 params,
2272 };
2273 let mut muxer = oxideav_ogg::mux::open_concrete(Box::new(File::create(out)?), &[stream])
2274 .map_err(|e| format!("ogg mux: {e:?}"))?;
2275 // Without this every audio packet of a short export lands on one page, and
2276 // the muxer's own note records what that costs: a first-audio-page-is-also-
2277 // EOS stream decodes short by half a small block in a reference decoder.
2278 muxer.set_page_target_bytes(Some(OGG_PAGE_BYTES));
2279 muxer
2280 .write_header()
2281 .map_err(|e| format!("ogg mux: {e:?}"))?;
2282 let last = packets.len() - 1;
2283 for (i, packet) in packets.iter().enumerate().skip(3) {
2284 // Correction 1 on every packet, correction 2 on the last one.
2285 let granule = match i == last {
2286 true => frames as i64,
2287 false => (packet.pts - VORBIS_HOP as i64).max(0),
2288 };
2289 muxer
2290 .write_packet(
2291 &oxideav_core::Packet::new(0, time_base, packet.data.clone())
2292 .with_pts(granule)
2293 .with_duration(packet.duration),
2294 )
2295 .map_err(|e| format!("ogg mux: {e:?}"))?;
2296 }
2297 muxer
2298 .write_trailer()
2299 .map_err(|e| format!("ogg mux: {e:?}"))?;
2300 Ok(())
2301}
2302
2303/// The page size [`write_ogg`] asks the Ogg muxer to aim at, in bytes. RFC 3533
2304/// describes pages as "usually 4-8 kB", which is also the muxer's own suggested
2305/// general-purpose value.
2306const OGG_PAGE_BYTES: usize = 4096;
2307
2308/// The same samples, losslessly compressed. `flacenc`'s errors are flattened to
2309/// text: they are not `Send + Sync`, and every one of them fails the export the
2310/// same way.
2311fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
2312 let config = flacenc::config::Encoder::default()
2313 .into_verified()
2314 .map_err(|(_, e)| format!("flac encoder config: {e}"))?;
2315 let source = flacenc::source::MemSource::from_samples(
2316 samples,
2317 usize::from(audio.channels),
2318 16,
2319 audio.sample_rate as usize,
2320 );
2321 let mut stream = flacenc::encode_with_fixed_block_size(&config, source, config.block_size)
2322 .map_err(|e| format!("flac encode: {e}"))?;
2323 // The block sizes are stated fixed, which is what the frames themselves say
2324 // (they are numbered, not sample-addressed). flacenc's single-threaded path
2325 // instead writes the *last* frame's length as the minimum, and a short final
2326 // frame is the normal case -- a stream whose `streaminfo` then disagrees
2327 // with its own blocking strategy. ffmpeg shrugs and plays it; symphonia,
2328 // which is this engine's own reader, rejects every frame header and reads
2329 // to EOF looking for a good one. Written this way the file reopens here,
2330 // which is the only test of an export that counts. (Same value flacenc's
2331 // own `par` path writes; the reference encoder does it too.)
2332 stream
2333 .stream_info_mut()
2334 .set_block_sizes(config.block_size, config.block_size)
2335 .map_err(|e| format!("flac block size: {e}"))?;
2336 let mut sink = flacenc::bitsink::ByteSink::new();
2337 stream
2338 .write(&mut sink)
2339 .map_err(|e| format!("flac write: {e}"))?;
2340 std::fs::write(out, sink.as_slice())?;
2341 Ok(())
2342}
2343
2344/// The I420 planes of one black picture, allocated once for a whole export: a
2345/// gap in the video lane is encoded, not skipped, or every frame after it would
2346/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention
2347/// [`crate::convert`] decodes with.
2348struct Black {
2349 y: Vec<u8>,
2350 uv: Vec<u8>,
2351 width: u32,
2352 height: u32,
2353}
2354
2355impl Black {
2356 fn new(meta: &VideoMeta) -> Self {
2357 let (w, h) = (meta.width as usize, meta.height as usize);
2358 Self {
2359 y: vec![16; w * h],
2360 uv: vec![128; w.div_ceil(2) * h.div_ceil(2)],
2361 width: meta.width,
2362 height: meta.height,
2363 }
2364 }
2365
2366 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
2367 (&self.y, &self.uv, &self.uv, self.width, self.height)
2368 }
2369}
2370
2371/// `Err` once a cancel has been asked for. Called at every point where the work
2372/// left is more than an instant, so an `esc` at 99.9% still stops the export
2373/// instead of quietly completing it.
2374fn cancelled(shared: &Shared) -> crate::Result<()> {
2375 if shared.cancel.load(Ordering::Relaxed) {
2376 return Err("export cancelled".into());
2377 }
2378 Ok(())
2379}
2380
2381/// The two containers an export writes, so the picture loop above is one loop:
2382/// H.264 goes into mp4, AV1 into Matroska, and nothing else is offered.
2383enum Muxer {
2384 Mp4(Mp4Muxer),
2385 Mkv(MkvMuxer),
2386}
2387
2388impl Muxer {
2389 fn finish(self) -> crate::Result<()> {
2390 match self {
2391 Self::Mp4(mp4) => mp4.finish(),
2392 Self::Mkv(mkv) => mkv.finish(),
2393 }
2394 }
2395}
2396
2397/// Writes one access unit, creating the file on the first one -- the parameter
2398/// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once
2399/// the encoder has coded something. Units with no coded slice are skipped: a
2400/// software encoder may hand back an empty buffer while it buffers, and the
2401/// muxer rejects a sample that would carry no picture.
2402fn write_video(
2403 muxer: &mut Option<Muxer>,
2404 out: &Path,
2405 meta: &VideoMeta,
2406 settings: &ExportSettings,
2407 audio: Option<&AudioParams>,
2408 packets: &mut Option<Vec<crate::AacPacket>>,
2409 subs: &mut Vec<SubParams>,
2410 au: &[u8],
2411 key: bool,
2412) -> crate::Result<()> {
2413 if settings.format.is_hevc() {
2414 // The parameter sets are in the access unit -- every intra AU carries
2415 // VPS, SPS and PPS -- and the record built from them is what *both*
2416 // containers declare the track with: an mp4's `hvcC` box and a
2417 // Matroska `CodecPrivate` are the same bytes, so the two files are one
2418 // stream written twice rather than two.
2419 let sample =
2420 crate::mux::annex_b_to_hvcc(au).ok_or("a coded HEVC unit with no slice in it")?;
2421 if settings.format == Format::Hevc {
2422 let muxer = match muxer {
2423 Some(Muxer::Mkv(mkv)) => mkv,
2424 Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
2425 none => {
2426 let hvcc = hevc_params(au)?;
2427 let sound = audio.zip(packets.take());
2428 let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create_hevc(
2429 out,
2430 &HevcParams {
2431 width: meta.width,
2432 height: meta.height,
2433 frame_rate: meta.frame_rate,
2434 hvcc: &hvcc,
2435 },
2436 sound,
2437 std::mem::take(subs),
2438 )?)) else {
2439 unreachable!("just inserted a Matroska muxer")
2440 };
2441 mkv
2442 }
2443 };
2444 return muxer.write_frame(&sample, key);
2445 }
2446 let muxer = match muxer {
2447 Some(Muxer::Mp4(mp4)) => mp4,
2448 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
2449 none => {
2450 let hvcc = hevc_params(au)?;
2451 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_hevc(
2452 out,
2453 &HevcParams {
2454 width: meta.width,
2455 height: meta.height,
2456 frame_rate: meta.frame_rate,
2457 hvcc: &hvcc,
2458 },
2459 audio,
2460 )?)) else {
2461 unreachable!("just inserted an mp4 muxer")
2462 };
2463 mp4
2464 }
2465 };
2466 return muxer.write_coded_sample(&sample, key);
2467 }
2468 if settings.format.is_av1() {
2469 // Every AV1 stream opens on a keyframe, and a keyframe carries the
2470 // sequence header the track has to declare: an encoder that handed back
2471 // neither has produced nothing a decoder can start. The same header goes
2472 // into a `CodecPrivate` and into an `av1C` -- one record, two containers.
2473 fn params<'a>(meta: &VideoMeta, au: &'a [u8]) -> crate::Result<Av1Params<'a>> {
2474 Ok(Av1Params {
2475 width: meta.width,
2476 height: meta.height,
2477 frame_rate: meta.frame_rate,
2478 config: crate::mux::av1_sequence_header(au)
2479 .ok_or("the first coded picture carries no AV1 sequence header")?,
2480 })
2481 }
2482 if settings.format == Format::Av1 {
2483 let muxer = match muxer {
2484 Some(Muxer::Mkv(mkv)) => mkv,
2485 Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
2486 none => {
2487 // The sound with it, all of it: the Matroska muxer writes the
2488 // packets into the clusters of the pictures they play under.
2489 let sound = audio.zip(packets.take());
2490 let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create(
2491 out,
2492 &params(meta, au)?,
2493 sound,
2494 std::mem::take(subs),
2495 )?)) else {
2496 unreachable!("just inserted a Matroska muxer")
2497 };
2498 mkv
2499 }
2500 };
2501 return muxer.write_frame(au, key);
2502 }
2503 let muxer = match muxer {
2504 Some(Muxer::Mp4(mp4)) => mp4,
2505 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
2506 none => {
2507 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1(
2508 out,
2509 &params(meta, au)?,
2510 audio,
2511 )?)) else {
2512 unreachable!("just inserted an mp4 muxer")
2513 };
2514 mp4
2515 }
2516 };
2517 return muxer.write_coded_sample(au, key);
2518 }
2519 if !crate::mux::has_coded_slice(au) {
2520 return Ok(());
2521 }
2522 let muxer = match muxer {
2523 Some(Muxer::Mp4(mp4)) => mp4,
2524 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
2525 none => {
2526 let (sps, pps) = crate::mux::parameter_sets(au)
2527 .ok_or("the first coded picture carries no SPS/PPS")?;
2528 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create(
2529 out,
2530 &VideoParams {
2531 width: meta.width,
2532 height: meta.height,
2533 frame_rate: meta.frame_rate,
2534 sps,
2535 pps,
2536 },
2537 audio,
2538 )?)) else {
2539 unreachable!("just inserted an mp4 muxer")
2540 };
2541 mp4
2542 }
2543 };
2544 muxer.write_video_au(au)
2545}
2546
2547/// The `hvcC` record of the first coded unit, or the refusal by name. Split out
2548/// because both HEVC containers ask it in the same words.
2549fn hevc_params(au: &[u8]) -> crate::Result<Vec<u8>> {
2550 crate::mux::hvcc_record(au)
2551 .ok_or_else(|| crate::Error::from("the first coded picture carries no HEVC VPS/SPS/PPS"))
2552}
2553
2554fn bitrate_for(meta: &VideoMeta) -> u64 {
2555 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;
2556 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)
2557}
2558
2559fn forced(var: &str) -> bool {
2560 std::env::var_os(var).is_some_and(|v| v == "1")
2561}
2562
2563/// Hardware where it is available, software everywhere else -- chosen once for
2564/// the whole export, so the stream never changes encoder mid-file. Both codecs
2565/// have both seats: an AV1 export runs on the plugin's VA-API encoder where the
2566/// GPU has one and on `rav1e` where it has not, which is the same pair H.264 has
2567/// had and the same silent fallback.
2568enum Enc {
2569 Hw(HwEncoder),
2570 Sw {
2571 encoder: Encoder,
2572 /// The last access unit; owned because `rusty_h264` hands back a `Vec`
2573 /// while the plugin lends a slice, and the two have to look alike here.
2574 au: Vec<u8>,
2575 flushed: bool,
2576 },
2577 /// AV1 on the GPU, through the same plugin the H.264 seat uses.
2578 Av1Hw(HwEncoder),
2579 Av1Sw {
2580 context: rav1e::Context<u8>,
2581 /// Temporal units the encoder has finished but the caller has not
2582 /// collected: `rav1e` reorders and may hand back several at once, while
2583 /// this interface is one picture in, one unit out (the plugin's own
2584 /// `ready` queue exists for the same reason).
2585 ready: std::collections::VecDeque<(Vec<u8>, bool)>,
2586 /// The unit currently lent out, for the same reason `Sw` owns one.
2587 au: Vec<u8>,
2588 flushed: bool,
2589 },
2590 /// HEVC, intra-only and software only: `encode_idr_intra_au_cropped` is a
2591 /// *stateless* function of one picture, so a batch of frames is coded on as
2592 /// many cores as there are lanes and collected back in order.
2593 Hevc(HevcEnc),
2594}
2595
2596/// The intra HEVC seat. Frames arrive one at a time (the export walk is one
2597/// picture per timeline frame) and are held until there are [`lanes`] of them,
2598/// then coded in parallel and queued in **display order** -- fanning out is the
2599/// only thing that makes a pure-Rust HEVC export bearable (4.30 fps at 1080p on
2600/// 12 lanes against 0.55 fps on one, measured 2026-08-11), and an export whose
2601/// frames came back shuffled would be no export at all.
2602///
2603/// ponytail: a batch of padded planes sits in memory (~3 MB a frame at 1080p,
2604/// so ~37 MB at 12 lanes) and the tail of a timeline is coded on fewer lanes
2605/// than the middle. Upgrade path is a pipeline that keeps every lane fed from a
2606/// decoder running ahead of the encoder rather than a batch barrier.
2607struct HevcEnc {
2608 /// Padded I420 planes waiting for a lane, in display order.
2609 pending: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)>,
2610 /// Coded access units not yet collected, in the same order.
2611 ready: std::collections::VecDeque<Vec<u8>>,
2612 /// The unit currently lent out, for the reason `Sw` owns one.
2613 au: Vec<u8>,
2614 /// The *coded* size: the picture's, rounded up to the 16-sample CTB grid.
2615 width: usize,
2616 height: usize,
2617 /// Luma samples the conformance window crops off the right and the bottom,
2618 /// so a decoder outputs the picture's own size ([`pad_to_ctb`]).
2619 crop: (usize, usize),
2620 qp: i32,
2621 lanes: usize,
2622 /// What the SPS says the samples mean. A decoder reads the bitstream before
2623 /// it reads the container, so an HEVC stream without this renders BT.601 in
2624 /// libavcodec however the file is tagged -- the container's `Colour` element
2625 /// and `colr` box are not enough on their own.
2626 signal: oxideav_h265::vui::VideoSignalType,
2627}
2628
2629impl Enc {
2630 /// Which seat this *is*, said the way [`video_label`] says it -- so the
2631 /// name a running export shows is the name the card showed, or the honest
2632 /// difference where the probe and the open disagreed.
2633 fn label(&self) -> &'static str {
2634 match self {
2635 Self::Hw(_) => video_label(Format::Mp4, true),
2636 Self::Sw { .. } => video_label(Format::Mp4, false),
2637 Self::Av1Hw(_) => video_label(Format::Av1, true),
2638 Self::Av1Sw { .. } => video_label(Format::Av1, false),
2639 Self::Hevc(_) => video_label(Format::Hevc, false),
2640 }
2641 }
2642
2643 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
2644 // Which *codec* the picture is, not which container it goes in: both AV1
2645 // formats run the same encoder, and so do both HEVC ones.
2646 if settings.format.is_av1() {
2647 return Self::open_av1(meta, settings);
2648 }
2649 if settings.format.is_hevc() {
2650 return Self::open_hevc(meta, settings);
2651 }
2652 // A caller's number goes through the same clamp as the computed one: a
2653 // zero bitrate switches the software encoder's lookahead on, which would
2654 // break the one-picture-per-call contract `encode` documents below.
2655 let bitrate = bitrate_of(meta, settings);
2656 // The plugin wants an exact rational, and the muxer already picks one
2657 // that is exact at every rate we can read -- `fps * 1000 / 1000` would
2658 // hand 24000/1001 over as a rounded 23.976, which is the same
2659 // truncation the container timing had.
2660 crate::mux::frame_timing(meta.frame_rate)?;
2661 if let Some(hw) = hw_seat(meta, settings) {
2662 eprintln!("export encoder: hardware (VA-API plugin)");
2663 return Ok(Self::Hw(hw));
2664 }
2665 eprintln!("export encoder: software (rusty_h264)");
2666 let mut cfg = EncoderConfig::new(meta.width as usize, meta.height as usize);
2667 cfg.framerate = meta.frame_rate as f32;
2668 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;
2669 // Two seconds between key frames, and no B-frames on either path: the
2670 // muxer times everything by duration alone, which reordering would break.
2671 cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32;
2672 cfg.bframes = 0;
2673 // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same
2674 // bitrate, so Fast is what a fallback should be.
2675 cfg.preset = Preset::Fast;
2676 let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?;
2677 Ok(Self::Sw {
2678 encoder,
2679 au: Vec::new(),
2680 flushed: false,
2681 })
2682 }
2683
2684 /// The AV1 pair. The hardware seat is the plugin's, opened by a symbol of
2685 /// its own (`vh_enc_av1_open`) so a plugin built before AV1 encode existed
2686 /// simply has none and this falls through -- the same "no" a GPU without an
2687 /// AV1 encode entrypoint gives, and the same silent fallback either way.
2688 ///
2689 /// It is **opt-in**, which is the one place this pair does not mirror the
2690 /// H.264 one: the vendored cros-codecs AV1 encoder hung the GPU on this
2691 /// project's own radeonsi box -- `engine_hw: operation failed`, then an
2692 /// amdgpu hard recovery and a lost context, measured 2026-08-10 exporting
2693 /// the 720p fixture. A software encoder that takes half a minute is a worse
2694 /// export than a hardware one; a driver reset is not an export at all. So
2695 /// the plugin's AV1 seat is wired, kept and only entered when `VE_HW_AV1=1`
2696 /// asks for it by name.
2697 ///
2698 /// ponytail: the upgrade path is a driver this was reproduced against (or a
2699 /// cros-codecs release that fixes it) plus a probe encode of one frame at
2700 /// open, after which this can prefer hardware the way H.264 does.
2701 fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
2702 let bitrate = bitrate_of(meta, settings);
2703 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
2704 // Two seconds between keyframes, as the H.264 seat does: a seek may only
2705 // land on one, and this is what a cluster of the Matroska file is.
2706 let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64;
2707 if let Some(hw) = hw_seat(meta, settings) {
2708 eprintln!("export encoder: hardware AV1 (VA-API plugin)");
2709 return Ok(Self::Av1Hw(hw));
2710 }
2711 eprintln!("export encoder: software AV1 (rav1e)");
2712 let mut cfg = rav1e::EncoderConfig::default();
2713 cfg.width = meta.width as usize;
2714 cfg.height = meta.height as usize;
2715 cfg.bit_depth = 8;
2716 cfg.chroma_sampling = rav1e::prelude::ChromaSampling::Cs420;
2717 // Seconds per frame, which is what `frame_timing` already has as an
2718 // exact rational -- 1001/24000 rather than a rounded 23.976.
2719 cfg.time_base = rav1e::prelude::Rational::new(u64::from(fps_den), u64::from(fps_num));
2720 cfg.min_key_frame_interval = gop;
2721 cfg.max_key_frame_interval = gop;
2722 cfg.bitrate = bitrate.min(i32::MAX as u64) as i32;
2723 // The fastest preset there is, and it is still slow: `rav1e` is built
2724 // here without its assembly (no `nasm` in this project's build), so an
2725 // export runs at a fraction of realtime. The export worker reports
2726 // progress the whole way, which is what makes that bearable rather than
2727 // hidden.
2728 cfg.speed_settings = rav1e::prelude::SpeedSettings::from_preset(AV1_SPEED);
2729 // What the sequence header says the samples mean, for the reason
2730 // [`video_signal_type`] gives: a container tag is the second answer a
2731 // decoder looks at, not the first. Written as rav1e's own enums rather
2732 // than the H.273 numbers -- the crate has no `from` for the code points,
2733 // and the output rule only ever picks one of these two spaces.
2734 let out = ColorDescription::output(meta.height);
2735 cfg.pixel_range = rav1e::prelude::PixelRange::Limited;
2736 cfg.color_description = Some(match out.matrix {
2737 Matrix::Bt709 => rav1e::prelude::ColorDescription {
2738 color_primaries: rav1e::prelude::ColorPrimaries::BT709,
2739 transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT709,
2740 matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT709,
2741 },
2742 _ => rav1e::prelude::ColorDescription {
2743 color_primaries: rav1e::prelude::ColorPrimaries::BT601,
2744 transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT601,
2745 matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT601,
2746 },
2747 });
2748 let config = rav1e::Config::new()
2749 .with_encoder_config(cfg)
2750 .with_threads(std::thread::available_parallelism().map_or(1, |n| n.get()));
2751 let context = config
2752 .new_context::<u8>()
2753 .map_err(|e| format!("software AV1 encoder: {e}"))?;
2754 Ok(Self::Av1Sw {
2755 context,
2756 ready: std::collections::VecDeque::new(),
2757 au: Vec::new(),
2758 flushed: false,
2759 })
2760 }
2761
2762 /// The intra HEVC seat, software and frame-parallel. There is no hardware
2763 /// half: the plugin encodes H.264 and AV1 and nothing else, which
2764 /// [`hw_seat`] says by refusing to probe one.
2765 ///
2766 /// **Intra-only, deliberately.** The vendored encoder's inter modes code
2767 /// 1080p at 0.81 fps across 12 cores (measured 2026-08-11) -- a minute of
2768 /// timeline in half an hour, which is not an export anybody waits for --
2769 /// while the intra path does 4.30 fps on the same picture and the same
2770 /// cores. So every frame is an IDR, the file is an intraframe master in the
2771 /// shape of ProRes or DNxHD, and the card says so where a user picks it.
2772 ///
2773 /// The picture is coded **padded** to the 16-sample CTB grid and the SPS
2774 /// crops it back ([`pad_to_ctb`], the vendored conformance-window patch), so
2775 /// 1920x1080 is a legal export rather than a refusal.
2776 fn open_hevc(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
2777 // The muxers time by it and the mp4 one wants an exact rational: asked
2778 // here so an impossible rate fails before a frame is coded.
2779 crate::mux::frame_timing(meta.frame_rate)?;
2780 // 4:2:0 addresses its conformance window in *chroma* samples, so an odd
2781 // picture cannot be cropped back to itself -- and an odd dimension has
2782 // no chroma plane of its own to begin with. Named rather than padded to
2783 // something a decoder would then show a column of.
2784 if meta.width % 2 != 0 || meta.height % 2 != 0 {
2785 return Err(format!(
2786 "{}x{} cannot be written as HEVC: 4:2:0 needs even dimensions",
2787 meta.width, meta.height
2788 )
2789 .into());
2790 }
2791 let (width, height) = (
2792 (meta.width as usize).next_multiple_of(CTB),
2793 (meta.height as usize).next_multiple_of(CTB),
2794 );
2795 let lanes = std::thread::available_parallelism().map_or(1, |n| n.get());
2796 eprintln!("export encoder: software HEVC intra (oxideav-h265)");
2797 Ok(Self::Hevc(HevcEnc {
2798 pending: Vec::new(),
2799 ready: std::collections::VecDeque::new(),
2800 au: Vec::new(),
2801 width,
2802 height,
2803 crop: (width - meta.width as usize, height - meta.height as usize),
2804 qp: hevc_qp(meta, settings),
2805 lanes: lanes.min(HEVC_LANES),
2806 signal: video_signal_type(meta.height),
2807 }))
2808 }
2809
2810 /// One picture in, at most one access unit out, and whether that unit is one
2811 /// a decoder may be started from -- which only the Matroska muxer asks, the
2812 /// mp4 one reading its own sync flag off the IDR slice.
2813 ///
2814 /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer
2815 /// when its lookahead is active, which would make this "one access unit"
2816 /// a lie and every sample duration with it. It is inactive here because
2817 /// lookahead needs a zero bitrate and this path is always CBR; a future
2818 /// constant-QP mode has to split the buffer per access unit first.
2819 fn encode(
2820 &mut self,
2821 y: &[u8],
2822 u: &[u8],
2823 v: &[u8],
2824 width: u32,
2825 height: u32,
2826 ) -> crate::Result<Option<(&[u8], bool)>> {
2827 match self {
2828 Self::Av1Hw(hw) => {
2829 let au = hw.encode(y, u, v, width, height, false)?;
2830 // What the *bitstream* says, not what was asked for: an AV1
2831 // keyframe carries the sequence header, which is the same mark
2832 // `demux` reads a sync point off. A driver that emitted one
2833 // unasked is then still a seek target, and one that skipped a
2834 // requested keyframe cannot be mistaken for a decoder's start.
2835 Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
2836 }
2837 Self::Av1Sw {
2838 context, ready, au, ..
2839 } => {
2840 let mut frame = context.new_frame();
2841 let (w, h) = (width as usize, height as usize);
2842 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
2843 frame.planes[0].copy_from_raw_u8(&y[..w * h], w, 1);
2844 frame.planes[1].copy_from_raw_u8(&u[..cw * ch], cw, 1);
2845 frame.planes[2].copy_from_raw_u8(&v[..cw * ch], cw, 1);
2846 if let Err(e) = context.send_frame(frame) {
2847 return Err(format!("software AV1 encode: {e}").into());
2848 }
2849 collect_av1(context, ready)?;
2850 Ok(pop_av1(ready, au))
2851 }
2852 Self::Hevc(hevc) => {
2853 hevc.pending.push(pad_to_ctb(
2854 y,
2855 u,
2856 v,
2857 width as usize,
2858 height as usize,
2859 hevc.width,
2860 hevc.height,
2861 ));
2862 if hevc.pending.len() >= hevc.lanes {
2863 hevc.code_batch()?;
2864 }
2865 // Every intra AU is an IDR, so every one of them is a key
2866 // frame -- which is what an intraframe master means.
2867 Ok(pop_hevc(hevc))
2868 }
2869 Self::Hw(hw) => Ok(hw
2870 .encode(y, u, v, width, height, false)?
2871 .map(|au| (au, false))),
2872 Self::Sw { encoder, au, .. } => {
2873 let frame = YuvFrame {
2874 width: width as usize,
2875 height: height as usize,
2876 y: y.to_vec(),
2877 u: u.to_vec(),
2878 v: v.to_vec(),
2879 };
2880 *au = encoder
2881 .try_encode(&frame)
2882 .map_err(|e| format!("software encode: {e}"))?;
2883 Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty()))
2884 }
2885 }
2886 }
2887
2888 /// End of stream; call until it returns `None`.
2889 fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> {
2890 match self {
2891 Self::Av1Hw(hw) => {
2892 let au = hw.drain()?;
2893 Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
2894 }
2895 Self::Av1Sw {
2896 context,
2897 ready,
2898 au,
2899 flushed,
2900 } => {
2901 if !*flushed {
2902 *flushed = true;
2903 context.flush();
2904 collect_av1(context, ready)?;
2905 }
2906 Ok(pop_av1(ready, au))
2907 }
2908 Self::Hevc(hevc) => {
2909 // The tail batch: fewer frames than lanes, coded on as many
2910 // cores as there are frames left.
2911 if !hevc.pending.is_empty() {
2912 hevc.code_batch()?;
2913 }
2914 Ok(pop_hevc(hevc))
2915 }
2916 Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))),
2917 Self::Sw {
2918 encoder,
2919 au,
2920 flushed,
2921 } => {
2922 if *flushed {
2923 return Ok(None);
2924 }
2925 *flushed = true;
2926 *au = encoder
2927 .try_flush()
2928 .map_err(|e| format!("software encoder flush: {e}"))?;
2929 Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty()))
2930 }
2931 }
2932 }
2933}
2934
2935impl HevcEnc {
2936 /// The whole pending batch, one frame per lane, collected back in the order
2937 /// it went out -- `std::thread::scope`, because the encode borrows the
2938 /// planes rather than copying them again. A panic inside a lane comes back
2939 /// as an error rather than unwinding the export thread.
2940 fn code_batch(&mut self) -> crate::Result<()> {
2941 let (width, height, qp, crop) = (self.width, self.height, self.qp, self.crop);
2942 let signal = self.signal;
2943 let coded: Vec<crate::Result<Vec<u8>>> = std::thread::scope(|scope| {
2944 let lanes: Vec<_> = self
2945 .pending
2946 .iter()
2947 .map(|(y, cb, cr)| {
2948 scope.spawn(move || {
2949 oxideav_h265::encoder::intra::encode_idr_intra_au_cropped(
2950 y,
2951 cb,
2952 cr,
2953 width,
2954 height,
2955 qp,
2956 crop.0,
2957 crop.1,
2958 Some(signal),
2959 )
2960 .map(|coded| coded.au)
2961 .map_err(|e| crate::Error::from(format!("HEVC intra encode: {e:?}")))
2962 })
2963 })
2964 .collect();
2965 lanes
2966 .into_iter()
2967 .map(|lane| {
2968 lane.join()
2969 .unwrap_or_else(|_| Err("an HEVC encode lane panicked".into()))
2970 })
2971 .collect()
2972 });
2973 for au in coded {
2974 self.ready.push_back(au?);
2975 }
2976 self.pending.clear();
2977 Ok(())
2978 }
2979}
2980
2981/// The oldest coded intra AU, lent out under the same "valid until the next
2982/// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key flag
2983/// is not a guess.
2984fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> {
2985 hevc.au = hevc.ready.pop_front()?;
2986 Some((&hevc.au[..], true))
2987}
2988
2989/// One I420 picture copied onto the padded plane sizes the CTB grid needs, the
2990/// added rows and columns filled by **replicating the edge** rather than with
2991/// black: the padding is coded and then cropped away, and a black border would
2992/// bleed into the last real column through the intra prediction and the
2993/// transform that straddles it.
2994fn pad_to_ctb(
2995 y: &[u8],
2996 u: &[u8],
2997 v: &[u8],
2998 width: usize,
2999 height: usize,
3000 padded_w: usize,
3001 padded_h: usize,
3002) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
3003 let plane = |src: &[u8], w: usize, h: usize, pw: usize, ph: usize| {
3004 let mut out = vec![0u8; pw * ph];
3005 for row in 0..ph {
3006 let src_row = &src[row.min(h - 1) * w..][..w];
3007 let dst = &mut out[row * pw..][..pw];
3008 dst[..w].copy_from_slice(src_row);
3009 dst[w..].fill(src_row[w - 1]);
3010 }
3011 out
3012 };
3013 (
3014 plane(y, width, height, padded_w, padded_h),
3015 plane(u, width / 2, height / 2, padded_w / 2, padded_h / 2),
3016 plane(v, width / 2, height / 2, padded_w / 2, padded_h / 2),
3017 )
3018}
3019
3020/// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a
3021/// user picked -- the card has no QP control and this codec has no rate control,
3022/// so the two are joined by measurement rather than promised to each other.
3023///
3024/// The encoder codes ~0.6 bits per pixel at QP 27 ([`HEVC_BPP_AT_27`], measured
3025/// on the 720p and 1080p benches to within 4% of each other), and a step of 6 QP
3026/// is a factor of two in rate, which is the classic HEVC relation. So the QP
3027/// that would land on a target is `27 + 6 * log2(0.6 / target)` -- and it is
3028/// clamped, because this is a *quality* dial and not a rate controller: below QP
3029/// 22 the file grows without a picture to show for it, and past QP 40 an
3030/// intra-only frame goes blocky in a way no bitrate row asked for. A 1080p30
3031/// timeline at the automatic 6.2 Mbps therefore codes at QP 40 and comes out
3032/// bigger than that, which is what "intra-only, large files" on the format row
3033/// means: the row buys quality, not a size.
3034fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 {
3035 let pixels = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate;
3036 let target = bitrate_of(meta, settings) as f64 / pixels.max(1.0);
3037 let qp = 27.0 + 6.0 * (HEVC_BPP_AT_27 / target.max(f64::MIN_POSITIVE)).log2();
3038 (qp.round() as i32).clamp(HEVC_QP_MIN, HEVC_QP_MAX)
3039}
3040
3041/// What the *bitstream* says the samples mean, in the words a sequence header
3042/// spells them -- the same H.273 code points [`crate::mux`] writes into the
3043/// container, from the same [`ColorDescription::output`] rule, so the two halves
3044/// of a file cannot drift apart.
3045///
3046/// This exists because a container tag is not enough: libavcodec takes the
3047/// bitstream's answer first, and a stream that says nothing is "unspecified",
3048/// which renders BT.601 -- a visible shift on a 709 export that a player reads
3049/// from the wrong matrix. Every export is limited range, which is what
3050/// `video_full_range_flag = false` says here.
3051fn video_signal_type(height: u32) -> oxideav_h265::vui::VideoSignalType {
3052 let (primaries, transfer, matrix) = ColorDescription::output(height).codes();
3053 oxideav_h265::vui::VideoSignalType {
3054 // "Unspecified", which is what every encoder here writes: the field is
3055 // the analogue system a picture came off, and none of these did.
3056 video_format: 5,
3057 video_full_range_flag: false,
3058 colour_description: Some(oxideav_h265::vui::ColourDescription {
3059 colour_primaries: primaries as u8,
3060 transfer_characteristics: transfer as u8,
3061 matrix_coeffs: matrix as u8,
3062 }),
3063 }
3064}
3065
3066/// Every temporal unit `rav1e` has finished, moved into the queue in display
3067/// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is
3068/// through) are the two ways it says there is nothing more; `Encoded` means a
3069/// picture was coded but not yet packetised, which is a *keep asking* -- taking
3070/// it for an end leaves the tail of the export inside the encoder.
3071fn collect_av1(
3072 context: &mut rav1e::Context<u8>,
3073 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
3074) -> crate::Result<()> {
3075 use rav1e::prelude::{EncoderStatus, FrameType};
3076 loop {
3077 match context.receive_packet() {
3078 Ok(packet) => ready.push_back((packet.data, packet.frame_type == FrameType::KEY)),
3079 Err(EncoderStatus::Encoded) => {}
3080 Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()),
3081 Err(e) => return Err(format!("software AV1 encode: {e}").into()),
3082 }
3083 }
3084}
3085
3086/// The oldest finished unit, moved into the buffer that is lent out -- the same
3087/// "valid until the next call" contract the plugin's slice has.
3088fn pop_av1<'a>(
3089 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
3090 au: &'a mut Vec<u8>,
3091) -> Option<(&'a [u8], bool)> {
3092 let (unit, key) = ready.pop_front()?;
3093 *au = unit;
3094 Some((&au[..], key))
3095}
3096
3097/// I420 straight out of the decoder: the export never converts to BGRA and back,
3098/// which would cost two conversions and a generation of colour precision.
3099///
3100/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`,
3101/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to
3102/// software: a hardware decode that fails after the first picture fails the
3103/// export, which then deletes the half-written file.
3104enum ClipDecoder {
3105 Hw(HwSession),
3106 Sw(SwDecoder),
3107 /// A still image: one picture, handed out for as long as the span runs.
3108 /// It is decoded here rather than in `run`'s loop for the same reason the
3109 /// other two are opened there -- the span's pictures come from one place.
3110 Still(crate::decode::Still),
3111}
3112
3113impl ClipDecoder {
3114 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
3115 // Before either decoder: an image is not a stream, so `start_frame`
3116 // means nothing to it -- every frame of a still span is the same
3117 // picture, which is what playback shows for it too.
3118 if crate::is_image(path) {
3119 return Ok(Self::Still(crate::decode::Still::open(path)?));
3120 }
3121 if !forced("VE_SW")
3122 && let Some(hw) = HwSession::open_at(path, start_frame)
3123 {
3124 return Ok(Self::Hw(hw));
3125 }
3126 Ok(Self::Sw(SwDecoder::open(path, start_frame)?))
3127 }
3128
3129 /// The next picture as tightly packed I420, borrowed until the call after.
3130 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
3131 match self {
3132 Self::Still(still) => Ok(Some(still.picture())),
3133 Self::Hw(hw) => hw.next_frame(),
3134 Self::Sw(sw) => {
3135 if !sw.advance()? {
3136 return Ok(None);
3137 }
3138 let frame = sw.frame.as_ref().expect("advance stored a picture");
3139 Ok(Some((
3140 &frame.y,
3141 &frame.u,
3142 &frame.v,
3143 frame.width as u32,
3144 frame.height as u32,
3145 )))
3146 }
3147 }
3148 }
3149}
3150
3151struct SwDecoder {
3152 demuxer: Demuxer,
3153 decoder: Decoder,
3154 /// Display index of the next picture the decoder will produce. Signed: a
3155 /// sync sample inside what the edit list trims is before frame 0.
3156 index: i64,
3157 start: u32,
3158 frame: Option<YuvFrame>,
3159}
3160
3161impl SwDecoder {
3162 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
3163 let (meta, mut demuxer) = Demuxer::open(path)?;
3164 // The software decoder is H.264-only; an HEVC or VP9 source that got
3165 // this far means the plugin refused it, and the export says so instead
3166 // of handing those bytes to `rusty_h264`.
3167 if meta.codec != crate::demux::Codec::H264 {
3168 return Err(meta.codec.needs_plugin().into());
3169 }
3170 // Decoding restarts at a sync sample, so pictures between it and the in
3171 // point are decoded (the target references them) and then dropped.
3172 let index = demuxer.seek_to_sync_at_or_before(start_frame);
3173 Ok(Self {
3174 demuxer,
3175 decoder: Decoder::new(),
3176 index,
3177 start: start_frame,
3178 frame: None,
3179 })
3180 }
3181
3182 /// Decodes up to and including the next picture at or after the in point,
3183 /// leaving it in `frame`. `false` at end of stream.
3184 fn advance(&mut self) -> crate::Result<bool> {
3185 loop {
3186 let Some(au) = self.demuxer.next_access_unit()? else {
3187 return Ok(false);
3188 };
3189 let decoded = self
3190 .decoder
3191 .decode(&au)
3192 .map_err(|e| format!("decode at picture {}: {e}", self.index))?;
3193 let Some(yuv) = decoded else { continue };
3194 let wanted = self.index >= i64::from(self.start);
3195 self.index += 1;
3196 if wanted {
3197 self.frame = Some(yuv);
3198 return Ok(true);
3199 }
3200 }
3201 }
3202}
3203
3204#[cfg(test)]
3205mod tests {
3206 use super::*;
3207
3208 /// Three seconds of two tones, one per channel, interleaved: enough shape
3209 /// that a correlation says something and enough length that the encoder
3210 /// settles into a mode.
3211 fn two_tones(secs: usize) -> Vec<f32> {
3212 (0..OPUS_RATE as usize * secs)
3213 .flat_map(|i| {
3214 let t = i as f32 / OPUS_RATE as f32;
3215 let tau = std::f32::consts::TAU;
3216 [
3217 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin(),
3218 0.25 * (tau * 880.0 * t).sin(),
3219 ]
3220 })
3221 .collect()
3222 }
3223
3224 /// The best correlation of one channel of `got` against `want`, and the
3225 /// offset it sat at.
3226 fn align(want: &[f32], got: &[f32]) -> (f64, usize) {
3227 let (mut best, mut at) = (-2.0, 0);
3228 let window = OPUS_RATE as usize;
3229 for lag in 0..1400 {
3230 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
3231 for (x, y) in want[..window]
3232 .iter()
3233 .step_by(2)
3234 .zip(got[lag * 2..].iter().step_by(2))
3235 {
3236 num += f64::from(*x) * f64::from(*y);
3237 da += f64::from(*x) * f64::from(*x);
3238 db += f64::from(*y) * f64::from(*y);
3239 }
3240 let c = num / (da.sqrt() * db.sqrt()).max(1e-12);
3241 if c > best {
3242 (best, at) = (c, lag);
3243 }
3244 }
3245 (best, at)
3246 }
3247
3248 fn ruopus_decode(packets: &[crate::AacPacket]) -> Vec<f32> {
3249 let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);
3250 let mut pcm = Vec::new();
3251 for packet in packets {
3252 pcm.extend(
3253 decoder
3254 .decode_packet(&packet.bytes)
3255 .expect("a valid packet"),
3256 );
3257 }
3258 pcm
3259 }
3260
3261 /// Why [`OPUS_MAX_KBPS`] is a cap, why [`OPUS_PRE_SKIP`] is a constant and
3262 /// why [`opus_fidelity`] exists at all -- all three measured here against
3263 /// `ruopus`, the decoder this project reads every Opus file back with, and
3264 /// which matches ffmpeg's libopus decode of a libopus file to correlation
3265 /// 1.00000 on this very signal.
3266 ///
3267 /// The last third **asserts the bug**: at 256 kbps stereo `opus-rs 0.1.26`
3268 /// writes packets that only its own decoder reads back, and pinning that
3269 /// here is what makes a version bump that fixes it *fail* -- which is the
3270 /// signal to raise the cap rather than a reason to widen it quietly.
3271 #[test]
3272 fn the_opus_encoder_is_pinned_to_the_band_it_was_measured_in() {
3273 let pcm = two_tones(3);
3274 for kbps in [96, OPUS_MAX_KBPS] {
3275 let (packets, pre_skip) = encode_opus(&pcm, kbps)
3276 .expect("the encoder opens")
3277 .expect("and inside the band it passes its own round trip");
3278 assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16);
3279 assert_eq!(
3280 packets.len(),
3281 pcm.len().div_ceil(OPUS_FRAME * 2) + 2,
3282 "one packet per 20 ms frame, plus the warm-up and the flush"
3283 );
3284 let decoded = ruopus_decode(&packets);
3285 let (c, lag) = align(&pcm, &decoded);
3286 // From the first audible sample, head included -- and the head is
3287 // why this is 0.98 and not the 0.999 below: the encoder's first
3288 // audible 20 ms still comes out about 6 dB down whatever is fed in
3289 // ahead of it (a second warm-up frame changes the numbers here in
3290 // no decimal place), so that ramp is a property of `opus-rs 0.1.26`
3291 // and is stated rather than hidden behind a loose threshold.
3292 assert!(c >= 0.98, "{kbps} kbps came back at correlation {c:.4}");
3293 let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..]);
3294 assert!(
3295 settled >= 0.999,
3296 "{kbps} kbps past the first frame: correlation {settled:.4}"
3297 );
3298 // The whole point of the number in the header: drop exactly that
3299 // many samples and the sound starts where the timeline says. A lag
3300 // that is not it is a file that plays late or eats its own head.
3301 assert_eq!(
3302 lag,
3303 usize::from(pre_skip),
3304 "{kbps} kbps: the declared pre-skip is not where the sound starts"
3305 );
3306 // ...and the tail is all there: the flush frame pushed the last
3307 // samples out, so what is left after the pre-skip covers the input.
3308 assert!(
3309 decoded.len() - usize::from(pre_skip) * 2 >= pcm.len(),
3310 "{kbps} kbps: the track ends {} samples short of the timeline",
3311 (pcm.len() + usize::from(pre_skip) * 2 - decoded.len()) / 2
3312 );
3313 // The gate the export runs before it writes anything, on a track
3314 // that deserves to pass it.
3315 let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip));
3316 assert!(
3317 fidelity >= OPUS_MIN_FIDELITY,
3318 "{kbps} kbps scored {fidelity:.4} on its own round trip"
3319 );
3320 }
3321
3322 // Above the band, straight at the crate, since `encode_opus` clamps: the
3323 // packets come back as noise, and the gate says so. This is the check
3324 // that the guard actually catches the failure it is built for -- and the
3325 // one that fails, loudly, the day `opus-rs` fixes it.
3326 let mut encoder =
3327 opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio).unwrap();
3328 encoder.bitrate_bps = 256_000;
3329 encoder.complexity = 10;
3330 let mut out = vec![0u8; 1500];
3331 let packets: Vec<crate::AacPacket> = pcm
3332 .chunks_exact(OPUS_FRAME * 2)
3333 .map(|block| {
3334 let len = encoder.encode(block, OPUS_FRAME, &mut out).unwrap();
3335 crate::AacPacket {
3336 bytes: out[..len].to_vec(),
3337 samples: OPUS_FRAME as u32,
3338 }
3339 })
3340 .collect();
3341 let fidelity = opus_fidelity(&packets, &pcm, usize::from(OPUS_PRE_SKIP));
3342 assert!(
3343 fidelity < OPUS_MIN_FIDELITY,
3344 "opus-rs now encodes 256 kbps stereo that a conformant decoder reads \
3345 back (fidelity {fidelity:.4}): raise OPUS_MAX_KBPS and delete this half"
3346 );
3347 }
3348
3349 /// The gate on a track too long to listen to whole: it samples, and what it
3350 /// samples it judges one window at a time. A five-second stretch that is not
3351 /// the mix fails the whole track -- where the old whole-track sum would have
3352 /// let it average away against the minutes either side -- and a silent track
3353 /// is not a failure at all, which is what it used to be scored as (0.0
3354 /// against a denominator of nothing, and an all-quiet timeline fell back to
3355 /// AAC for it).
3356 ///
3357 /// 61 s of sound: one second past the minute the gate stops listening whole,
3358 /// which is what puts this on the sampled path at all.
3359 #[test]
3360 fn a_long_track_is_judged_by_its_worst_sampled_window() {
3361 let pcm = two_tones(61);
3362 let (packets, pre_skip) = encode_opus(&pcm, 96)
3363 .expect("the encoder opens")
3364 .expect("and passes its own round trip");
3365 assert!(
3366 packets.len() > FIDELITY_WINDOW * FIDELITY_WINDOWS,
3367 "{} packets is not the sampled path",
3368 packets.len()
3369 );
3370 let pre_skip = usize::from(pre_skip);
3371 let whole = opus_fidelity(&packets, &pcm, pre_skip);
3372 assert!(whole >= OPUS_MIN_FIDELITY, "a good track scored {whole:.4}");
3373
3374 // One window's worth of the *mix* replaced by its own phase inverse:
3375 // the packets still decode, they are simply no longer this sound. Placed
3376 // on a window the gate samples -- window 6 of the twelve, by the same
3377 // arithmetic the gate spreads them with.
3378 let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);
3379 let from = (6 * step * OPUS_FRAME).saturating_sub(pre_skip) * 2;
3380 let mut ruined = pcm.clone();
3381 for sample in &mut ruined[from..(from + FIDELITY_WINDOW * OPUS_FRAME * 2).min(pcm.len())] {
3382 *sample = -*sample;
3383 }
3384 let worst = opus_fidelity(&packets, &ruined, pre_skip);
3385 assert!(
3386 worst < OPUS_MIN_FIDELITY,
3387 "five seconds of a long track that is not the mix scored {worst:.4}"
3388 );
3389
3390 // ...and silence is silence: nothing to correlate is not a round trip
3391 // that failed. Short, because the floor is the same on either path.
3392 let quiet = vec![0f32; OPUS_RATE as usize * 2 * 2];
3393 let (packets, pre_skip) = encode_opus(&quiet, 96)
3394 .expect("the encoder opens")
3395 .expect("silence is written as Opus, not sent to AAC");
3396 let fidelity = opus_fidelity(&packets, &quiet, usize::from(pre_skip));
3397 assert!(
3398 fidelity >= OPUS_MIN_FIDELITY,
3399 "a silent track scored {fidelity:.4} and would fall back to AAC"
3400 );
3401 }
3402
3403 /// The one rule that keeps a picture from being converted twice: a frame the
3404 /// tone map has already brought to BT.709 is never handed the 2020 matrix as
3405 /// well, on either canvas -- and everything else about the remap is
3406 /// unchanged by the tone map existing.
3407 #[test]
3408 fn a_tone_mapped_span_is_never_matrix_remapped_too() {
3409 let hdr = ColorDescription {
3410 matrix: Matrix::Bt2020Ncl,
3411 transfer: Transfer::Pq,
3412 full_range: false,
3413 };
3414 let sdr = ColorDescription::default(); // BT.601
3415 for out in [Matrix::Bt709, Matrix::Bt601] {
3416 let toned = remap_into(Some(hdr), true, out);
3417 assert!(
3418 toned.is_none_or(|(from, _)| from == Matrix::Bt709),
3419 "tone-mapped onto a {out:?} canvas asked for {toned:?}"
3420 );
3421 // Untouched by any of this: the 2020 clip that was *not* tone-mapped
3422 // (an unreachable state today, and still the matrix answer), the
3423 // ordinary 601-on-709 reconcile, and a gap.
3424 assert_eq!(
3425 remap_into(Some(hdr), false, out),
3426 (out != Matrix::Bt2020Ncl).then_some((Matrix::Bt2020Ncl, out))
3427 );
3428 assert_eq!(
3429 remap_into(Some(sdr), false, out),
3430 (out != Matrix::Bt601).then_some((Matrix::Bt601, out))
3431 );
3432 assert_eq!(remap_into(None, false, out), None);
3433 }
3434 assert_eq!(
3435 remap_into(Some(hdr), true, Matrix::Bt601),
3436 Some((Matrix::Bt709, Matrix::Bt601)),
3437 "a tone-mapped clip below 720 lines still takes its 709 -> 601 step"
3438 );
3439 }
3440
3441 /// A track of three cues, in whichever clock `track` says: `Some(n)` is a
3442 /// track of the media file, `None` a `.srt` beside it.
3443 fn subtitles(path: &str, track: Option<u64>) -> SubtitleTrack {
3444 SubtitleTrack {
3445 path: path.into(),
3446 track,
3447 language: "eng".into(),
3448 name: String::new(),
3449 label: "eng".into(),
3450 bitmap: false,
3451 cues: vec![
3452 Cue {
3453 start_us: 500_000,
3454 end_us: 1_500_000,
3455 text: "first".into(),
3456 image: None,
3457 },
3458 Cue {
3459 start_us: 2_000_000,
3460 end_us: 3_250_000,
3461 text: "second".into(),
3462 image: None,
3463 },
3464 Cue {
3465 start_us: 4_000_000,
3466 end_us: 4_750_000,
3467 text: "third".into(),
3468 image: None,
3469 },
3470 ],
3471 refused: None,
3472 }
3473 }
3474
3475 /// A standalone subtitle file is timed against the timeline itself -- there
3476 /// is no clip to hang it on -- so a cut moves the pictures and not it. What
3477 /// it does get is the exported length: a cue past the end of the file would
3478 /// otherwise be a block after the last picture.
3479 ///
3480 /// The pair of this, the embedded clock, is measured against a real exported
3481 /// file in `tests/export_subs.rs`; both live in one function and this is the
3482 /// half that needs no encoder.
3483 #[test]
3484 fn a_subtitle_file_beside_the_media_keeps_the_timelines_own_clock() {
3485 // 5 seconds at 30, with `[0.5s, 2.5s)` cut out of it: 3 seconds left.
3486 let mut project = Project::single("/nonexistent/film.mp4", 150);
3487 let track = subtitles("/nonexistent/film.srt", None);
3488 assert!(project.ripple_delete(15, 60));
3489 assert_eq!(project.timeline_frames(), 90);
3490 let cues = timeline_cues(&project, &track, 30.0);
3491 assert_eq!(
3492 cues,
3493 vec![
3494 Cue {
3495 start_us: 500_000,
3496 end_us: 1_500_000,
3497 text: "first".into(),
3498 image: None,
3499 },
3500 // Clipped to the three seconds the export writes...
3501 Cue {
3502 start_us: 2_000_000,
3503 end_us: 3_000_000,
3504 text: "second".into(),
3505 image: None,
3506 },
3507 // ...and the one wholly past the end is not written at all.
3508 ]
3509 );
3510 // A track *of a file* the project no longer plays has no span to be
3511 // carried through either, so it falls back to the same clock rather
3512 // than exporting nothing.
3513 let orphan = subtitles("/nonexistent/other.mkv", Some(2));
3514 assert_eq!(timeline_cues(&project, &orphan, 30.0).len(), 2);
3515 }
3516
3517 /// The embedded clock, without an encoder in it: the cut moves the cues with
3518 /// the pictures, and a cue nothing clipped keeps its own microseconds.
3519 #[test]
3520 fn a_track_of_the_media_is_carried_through_the_cut() {
3521 let mut project = Project::single("/nonexistent/film.mkv", 150);
3522 let track = subtitles("/nonexistent/film.mkv", Some(2));
3523 assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out");
3524 let cues = timeline_cues(&project, &track, 30.0);
3525 assert_eq!(
3526 cues,
3527 vec![
3528 // The first cue was wholly inside the cut. The second straddled
3529 // its far edge and kept the 0.75s that is still there...
3530 Cue {
3531 start_us: 500_000,
3532 end_us: 1_250_000,
3533 text: "second".into(),
3534 image: None,
3535 },
3536 // ...and the third simply moves back the two seconds that went.
3537 Cue {
3538 start_us: 2_000_000,
3539 end_us: 2_750_000,
3540 text: "third".into(),
3541 image: None,
3542 },
3543 ]
3544 );
3545 }
3546
3547 #[test]
3548 fn bitrate_clamps_at_both_ends() {
3549 let meta = |width, height, frame_rate| VideoMeta {
3550 width,
3551 height,
3552 frame_rate,
3553 frame_count: 1,
3554 codec: crate::demux::Codec::H264,
3555 color: Default::default(),
3556 };
3557 // 1280 * 720 * 30 * 0.1
3558 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
3559 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny");
3560 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
3561 }
3562
3563 fn meta(width: u32, height: u32) -> VideoMeta {
3564 VideoMeta {
3565 width,
3566 height,
3567 frame_rate: 30.0,
3568 frame_count: 1,
3569 codec: crate::demux::Codec::H264,
3570 color: Default::default(),
3571 }
3572 }
3573
3574 /// The bitrate row a user picked, read as the quality tier it is: a higher
3575 /// row is a lower QP, the band is honoured at both ends, and the same
3576 /// picture at the same rate gets the same number whatever its size (the
3577 /// mapping is bits per *pixel*, which is what makes 720p and 1080p one
3578 /// table).
3579 #[test]
3580 fn the_quality_rows_map_onto_quantisers_that_only_go_one_way() {
3581 let at = |width, height, mbps: Option<u64>| {
3582 hevc_qp(
3583 &meta(width, height),
3584 &ExportSettings {
3585 bitrate: mbps.map(|m| m * 1_000_000),
3586 ..Default::default()
3587 },
3588 )
3589 };
3590 // 20 Mbps at 1080p30 is 0.32 bits a pixel against the 0.6 measured at
3591 // QP 27, which is just over half: five QP up, and QP is not an
3592 // arithmetic scale, so this is the number the formula gives.
3593 assert_eq!(at(1920, 1080, Some(20)), 32);
3594 // Every step down the card is a step up in QP, never sideways.
3595 let rows: Vec<i32> = [20, 12, 8, 4, 2, 1]
3596 .into_iter()
3597 .map(|mbps| at(1920, 1080, Some(mbps)))
3598 .collect();
3599 assert!(
3600 rows.windows(2).all(|w| w[0] <= w[1]),
3601 "a lower bitrate row must never code at a lower QP: {rows:?}"
3602 );
3603 assert_eq!(*rows.last().unwrap(), HEVC_QP_MAX, "the floor is clamped");
3604 // ...and the top of the range is the clamp, not an unbounded number: 20
3605 // Mbps at 320x240 is 8.7 bits a pixel, which no picture needs.
3606 assert_eq!(at(320, 240, Some(20)), HEVC_QP_MIN);
3607 // The same bits per pixel is the same quantiser at any size: 1080p at
3608 // 20 Mbps and 720p at 8.9 Mbps are one picture quality.
3609 assert_eq!(at(1920, 1080, Some(20)), at(1280, 720, Some(9)));
3610 // The automatic bitrate is 0.1 bpp at every size, so it is one QP
3611 // everywhere -- the honest end of "intra-only, large files": the file
3612 // will be bigger than the row says, and the row buys quality.
3613 assert_eq!(at(1920, 1080, None), at(1280, 720, None));
3614 }
3615
3616 /// The padding a non-%16 picture is coded with replicates the edge instead
3617 /// of filling black: the coded rows past the picture carry its last row, so
3618 /// nothing bleeds into the last real line through the intra prediction.
3619 #[test]
3620 fn the_ctb_padding_replicates_the_edge() {
3621 // 6x2 luma, values 1..=12, padded to 8x4 (CTB is 16, so this checks the
3622 // copy itself with numbers small enough to read).
3623 let y: Vec<u8> = (1..=12).collect();
3624 let u: Vec<u8> = vec![40, 41, 42];
3625 let v: Vec<u8> = vec![50, 51, 52];
3626 let (py, pu, pv) = pad_to_ctb(&y, &u, &v, 6, 2, 8, 4);
3627 assert_eq!(
3628 py,
3629 vec![
3630 1, 2, 3, 4, 5, 6, 6, 6, // the row, then its last sample twice
3631 7, 8, 9, 10, 11, 12, 12, 12, //
3632 7, 8, 9, 10, 11, 12, 12, 12, // the last row, replicated
3633 7, 8, 9, 10, 11, 12, 12, 12,
3634 ]
3635 );
3636 // Chroma is half of everything, padded the same way.
3637 assert_eq!(pu, vec![40, 41, 42, 42, 40, 41, 42, 42]);
3638 assert_eq!(pv, vec![50, 51, 52, 52, 50, 51, 52, 52]);
3639 }
3640
3641 /// An odd picture cannot be cropped back to itself in 4:2:0 -- the
3642 /// conformance window is stated in chroma samples -- so it is refused by
3643 /// name rather than written a column wider than the timeline.
3644 #[test]
3645 fn an_odd_picture_is_refused_an_hevc_export_by_name() {
3646 let settings = ExportSettings {
3647 format: Format::Hevc,
3648 ..Default::default()
3649 };
3650 let refused = Enc::open(&meta(1919, 1080), &settings)
3651 .err()
3652 .expect("an odd width has no chroma plane")
3653 .to_string();
3654 assert!(refused.contains("1919x1080"), "{refused}");
3655 assert!(refused.contains("even"), "{refused}");
3656 // ...and the even one it neighbours opens.
3657 assert!(Enc::open(&meta(1920, 1080), &settings).is_ok());
3658 }
3659}