forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB684b8a4Tahinli3 months ago585 commits

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