forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb8aec29Tahinli2 months ago966 commits

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