forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBf2bee6bTahinli2 months ago781 commits

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