forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcda6d0eTahinli3 months ago476 commits

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