forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

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