forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7cb30bfTahinli2 months ago908 commits

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