forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB286fcbbTahinli3 months ago748 commits

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