forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB892f813Tahinli3 months ago398 commits

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