forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbdb07d9Tahinli3 months ago645 commits

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