forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBeef3d5dTahinli3 months ago444 commits

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