forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2c8e3aaTahinli3 months ago335 commits

export.rs3422 lines, 157.7 KiBHistoryRawDownload
1//! Export: the edit list rendered back out as one mp4 (H.264, AV1 or HEVC) or
2//! one Matroska file (AV1 or HEVC) — or, picture left behind, as one WAV, FLAC,
3//! MP3 or Ogg Vorbis of the timeline's audio alone.
4//!
5//! The HEVC pair is **intra-only**, and says so wherever it is offered: every
6//! frame is a self-contained IDR from the vendored `oxideav-h265`, which is the
7//! only shape of a pure-Rust HEVC encode fast enough to wait for (its inter
8//! modes code 1080p at 0.81 fps across 12 cores against the intra path's 4.30).
9//! That makes it an intraframe master in the family of ProRes and DNxHD — large
10//! files, every frame a cut point — and not a delivery codec.
11//!
12//! Picture and sound are both **copied wherever a copy says exactly what the
13//! timeline says** — a copy is exact, free and never a generation of loss. For
14//! the sound that is packet for packet ([`copy_audio`]); for the picture it is
15//! block for block out of a Matroska source into a Matroska file ([`CopyPlan`]),
16//! which is what makes a cut in a two-hour film cost the reading of it rather
17//! than the re-encoding of it. The picture's copy is all-or-nothing per export,
18//! because a copied span and an encoded one cannot share one track: what it
19//! needs of a cut is that it lands on a sync point, and everything else — a
20//! grade, a speed, a gap, a source of another size or codec, an mp4 — goes
21//! through the encoder exactly as it always did. Where the *sound* cannot be
22//! copied — a second audio lane to mix in, a speeded clip, an
23//! equalized one, a source that is not AAC inside an mp4's own sample table —
24//! the sound is decoded, mixed and encoded again with `rusty_aac`
25//! ([`encode_audio`]). The audio-only formats have no such split: `hound` writes
26//! PCM, `flacenc` encodes FLAC, `rusty_mp3` encodes MP3 and `rusty_vorbis`
27//! encodes Vorbis, so those are always *decoded* out of the timeline. The worker owns everything: the caller gets an
28//! [`ExportHandle`] and polls it from its render loop.
29//!
30//! **Every video format here carries the timeline's sound**, in whichever
31//! container: the mp4 muxer writes an AAC track and so does the Matroska one.
32//! Nothing is written picture-only and nothing is left silent without saying so
33//! — the only sound that does not come out is sound this engine cannot decode at
34//! all (Opus and AC-3 inside a Matroska file), and that is an error by name.
35//!
36//! A **speeded** clip splits along the same line, and for the same reason. The
37//! picture is re-encoded, so the frame walk honours a rate: it takes the source
38//! frame each timeline frame shows ([`crate::project::Speed::source_at`], the
39//! very frame preview holds there) and encodes a held one again rather than
40//! decoding it twice. A clip whose *file* was shot at another rate than the
41//! timeline goes through the same walk with one more conversion on the end
42//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at.
43//! The sound is *copied* unless something forces a decode, and a packet carries
44//! no rate — so a speeded lane is one of the things that forces one
45//! ([`copy_audio`]) rather than being written out at 1.00x under a re-timed
46//! picture. The audio-only formats are decoded and resampled, so they honour a
47//! rate like the picture does.
48//!
49//! Nothing partial survives a failure: the worker writes to `<out>.part` and
50//! renames it onto `out` only once the file is closed and complete, so the
51//! output either does not exist or is finished — there is no window where a
52//! half-written `.export.mp4` is sitting there looking playable. Cancel and
53//! every error path delete the `.part`. A killed *process* leaves the `.part`
54//! behind (only in-process cleanup is promised), which is an orphan a user can
55//! delete rather than a file that plays for two seconds and stops.
56
57use std::fs::File;
58use std::io::{BufWriter, Write};
59use std::path::{Path, PathBuf};
60use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
61use std::sync::{Arc, Mutex};
62use std::thread;
63
64use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame};
65
66use flacenc::component::BitRepr;
67use flacenc::error::Verify;
68// The trait the Ogg muxer's `write_header` / `write_packet` / `write_trailer`
69// live on -- `oxideav_ogg::mux::open_concrete` hands back the concrete muxer
70// (the only way to reach `set_page_target_bytes`), so the trait has to be here.
71use oxideav_core::Muxer as _;
72
73use crate::audio::{AudioMeta, AudioSession};
74use crate::colorspace::{ColorDescription, Matrix, Transfer};
75use crate::demux::{Codec, Demuxer, MkvDemuxer, VideoMeta};
76use crate::hw::{HwEncoder, HwSession};
77use crate::mux::{
78 AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams,
79};
80use crate::project::{LaneKind, Project, Rate};
81use crate::scale::Composer;
82use crate::subtitle::{Cue, SubtitleTrack};
83use crate::tonemap::{self, ToneMapper};
84
85/// Progress is reported in permille: an atomic integer the render loop can read
86/// without a lock, fine enough for any progress bar.
87const PROGRESS_SCALE: u32 = 1_000;
88
89/// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
90/// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%.
91const BITS_PER_PIXEL: f64 = 0.1;
92const MIN_BITRATE: u64 = 1_000_000;
93const MAX_BITRATE: u64 = 20_000_000;
94
95/// The rates the sound may be coded at, smallest first -- what a front-end
96/// offers and what [`ExportSettings::audio_kbps`] is clamped into. Every one of
97/// them is a legal MPEG-1 Layer III value, so the MP3 path writes the figure it
98/// was given rather than the nearest one `rusty_mp3` snaps to.
99pub const AUDIO_KBPS: [u32; 4] = [128, 192, 256, 320];
100
101/// What the sound is coded at when nobody picked: the rate this project wrote
102/// before the choice existed. 256 and not the encoders' own 128, because an
103/// export is a master a person edits from again and this is a second lossy
104/// generation over sources that may already have been one -- measured on the
105/// suite's fixtures, an untouched clip re-encoded moves 0.15 dB here against
106/// 0.46 dB at 128, and 32 KB/s beside a 2.76 Mbps picture is not a size anyone
107/// is counting.
108pub const DEFAULT_AUDIO_KBPS: u32 = 256;
109
110/// `rav1e`'s fastest preset. Anything slower is minutes per second of timeline
111/// on a build with no assembly, which is what this one is.
112const AV1_SPEED: u8 = 10;
113
114/// The HEVC coding tree block this encoder is fixed at: the coded picture is a
115/// whole number of them, which is what the conformance window crops back.
116const CTB: usize = 16;
117/// How many frames the intra HEVC encoder codes at once. Twelve is where the
118/// 2026-08-11 bench stopped scaling on this box (4.30 fps at 1080p); more lanes
119/// only holds more decoded frames in memory.
120const HEVC_LANES: usize = 12;
121/// Bits per pixel the intra encoder spends at QP 27, measured on the same bench:
122/// 0.607 at 720p and 0.586 at 1080p. What [`hevc_qp`] maps a bitrate row through.
123const HEVC_BPP_AT_27: f64 = 0.6;
124/// The band [`hevc_qp`] is clamped into, for the reason stated there.
125const HEVC_QP_MIN: i32 = 22;
126const HEVC_QP_MAX: i32 = 40;
127
128/// What an export writes. H.264-in-mp4, AV1 and HEVC -- each of the last two in
129/// Matroska or in mp4, the user's pick of container -- are the *video* pairs
130/// with both an encoder and a decoder under this project's no-install rule, and
131/// WAV, FLAC, MP3 and Ogg Vorbis are the standalone audio formats with a
132/// pure-Rust encoder: `hound`, `flacenc`, `rusty_mp3` and `rusty_vorbis`. Opus
133/// still has none -- `oxideav-opus` encodes CELT alone, which is half a codec.
134/// (AAC has one too -- `rusty_aac`, which is what a re-encoded video track's
135/// sound leaves through -- but AAC is a container's own audio, never a file of
136/// its own here.) VP9 is the
137/// one codec left that comes in through the plugin and stops there, HEVC having
138/// gained an encoder (an intra-only one, which the rows say). A front-end says
139/// so rather than hiding the row.
140///
141/// **Every video format carries sound.** Which way it carries it is the only
142/// difference: copied packet for packet where a copy can say what the timeline
143/// says, decoded and encoded again ([`encode_audio`]) where it cannot.
144#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
145pub enum Format {
146 /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too,
147 /// where a copy could not carry the edit (a second audio lane to mix in, a
148 /// speeded clip, an equalized one, a source no mp4 sample table holds).
149 #[default]
150 Mp4,
151 /// AV1 in Matroska, with the timeline's AAC beside it: this engine's
152 /// Matroska writer carries an audio track ([`crate::mux::MkvMuxer`]) and its
153 /// reader reads one back, symphonia's `mkv` reader being what
154 /// `audio::Track::open` opens it with.
155 Av1,
156 /// The same AV1 stream in an mp4, for everything that plays mp4 and not
157 /// Matroska. The sample entry `mp4 0.14` cannot write is written by hand
158 /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own,
159 /// unchanged.
160 Av1Mp4,
161 /// HEVC in Matroska, **intra-only**: every frame is a self-contained IDR
162 /// picture ([`Enc::open_hevc`]), which is what makes a pure-Rust HEVC
163 /// encoder fast enough to be an export at all. An intraframe master, like
164 /// ProRes or DNxHD -- large files, and every frame a cut point.
165 Hevc,
166 /// The same HEVC stream in an mp4 (`hvc1`), for everything that plays mp4
167 /// and not Matroska -- the AV1 pair's split, for the same reason.
168 HevcMp4,
169 /// The audio lanes alone, 16-bit PCM.
170 Wav,
171 /// The audio lanes alone, losslessly compressed.
172 Flac,
173 /// The audio lanes alone, MPEG-1 Layer III CBR (`rusty_mp3`) at the rate
174 /// [`ExportSettings::audio_kbps`] asks for.
175 Mp3,
176 /// The audio lanes alone, Vorbis I in an Ogg container -- `rusty_vorbis`
177 /// encoding, `oxideav-ogg` paging. Quality-coded and not rate-coded, which
178 /// is why [`audio_rate_refusal`] takes the Sound row away here: see
179 /// [`VORBIS_QUALITY`] for the operating point and how it was measured.
180 Ogg,
181}
182
183impl Format {
184 /// The extension a file of this format is named with -- a front-end builds
185 /// the destination path from it, so the name never disagrees with the bytes.
186 pub fn ext(self) -> &'static str {
187 match self {
188 Self::Mp4 | Self::Av1Mp4 | Self::HevcMp4 => "mp4",
189 Self::Av1 | Self::Hevc => "mkv",
190 Self::Wav => "wav",
191 Self::Flac => "flac",
192 Self::Mp3 => "mp3",
193 Self::Ogg => "ogg",
194 }
195 }
196
197 /// Whether this format carries the picture. The bitrate settings are video
198 /// settings and mean nothing to the audio-only ones.
199 pub fn has_video(self) -> bool {
200 matches!(
201 self,
202 Self::Mp4 | Self::Av1 | Self::Av1Mp4 | Self::Hevc | Self::HevcMp4
203 )
204 }
205
206 /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs
207 /// and which of the two AV1 containers is being written are separate
208 /// questions, and this is the first.
209 fn is_av1(self) -> bool {
210 matches!(self, Self::Av1 | Self::Av1Mp4)
211 }
212
213 /// The same question for HEVC, and the same answer for both its containers:
214 /// one encoder, two boxes to put its stream in.
215 fn is_hevc(self) -> bool {
216 matches!(self, Self::Hevc | Self::HevcMp4)
217 }
218
219 /// Whether the file is a Matroska one. Only that container carries this
220 /// project's Opus track ([`encode_opus`]): an mp4 may hold Opus by spec, but
221 /// the crate that writes the mp4s here has no sample entry for it, so the
222 /// mp4 formats stay on AAC and say so.
223 fn is_mkv(self) -> bool {
224 matches!(self, Self::Av1 | Self::Hevc)
225 }
226
227 /// What the format is called where a refusal names it.
228 pub fn name(self) -> &'static str {
229 match self {
230 Self::Mp4 => "an mp4",
231 Self::Av1 => "an AV1 Matroska",
232 Self::Av1Mp4 => "an AV1 mp4",
233 Self::Hevc => "an HEVC Matroska",
234 Self::HevcMp4 => "an HEVC mp4",
235 Self::Wav => "a WAV",
236 Self::Flac => "a FLAC",
237 Self::Mp3 => "an MP3",
238 Self::Ogg => "an Ogg Vorbis",
239 }
240 }
241}
242
243/// What the caller gets to decide about the output. The codec is not among it:
244/// [`Format`] names a container *and* what goes in it, because every pair we
245/// can write is a pair we can also read back.
246#[derive(Debug, Clone, Default, PartialEq, Eq)]
247pub struct ExportSettings {
248 /// Bits per second, clamped to the same sane range the automatic value uses.
249 /// `None` picks it from the picture size and frame rate. Video only.
250 pub bitrate: Option<u64>,
251 /// Skip the hardware encoder even where it is available -- an escape hatch
252 /// for a driver that encodes badly, matching the `VE_SW_ENC` env pin.
253 pub force_sw: bool,
254 /// The file to write. Defaults to [`Format::Mp4`], which is what every
255 /// caller wrote before there was a choice.
256 pub format: Format,
257 /// What the *sound* is coded at, in kbps, wherever an encoder writes it --
258 /// the AAC of a video export as much as an MP3. `None` is
259 /// [`DEFAULT_AUDIO_KBPS`], which is what every caller wrote before there
260 /// was a choice, so a settings value nobody touched writes the same bytes
261 /// it used to. Means nothing to WAV and FLAC, which code no rate, and
262 /// nothing to a *copied* AAC track, which carries its source's.
263 pub audio_kbps: Option<u32>,
264 /// Which of the project's subtitle tracks travel with the file: indices into
265 /// [`Project::subtitles`], which is the same list a front-end picks rows of.
266 /// As many as the timeline holds, in the order given -- the file declares
267 /// them in that order and a player's subtitle menu lists them in it. Empty
268 /// writes none -- what every caller wrote before there was a choice, so an
269 /// export of a timeline without subtitles is the file it always was, byte
270 /// for byte.
271 ///
272 /// Every container that carries picture carries them: Matroska as
273 /// `S_TEXT/UTF8` blocks, an mp4 as a `tx3g` timed-text track
274 /// ([`crate::mux::Mp4Muxer::write_subtitles`]). A Matroska block names its
275 /// track in one byte, so a Matroska file carries at most
276 /// [`crate::mux::MAX_SUB_TRACKS`] of them and asking for more is refused by
277 /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has
278 /// no such ceiling.
279 pub subtitles: Vec<usize>,
280}
281
282struct Shared {
283 progress: AtomicU32,
284 cancel: AtomicBool,
285 finished: AtomicBool,
286 outcome: Mutex<Option<crate::Result<()>>>,
287 /// The encoders this job really opened, published the moment they are
288 /// chosen and never changed after -- one seat for the whole file, which is
289 /// what [`Enc`] states. `None` until then.
290 encoders: Mutex<Option<String>>,
291}
292
293/// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
294/// rendered frame and take the [`result`](ExportHandle::result) when it flips;
295/// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel)
296/// does.
297pub struct ExportHandle {
298 shared: Arc<Shared>,
299}
300
301impl ExportHandle {
302 /// Fraction of the timeline written, `0.0..=1.0`.
303 pub fn progress(&self) -> f32 {
304 self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32
305 }
306
307 /// Asks the worker to stop at its next checkpoint and delete the partial
308 /// file. The outcome then reports the cancellation as an error. Checkpoints
309 /// run to the last instant before the rename, so even a cancel at full
310 /// progress leaves no output.
311 pub fn cancel(&self) {
312 self.shared.cancel.store(true, Ordering::Relaxed);
313 }
314
315 pub fn is_finished(&self) -> bool {
316 self.shared.finished.load(Ordering::Acquire)
317 }
318
319 /// What this export is encoding with -- the video seat and what the sound
320 /// is doing -- as the worker chose them, hardware fallback included.
321 /// `None` for the first instants of a job, before the encoder is open.
322 pub fn encoders(&self) -> Option<String> {
323 self.shared.encoders.lock().unwrap().clone()
324 }
325
326 /// The outcome, once — taken out of the handle, so a caller that already
327 /// reported it sees `None` afterwards. `None` while the export is running.
328 pub fn result(&self) -> Option<crate::Result<()>> {
329 self.shared.outcome.lock().unwrap().take()
330 }
331}
332
333/// Starts the worker. Failures are reported through the handle rather than
334/// returned, so a caller has exactly one place to look. The files to read are
335/// the project's own [`sources`](Project::sources) -- every clip names one --
336/// so nothing but the edit list decides what is decoded.
337pub fn start(
338 project: Project,
339 meta: VideoMeta,
340 out: &Path,
341 settings: &ExportSettings,
342) -> ExportHandle {
343 let settings = settings.clone();
344 let shared = Arc::new(Shared {
345 progress: AtomicU32::new(0),
346 cancel: AtomicBool::new(false),
347 finished: AtomicBool::new(false),
348 outcome: Mutex::new(None),
349 encoders: Mutex::new(None),
350 });
351 let worker = Arc::clone(&shared);
352 let out = out.to_path_buf();
353 // `<out>.part`, appended rather than substituted: the temporary of
354 // `a.export.mp4` is `a.export.mp4.part`, which no other export claims.
355 let mut part = out.clone().into_os_string();
356 part.push(".part");
357 let part = PathBuf::from(part);
358 let spawned = thread::Builder::new().name("export".into()).spawn(move || {
359 // The rename is the last step and the only one that publishes a file
360 // under the name the caller asked for; it stays on the same directory,
361 // so it is atomic.
362 //
363 // An emptied timeline is a legal project and an illegal file: no
364 // picture, no sound, and a muxer that is never created because no coded
365 // frame arrives. Refused by name here -- before the format is even
366 // looked at, so an mp4 and a WAV refuse in the same words -- rather than
367 // left to write a file of no frames that nothing opens. Every caller of
368 // `start` comes through this, the app's own door
369 // (`PlaybackSession::is_empty`) being only the first fence.
370 //
371 // An audio-only timeline is the other legal project no mp4 can be made
372 // of: every frame of it is a gap, so the file would be black picture
373 // over the sound -- minutes of encoding for a video of nothing. Refused
374 // by name, with the two formats that *are* that timeline, rather than
375 // written; the app says the same on the format row before a destination
376 // is even picked (`mp4_refusal`).
377 let written = match settings.format {
378 _ if project.timeline_frames() == 0 => {
379 Err("the timeline is empty: there is nothing to export".into())
380 }
381 format if format.has_video() && !has_picture(&project) => Err(format!(
382 "the timeline has no picture: {} would be black. Export WAV, \
383 FLAC or MP3, which are the sound itself",
384 format.name()
385 )
386 .into()),
387 format if format.has_video() => run(&project, &meta, &part, &worker, &settings),
388 _ => run_audio(&project, &meta, &part, &worker, &settings),
389 };
390 let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
391 if result.is_err() {
392 // The muxer -- and with it the file handle -- died with `run`.
393 let _ = std::fs::remove_file(&part);
394 }
395 settle(&worker, result);
396 });
397 if let Err(e) = spawned {
398 settle(&shared, Err(e.into()));
399 }
400 ExportHandle { shared }
401}
402
403/// Whether any video lane holds anything at all -- what tells an audio-only
404/// timeline from one that merely opens on a gap. Asked of the *lanes* rather
405/// than of the sources, because a project may name a video file no clip plays
406/// from any more.
407fn has_picture(project: &Project) -> bool {
408 project
409 .lanes()
410 .into_iter()
411 .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty())
412}
413
414/// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a
415/// timeline whose export will carry sound from one whose file has none.
416fn has_sound(project: &Project) -> bool {
417 project
418 .lanes()
419 .into_iter()
420 .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty())
421}
422
423/// Whether any equalizer on the sound is doing something -- the one edit a
424/// packet copy cannot carry, so an mp4 whose lane has one is decoded and
425/// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane:
426/// the copy path has exactly one by the time it asks, and [`planned_audio`] is
427/// asked before that is settled.
428fn equalized(project: &Project) -> bool {
429 project.audio_lanes().into_iter().any(|lane| {
430 (0..project.lane(lane).len())
431 .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity()))
432 })
433}
434
435/// Whether the *mix* is doing something -- a lane turned off unity, or a
436/// limiter in circuit. [`equalized`]'s pair, and a copy cannot carry either of
437/// them: both live where the lanes are summed
438/// ([`AudioSession::open_mixed_streams_master`]), and a copied packet was never
439/// summed at all. An mp4 whose timeline is mixed is decoded and re-encoded.
440fn mastered(project: &Project) -> bool {
441 project.limiter().is_active() || project.audio_gains().iter().any(|&g| g != 1.0)
442}
443
444/// The bitrate an export codes at: the caller's number through the same clamp
445/// as the computed one, for the reason [`Enc::open`] states.
446fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 {
447 settings
448 .bitrate
449 .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE))
450}
451
452/// The rate the sound codes at: the caller's pick clamped into the offered
453/// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused,
454/// for [`bitrate_of`]'s reason -- a number out of range is a caller's slip and
455/// not a file worth failing.
456fn audio_kbps_of(settings: &ExportSettings) -> u32 {
457 settings.audio_kbps.map_or(DEFAULT_AUDIO_KBPS, |k| {
458 k.clamp(AUDIO_KBPS[0], AUDIO_KBPS[3])
459 })
460}
461
462/// The hardware seat for these settings, opened exactly as the export opens it
463/// -- the same pins, the same AV1 opt-in, the same dimensions a driver may
464/// refuse -- or `None` where the software encoder takes the file. The single
465/// place that choice is made, which is what lets [`planned_video`] *measure* it
466/// instead of promising it.
467fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
468 if settings.force_sw || forced("VE_SW_ENC") {
469 return None;
470 }
471 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
472 let bitrate = bitrate_of(meta, settings);
473 match settings.format {
474 // The HEVC pair is software only, and not for want of a GPU: the plugin
475 // has no HEVC *encode* entry point at all (`hw::HwEncoder` opens H.264
476 // and AV1), so there is no seat to probe. Said here rather than left to
477 // a failed open, which would read as a driver refusal.
478 format if format.is_hevc() => None,
479 // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both
480 // AV1 formats sit on it: the container is not the encoder's business.
481 format if format.is_av1() && !forced("VE_HW_AV1") => None,
482 format if format.is_av1() => {
483 HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate)
484 }
485 _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate),
486 }
487}
488
489/// How a front-end names a video seat: which of the two encoders has the file,
490/// and which library that is. Not the codec -- a caller shows this beside the
491/// format it picked, and `rav1e` names AV1 as `rusty_h264` names H.264. One
492/// place, so what a card says before an export and what its progress line says
493/// during one cannot drift apart.
494fn video_label(format: Format, hw: bool) -> &'static str {
495 match (format, hw) {
496 (_, true) => "HW encode (VA-API)",
497 (Format::Hevc | Format::HevcMp4, false) => "SW encode (oxideav-h265 intra)",
498 (Format::Av1 | Format::Av1Mp4, false) => "SW encode (rav1e)",
499 (_, false) => "SW encode (rusty_h264)",
500 }
501}
502
503/// The cheap half of "does this timeline's sound have to be re-encoded": what
504/// the *edit* says, with no file opened. Two lanes are a mix and a mix is not a
505/// copy; a speeded lane is resampled; an equalizer is sample math. The other
506/// half -- whether the sources can be copied out of at all -- costs a file open
507/// each and belongs to [`copy_audio`], which may re-encode where this says copy.
508fn forces_encode(project: &Project) -> bool {
509 let lanes: Vec<_> = project
510 .audio_lanes()
511 .into_iter()
512 .filter(|&lane| !project.lane(lane).is_empty())
513 .collect();
514 lanes.len() > 1
515 || lanes
516 .iter()
517 .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal()))
518 || equalized(project)
519 || mastered(project)
520}
521
522/// What the sound is written by. Every audio encoder here is software -- there
523/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and
524/// whether a container escapes encoding altogether by copying the packets it was
525/// given. Both AV1 formats are in it like the mp4: an AV1 export carries the
526/// timeline's sound too, so leaving it unnamed would be the old lie.
527///
528/// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a
529/// card asking before the export has no way to know (a source that cannot be
530/// copied out of is only found by opening it). `None` predicts from the edit
531/// alone.
532fn audio_label(
533 project: &Project,
534 format: Format,
535 sound: bool,
536 copied: Option<bool>,
537) -> &'static str {
538 if !sound {
539 return "no sound to write";
540 }
541 match format {
542 Format::Wav => "PCM · SW (hound)",
543 Format::Flac => "FLAC · SW (flacenc)",
544 Format::Mp3 => "MP3 · SW (rusty_mp3)",
545 Format::Ogg => "Vorbis · SW (rusty_vorbis)",
546 _ => match copied.unwrap_or(!forces_encode(project)) {
547 true => "AAC copy",
548 // A Matroska file gets Opus where the mix allows it -- 48 kHz and
549 // stereo, which is every Opus source and most of everything else --
550 // and AAC where it does not ([`encode_audio`]). Which of the two it
551 // will be cannot be known here: both answers need a source opened,
552 // and this function may be asked per repaint. So the card names the
553 // codec it will nearly always be, as a prediction like the copy above
554 // it, and the line the export publishes while it runs is the measured
555 // one ([`run`]) -- it says AAC when the fallback took it, so the
556 // fallback is visible rather than silent.
557 //
558 // It is one line and 76 characters wide (`summary_head` in the app
559 // has the test), which is why the condition is in this comment
560 // instead of in the string.
561 false if format.is_mkv() => "Opus · SW encode (opus-rs)",
562 false => "AAC · SW encode (rusty_aac)",
563 },
564 }
565}
566
567/// What [`start`] would write this timeline's sound with, before one is
568/// started. Pure: no probe and no file opened, so a card may ask it per repaint.
569pub fn planned_audio(project: &Project, format: Format) -> &'static str {
570 audio_label(project, format, has_sound(project), None)
571}
572
573/// Why the sound's rate is nothing this timeline can be asked about in this
574/// format, or `None` where it is a real choice: there is no sound to write, the
575/// format codes the samples themselves, or the packets are the source's own and
576/// carry the rate *it* was coded at. Pure, like [`planned_audio`], and a
577/// prediction in the same way -- a copy that turns out impossible (a source no
578/// mp4 sample table holds) falls through to [`encode_audio`], which codes at
579/// [`ExportSettings::audio_kbps`] like every other encode. So the value travels
580/// even where this refuses; what it cannot do is silently write a rate nobody
581/// picked.
582pub fn audio_rate_refusal(project: &Project, format: Format) -> Option<&'static str> {
583 match format {
584 _ if !has_sound(project) => Some("no sound to write"),
585 Format::Wav | Format::Flac => Some("lossless — the samples themselves, at no rate"),
586 // Vorbis has a quality knob and no rate knob, and the two are not the
587 // same control wearing different words: measured across this suite's
588 // fixtures, the whole usable quality band lands between 55 and 175 kbps
589 // ([`VORBIS_QUALITY`]), so two of the four rates on offer here are not
590 // rates it can reach at all. A live row would print a figure the file
591 // does not hold, which is the one thing this card is built not to do.
592 Format::Ogg => Some("quality-coded — Vorbis holds no rate to pick"),
593 Format::Mp3 => None,
594 _ if forces_encode(project) => None,
595 _ => Some("the source's own packets are copied — at the rate they hold"),
596 }
597}
598
599/// The tracks an export carries, in the order they were picked, and empty where
600/// it carries none: no pick, a pick nothing answers, a track that could not be
601/// read, one with no cue left on the exported timeline -- and every format that
602/// is the sound alone, which has nowhere to put them. Filtered *per track*, so
603/// one unusable pick costs its own row and not the others.
604///
605/// Both containers, since the mp4 muxer gained its `tx3g` track: what the two
606/// do with the very same [`SubParams`] is theirs to say
607/// ([`crate::mux::Mp4Muxer::write_subtitles`], [`MkvMuxer`]), and nothing here
608/// asks which one is being written.
609fn export_subtitles(
610 project: &Project,
611 meta: &VideoMeta,
612 settings: &ExportSettings,
613) -> Vec<SubParams> {
614 if !settings.format.has_video() {
615 return Vec::new();
616 }
617 settings
618 .subtitles
619 .iter()
620 .filter_map(|&pick| {
621 let track = project.subtitles().get(pick)?;
622 // A picture is not a line: the muxer writes an `S_TEXT/UTF8` track
623 // and a PGS cue has no words to put in one. `planned_subtitles` says
624 // so before the button is pressed rather than the file coming out
625 // short.
626 if track.refused.is_some() || track.is_bitmap() {
627 return None;
628 }
629 let cues = timeline_cues(project, track, meta.frame_rate);
630 // The container's own two fields, carried as two
631 // ([`SubtitleTrack::language`]): a `TrackEntry` with no `Language`
632 // means `eng` by spec, so a French track that arrives here as one
633 // flattened string leaves as an English one.
634 (!cues.is_empty()).then(|| SubParams {
635 language: track.language.clone(),
636 name: track.name.clone(),
637 cues,
638 })
639 })
640 .collect()
641}
642
643/// The track's cues where the *exported* timeline puts them, which is the only
644/// clock the file has: the export writes timeline frame 0 onwards and nothing
645/// else, exactly as the sound is mixed from frame 0 and resized to the
646/// timeline's own length ([`encode_audio`]).
647///
648/// Which clock the cues arrive in is what the track itself says:
649///
650/// * a track out of a *file* (`SubtitleTrack::track`) is timed against that
651/// file, so each cue is carried through the spans that play it -- a cue over
652/// a stretch that was cut out is gone, one straddling a cut keeps the half
653/// that is still there, and one after a rippled delete moves back with the
654/// picture it belongs to. The *edges* a cut clips to are frames -- that is
655/// what a cut is -- but a cue nothing clipped keeps its own microseconds, so
656/// an untouched timeline exports the times the source states.
657/// * a *standalone* file (`subs.srt`) is timed against nothing else -- there is
658/// no clip to hang it on and no offset in the project to shift it by -- so it
659/// is the timeline's own clock, which is where it was drawn while editing
660/// (`Player::subtitle_overlay`). Clipped to the exported length and no more.
661///
662/// This is also what the *preview* draws: the plate over the picture and the
663/// timeline strip both ask it through
664/// [`PlaybackSession::timeline_cues`](crate::PlaybackSession::timeline_cues), so
665/// what a rippled timeline shows and what its export writes are one answer by
666/// construction rather than two maps kept in step by hand.
667///
668/// Pure and cheap enough to ask per repaint (a walk of the spans and of the
669/// cues, no file opened), which is how a front-end asks it.
670pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<Cue> {
671 let frames = project.timeline_frames();
672 let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64;
673 let end = us(frames);
674 // The file the cues are timed against, when there is one on this timeline.
675 // A track whose media has since been dropped from the project has no span
676 // to be carried through and falls back to the timeline's clock, which is
677 // what it was drawn on.
678 //
679 // Through the same `canonical` a source is indexed by, or the two spellings
680 // of one file (an argv `../assets/film.mkv`, a symlinked folder) would read
681 // as two files and the cues would quietly fall back to the timeline's clock.
682 let source = track.track.and_then(|_| {
683 let path = crate::project::canonical(&track.path);
684 project.sources().iter().position(|s| s.path == path)
685 });
686 let Some(source) = source else {
687 return track
688 .cues
689 .iter()
690 .filter_map(|cue| {
691 let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end));
692 (end_us > start_us).then(|| Cue {
693 start_us,
694 end_us,
695 text: cue.text.clone(),
696 image: cue.image.clone(),
697 })
698 })
699 .collect();
700 };
701 let mut out = Vec::new();
702 for span in project.composite_spans_from(0) {
703 let Some((_, in_frame)) = span.from.filter(|&(from, _)| from == source) else {
704 continue;
705 };
706 // What of the file this span plays, as *time in the file*: a clip counts
707 // the timeline's frames whatever its file was shot at ([`Rate`]), which
708 // is what makes those frames the same seconds a cue is timed in.
709 let (first, last) = (us(in_frame), us(in_frame + span.source_len()));
710 // Where that lands, and how fast: a cue is carried by the same factor
711 // the pictures under it are, so a slowed clip stretches its subtitles
712 // with it instead of leaving them behind.
713 let start = us(span.start);
714 let onto = |t: i64| start + ((t - first) as f64 / span.speed.as_f64()).round() as i64;
715 for cue in &track.cues {
716 let (a, b) = (cue.start_us.max(first), cue.end_us.min(last));
717 if b <= a {
718 continue; // wholly outside what this span kept
719 }
720 out.push(Cue {
721 start_us: onto(a),
722 end_us: onto(b).min(end),
723 text: cue.text.clone(),
724 image: cue.image.clone(),
725 });
726 }
727 }
728 // The spans come in timeline order but a cue's *own* order across them does
729 // not: a Matroska muxer writes blocks as they come up.
730 out.sort_by_key(|cue| cue.start_us);
731 out
732}
733
734/// What [`start`] would do about the subtitles, in the words a card shows: what
735/// travels, and the reason beside every pick that does not. Pure, like
736/// [`planned_audio`]: no file is opened, so it may be asked per repaint.
737///
738/// `picks` is any run of indices into [`Project::subtitles`] -- an
739/// [`ExportSettings::subtitles`] list (`picks.iter().copied()`) as much as a
740/// single `Some(row)`, which is what a front-end holding one row still hands it.
741pub fn planned_subtitles(
742 project: &Project,
743 format: Format,
744 picks: impl IntoIterator<Item = usize>,
745) -> String {
746 let mut embedded: Vec<&str> = Vec::new();
747 let mut dropped: Vec<String> = Vec::new();
748 let picks: Vec<usize> = picks.into_iter().collect();
749 // One statement about the *file*, said before any about a track: a format
750 // that is the sound alone has nowhere to put a single one of them, and the
751 // reason a pick would not have travelled anyway (a picture track, no cues)
752 // is not the reason it does not travel here. Nothing picked is "none" --
753 // there is nothing to say a container cannot carry.
754 if !picks.is_empty() && !format.has_video() {
755 return "none — this format is the sound alone".into();
756 }
757 for pick in picks {
758 // A pick the project has no row for: a caller holding an index the list
759 // no longer has (a removed row shifts every later one down). Every other
760 // reason a pick does not travel is named on this card, so this one is
761 // too -- a bug that says nothing is a bug found in the finished file.
762 let Some(track) = project.subtitles().get(pick) else {
763 dropped.push(format!("#{pick} — no such track"));
764 continue;
765 };
766 if let Some(why) = &track.refused {
767 dropped.push(format!("{} — {why}", track.label));
768 } else if track.is_bitmap() {
769 // Drawn over the picture, written into no file: the exported track
770 // is text and these cues are bitmaps. Said whatever the format,
771 // because it is the track and not the container that cannot be
772 // carried.
773 dropped.push(format!("{} — pictures; drawn, not written", track.label));
774 } else if track.cues.is_empty() {
775 dropped.push(format!("{} — no cues", track.label));
776 } else {
777 // Whichever container: a Matroska carries the track as
778 // `S_TEXT/UTF8` blocks and an mp4 as a `tx3g` timed-text track, and
779 // a pick travels either way. There is no container refusal left on
780 // this card -- the sound-alone one above is about the *file* and the
781 // ones beside it about the *track*.
782 embedded.push(&track.label);
783 }
784 }
785 let mut parts = match embedded.len() {
786 0 => Vec::new(),
787 1 => vec![format!("{} → embedded", embedded[0])],
788 n => vec![format!("{n} tracks → embedded ({})", embedded.join(", "))],
789 };
790 parts.extend(dropped);
791 match parts.is_empty() {
792 true => "none".into(),
793 false => parts.join("; "),
794 }
795}
796
797/// What [`start`] would encode the picture with, probed the way the export
798/// probes it -- the very encoder is opened and closed again -- so this is a
799/// measurement and not a promise. `None` for a format that carries no picture.
800///
801/// Costs that open (~100 ms here): ask it off a render thread and keep the
802/// answer until the format, the resolution or the bitrate changes.
803pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> {
804 settings
805 .format
806 .has_video()
807 .then(|| video_label(settings.format, hw_seat(meta, settings).is_some()))
808}
809
810fn settle(shared: &Shared, result: crate::Result<()>) {
811 *shared.outcome.lock().unwrap() = Some(result);
812 // Published last: a caller that sees the flag is guaranteed the outcome.
813 shared.finished.store(true, Ordering::Release);
814}
815
816/// The audio track an export writes, and how it was made -- a copy is the
817/// source's own packets, bit for bit, and anything else is this project's
818/// encoder over the decoded mix. [`run`] publishes which of the two really
819/// happened, so the encoder line a user reads is measured and not promised.
820pub(crate) struct ExportAudio {
821 pub params: crate::AacTrackParams,
822 pub packets: Vec<crate::AacPacket>,
823 /// Whether those packets are the source's, untouched.
824 pub copied: bool,
825 /// The track's pre-skip in samples where those packets are **Opus** and not
826 /// AAC ([`encode_opus`]), which is what the Matroska track entry states in
827 /// its `OpusHead` and its `CodecDelay`. `None` is an AAC track, which is
828 /// every copy and every mp4.
829 pub opus_pre_skip: Option<u16>,
830}
831
832/// The timeline's audio track for a file that carries picture: copied packet for
833/// packet where a copy says exactly what the timeline says, and decoded, mixed
834/// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane,
835/// a speeded clip, an equalizer, a source that is not AAC inside an mp4 sample
836/// table. Nothing is refused for being uncopyable any more; the only refusals
837/// left below the copy are about sound this engine cannot *decode* either, and
838/// those come out of the decode path by name.
839///
840/// The copy is still the default and still bit-exact: a timeline nobody has
841/// touched leaves as the very packets its source holds.
842///
843/// ponytail: this holds the whole exported AAC track in memory (~3 kB per
844/// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
845/// `copy_segments` that yields packets instead of collecting them.
846fn copy_audio(
847 project: &Project,
848 meta: &VideoMeta,
849 kbps: u32,
850 mkv: bool,
851) -> crate::Result<Option<ExportAudio>> {
852 // The segments name their source, and the copy carries its packet-rounding
853 // debt across a source join exactly as across a cut, so a timeline spanning
854 // files stays in sync. A source whose AAC parameters disagree with the
855 // first one is an `Err` from there -- import refuses those up front, this
856 // is the backstop -- and the caller deletes the `.part`.
857 //
858 // The stream each source is copied from is the one it plays: `audio_sources`
859 // is the same list `PlaybackSession::seek` hands the decoder, so an export
860 // of a timeline playing a file's second audio track carries *that* track.
861 //
862 // One lane is the only shape a *copy* has: summing two means decoding both,
863 // and a sum is not a copy. Two or more go to [`encode_audio`], which is the
864 // very mix the WAV path writes -- it used to be a refusal, and a refusal is
865 // what a file missing half its sound deserves, not what a mix does.
866 //
867 // *Which* lane is the same question `audio_segments_from` answers for
868 // playback, and it is asked here rather than assumed: the lane that holds
869 // the sound need not be `A1` (a project may leave `A1` empty and place
870 // everything on `A2`), and copying `A1`'s list in that case would write a
871 // file with no audio track at all -- silently, which is the failure this
872 // whole comment is about.
873 let lanes = project.audio_segments_from(0, meta.frame_rate);
874 let [segments] = &lanes[..] else {
875 return encode_audio(project, meta, kbps, mkv);
876 };
877 // ...and the same list names *which* lane those clips sit on, which is the
878 // only way to ask what has been done to them.
879 let lane = project.audio_lanes()[0];
880 // ...and the same list decides whether any clip this would copy plays at a
881 // rate other than the one it was recorded at. A copy hands the muxer the
882 // very AAC packets the source holds and there is no rate inside a packet to
883 // change: the picture would come out re-timed (the walk in [`run`] honours
884 // it) over sound at 1.00x, which is the drift a person finds only after the
885 // file has gone somewhere. Decoded and resampled instead, by the same worker
886 // playback feeds from.
887 //
888 // ...and whether any clip on it carries an equalizer, which is sample math a
889 // copy never reaches: copying such a lane would write the clip *flat*,
890 // silently.
891 //
892 // A frame *rate* of its own is not one of those, and that is deliberate: do
893 // not "fix" this into a re-encode. A clip counts the **timeline's** frames
894 // whatever its file was shot at ([`crate::project::Rate`]), so the window
895 // this copy trims a source's sound to is `start..end` in whole timeline
896 // frames -- exactly the seconds the picture covers -- and the file is read
897 // at the pitch it was recorded at, which is what playing at the rate it was
898 // shot at means. There is no per-clip stretch to express, so the packets are
899 // already the right sound in the right place; re-encoding a conformed lane
900 // would buy nothing and cost a generation of loss on every mixed-rate export
901 // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot`
902 // measures the copied sound against the picture). A *speed* is different
903 // because it resamples, which is why it leaves through the re-encode above.
904 //
905 // Only these: a timeline nobody has touched still leaves through the copy
906 // below, packet for packet, so no passthrough quietly becomes a generation
907 // of loss.
908 // ...and whether the mix itself does anything a packet never went through:
909 // a lane volume is applied at the sum and a limiter over it, so copying
910 // such a lane would write it at unity and unlimited, silently.
911 let speeded = project.lane(lane).iter().any(|c| !c.speed.is_normal());
912 if speeded || equalized(project) || mastered(project) {
913 return encode_audio(project, meta, kbps, mkv);
914 }
915 // What is left is a copy the *sources* may still not be able to give: AAC
916 // inside a Matroska file (readable, but not out of a sample table this walks
917 // -- there is none), an mp3 or a wav on the timeline, an AC-3 track, two
918 // sources whose AAC parameters disagree. Every one of them decodes, and what
919 // decodes can be encoded again, so the copy's refusal is now a route: the
920 // error a *decode* cannot get past -- Opus or AC-3 inside a Matroska file,
921 // which symphonia has no decoder for at any version -- is the one that comes
922 // back, by name, from [`encode_audio`].
923 match AudioSession::copy_multi_streams(&project.audio_sources(), segments) {
924 Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio {
925 params,
926 packets,
927 copied: true,
928 // A copy is the source's own AAC packets: there is no Opus copy
929 // path here, since the packets an mkv source holds never reach this
930 // (they are not in a sample table) and every one of them re-encodes.
931 opus_pre_skip: None,
932 })),
933 Err(_) => encode_audio(project, meta, kbps, mkv),
934 }
935}
936
937/// The picture's half of [`copy_audio`]: a Matroska export whose every span is
938/// its source's own coded blocks, written back out without a decoder or an
939/// encoder anywhere in the path.
940///
941/// **When.** A copy is entered only where it says *exactly* what the timeline
942/// says, which is the audio gate's rule and not a looser one: the file this
943/// export writes is Matroska, the source's codec is the one that file would
944/// carry ([`Format::Hevc`] over HEVC, [`Format::Av1`] over AV1), and nothing on
945/// the way has touched a sample -- no grade, no speed, no rate conversion, no
946/// gap to fill with black, no source of another size to place on the canvas,
947/// no `ContentEncodings` packing to undo. Anything else re-encodes exactly as
948/// it always did; there is no half-copied file.
949///
950/// **All or nothing, per export.** A copied span and an encoded one cannot
951/// share one track: this project's encoders write 8-bit SDR streams whose
952/// parameter sets are their own, so splicing them into (say) a Main 10 HDR
953/// source would change bit depth and colour mid-track, and a container states
954/// its configuration record once. So the head and tail fragments of a cut that
955/// lands mid-GOP are *not* re-encoded into the copy -- they are what makes the
956/// whole export fall back to the encoder. What a copy needs instead is that
957/// every span begins on a sync point and ends where the next one begins, which
958/// is what a cut placed on a keyframe gives it.
959///
960/// **What a cut costs.** An open-GOP source (x265's default) writes leading
961/// pictures after a sync point that are shown *before* it and reference the
962/// group before it. At the start of a copied region those references are not in
963/// the file, so they are dropped -- the picture before the cut is held for those
964/// few frames (four at this film's B-depth, a sixth of a second) rather than
965/// being written as pictures that cannot decode. The region still starts at the
966/// timeline frame it owns, so the sound never drifts.
967///
968/// ponytail: mp4 is not copied (its `hvc1` sample entry forbids in-band
969/// parameter sets, and the mp4 muxer here writes its sample table from a frame
970/// counter), and neither is H.264, which this project only writes into mp4. The
971/// upgrade path for both is a sample-table writer that takes explicit
972/// timestamps, which is what [`MkvMuxer::write_block`] already is for Matroska.
973struct CopyPlan {
974 /// Every source a region reads, by the index the project names it with;
975 /// `None` for a source no clip plays from.
976 sources: Vec<Option<MkvDemuxer>>,
977 regions: Vec<CopyRegion>,
978 codec_id: &'static [u8],
979 /// The `CodecPrivate` every region's source agrees on -- a track is declared
980 /// once, so two sources that disagree about their parameter sets are not one
981 /// copy.
982 private: Vec<u8>,
983 colour: ColorDescription,
984 width: u32,
985 height: u32,
986}
987
988/// A run of source blocks copied in one piece: what a cut leaves behind, and
989/// what two spans that continue each other in the same file merge back into.
990struct CopyRegion {
991 source: usize,
992 /// Blocks of that source, in the file's own decode order.
993 blocks: std::ops::Range<usize>,
994 /// The timeline frame the region's first picture is shown at.
995 start: u32,
996}
997
998impl CopyPlan {
999 /// The plan for this timeline, or `None` where anything at all makes a copy
1000 /// say something other than what the timeline says -- in which case the
1001 /// caller encodes, which is what it always did.
1002 fn of(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<Self> {
1003 let (codec_id, codec): (&'static [u8], Codec) = match settings.format {
1004 Format::Hevc => (b"V_MPEGH/ISO/HEVC", Codec::Hevc),
1005 Format::Av1 => (b"V_AV1", Codec::Av1),
1006 _ => return None,
1007 };
1008 let entries = project.sources();
1009 let mut sources: Vec<Option<MkvDemuxer>> = (0..entries.len()).map(|_| None).collect();
1010 let mut declared: Option<(Vec<u8>, ColorDescription)> = None;
1011 let mut regions: Vec<CopyRegion> = Vec::new();
1012 for span in project.composite_spans_from(0) {
1013 // A gap is black frames, which only an encoder makes.
1014 let (source, in_frame) = span.from?;
1015 if !span.speed.is_normal() {
1016 return None;
1017 }
1018 // The grade playback shows, which a copied packet never went
1019 // through. `None` and the identity are the same untouched picture.
1020 if project
1021 .composite_color_at(span.start)
1022 .is_some_and(|params| !params.is_identity())
1023 {
1024 return None;
1025 }
1026 let path = &entries.get(source)?.path;
1027 if sources.get(source)?.is_none() {
1028 if !crate::demux::is_matroska(path) {
1029 return None;
1030 }
1031 let (source_meta, demuxer) = Demuxer::open(path).ok()?;
1032 let Demuxer::Mkv(demuxer) = demuxer else {
1033 return None;
1034 };
1035 // The stream this file would carry, at the size and the rate the
1036 // timeline is in: anything else is a picture that has to be
1037 // coded again to become this file's.
1038 if source_meta.codec != codec
1039 || source_meta.width != meta.width
1040 || source_meta.height != meta.height
1041 || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()?
1042 != Rate::REAL_TIME
1043 || !demuxer.plain_blocks()
1044 {
1045 return None;
1046 }
1047 // One track, one configuration record and one `Colour`: two
1048 // sources that disagree about either are two streams, and this
1049 // writes one.
1050 let declares = (demuxer.codec_private().to_vec(), source_meta.color);
1051 if declared.get_or_insert(declares.clone()) != &declares {
1052 return None;
1053 }
1054 sources[source] = Some(demuxer);
1055 }
1056 let demuxer = sources.get_mut(source)?.as_mut()?;
1057 // The window this span reads, in the blocks the whole engine counts
1058 // a source's frames in. It has to *be* whole groups of pictures: a
1059 // copy that began between two sync points would hand a decoder
1060 // pictures whose references are not in the file, and one that ended
1061 // between them would drop a reference the pictures before it need.
1062 let (start, end) = (in_frame as usize, in_frame as usize + span.len as usize);
1063 if end > demuxer.block_count()
1064 || !demuxer.is_sync(start)
1065 || (end < demuxer.block_count() && !demuxer.is_sync(end))
1066 {
1067 return None;
1068 }
1069 // Two spans that continue each other in one file are one region:
1070 // nothing was cut between them, so the leading pictures across that
1071 // boundary still have every reference they need.
1072 match regions.last_mut() {
1073 Some(last)
1074 if last.source == source
1075 && last.blocks.end == start
1076 && last.start + (last.blocks.end - last.blocks.start) as u32
1077 == span.start =>
1078 {
1079 last.blocks.end = end;
1080 }
1081 _ => regions.push(CopyRegion {
1082 source,
1083 blocks: start..end,
1084 start: span.start,
1085 }),
1086 }
1087 }
1088 let (private, colour) = declared?;
1089 Some(Self {
1090 sources,
1091 regions,
1092 codec_id,
1093 private,
1094 colour,
1095 width: meta.width,
1096 height: meta.height,
1097 })
1098 }
1099
1100 /// The file itself: one Matroska muxer, every region's blocks through it in
1101 /// the order and at the timing their source states.
1102 fn run(
1103 mut self,
1104 out: &Path,
1105 meta: &VideoMeta,
1106 shared: &Shared,
1107 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
1108 subs: Vec<SubParams>,
1109 total: u32,
1110 ) -> crate::Result<()> {
1111 let mut muxer = MkvMuxer::create_copy(
1112 out,
1113 &CopyParams {
1114 width: self.width,
1115 height: self.height,
1116 frame_rate: meta.frame_rate,
1117 codec_id: self.codec_id,
1118 codec_private: &self.private,
1119 colour: self.colour,
1120 },
1121 audio,
1122 subs,
1123 )?;
1124 // Nanoseconds a timeline frame lasts, which is what a region's own
1125 // position on the timeline is measured in.
1126 let frame_ns = 1e9 / meta.frame_rate;
1127 let mut done = 0u32;
1128 for region in &self.regions {
1129 let demuxer = self.sources[region.source]
1130 .as_mut()
1131 .ok_or("a copied region names a source that was never opened")?;
1132 let base = (f64::from(region.start) * frame_ns).round() as i64;
1133 // When the region's first picture is shown on its source's clock;
1134 // everything after it is written that far along from `base`.
1135 let mut origin: Option<i64> = None;
1136 for index in region.blocks.clone() {
1137 cancelled(shared)?;
1138 let Some(block) = demuxer.coded_block(index)? else {
1139 break;
1140 };
1141 let origin = *origin.get_or_insert(block.ts_ns);
1142 // The leading pictures of the group this region opens on: shown
1143 // before it, coded against the group before it, and that group
1144 // is not in this file. Dropped rather than written as pictures
1145 // no decoder can put back together.
1146 if block.ts_ns < origin {
1147 continue;
1148 }
1149 muxer.write_block(block.bytes, block.key, base + block.ts_ns - origin)?;
1150 done += 1;
1151 shared
1152 .progress
1153 .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);
1154 }
1155 }
1156 // Everything up to here is still cancellable, exactly as the encoded
1157 // path is up to its own `finish`.
1158 cancelled(shared)?;
1159 muxer.finish()?;
1160 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
1161 Ok(())
1162 }
1163}
1164
1165/// The same lane, *decoded*: what a packet copy cannot carry comes out here as
1166/// AAC written by this project's own encoder.
1167///
1168/// The samples are the very ones [`run_audio`] would put in a WAV -- the same
1169/// opener with the same equalizers, the same rates and the same resize onto the
1170/// timeline's own length -- so an mp4 and a WAV of one timeline are one mix,
1171/// not two that could disagree.
1172///
1173/// AAC-LC's encoder delay is one 1024-frame block, which is exactly the priming
1174/// a reader drops when the file carries no edit list (`audio::DEFAULT_PRIMING`,
1175/// and [`crate::mux::Mp4Muxer`] writes none): the first packet is that delay, so
1176/// the sound starts at timeline frame 0 as a copied track's does.
1177///
1178/// ponytail: the mix sits in memory as f32 before it is encoded (~46 MB a
1179/// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers
1180/// the whole stream anyway, since it encodes its frames in parallel. Upgrade
1181/// path is a chunked push once that encoder streams.
1182fn encode_audio(
1183 project: &Project,
1184 meta: &VideoMeta,
1185 kbps: u32,
1186 mkv: bool,
1187) -> crate::Result<Option<ExportAudio>> {
1188 let sources = project.audio_sources();
1189 let segs = project.audio_segments_from(0, meta.frame_rate);
1190 let eqs = project.audio_eqs_from(0, meta.frame_rate);
1191 let speeds = project.audio_speeds_from(0, meta.frame_rate);
1192 let Some((audio, chunks)) = AudioSession::open_mixed_streams_master(
1193 &sources,
1194 &segs,
1195 &eqs,
1196 &speeds,
1197 &project.audio_gains(),
1198 project.limiter(),
1199 )?
1200 else {
1201 return Ok(None); // no audio to write, exactly as a copy of nothing is
1202 };
1203 let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| {
1204 format!(
1205 "{} Hz is not an AAC sample rate: export WAV, FLAC, MP3 or OGG, which write it as \
1206 it is",
1207 audio.sample_rate
1208 )
1209 })?;
1210 let channels = usize::from(audio.channels.max(1));
1211 // The timeline's length, not the mix's: a segment resolves its window to
1212 // whole samples on its own, so the sum can miss by a sample or two and a
1213 // source that ran out early would leave the track short under a picture
1214 // that is not. One resize settles both, as [`run_audio`]'s does.
1215 let total = (f64::from(project.timeline_frames()) / meta.frame_rate
1216 * f64::from(audio.sample_rate))
1217 .round() as usize
1218 * channels;
1219 let mut samples: Vec<f32> = Vec::with_capacity(total);
1220 for chunk in chunks {
1221 samples.extend(chunk.samples);
1222 }
1223 samples.resize(total, 0.0);
1224
1225 // Opus where the container carries it and the mix is inside the envelope
1226 // this encoder was *measured* correct in ([`encode_opus`]): a Matroska file,
1227 // 48 kHz, stereo. An Opus source edited into an mkv export therefore leaves
1228 // as Opus instead of being turned into AAC on the way out, which is the one
1229 // generation of loss an all-Opus timeline used to pay for being cut.
1230 //
1231 // Everything else falls through to the AAC below and is unchanged by this:
1232 // every mp4, a mono mix, a 44.1 kHz timeline. The rate is the mix's own --
1233 // there is no resampler on this path, and inventing one to reach 48 kHz
1234 // would resample a whole timeline to satisfy a codec, which is a bigger
1235 // change to the sound than the codec is.
1236 if mkv
1237 && audio.sample_rate == OPUS_RATE
1238 && channels == 2
1239 && let Some((packets, pre_skip)) = encode_opus(&samples, kbps)?
1240 {
1241 return Ok(Some(ExportAudio {
1242 params: crate::AacTrackParams {
1243 freq_index,
1244 chan_conf: 2,
1245 sample_rate: OPUS_RATE,
1246 },
1247 packets,
1248 copied: false,
1249 opus_pre_skip: Some(pre_skip),
1250 }));
1251 }
1252
1253 // The caller's rate, never the encoder's own 128 default -- see
1254 // [`DEFAULT_AUDIO_KBPS`] for why the untouched figure is 256.
1255 let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig {
1256 bitrate_bps: kbps * 1_000,
1257 ..Default::default()
1258 });
1259 encoder.push_pcm(&samples, audio.channels.max(1), audio.sample_rate)?;
1260 encoder.finish();
1261 let mut packets = Vec::new();
1262 // `next_packet` after `finish` yields packets until `Eof` and nothing else,
1263 // so the loop ends on the only error it can see.
1264 while let Ok(packet) = encoder.next_packet() {
1265 packets.push(crate::AacPacket {
1266 bytes: packet.data,
1267 samples: packet.duration,
1268 });
1269 }
1270 Ok(Some(ExportAudio {
1271 params: crate::AacTrackParams {
1272 freq_index,
1273 // 1 and 2 are the ISO channel configurations for mono and stereo,
1274 // and what the opener hands the timeline is one of those whatever
1275 // the source carried ([`crate::audio::downmix`]).
1276 chan_conf: audio.channels.max(1) as u8,
1277 sample_rate: audio.sample_rate,
1278 },
1279 packets,
1280 copied: false,
1281 opus_pre_skip: None,
1282 }))
1283}
1284
1285/// The one rate Opus codes at. The container may state another one in its
1286/// `OpusHead` and every decoder still runs at 48 kHz (RFC 7845 §5.1), so a
1287/// timeline at any other rate is not "encoded at its own rate" here -- it is
1288/// resampled or it is not Opus, and [`encode_audio`] picks the second.
1289pub(crate) const OPUS_RATE: u32 = 48_000;
1290
1291/// 20 ms at [`OPUS_RATE`], the frame every Opus muxer in the wild writes:
1292/// long enough that the per-packet overhead is nothing, short enough that a
1293/// Matroska block timestamp in whole milliseconds is exact.
1294const OPUS_FRAME: usize = 960;
1295
1296/// The most this project asks of `opus-rs`, in kbps, and why it is a cap rather
1297/// than the four rates the Sound row offers: this encoder falls off a cliff at a
1298/// rate that depends on the *content*, and above it a conformant decoder gets
1299/// noise back. Measured on three one-second spans of a real 5.1 Opus film,
1300/// encoded here and decoded with `ruopus` -- which is not the suspect, since it
1301/// decodes ffmpeg's own libopus at 256 kbps to correlation 1.00000 on the same
1302/// material:
1303///
1304/// ```text
1305/// kbps 120 128 136 144 152 160
1306/// span A 0.945 0.937 0.452 0.206 0.223 0.163
1307/// span B 0.986 0.989 0.697 0.153 0.114 0.149
1308/// span C 0.999 0.994 0.951 0.335 0.266 0.326
1309/// libopus 0.997 0.998 -- -- -- 0.996 (same spans, control)
1310/// ```
1311///
1312/// So: usable to 128, ruined by 136 on real film sound, and the pure-tone
1313/// fixtures that first suggested a 165 kbps ceiling were simply easy material.
1314/// 128 kbps stereo Opus is around transparency anyway (libopus scores 0.998
1315/// there on the worst of those spans), so the cap costs nothing a listener has.
1316/// It is still not *trusted*: every track is decoded again and measured before
1317/// it is written ([`opus_fidelity`]), because a cliff whose edge moves with the
1318/// material is not something a constant can be safe against on its own.
1319///
1320/// ponytail: the ceiling is this encoder's, not the format's. Upgrade path is a
1321/// released `opus-rs` that survives its own high rates -- the unit test pins the
1322/// failure, so it fails the day the bug is fixed and this can be raised.
1323pub(crate) const OPUS_MAX_KBPS: u32 = 128;
1324
1325/// How well a track has to survive its own round trip to be written as Opus:
1326/// the correlation between the mix and the decode of what was encoded from it.
1327/// A good encoder scores 0.98-0.999 on this material (libopus, measured above);
1328/// the failure mode is not subtle at all, scoring 0.1-0.7. 0.95 sits in the gap
1329/// with room on both sides, and what fails it is written as AAC -- the export's
1330/// own encoder line then says AAC, so the fallback is visible rather than
1331/// silent.
1332const OPUS_MIN_FIDELITY: f64 = 0.95;
1333
1334/// The encoder's lookahead at [`OPUS_RATE`] in the mode this envelope always
1335/// selects (CELT-only: 2.5 ms). The pre-skip a file states is this *plus* the
1336/// warm-up frame [`encode_opus`] throws away. Measured by
1337/// cross-correlating the decode against the source, not taken from the crate --
1338/// it exposes no lookahead getter -- and asserted at both ends of the rate band
1339/// in `tests/opus_export.rs`, which is what catches a version that changes it.
1340const OPUS_PRE_SKIP: u16 = 120;
1341
1342/// The mix as Opus packets, one per [`OPUS_FRAME`], plus the pre-skip that has
1343/// to be declared in front of them. Stereo and [`OPUS_RATE`] only -- the caller
1344/// checks both, because outside that pair this encoder is not one this project
1345/// is willing to write files with ([`OPUS_MAX_KBPS`]).
1346///
1347/// The tail frame is padded with silence rather than dropped: Opus codes whole
1348/// frames and a track a few milliseconds short under a picture that is not is
1349/// the drift every other path here is written to avoid. The pre-skip trims the
1350/// front; the container's duration trims the back.
1351fn encode_opus(samples: &[f32], kbps: u32) -> crate::Result<Option<(Vec<crate::AacPacket>, u16)>> {
1352 let mut encoder = opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio)
1353 .map_err(|e| format!("the Opus encoder refused 48 kHz stereo: {e}"))?;
1354 encoder.bitrate_bps = (kbps.min(OPUS_MAX_KBPS) * 1_000) as i32;
1355 encoder.complexity = 10;
1356 let mut packets = Vec::new();
1357 let mut frame = vec![0f32; OPUS_FRAME * 2];
1358 // 1275 bytes is the most one Opus frame may weigh (RFC 6716 §3.2); this is
1359 // that with room for the TOC and a padded frame, so `encode` never has to
1360 // refuse for want of a buffer.
1361 let mut out = vec![0u8; 1500];
1362 // The head, coded **twice**. An encoder's very first frame has no history
1363 // behind it and comes out ramped and out of phase -- measured on a 440 Hz
1364 // fixture, the first 20 ms of the export correlated 0.09 with the source
1365 // where every later window correlated 0.9997 -- and 20 ms of wrong sound at
1366 // the head of a file is the kind of thing nobody hears in a test and
1367 // everybody hears in the first frame of a cut. So the first frame is fed in
1368 // once to warm the encoder, and thrown away again by the pre-skip: exactly
1369 // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet.
1370 let warm = samples.len().min(OPUS_FRAME * 2);
1371 // ...and one silent frame after the sound, for the same delay seen from the
1372 // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so
1373 // without a frame to push them out the last 2.5 ms of the timeline stay
1374 // inside it and the track ends short under a picture that does not.
1375 let blocks = std::iter::once(&samples[..warm])
1376 .chain(samples.chunks(OPUS_FRAME * 2))
1377 .chain(std::iter::once(&samples[..0]));
1378 for block in blocks {
1379 frame[..block.len()].copy_from_slice(block);
1380 frame[block.len()..].fill(0.0);
1381 let len = encoder
1382 .encode(&frame, OPUS_FRAME, &mut out)
1383 .map_err(|e| format!("Opus encode failed: {e}"))?;
1384 packets.push(crate::AacPacket {
1385 bytes: out[..len].to_vec(),
1386 samples: OPUS_FRAME as u32,
1387 });
1388 }
1389 // ...and now the part that is not optimism: what was just written is
1390 // decoded again and measured against what went in, and a track that does
1391 // not come back is not written at all ([`OPUS_MIN_FIDELITY`]). The caller
1392 // falls through to AAC, which is exactly where it stood before this seat
1393 // existed -- a worse codec is a fair trade for a track that is the sound.
1394 //
1395 // ponytail: this costs one Opus decode of the whole track (a minute of
1396 // sound in a few hundred milliseconds, against a video encode that is
1397 // minutes). Upgrade path is deleting it, the day this encoder can be
1398 // trusted at the rate it is asked for.
1399 let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16;
1400 let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip));
1401 Ok((fidelity >= OPUS_MIN_FIDELITY).then_some((packets, pre_skip)))
1402}
1403
1404/// The correlation between `samples` and the decode of `packets` with the first
1405/// `pre_skip` frames dropped: 1.0 is the same waveform, and this codec's failure
1406/// mode lands near 0.1. Streamed packet by packet -- the decode is never held,
1407/// only three running sums -- because the mix behind it is already the biggest
1408/// thing in an export ([`encode_audio`]'s ponytail).
1409///
1410/// A packet the decoder refuses is 0.0 and no argument: a track this project
1411/// cannot read is exactly what this is here to catch.
1412fn opus_fidelity(packets: &[crate::AacPacket], samples: &[f32], pre_skip: usize) -> f64 {
1413 let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);
1414 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
1415 let mut drop = pre_skip * 2;
1416 let mut at = 0;
1417 for packet in packets {
1418 let Ok(pcm) = decoder.decode_packet(&packet.bytes) else {
1419 return 0.0;
1420 };
1421 let pcm = &pcm[drop.min(pcm.len())..];
1422 drop = drop.saturating_sub(packet.samples as usize * 2);
1423 for (want, got) in samples[at.min(samples.len())..].iter().zip(pcm) {
1424 let (x, y) = (f64::from(*want), f64::from(*got));
1425 num += x * y;
1426 da += x * x;
1427 db += y * y;
1428 at += 1;
1429 }
1430 }
1431 num / (da.sqrt() * db.sqrt()).max(1e-12)
1432}
1433
1434fn run(
1435 project: &Project,
1436 meta: &VideoMeta,
1437 out: &Path,
1438 shared: &Shared,
1439 settings: &ExportSettings,
1440) -> crate::Result<()> {
1441 let total = project.timeline_frames();
1442 let sources = project.sources();
1443 // Audio first: a track has to be declared when the muxer is created, which
1444 // happens as soon as the first coded picture arrives -- and the Matroska
1445 // muxer wants the packets themselves that early too, because it interleaves
1446 // them into the clusters as it writes. Every video format gets the same
1447 // track: none of them is picture-only any more.
1448 let audio = copy_audio(
1449 project,
1450 meta,
1451 audio_kbps_of(settings),
1452 settings.format.is_mkv(),
1453 )?;
1454 let audio_params = audio.as_ref().map(|track| AudioParams {
1455 freq_index: track.params.freq_index,
1456 chan_conf: track.params.chan_conf,
1457 sample_rate: track.params.sample_rate,
1458 opus_pre_skip: track.opus_pre_skip,
1459 });
1460 // What the track *is*, kept before the packets are handed to a muxer: the
1461 // encoder line names a copy or an encode and only `copy_audio` knows which.
1462 let sound = audio.as_ref().map(|track| track.copied);
1463 // ...and *which* encoder, for the same line: the card predicts Opus from the
1464 // format alone and cannot know the mix's rate or width ([`audio_label`]),
1465 // while this is after the mix was opened, so it is the measured answer.
1466 let opus = audio
1467 .as_ref()
1468 .is_some_and(|track| track.opus_pre_skip.is_some());
1469 // Taken by the Matroska muxer at creation; the mp4 one writes its track
1470 // after the picture, so for that path this is still `Some` at the end.
1471 let mut packets = audio.map(|track| track.packets);
1472 // ...and the cues with them, for the same reason: the subtitle track is
1473 // declared in the header and its blocks are interleaved into the clusters,
1474 // so the muxer needs the lot before the first picture is written.
1475 let mut subs = export_subtitles(project, meta, settings);
1476
1477 // Before an encoder is opened at all: a timeline nobody has touched, whose
1478 // sources this file can hold as they are, is written by copying their coded
1479 // blocks -- the picture's half of what `copy_audio` just did for the sound,
1480 // and the difference between an export bounded by the *edited* spans and one
1481 // that re-encodes a whole film to change a cut. [`CopyPlan`] states the
1482 // whole rule; anything at all outside it falls through to the walk below.
1483 if let Some(plan) = CopyPlan::of(project, meta, settings) {
1484 eprintln!("export video: copy (source packets)");
1485 *shared.encoders.lock().unwrap() = Some(format!(
1486 "copy · {}",
1487 audio_label(project, settings.format, sound.is_some(), sound)
1488 ));
1489 return plan.run(
1490 out,
1491 meta,
1492 shared,
1493 audio_params.as_ref().zip(packets.take()),
1494 std::mem::take(&mut subs),
1495 total,
1496 );
1497 }
1498
1499 // One header parse per source, before any of them is decoded: what rate
1500 // each file was shot at against the timeline's ([`Rate`]), which is how the
1501 // clip's timeline frames below become frames of the file, and what its
1502 // samples *mean* ([`ColorDescription`]), which is what decides whether they
1503 // are remapped on the way in. Real time for a still, a song and a
1504 // single-rate project, where every conversion below is the identity.
1505 let rates: Vec<(Rate, ColorDescription, Option<f32>)> = sources
1506 .iter()
1507 .map(|source| source_rate(&source.path, meta.frame_rate))
1508 .collect();
1509 // ...and, for a source on an HDR curve, the tone map that brings its samples
1510 // down to the SDR this file is written in ([`crate::tonemap`]). Once per
1511 // source stream: the table costs a couple of milliseconds to build and a
1512 // span reopens its file, so building it here rather than in the loop below
1513 // is the difference between paying that once and paying it per cut. An SDR
1514 // source -- the whole of an ordinary project -- builds no table at all.
1515 //
1516 // Through the project's own preset ([`tonemap::Preset`]) and each source's
1517 // own declared peak, which is the pair playback's decode funnel builds its
1518 // tables with: preview and export are the same rendition of the same film
1519 // because they are told the same two things, not because two numbers happen
1520 // to agree.
1521 let preset = project.tone();
1522 let tone: Vec<Option<ToneMapper>> = rates
1523 .iter()
1524 .map(|(_, color, peak)| match color.transfer {
1525 Transfer::Sdr => None,
1526 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)),
1527 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)),
1528 })
1529 .collect();
1530 // ...and the one space they are all written in, the same rule a reader with
1531 // no tags to read would apply to this file's height.
1532 let out_color = ColorDescription::output(meta.height);
1533
1534 let mut encoder = Enc::open(meta, settings)?;
1535 // What this file is really being written by, for a progress line to name.
1536 // Published *after* the seat is open, so a hardware encoder the driver
1537 // refused reads as the software one that took over rather than as the hope
1538 // it replaced -- and the sound says whether it was copied or encoded, which
1539 // `copy_audio` decided a few lines up.
1540 *shared.encoders.lock().unwrap() = Some(format!(
1541 "{} · {}",
1542 encoder.label(),
1543 match opus {
1544 true => "Opus · SW encode (opus-rs)",
1545 false => audio_label(project, settings.format, sound.is_some(), sound),
1546 }
1547 ));
1548 let mut muxer = None;
1549 let mut done = 0u32;
1550 let black = Black::new(meta);
1551 // Spans, not clips: a gap in the video is part of the timeline and gets
1552 // encoded too, as black frames. The picture count is therefore
1553 // `timeline_frames` however the lanes are arranged -- and *which* lane a
1554 // span comes from is `composite_spans_from`'s answer, the same one playback
1555 // shows, so an export is what was watched.
1556 for span in project.composite_spans_from(0) {
1557 // Every clip reopens its own source file at its own in point; the
1558 // encoder is *not* reopened, so the export is one continuous stream
1559 // whose GOP boundaries need not line up with the cuts -- nor with the
1560 // file boundaries, which are just cuts that change the path.
1561 let (mut pictures, rate, in_frame, color, mapper) = match span.from {
1562 Some((source, in_frame)) => {
1563 let entry = sources
1564 .get(source)
1565 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
1566 let (rate, color, _peak) = rates[source];
1567 // Opened at the file's own frame, which is the only place the
1568 // file's numbering is used -- the span's are the timeline's.
1569 let pictures = ClipDecoder::open(&entry.path, rate.source_at(in_frame))?;
1570 (
1571 Some(pictures),
1572 rate,
1573 in_frame,
1574 Some(color),
1575 tone[source].as_ref(),
1576 )
1577 }
1578 // A gap's black is 16/128/128, which is black in every matrix here
1579 // and on every curve: nothing to remap and nothing to tone-map,
1580 // which is what `None` says.
1581 None => (None, Rate::REAL_TIME, 0, None, None),
1582 };
1583 // Mixed spaces on one timeline: a clip coded against another matrix than
1584 // the one this file declares is rewritten into it, *after* the grade --
1585 // playback grades in the source's own space and converts for the screen
1586 // ([`crate::decode`]), so a grade applied to remapped samples is a
1587 // different picture than the one the canvas showed. Same-space clips --
1588 // the whole of an ordinary project -- take `None` and not a byte is
1589 // touched.
1590 //
1591 // ...and what the samples mean when that remap sees them is not always
1592 // what the file said, which is [`remap_into`]'s whole question.
1593 let remap = remap_into(color, mapper.is_some(), out_color.matrix);
1594 // What this span is graded by -- the same answer playback's decoder
1595 // carries, so the export is the picture that was watched. `None` for a
1596 // gap and for an ungraded clip, and that is the path where not a byte
1597 // is touched. Scratch outside the frame loop: it is refilled per frame
1598 // and its allocation survives the whole span.
1599 let grade = project.composite_color_at(span.start).copied();
1600 let mut graded = (Vec::new(), Vec::new(), Vec::new());
1601 // ...and the canvas it is placed on, which is where a source of another
1602 // resolution becomes a picture at the project's. The same `Composer`
1603 // playback composes with, given the same policy, so an export is what
1604 // was watched down to the letterbox; a clip already the project's size
1605 // passes through it untouched.
1606 let mut canvas = Composer::new(
1607 meta.width,
1608 meta.height,
1609 project.composite_fit_at(span.start),
1610 );
1611 // Timeline frames, taken a *source* frame at a time: at a rate other
1612 // than real time the two are not the same count, and the span says which
1613 // source frame each timeline frame shows ([`Speed::source_at`]) -- the
1614 // very frame playback is holding there, because the two conversions are
1615 // one floor/ceil pair (`speed_maps_both_ways`). A speed-up decodes the
1616 // frames it skips and drops them, because the pictures after them
1617 // reference those; a slow-down encodes the picture it is holding again
1618 // rather than decoding it twice. At real time `repeats` is 1 and `want`
1619 // advances by one, which is the loop this always ran.
1620 let mut done_here = 0u32;
1621 // Source frames already taken out of this span's decoder.
1622 let mut taken = 0u32;
1623 // The whole of the mapping, in the order it composes: the speed says
1624 // which of the clip's (timeline-rate) frames a timeline frame shows,
1625 // and the rate says which frame of the *file* that is -- counted from
1626 // the one the decoder was opened at. At real time and at the timeline's
1627 // own rate this is `Speed::source_at` and nothing else, which is the
1628 // walk a single-rate project has always taken.
1629 let opened_at = rate.source_at(in_frame);
1630 let source_at =
1631 |offset: u32| rate.source_at(in_frame + span.speed.source_at(offset)) - opened_at;
1632 while done_here < span.len {
1633 cancelled(shared)?;
1634 let want = source_at(done_here);
1635 // How many timeline frames from here show that same picture: one at
1636 // real time, more when the clip is slowed or its file is slower
1637 // than the timeline. Encoded again rather than decoded twice.
1638 let repeats = (done_here..span.len)
1639 .take_while(|&offset| source_at(offset) == want)
1640 .count() as u32;
1641 let picture = match &mut pictures {
1642 Some(pictures) => {
1643 let mut ran_out = false;
1644 while taken < want && !ran_out {
1645 ran_out = pictures.next()?.is_none();
1646 taken += 1;
1647 }
1648 match ran_out {
1649 true => None,
1650 false => {
1651 taken += 1;
1652 pictures.next()?
1653 }
1654 }
1655 }
1656 None => Some(black.picture()),
1657 };
1658 let Some((y, u, v, width, height)) = picture else {
1659 break; // source ran out early; the clip list outlives the file
1660 };
1661 // The planes are borrowed from the decoder (and `Black::picture`
1662 // hands the same slice as both u and v), so a grade cannot be
1663 // applied in place: it goes onto a copy, which the encoder then
1664 // reads instead.
1665 let params = grade.filter(|p| !p.is_identity());
1666 let (y, u, v) = match (params, remap, mapper) {
1667 (None, None, None) => (y, u, v),
1668 (params, remap, mapper) => {
1669 let (gy, gu, gv) = &mut graded;
1670 gy.clear();
1671 gy.extend_from_slice(y);
1672 gu.clear();
1673 gu.extend_from_slice(u);
1674 gv.clear();
1675 gv.extend_from_slice(v);
1676 // Tone-map first, so the grade is applied to the SDR picture
1677 // the canvas showed and not to HDR codes; then remap the
1678 // graded result. The order playback renders in, and the
1679 // only order in which preview and export agree.
1680 if let Some(mapper) = mapper {
1681 mapper.map(gy, gu, gv, width as usize, height as usize);
1682 }
1683 if let Some(params) = params {
1684 crate::color::apply_yuv(&params, gy, gu, gv);
1685 }
1686 if let Some((from, to)) = remap {
1687 crate::colorspace::remap(from, to, gy, gu, gv, width as usize);
1688 }
1689 (&gy[..], &gu[..], &gv[..])
1690 }
1691 };
1692 // Grade first, place second: the grade is the clip's own pixels
1693 // and the bars around them are not the clip (see `scale::Composer`).
1694 let (y, u, v, width, height) = canvas.place(y, u, v, width, height);
1695 // Once per timeline frame this source frame covers: one at real time
1696 // and faster, more when the clip is slowed -- the picture is already
1697 // graded and placed, so a held frame costs an encode and no decode.
1698 for _ in 0..repeats {
1699 if let Some((au, key)) = encoder.encode(y, u, v, width, height)? {
1700 write_video(
1701 &mut muxer,
1702 out,
1703 meta,
1704 settings,
1705 audio_params.as_ref(),
1706 &mut packets,
1707 &mut subs,
1708 au,
1709 key,
1710 )?;
1711 }
1712 done += 1;
1713 shared
1714 .progress
1715 .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);
1716 }
1717 done_here += repeats;
1718 }
1719 }
1720 while let Some((au, key)) = encoder.drain()? {
1721 write_video(
1722 &mut muxer,
1723 out,
1724 meta,
1725 settings,
1726 audio_params.as_ref(),
1727 &mut packets,
1728 &mut subs,
1729 au,
1730 key,
1731 )?;
1732 }
1733 // Progress reads 100% from here on, but nothing is published yet: draining,
1734 // the audio pass and `finish` are all still cancellable.
1735 cancelled(shared)?;
1736
1737 let Some(muxer) = muxer else {
1738 return Err("export produced no coded pictures".into());
1739 };
1740 // The mp4's audio and subtitle tracks after its picture -- the Matroska one
1741 // interleaved its own as it went and left `packets` and `subs` empty behind
1742 // it. The text last, so its samples are written knowing how long the picture
1743 // turned out to be.
1744 let muxer = match muxer {
1745 Muxer::Mp4(mut mp4) => {
1746 for packet in packets.into_iter().flatten() {
1747 mp4.write_audio_packet(&packet.bytes)?;
1748 }
1749 mp4.write_subtitles(&subs)?;
1750 Muxer::Mp4(mp4)
1751 }
1752 muxer => muxer,
1753 };
1754 cancelled(shared)?;
1755 muxer.finish()?;
1756 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
1757 Ok(())
1758}
1759
1760/// Which matrix pair a span's samples are rewritten by on the way into a file
1761/// whose own matrix is `out` -- `None` when they are already coded against it,
1762/// and for a gap, whose 16/128/128 black is black in every matrix here.
1763///
1764/// `toned` says the tone map ran on this span: it hands back BT.709 SDR whatever
1765/// the source was coded as, so an HDR clip is never *also* given the matrix
1766/// treatment its BT.2020 tag would ask for -- one conversion or the other, never
1767/// both on one frame -- while a tone-mapped clip on a canvas below 720 lines
1768/// still takes its 709 -> 601 step.
1769fn remap_into(
1770 color: Option<ColorDescription>,
1771 toned: bool,
1772 out: Matrix,
1773) -> Option<(Matrix, Matrix)> {
1774 let from = match toned {
1775 true => Matrix::Bt709,
1776 false => color?.matrix,
1777 };
1778 (from != out).then_some((from, out))
1779}
1780
1781/// What rate `path` was shot at against a timeline at `timeline_fps`
1782/// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own
1783/// -- a still, a song -- and for one that will not open here: the decoder is
1784/// opened a few lines later and fails the export by name, which is a better
1785/// error than this one could raise.
1786fn source_rate(path: &Path, timeline_fps: f64) -> (Rate, ColorDescription, Option<f32>) {
1787 if crate::is_image(path) || crate::is_audio(path) {
1788 // A still is BT.601 by construction whatever it was authored as:
1789 // `decode::rgb_to_i420` is the one matrix that turns its pixels into
1790 // planes. A song has no picture and the answer is never read.
1791 return (Rate::REAL_TIME, ColorDescription::default(), None);
1792 }
1793 match Demuxer::open(path) {
1794 // ...and one whose rate cannot be named against the timeline's, which
1795 // `matches_timeline` refuses at import, so nothing on a timeline is on
1796 // this arm either.
1797 //
1798 // The declared peak comes off the same open the space does, which is
1799 // what keeps export on the number playback's decode funnel read: one
1800 // header parse, both answers.
1801 Ok((meta, demuxer)) => (
1802 Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME),
1803 meta.color,
1804 demuxer.light().peak(),
1805 ),
1806 // Unreadable here means unreadable below too, where the span dies with a
1807 // real message; the file's own space is the least of that.
1808 Err(_) => (Rate::REAL_TIME, ColorDescription::default(), None),
1809 }
1810}
1811
1812/// The audio lanes alone, summed, as a WAV or a FLAC.
1813///
1814/// Nothing here re-derives the edit: the play lists are
1815/// [`Project::audio_segments_from`] and they are handed to the very
1816/// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written
1817/// is what was heard -- every lane, mixed the same way, gaps included, which
1818/// arrive as real silence from that choke point rather than as a hole this would
1819/// have to invent.
1820///
1821/// The length is the *timeline's*: each segment resolves its window to whole
1822/// samples on its own, so the sum can miss the timeline by a sample or two, and
1823/// a source that runs out early would leave the file short. Both are settled by
1824/// one `resize` at the end -- padding with silence, trimming what overshot --
1825/// so an exported file is exactly as long as what was edited.
1826fn run_audio(
1827 project: &Project,
1828 meta: &VideoMeta,
1829 out: &Path,
1830 shared: &Shared,
1831 settings: &ExportSettings,
1832) -> crate::Result<()> {
1833 let format = settings.format;
1834 let sources = project.audio_sources();
1835 let segs = project.audio_segments_from(0, meta.frame_rate);
1836 // The equalizers with them, so what is written is what is heard down to the
1837 // filter: the worker applies them per segment before the lanes are summed
1838 // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point
1839 // playback's feeder reads from -- there is no second place here that could
1840 // apply them differently.
1841 let eqs = project.audio_eqs_from(0, meta.frame_rate);
1842 // ...and the rates with them, for exactly the same reason: a speeded clip is
1843 // resampled inside the worker playback feeds from, so a WAV of a timeline at
1844 // 2x is half as long and holds the samples that were heard -- not a
1845 // second pass here that could disagree with what the ear got.
1846 let speeds = project.audio_speeds_from(0, meta.frame_rate);
1847 // ...and the mix over both: each lane's volume into the sum, the master
1848 // limiter out of it. The same opener playback's feeder reads from, so a
1849 // file is written at the levels it was heard at -- there is no second
1850 // place here that could mix it differently.
1851 let Some((audio, chunks)) = AudioSession::open_mixed_streams_master(
1852 &sources,
1853 &segs,
1854 &eqs,
1855 &speeds,
1856 &project.audio_gains(),
1857 project.limiter(),
1858 )?
1859 else {
1860 return Err("this timeline has no audio to export".into());
1861 };
1862 // The picture path's line, for a file that is sound alone: there is sound
1863 // by the line above, so this names the encoder writing it.
1864 *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true, None).to_string());
1865 let channels = usize::from(audio.channels);
1866 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate
1867 * f64::from(audio.sample_rate))
1868 .round() as u64;
1869 let total = frames as usize * channels;
1870 // ponytail: the whole export sits in memory (4 bytes a sample, so ~23 MB
1871 // per minute of 48 kHz stereo). `flacenc::MemSource` wants it that way and
1872 // the mp4 path already collects its copied AAC track the same. Upgrade path
1873 // is hound's incremental writer plus flacenc's `Source` trait.
1874 let mut samples: Vec<i32> = Vec::with_capacity(total);
1875 for chunk in chunks {
1876 cancelled(shared)?;
1877 // Already equalized: the chunks come out of the per-lane workers, which
1878 // filter each segment before the mix (`open_mixed_streams_eq` above).
1879 samples.extend(
1880 chunk
1881 .samples
1882 .iter()
1883 .map(|s| (s.clamp(-1.0, 1.0) * f32::from(i16::MAX)).round() as i32),
1884 );
1885 let done = samples.len().min(total) * PROGRESS_SCALE as usize / total.max(1);
1886 shared.progress.store(done as u32, Ordering::Relaxed);
1887 }
1888 samples.resize(total, 0);
1889 // Written in one go and still cancellable up to here, exactly as the mp4
1890 // path is up to its `finish`: the `.part` is what either gets renamed or
1891 // deleted.
1892 cancelled(shared)?;
1893 match format {
1894 Format::Wav => write_wav(out, &samples, &audio)?,
1895 Format::Flac => write_flac(out, &samples, &audio)?,
1896 Format::Mp3 => write_mp3(out, &samples, &audio, audio_kbps_of(settings))?,
1897 Format::Ogg => write_ogg(out, &samples, &audio)?,
1898 _ => unreachable!("the picture formats are `run`"),
1899 }
1900 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
1901 Ok(())
1902}
1903
1904/// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in
1905/// this engine, so what the decoder handed over is what the header says.
1906fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
1907 let mut writer = hound::WavWriter::create(
1908 out,
1909 hound::WavSpec {
1910 channels: audio.channels,
1911 sample_rate: audio.sample_rate,
1912 bits_per_sample: 16,
1913 sample_format: hound::SampleFormat::Int,
1914 },
1915 )?;
1916 for &sample in samples {
1917 writer.write_sample(sample as i16)?;
1918 }
1919 // Not `drop`: this is what rewrites the RIFF sizes in the header, and its
1920 // failure is the difference between a finished file and a truncated one.
1921 writer.finalize()?;
1922 Ok(())
1923}
1924
1925/// The same samples as MPEG-1 Layer III, `rusty_mp3` doing the encoding -- pure
1926/// Rust like every other encoder here, and the reason this format is a row at
1927/// all: the LGPL `shine-rs` was the only one when it was not.
1928///
1929/// CBR at the caller's rate, [`DEFAULT_AUDIO_KBPS`] where there was none. Every
1930/// offered rate is already a legal Layer III value, so the encoder's snap is a
1931/// backstop and not a silent substitution; a sample rate MPEG has no frame for
1932/// (anything but 8-48 kHz) is refused there by name rather than written as
1933/// something else.
1934///
1935/// ponytail: CBR only -- the card offers rates and not a quality index. Upgrade
1936/// path is `Mp3EncoderConfig::vbr_quality` behind a setting of its own.
1937fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta, kbps: u32) -> crate::Result<()> {
1938 let mut encoder = rusty_mp3::Mp3Encoder::new(rusty_mp3::Mp3EncoderConfig {
1939 bitrate_kbps: kbps,
1940 vbr_quality: None,
1941 });
1942 // The samples are the 16-bit ones a WAV of this timeline holds, so the two
1943 // files are one mix -- and `push_pcm_s16` divides by 32768 exactly as this
1944 // engine's own decoders do.
1945 let pcm: Vec<i16> = samples.iter().map(|&s| s as i16).collect();
1946 encoder
1947 .push_pcm_s16(&pcm, audio.channels, audio.sample_rate)
1948 .map_err(|e| format!("mp3 encode: {e}"))?;
1949 encoder.finish();
1950 let mut file = BufWriter::new(File::create(out)?);
1951 // `next_packet` after `finish` yields frames until `Eof`, the Xing/Info
1952 // header first: the loop ends on the only error it can see.
1953 while let Ok(frame) = encoder.next_packet() {
1954 file.write_all(&frame)?;
1955 }
1956 file.flush()?;
1957 Ok(())
1958}
1959
1960/// The Vorbis quality every `.ogg` this program writes is coded at, on
1961/// `rusty_vorbis`'s normalised `[0, 1]` scale -- about `-q 8.35` on the scale
1962/// Vorbis itself is spoken in (`quality01_from_vorbis_q`).
1963///
1964/// A measured number, not a taste. The 2026-08-11 bench encoded three of this
1965/// suite's fixtures (`test_tone_48k.wav`, `test_av.mp4`, `test_tone.mp3`) at
1966/// every quality from 0.40 to 0.95 and decoded each back with **symphonia** --
1967/// an independent decoder, and the very one [`crate::audio`] reopens an export
1968/// with. Two things came out of it:
1969///
1970/// * **Below 0.50 the encoder is quiet, not just coarse.** The decoded RMS
1971/// against the source's runs 0.83-0.94 at quality 0.40 (a 1 to 1.6 dB level
1972/// error), and at 0.10 and below the file decodes to near-silence -- the same
1973/// class of failure the AC-3 mono downmix has in `crate::audio`. From 0.55 up
1974/// the level sits at 1.000-1.009, which is what a lossy codec should do.
1975/// * **The band tops out well under the rates the Sound row offers.** Quality
1976/// 0.85 measured 176, 144 and 148 kbps on the three fixtures; 0.95 only
1977/// reaches ~200. That is why [`audio_rate_refusal`] takes the row away rather
1978/// than mapping 128/192/256/320 onto quality steps: the top two are numbers
1979/// this encoder cannot produce, and a card that printed them would be lying.
1980///
1981/// 0.85 is the top of the band where every fixture still decoded to *exactly*
1982/// its own length (0.95 overshot one by 820 samples), which is the property
1983/// [`write_ogg`] is built around.
1984const VORBIS_QUALITY: f32 = 0.85;
1985
1986/// The Vorbis block hop, and the size of the pre-roll [`write_ogg`] feeds the
1987/// encoder. `rusty_vorbis` emits long blocks only (`N = 2048`, hop `N/2`).
1988const VORBIS_HOP: usize = 1024;
1989
1990/// The same samples as Vorbis I in an Ogg container: `rusty_vorbis` encodes,
1991/// `oxideav-ogg` pages. Pure Rust on both halves, like every other encoder here.
1992///
1993/// Two corrections stand between that library pair and a file this project would
1994/// ship, and both are measured rather than guessed (2026-08-11, decoded back
1995/// with symphonia every time):
1996///
1997/// 1. **One hop of pre-roll.** `rusty_vorbis` advances the granule by a full hop
1998/// on its *first* audio packet, which its own doc comment says decodes to
1999/// zero samples. Written straight through, every sample lands ~1024 early:
2000/// a marker signal whose only energy was its first and last 1024 samples came
2001/// back with the head at 36% of its amplitude and a full-scale burst 1500
2002/// samples *before* the real one, in what should have been silence. Feeding
2003/// [`VORBIS_HOP`] samples of silence ahead of the mix and subtracting the same
2004/// from every granule puts it back: head 0.86 against an input peak of 0.80,
2005/// the phantom burst down to 0.04, the real burst at its own place. The
2006/// decoder drops the pre-roll itself -- a first page whose granule is under
2007/// what its packets decode to is exactly how Ogg says "skip this much".
2008/// 2. **The tail is declared, not encoded.** The block grid overshoots the last
2009/// sample, so the stream is padded out and the *last* page's granule is set
2010/// to the timeline's own frame count. A decoder trims to it, which is what
2011/// makes an `.ogg` here exactly as long as the WAV of the same timeline --
2012/// the promise [`run_audio`] makes for every other audio format.
2013///
2014/// **Stereo, always.** The embedded setup header `rusty_vorbis` ships is a
2015/// stereo profile: a mono push is refused outright ("bad coupling channels"),
2016/// and so is anything wider. A mono mix is therefore written as dual mono, both
2017/// channels bit-identical (measured: `max|L-R|` is exactly 0, and Vorbis's own
2018/// channel coupling codes the empty side channel for almost nothing). Wider than
2019/// stereo cannot reach here -- [`crate::audio`] folds 5.1 to stereo when the
2020/// source is opened -- but it is refused by name rather than left to the
2021/// library's own message.
2022///
2023/// ponytail: one quality, [`VORBIS_QUALITY`], with no user control -- the Sound
2024/// row is refused for this format because the rates it offers are not rates
2025/// Vorbis reaches. Upgrade path is a quality picker of its own, worth building
2026/// the day the card has a control that speaks in quality rather than kbps.
2027fn write_ogg(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
2028 if audio.channels > 2 {
2029 return Err(format!(
2030 "Ogg Vorbis is written in stereo here and this mix has {} channels",
2031 audio.channels
2032 )
2033 .into());
2034 }
2035 // The mp3 path's conversion, so the two files are one mix, plus the pre-roll
2036 // and (for a mono mix) the dual-mono widening: the same sample in both
2037 // channels is the same signal, not a widening of it, so what a player folds
2038 // back down is what was mixed.
2039 let mut pcm: Vec<i16> = vec![0; VORBIS_HOP * 2];
2040 match audio.channels < 2 {
2041 true => pcm.extend(samples.iter().flat_map(|&s| [s as i16, s as i16])),
2042 false => pcm.extend(samples.iter().map(|&s| s as i16)),
2043 }
2044 // The block grid has to run past the last real sample or the tail is never
2045 // coded at all; the granule below is what trims the padding back off.
2046 let frames = samples.len() / usize::from(audio.channels).max(1);
2047 pcm.resize(pcm.len() + VORBIS_HOP * 4 * 2, 0);
2048
2049 let mut encoder = rusty_vorbis::VorbisEncoder::new(rusty_vorbis::VorbisEncoderConfig {
2050 bitrate_bps: rusty_vorbis::BITRATE_NOMINAL,
2051 quality: VORBIS_QUALITY,
2052 });
2053 encoder
2054 .push_pcm_s16(&pcm, 2, audio.sample_rate)
2055 .map_err(|e| format!("vorbis encode: {e}"))?;
2056 encoder.finish();
2057 let mut packets = Vec::new();
2058 loop {
2059 match encoder.next_packet() {
2060 Ok(packet) => packets.push(packet),
2061 Err(rusty_vorbis::Error::Eof) => break,
2062 Err(e) => return Err(format!("vorbis encode: {e}").into()),
2063 }
2064 }
2065 // Identification, comment and setup, then at least one audio packet: fewer
2066 // than four and there is no stream to page.
2067 if packets.len() < 4 {
2068 return Err(format!("vorbis encode: {} packets is not a stream", packets.len()).into());
2069 }
2070 let headers = [
2071 &packets[0].data[..],
2072 &packets[1].data[..],
2073 &packets[2].data[..],
2074 ];
2075 let extradata = oxideav_ogg::mux::xiph_lace(&headers)
2076 .ok_or("vorbis encode: the three headers would not lace")?;
2077
2078 let time_base = oxideav_core::TimeBase::new(1, i64::from(audio.sample_rate));
2079 let mut params = oxideav_core::CodecParameters::audio(oxideav_core::CodecId::new("vorbis"));
2080 params.sample_rate = Some(audio.sample_rate);
2081 params.channels = Some(2);
2082 params.extradata = extradata;
2083 let stream = oxideav_core::StreamInfo {
2084 index: 0,
2085 time_base,
2086 duration: Some(frames as i64),
2087 start_time: Some(0),
2088 params,
2089 };
2090 let mut muxer = oxideav_ogg::mux::open_concrete(Box::new(File::create(out)?), &[stream])
2091 .map_err(|e| format!("ogg mux: {e:?}"))?;
2092 // Without this every audio packet of a short export lands on one page, and
2093 // the muxer's own note records what that costs: a first-audio-page-is-also-
2094 // EOS stream decodes short by half a small block in a reference decoder.
2095 muxer.set_page_target_bytes(Some(OGG_PAGE_BYTES));
2096 muxer
2097 .write_header()
2098 .map_err(|e| format!("ogg mux: {e:?}"))?;
2099 let last = packets.len() - 1;
2100 for (i, packet) in packets.iter().enumerate().skip(3) {
2101 // Correction 1 on every packet, correction 2 on the last one.
2102 let granule = match i == last {
2103 true => frames as i64,
2104 false => (packet.pts - VORBIS_HOP as i64).max(0),
2105 };
2106 muxer
2107 .write_packet(
2108 &oxideav_core::Packet::new(0, time_base, packet.data.clone())
2109 .with_pts(granule)
2110 .with_duration(packet.duration),
2111 )
2112 .map_err(|e| format!("ogg mux: {e:?}"))?;
2113 }
2114 muxer
2115 .write_trailer()
2116 .map_err(|e| format!("ogg mux: {e:?}"))?;
2117 Ok(())
2118}
2119
2120/// The page size [`write_ogg`] asks the Ogg muxer to aim at, in bytes. RFC 3533
2121/// describes pages as "usually 4-8 kB", which is also the muxer's own suggested
2122/// general-purpose value.
2123const OGG_PAGE_BYTES: usize = 4096;
2124
2125/// The same samples, losslessly compressed. `flacenc`'s errors are flattened to
2126/// text: they are not `Send + Sync`, and every one of them fails the export the
2127/// same way.
2128fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
2129 let config = flacenc::config::Encoder::default()
2130 .into_verified()
2131 .map_err(|(_, e)| format!("flac encoder config: {e}"))?;
2132 let source = flacenc::source::MemSource::from_samples(
2133 samples,
2134 usize::from(audio.channels),
2135 16,
2136 audio.sample_rate as usize,
2137 );
2138 let mut stream = flacenc::encode_with_fixed_block_size(&config, source, config.block_size)
2139 .map_err(|e| format!("flac encode: {e}"))?;
2140 // The block sizes are stated fixed, which is what the frames themselves say
2141 // (they are numbered, not sample-addressed). flacenc's single-threaded path
2142 // instead writes the *last* frame's length as the minimum, and a short final
2143 // frame is the normal case -- a stream whose `streaminfo` then disagrees
2144 // with its own blocking strategy. ffmpeg shrugs and plays it; symphonia,
2145 // which is this engine's own reader, rejects every frame header and reads
2146 // to EOF looking for a good one. Written this way the file reopens here,
2147 // which is the only test of an export that counts. (Same value flacenc's
2148 // own `par` path writes; the reference encoder does it too.)
2149 stream
2150 .stream_info_mut()
2151 .set_block_sizes(config.block_size, config.block_size)
2152 .map_err(|e| format!("flac block size: {e}"))?;
2153 let mut sink = flacenc::bitsink::ByteSink::new();
2154 stream
2155 .write(&mut sink)
2156 .map_err(|e| format!("flac write: {e}"))?;
2157 std::fs::write(out, sink.as_slice())?;
2158 Ok(())
2159}
2160
2161/// The I420 planes of one black picture, allocated once for a whole export: a
2162/// gap in the video lane is encoded, not skipped, or every frame after it would
2163/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention
2164/// [`crate::convert`] decodes with.
2165struct Black {
2166 y: Vec<u8>,
2167 uv: Vec<u8>,
2168 width: u32,
2169 height: u32,
2170}
2171
2172impl Black {
2173 fn new(meta: &VideoMeta) -> Self {
2174 let (w, h) = (meta.width as usize, meta.height as usize);
2175 Self {
2176 y: vec![16; w * h],
2177 uv: vec![128; w.div_ceil(2) * h.div_ceil(2)],
2178 width: meta.width,
2179 height: meta.height,
2180 }
2181 }
2182
2183 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
2184 (&self.y, &self.uv, &self.uv, self.width, self.height)
2185 }
2186}
2187
2188/// `Err` once a cancel has been asked for. Called at every point where the work
2189/// left is more than an instant, so an `esc` at 99.9% still stops the export
2190/// instead of quietly completing it.
2191fn cancelled(shared: &Shared) -> crate::Result<()> {
2192 if shared.cancel.load(Ordering::Relaxed) {
2193 return Err("export cancelled".into());
2194 }
2195 Ok(())
2196}
2197
2198/// The two containers an export writes, so the picture loop above is one loop:
2199/// H.264 goes into mp4, AV1 into Matroska, and nothing else is offered.
2200enum Muxer {
2201 Mp4(Mp4Muxer),
2202 Mkv(MkvMuxer),
2203}
2204
2205impl Muxer {
2206 fn finish(self) -> crate::Result<()> {
2207 match self {
2208 Self::Mp4(mp4) => mp4.finish(),
2209 Self::Mkv(mkv) => mkv.finish(),
2210 }
2211 }
2212}
2213
2214/// Writes one access unit, creating the file on the first one -- the parameter
2215/// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once
2216/// the encoder has coded something. Units with no coded slice are skipped: a
2217/// software encoder may hand back an empty buffer while it buffers, and the
2218/// muxer rejects a sample that would carry no picture.
2219fn write_video(
2220 muxer: &mut Option<Muxer>,
2221 out: &Path,
2222 meta: &VideoMeta,
2223 settings: &ExportSettings,
2224 audio: Option<&AudioParams>,
2225 packets: &mut Option<Vec<crate::AacPacket>>,
2226 subs: &mut Vec<SubParams>,
2227 au: &[u8],
2228 key: bool,
2229) -> crate::Result<()> {
2230 if settings.format.is_hevc() {
2231 // The parameter sets are in the access unit -- every intra AU carries
2232 // VPS, SPS and PPS -- and the record built from them is what *both*
2233 // containers declare the track with: an mp4's `hvcC` box and a
2234 // Matroska `CodecPrivate` are the same bytes, so the two files are one
2235 // stream written twice rather than two.
2236 let sample =
2237 crate::mux::annex_b_to_hvcc(au).ok_or("a coded HEVC unit with no slice in it")?;
2238 if settings.format == Format::Hevc {
2239 let muxer = match muxer {
2240 Some(Muxer::Mkv(mkv)) => mkv,
2241 Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
2242 none => {
2243 let hvcc = hevc_params(au)?;
2244 let sound = audio.zip(packets.take());
2245 let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create_hevc(
2246 out,
2247 &HevcParams {
2248 width: meta.width,
2249 height: meta.height,
2250 frame_rate: meta.frame_rate,
2251 hvcc: &hvcc,
2252 },
2253 sound,
2254 std::mem::take(subs),
2255 )?)) else {
2256 unreachable!("just inserted a Matroska muxer")
2257 };
2258 mkv
2259 }
2260 };
2261 return muxer.write_frame(&sample, key);
2262 }
2263 let muxer = match muxer {
2264 Some(Muxer::Mp4(mp4)) => mp4,
2265 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
2266 none => {
2267 let hvcc = hevc_params(au)?;
2268 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_hevc(
2269 out,
2270 &HevcParams {
2271 width: meta.width,
2272 height: meta.height,
2273 frame_rate: meta.frame_rate,
2274 hvcc: &hvcc,
2275 },
2276 audio,
2277 )?)) else {
2278 unreachable!("just inserted an mp4 muxer")
2279 };
2280 mp4
2281 }
2282 };
2283 return muxer.write_coded_sample(&sample, key);
2284 }
2285 if settings.format.is_av1() {
2286 // Every AV1 stream opens on a keyframe, and a keyframe carries the
2287 // sequence header the track has to declare: an encoder that handed back
2288 // neither has produced nothing a decoder can start. The same header goes
2289 // into a `CodecPrivate` and into an `av1C` -- one record, two containers.
2290 fn params<'a>(meta: &VideoMeta, au: &'a [u8]) -> crate::Result<Av1Params<'a>> {
2291 Ok(Av1Params {
2292 width: meta.width,
2293 height: meta.height,
2294 frame_rate: meta.frame_rate,
2295 config: crate::mux::av1_sequence_header(au)
2296 .ok_or("the first coded picture carries no AV1 sequence header")?,
2297 })
2298 }
2299 if settings.format == Format::Av1 {
2300 let muxer = match muxer {
2301 Some(Muxer::Mkv(mkv)) => mkv,
2302 Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
2303 none => {
2304 // The sound with it, all of it: the Matroska muxer writes the
2305 // packets into the clusters of the pictures they play under.
2306 let sound = audio.zip(packets.take());
2307 let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create(
2308 out,
2309 &params(meta, au)?,
2310 sound,
2311 std::mem::take(subs),
2312 )?)) else {
2313 unreachable!("just inserted a Matroska muxer")
2314 };
2315 mkv
2316 }
2317 };
2318 return muxer.write_frame(au, key);
2319 }
2320 let muxer = match muxer {
2321 Some(Muxer::Mp4(mp4)) => mp4,
2322 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
2323 none => {
2324 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1(
2325 out,
2326 &params(meta, au)?,
2327 audio,
2328 )?)) else {
2329 unreachable!("just inserted an mp4 muxer")
2330 };
2331 mp4
2332 }
2333 };
2334 return muxer.write_coded_sample(au, key);
2335 }
2336 if !crate::mux::has_coded_slice(au) {
2337 return Ok(());
2338 }
2339 let muxer = match muxer {
2340 Some(Muxer::Mp4(mp4)) => mp4,
2341 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
2342 none => {
2343 let (sps, pps) = crate::mux::parameter_sets(au)
2344 .ok_or("the first coded picture carries no SPS/PPS")?;
2345 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create(
2346 out,
2347 &VideoParams {
2348 width: meta.width,
2349 height: meta.height,
2350 frame_rate: meta.frame_rate,
2351 sps,
2352 pps,
2353 },
2354 audio,
2355 )?)) else {
2356 unreachable!("just inserted an mp4 muxer")
2357 };
2358 mp4
2359 }
2360 };
2361 muxer.write_video_au(au)
2362}
2363
2364/// The `hvcC` record of the first coded unit, or the refusal by name. Split out
2365/// because both HEVC containers ask it in the same words.
2366fn hevc_params(au: &[u8]) -> crate::Result<Vec<u8>> {
2367 crate::mux::hvcc_record(au)
2368 .ok_or_else(|| crate::Error::from("the first coded picture carries no HEVC VPS/SPS/PPS"))
2369}
2370
2371fn bitrate_for(meta: &VideoMeta) -> u64 {
2372 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;
2373 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)
2374}
2375
2376fn forced(var: &str) -> bool {
2377 std::env::var_os(var).is_some_and(|v| v == "1")
2378}
2379
2380/// Hardware where it is available, software everywhere else -- chosen once for
2381/// the whole export, so the stream never changes encoder mid-file. Both codecs
2382/// have both seats: an AV1 export runs on the plugin's VA-API encoder where the
2383/// GPU has one and on `rav1e` where it has not, which is the same pair H.264 has
2384/// had and the same silent fallback.
2385enum Enc {
2386 Hw(HwEncoder),
2387 Sw {
2388 encoder: Encoder,
2389 /// The last access unit; owned because `rusty_h264` hands back a `Vec`
2390 /// while the plugin lends a slice, and the two have to look alike here.
2391 au: Vec<u8>,
2392 flushed: bool,
2393 },
2394 /// AV1 on the GPU, through the same plugin the H.264 seat uses.
2395 Av1Hw(HwEncoder),
2396 Av1Sw {
2397 context: rav1e::Context<u8>,
2398 /// Temporal units the encoder has finished but the caller has not
2399 /// collected: `rav1e` reorders and may hand back several at once, while
2400 /// this interface is one picture in, one unit out (the plugin's own
2401 /// `ready` queue exists for the same reason).
2402 ready: std::collections::VecDeque<(Vec<u8>, bool)>,
2403 /// The unit currently lent out, for the same reason `Sw` owns one.
2404 au: Vec<u8>,
2405 flushed: bool,
2406 },
2407 /// HEVC, intra-only and software only: `encode_idr_intra_au_cropped` is a
2408 /// *stateless* function of one picture, so a batch of frames is coded on as
2409 /// many cores as there are lanes and collected back in order.
2410 Hevc(HevcEnc),
2411}
2412
2413/// The intra HEVC seat. Frames arrive one at a time (the export walk is one
2414/// picture per timeline frame) and are held until there are [`lanes`] of them,
2415/// then coded in parallel and queued in **display order** -- fanning out is the
2416/// only thing that makes a pure-Rust HEVC export bearable (4.30 fps at 1080p on
2417/// 12 lanes against 0.55 fps on one, measured 2026-08-11), and an export whose
2418/// frames came back shuffled would be no export at all.
2419///
2420/// ponytail: a batch of padded planes sits in memory (~3 MB a frame at 1080p,
2421/// so ~37 MB at 12 lanes) and the tail of a timeline is coded on fewer lanes
2422/// than the middle. Upgrade path is a pipeline that keeps every lane fed from a
2423/// decoder running ahead of the encoder rather than a batch barrier.
2424struct HevcEnc {
2425 /// Padded I420 planes waiting for a lane, in display order.
2426 pending: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)>,
2427 /// Coded access units not yet collected, in the same order.
2428 ready: std::collections::VecDeque<Vec<u8>>,
2429 /// The unit currently lent out, for the reason `Sw` owns one.
2430 au: Vec<u8>,
2431 /// The *coded* size: the picture's, rounded up to the 16-sample CTB grid.
2432 width: usize,
2433 height: usize,
2434 /// Luma samples the conformance window crops off the right and the bottom,
2435 /// so a decoder outputs the picture's own size ([`pad_to_ctb`]).
2436 crop: (usize, usize),
2437 qp: i32,
2438 lanes: usize,
2439 /// What the SPS says the samples mean. A decoder reads the bitstream before
2440 /// it reads the container, so an HEVC stream without this renders BT.601 in
2441 /// libavcodec however the file is tagged -- the container's `Colour` element
2442 /// and `colr` box are not enough on their own.
2443 signal: oxideav_h265::vui::VideoSignalType,
2444}
2445
2446impl Enc {
2447 /// Which seat this *is*, said the way [`video_label`] says it -- so the
2448 /// name a running export shows is the name the card showed, or the honest
2449 /// difference where the probe and the open disagreed.
2450 fn label(&self) -> &'static str {
2451 match self {
2452 Self::Hw(_) => video_label(Format::Mp4, true),
2453 Self::Sw { .. } => video_label(Format::Mp4, false),
2454 Self::Av1Hw(_) => video_label(Format::Av1, true),
2455 Self::Av1Sw { .. } => video_label(Format::Av1, false),
2456 Self::Hevc(_) => video_label(Format::Hevc, false),
2457 }
2458 }
2459
2460 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
2461 // Which *codec* the picture is, not which container it goes in: both AV1
2462 // formats run the same encoder, and so do both HEVC ones.
2463 if settings.format.is_av1() {
2464 return Self::open_av1(meta, settings);
2465 }
2466 if settings.format.is_hevc() {
2467 return Self::open_hevc(meta, settings);
2468 }
2469 // A caller's number goes through the same clamp as the computed one: a
2470 // zero bitrate switches the software encoder's lookahead on, which would
2471 // break the one-picture-per-call contract `encode` documents below.
2472 let bitrate = bitrate_of(meta, settings);
2473 // The plugin wants an exact rational, and the muxer already picks one
2474 // that is exact at every rate we can read -- `fps * 1000 / 1000` would
2475 // hand 24000/1001 over as a rounded 23.976, which is the same
2476 // truncation the container timing had.
2477 crate::mux::frame_timing(meta.frame_rate)?;
2478 if let Some(hw) = hw_seat(meta, settings) {
2479 eprintln!("export encoder: hardware (VA-API plugin)");
2480 return Ok(Self::Hw(hw));
2481 }
2482 eprintln!("export encoder: software (rusty_h264)");
2483 let mut cfg = EncoderConfig::new(meta.width as usize, meta.height as usize);
2484 cfg.framerate = meta.frame_rate as f32;
2485 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;
2486 // Two seconds between key frames, and no B-frames on either path: the
2487 // muxer times everything by duration alone, which reordering would break.
2488 cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32;
2489 cfg.bframes = 0;
2490 // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same
2491 // bitrate, so Fast is what a fallback should be.
2492 cfg.preset = Preset::Fast;
2493 let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?;
2494 Ok(Self::Sw {
2495 encoder,
2496 au: Vec::new(),
2497 flushed: false,
2498 })
2499 }
2500
2501 /// The AV1 pair. The hardware seat is the plugin's, opened by a symbol of
2502 /// its own (`vh_enc_av1_open`) so a plugin built before AV1 encode existed
2503 /// simply has none and this falls through -- the same "no" a GPU without an
2504 /// AV1 encode entrypoint gives, and the same silent fallback either way.
2505 ///
2506 /// It is **opt-in**, which is the one place this pair does not mirror the
2507 /// H.264 one: the vendored cros-codecs AV1 encoder hung the GPU on this
2508 /// project's own radeonsi box -- `engine_hw: operation failed`, then an
2509 /// amdgpu hard recovery and a lost context, measured 2026-08-10 exporting
2510 /// the 720p fixture. A software encoder that takes half a minute is a worse
2511 /// export than a hardware one; a driver reset is not an export at all. So
2512 /// the plugin's AV1 seat is wired, kept and only entered when `VE_HW_AV1=1`
2513 /// asks for it by name.
2514 ///
2515 /// ponytail: the upgrade path is a driver this was reproduced against (or a
2516 /// cros-codecs release that fixes it) plus a probe encode of one frame at
2517 /// open, after which this can prefer hardware the way H.264 does.
2518 fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
2519 let bitrate = bitrate_of(meta, settings);
2520 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
2521 // Two seconds between keyframes, as the H.264 seat does: a seek may only
2522 // land on one, and this is what a cluster of the Matroska file is.
2523 let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64;
2524 if let Some(hw) = hw_seat(meta, settings) {
2525 eprintln!("export encoder: hardware AV1 (VA-API plugin)");
2526 return Ok(Self::Av1Hw(hw));
2527 }
2528 eprintln!("export encoder: software AV1 (rav1e)");
2529 let mut cfg = rav1e::EncoderConfig::default();
2530 cfg.width = meta.width as usize;
2531 cfg.height = meta.height as usize;
2532 cfg.bit_depth = 8;
2533 cfg.chroma_sampling = rav1e::prelude::ChromaSampling::Cs420;
2534 // Seconds per frame, which is what `frame_timing` already has as an
2535 // exact rational -- 1001/24000 rather than a rounded 23.976.
2536 cfg.time_base = rav1e::prelude::Rational::new(u64::from(fps_den), u64::from(fps_num));
2537 cfg.min_key_frame_interval = gop;
2538 cfg.max_key_frame_interval = gop;
2539 cfg.bitrate = bitrate.min(i32::MAX as u64) as i32;
2540 // The fastest preset there is, and it is still slow: `rav1e` is built
2541 // here without its assembly (no `nasm` in this project's build), so an
2542 // export runs at a fraction of realtime. The export worker reports
2543 // progress the whole way, which is what makes that bearable rather than
2544 // hidden.
2545 cfg.speed_settings = rav1e::prelude::SpeedSettings::from_preset(AV1_SPEED);
2546 // What the sequence header says the samples mean, for the reason
2547 // [`video_signal_type`] gives: a container tag is the second answer a
2548 // decoder looks at, not the first. Written as rav1e's own enums rather
2549 // than the H.273 numbers -- the crate has no `from` for the code points,
2550 // and the output rule only ever picks one of these two spaces.
2551 let out = ColorDescription::output(meta.height);
2552 cfg.pixel_range = rav1e::prelude::PixelRange::Limited;
2553 cfg.color_description = Some(match out.matrix {
2554 Matrix::Bt709 => rav1e::prelude::ColorDescription {
2555 color_primaries: rav1e::prelude::ColorPrimaries::BT709,
2556 transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT709,
2557 matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT709,
2558 },
2559 _ => rav1e::prelude::ColorDescription {
2560 color_primaries: rav1e::prelude::ColorPrimaries::BT601,
2561 transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT601,
2562 matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT601,
2563 },
2564 });
2565 let config = rav1e::Config::new()
2566 .with_encoder_config(cfg)
2567 .with_threads(std::thread::available_parallelism().map_or(1, |n| n.get()));
2568 let context = config
2569 .new_context::<u8>()
2570 .map_err(|e| format!("software AV1 encoder: {e}"))?;
2571 Ok(Self::Av1Sw {
2572 context,
2573 ready: std::collections::VecDeque::new(),
2574 au: Vec::new(),
2575 flushed: false,
2576 })
2577 }
2578
2579 /// The intra HEVC seat, software and frame-parallel. There is no hardware
2580 /// half: the plugin encodes H.264 and AV1 and nothing else, which
2581 /// [`hw_seat`] says by refusing to probe one.
2582 ///
2583 /// **Intra-only, deliberately.** The vendored encoder's inter modes code
2584 /// 1080p at 0.81 fps across 12 cores (measured 2026-08-11) -- a minute of
2585 /// timeline in half an hour, which is not an export anybody waits for --
2586 /// while the intra path does 4.30 fps on the same picture and the same
2587 /// cores. So every frame is an IDR, the file is an intraframe master in the
2588 /// shape of ProRes or DNxHD, and the card says so where a user picks it.
2589 ///
2590 /// The picture is coded **padded** to the 16-sample CTB grid and the SPS
2591 /// crops it back ([`pad_to_ctb`], the vendored conformance-window patch), so
2592 /// 1920x1080 is a legal export rather than a refusal.
2593 fn open_hevc(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
2594 // The muxers time by it and the mp4 one wants an exact rational: asked
2595 // here so an impossible rate fails before a frame is coded.
2596 crate::mux::frame_timing(meta.frame_rate)?;
2597 // 4:2:0 addresses its conformance window in *chroma* samples, so an odd
2598 // picture cannot be cropped back to itself -- and an odd dimension has
2599 // no chroma plane of its own to begin with. Named rather than padded to
2600 // something a decoder would then show a column of.
2601 if meta.width % 2 != 0 || meta.height % 2 != 0 {
2602 return Err(format!(
2603 "{}x{} cannot be written as HEVC: 4:2:0 needs even dimensions",
2604 meta.width, meta.height
2605 )
2606 .into());
2607 }
2608 let (width, height) = (
2609 (meta.width as usize).next_multiple_of(CTB),
2610 (meta.height as usize).next_multiple_of(CTB),
2611 );
2612 let lanes = std::thread::available_parallelism().map_or(1, |n| n.get());
2613 eprintln!("export encoder: software HEVC intra (oxideav-h265)");
2614 Ok(Self::Hevc(HevcEnc {
2615 pending: Vec::new(),
2616 ready: std::collections::VecDeque::new(),
2617 au: Vec::new(),
2618 width,
2619 height,
2620 crop: (width - meta.width as usize, height - meta.height as usize),
2621 qp: hevc_qp(meta, settings),
2622 lanes: lanes.min(HEVC_LANES),
2623 signal: video_signal_type(meta.height),
2624 }))
2625 }
2626
2627 /// One picture in, at most one access unit out, and whether that unit is one
2628 /// a decoder may be started from -- which only the Matroska muxer asks, the
2629 /// mp4 one reading its own sync flag off the IDR slice.
2630 ///
2631 /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer
2632 /// when its lookahead is active, which would make this "one access unit"
2633 /// a lie and every sample duration with it. It is inactive here because
2634 /// lookahead needs a zero bitrate and this path is always CBR; a future
2635 /// constant-QP mode has to split the buffer per access unit first.
2636 fn encode(
2637 &mut self,
2638 y: &[u8],
2639 u: &[u8],
2640 v: &[u8],
2641 width: u32,
2642 height: u32,
2643 ) -> crate::Result<Option<(&[u8], bool)>> {
2644 match self {
2645 Self::Av1Hw(hw) => {
2646 let au = hw.encode(y, u, v, width, height, false)?;
2647 // What the *bitstream* says, not what was asked for: an AV1
2648 // keyframe carries the sequence header, which is the same mark
2649 // `demux` reads a sync point off. A driver that emitted one
2650 // unasked is then still a seek target, and one that skipped a
2651 // requested keyframe cannot be mistaken for a decoder's start.
2652 Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
2653 }
2654 Self::Av1Sw {
2655 context, ready, au, ..
2656 } => {
2657 let mut frame = context.new_frame();
2658 let (w, h) = (width as usize, height as usize);
2659 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
2660 frame.planes[0].copy_from_raw_u8(&y[..w * h], w, 1);
2661 frame.planes[1].copy_from_raw_u8(&u[..cw * ch], cw, 1);
2662 frame.planes[2].copy_from_raw_u8(&v[..cw * ch], cw, 1);
2663 if let Err(e) = context.send_frame(frame) {
2664 return Err(format!("software AV1 encode: {e}").into());
2665 }
2666 collect_av1(context, ready)?;
2667 Ok(pop_av1(ready, au))
2668 }
2669 Self::Hevc(hevc) => {
2670 hevc.pending.push(pad_to_ctb(
2671 y,
2672 u,
2673 v,
2674 width as usize,
2675 height as usize,
2676 hevc.width,
2677 hevc.height,
2678 ));
2679 if hevc.pending.len() >= hevc.lanes {
2680 hevc.code_batch()?;
2681 }
2682 // Every intra AU is an IDR, so every one of them is a key
2683 // frame -- which is what an intraframe master means.
2684 Ok(pop_hevc(hevc))
2685 }
2686 Self::Hw(hw) => Ok(hw
2687 .encode(y, u, v, width, height, false)?
2688 .map(|au| (au, false))),
2689 Self::Sw { encoder, au, .. } => {
2690 let frame = YuvFrame {
2691 width: width as usize,
2692 height: height as usize,
2693 y: y.to_vec(),
2694 u: u.to_vec(),
2695 v: v.to_vec(),
2696 };
2697 *au = encoder
2698 .try_encode(&frame)
2699 .map_err(|e| format!("software encode: {e}"))?;
2700 Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty()))
2701 }
2702 }
2703 }
2704
2705 /// End of stream; call until it returns `None`.
2706 fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> {
2707 match self {
2708 Self::Av1Hw(hw) => {
2709 let au = hw.drain()?;
2710 Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
2711 }
2712 Self::Av1Sw {
2713 context,
2714 ready,
2715 au,
2716 flushed,
2717 } => {
2718 if !*flushed {
2719 *flushed = true;
2720 context.flush();
2721 collect_av1(context, ready)?;
2722 }
2723 Ok(pop_av1(ready, au))
2724 }
2725 Self::Hevc(hevc) => {
2726 // The tail batch: fewer frames than lanes, coded on as many
2727 // cores as there are frames left.
2728 if !hevc.pending.is_empty() {
2729 hevc.code_batch()?;
2730 }
2731 Ok(pop_hevc(hevc))
2732 }
2733 Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))),
2734 Self::Sw {
2735 encoder,
2736 au,
2737 flushed,
2738 } => {
2739 if *flushed {
2740 return Ok(None);
2741 }
2742 *flushed = true;
2743 *au = encoder
2744 .try_flush()
2745 .map_err(|e| format!("software encoder flush: {e}"))?;
2746 Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty()))
2747 }
2748 }
2749 }
2750}
2751
2752impl HevcEnc {
2753 /// The whole pending batch, one frame per lane, collected back in the order
2754 /// it went out -- `std::thread::scope`, because the encode borrows the
2755 /// planes rather than copying them again. A panic inside a lane comes back
2756 /// as an error rather than unwinding the export thread.
2757 fn code_batch(&mut self) -> crate::Result<()> {
2758 let (width, height, qp, crop) = (self.width, self.height, self.qp, self.crop);
2759 let signal = self.signal;
2760 let coded: Vec<crate::Result<Vec<u8>>> = std::thread::scope(|scope| {
2761 let lanes: Vec<_> = self
2762 .pending
2763 .iter()
2764 .map(|(y, cb, cr)| {
2765 scope.spawn(move || {
2766 oxideav_h265::encoder::intra::encode_idr_intra_au_cropped(
2767 y,
2768 cb,
2769 cr,
2770 width,
2771 height,
2772 qp,
2773 crop.0,
2774 crop.1,
2775 Some(signal),
2776 )
2777 .map(|coded| coded.au)
2778 .map_err(|e| crate::Error::from(format!("HEVC intra encode: {e:?}")))
2779 })
2780 })
2781 .collect();
2782 lanes
2783 .into_iter()
2784 .map(|lane| {
2785 lane.join()
2786 .unwrap_or_else(|_| Err("an HEVC encode lane panicked".into()))
2787 })
2788 .collect()
2789 });
2790 for au in coded {
2791 self.ready.push_back(au?);
2792 }
2793 self.pending.clear();
2794 Ok(())
2795 }
2796}
2797
2798/// The oldest coded intra AU, lent out under the same "valid until the next
2799/// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key flag
2800/// is not a guess.
2801fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> {
2802 hevc.au = hevc.ready.pop_front()?;
2803 Some((&hevc.au[..], true))
2804}
2805
2806/// One I420 picture copied onto the padded plane sizes the CTB grid needs, the
2807/// added rows and columns filled by **replicating the edge** rather than with
2808/// black: the padding is coded and then cropped away, and a black border would
2809/// bleed into the last real column through the intra prediction and the
2810/// transform that straddles it.
2811fn pad_to_ctb(
2812 y: &[u8],
2813 u: &[u8],
2814 v: &[u8],
2815 width: usize,
2816 height: usize,
2817 padded_w: usize,
2818 padded_h: usize,
2819) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2820 let plane = |src: &[u8], w: usize, h: usize, pw: usize, ph: usize| {
2821 let mut out = vec![0u8; pw * ph];
2822 for row in 0..ph {
2823 let src_row = &src[row.min(h - 1) * w..][..w];
2824 let dst = &mut out[row * pw..][..pw];
2825 dst[..w].copy_from_slice(src_row);
2826 dst[w..].fill(src_row[w - 1]);
2827 }
2828 out
2829 };
2830 (
2831 plane(y, width, height, padded_w, padded_h),
2832 plane(u, width / 2, height / 2, padded_w / 2, padded_h / 2),
2833 plane(v, width / 2, height / 2, padded_w / 2, padded_h / 2),
2834 )
2835}
2836
2837/// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a
2838/// user picked -- the card has no QP control and this codec has no rate control,
2839/// so the two are joined by measurement rather than promised to each other.
2840///
2841/// The encoder codes ~0.6 bits per pixel at QP 27 ([`HEVC_BPP_AT_27`], measured
2842/// on the 720p and 1080p benches to within 4% of each other), and a step of 6 QP
2843/// is a factor of two in rate, which is the classic HEVC relation. So the QP
2844/// that would land on a target is `27 + 6 * log2(0.6 / target)` -- and it is
2845/// clamped, because this is a *quality* dial and not a rate controller: below QP
2846/// 22 the file grows without a picture to show for it, and past QP 40 an
2847/// intra-only frame goes blocky in a way no bitrate row asked for. A 1080p30
2848/// timeline at the automatic 6.2 Mbps therefore codes at QP 40 and comes out
2849/// bigger than that, which is what "intra-only, large files" on the format row
2850/// means: the row buys quality, not a size.
2851fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 {
2852 let pixels = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate;
2853 let target = bitrate_of(meta, settings) as f64 / pixels.max(1.0);
2854 let qp = 27.0 + 6.0 * (HEVC_BPP_AT_27 / target.max(f64::MIN_POSITIVE)).log2();
2855 (qp.round() as i32).clamp(HEVC_QP_MIN, HEVC_QP_MAX)
2856}
2857
2858/// What the *bitstream* says the samples mean, in the words a sequence header
2859/// spells them -- the same H.273 code points [`crate::mux`] writes into the
2860/// container, from the same [`ColorDescription::output`] rule, so the two halves
2861/// of a file cannot drift apart.
2862///
2863/// This exists because a container tag is not enough: libavcodec takes the
2864/// bitstream's answer first, and a stream that says nothing is "unspecified",
2865/// which renders BT.601 -- a visible shift on a 709 export that a player reads
2866/// from the wrong matrix. Every export is limited range, which is what
2867/// `video_full_range_flag = false` says here.
2868fn video_signal_type(height: u32) -> oxideav_h265::vui::VideoSignalType {
2869 let (primaries, transfer, matrix) = ColorDescription::output(height).codes();
2870 oxideav_h265::vui::VideoSignalType {
2871 // "Unspecified", which is what every encoder here writes: the field is
2872 // the analogue system a picture came off, and none of these did.
2873 video_format: 5,
2874 video_full_range_flag: false,
2875 colour_description: Some(oxideav_h265::vui::ColourDescription {
2876 colour_primaries: primaries as u8,
2877 transfer_characteristics: transfer as u8,
2878 matrix_coeffs: matrix as u8,
2879 }),
2880 }
2881}
2882
2883/// Every temporal unit `rav1e` has finished, moved into the queue in display
2884/// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is
2885/// through) are the two ways it says there is nothing more; `Encoded` means a
2886/// picture was coded but not yet packetised, which is a *keep asking* -- taking
2887/// it for an end leaves the tail of the export inside the encoder.
2888fn collect_av1(
2889 context: &mut rav1e::Context<u8>,
2890 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
2891) -> crate::Result<()> {
2892 use rav1e::prelude::{EncoderStatus, FrameType};
2893 loop {
2894 match context.receive_packet() {
2895 Ok(packet) => ready.push_back((packet.data, packet.frame_type == FrameType::KEY)),
2896 Err(EncoderStatus::Encoded) => {}
2897 Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()),
2898 Err(e) => return Err(format!("software AV1 encode: {e}").into()),
2899 }
2900 }
2901}
2902
2903/// The oldest finished unit, moved into the buffer that is lent out -- the same
2904/// "valid until the next call" contract the plugin's slice has.
2905fn pop_av1<'a>(
2906 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
2907 au: &'a mut Vec<u8>,
2908) -> Option<(&'a [u8], bool)> {
2909 let (unit, key) = ready.pop_front()?;
2910 *au = unit;
2911 Some((&au[..], key))
2912}
2913
2914/// I420 straight out of the decoder: the export never converts to BGRA and back,
2915/// which would cost two conversions and a generation of colour precision.
2916///
2917/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`,
2918/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to
2919/// software: a hardware decode that fails after the first picture fails the
2920/// export, which then deletes the half-written file.
2921enum ClipDecoder {
2922 Hw(HwSession),
2923 Sw(SwDecoder),
2924 /// A still image: one picture, handed out for as long as the span runs.
2925 /// It is decoded here rather than in `run`'s loop for the same reason the
2926 /// other two are opened there -- the span's pictures come from one place.
2927 Still(crate::decode::Still),
2928}
2929
2930impl ClipDecoder {
2931 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
2932 // Before either decoder: an image is not a stream, so `start_frame`
2933 // means nothing to it -- every frame of a still span is the same
2934 // picture, which is what playback shows for it too.
2935 if crate::is_image(path) {
2936 return Ok(Self::Still(crate::decode::Still::open(path)?));
2937 }
2938 if !forced("VE_SW")
2939 && let Some(hw) = HwSession::open_at(path, start_frame)
2940 {
2941 return Ok(Self::Hw(hw));
2942 }
2943 Ok(Self::Sw(SwDecoder::open(path, start_frame)?))
2944 }
2945
2946 /// The next picture as tightly packed I420, borrowed until the call after.
2947 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
2948 match self {
2949 Self::Still(still) => Ok(Some(still.picture())),
2950 Self::Hw(hw) => hw.next_frame(),
2951 Self::Sw(sw) => {
2952 if !sw.advance()? {
2953 return Ok(None);
2954 }
2955 let frame = sw.frame.as_ref().expect("advance stored a picture");
2956 Ok(Some((
2957 &frame.y,
2958 &frame.u,
2959 &frame.v,
2960 frame.width as u32,
2961 frame.height as u32,
2962 )))
2963 }
2964 }
2965 }
2966}
2967
2968struct SwDecoder {
2969 demuxer: Demuxer,
2970 decoder: Decoder,
2971 /// Display index of the next picture the decoder will produce. Signed: a
2972 /// sync sample inside what the edit list trims is before frame 0.
2973 index: i64,
2974 start: u32,
2975 frame: Option<YuvFrame>,
2976}
2977
2978impl SwDecoder {
2979 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
2980 let (meta, mut demuxer) = Demuxer::open(path)?;
2981 // The software decoder is H.264-only; an HEVC or VP9 source that got
2982 // this far means the plugin refused it, and the export says so instead
2983 // of handing those bytes to `rusty_h264`.
2984 if meta.codec != crate::demux::Codec::H264 {
2985 return Err(meta.codec.needs_plugin().into());
2986 }
2987 // Decoding restarts at a sync sample, so pictures between it and the in
2988 // point are decoded (the target references them) and then dropped.
2989 let index = demuxer.seek_to_sync_at_or_before(start_frame);
2990 Ok(Self {
2991 demuxer,
2992 decoder: Decoder::new(),
2993 index,
2994 start: start_frame,
2995 frame: None,
2996 })
2997 }
2998
2999 /// Decodes up to and including the next picture at or after the in point,
3000 /// leaving it in `frame`. `false` at end of stream.
3001 fn advance(&mut self) -> crate::Result<bool> {
3002 loop {
3003 let Some(au) = self.demuxer.next_access_unit()? else {
3004 return Ok(false);
3005 };
3006 let decoded = self
3007 .decoder
3008 .decode(&au)
3009 .map_err(|e| format!("decode at picture {}: {e}", self.index))?;
3010 let Some(yuv) = decoded else { continue };
3011 let wanted = self.index >= i64::from(self.start);
3012 self.index += 1;
3013 if wanted {
3014 self.frame = Some(yuv);
3015 return Ok(true);
3016 }
3017 }
3018 }
3019}
3020
3021#[cfg(test)]
3022mod tests {
3023 use super::*;
3024
3025 /// Three seconds of two tones, one per channel, interleaved: enough shape
3026 /// that a correlation says something and enough length that the encoder
3027 /// settles into a mode.
3028 fn two_tones(secs: usize) -> Vec<f32> {
3029 (0..OPUS_RATE as usize * secs)
3030 .flat_map(|i| {
3031 let t = i as f32 / OPUS_RATE as f32;
3032 let tau = std::f32::consts::TAU;
3033 [
3034 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin(),
3035 0.25 * (tau * 880.0 * t).sin(),
3036 ]
3037 })
3038 .collect()
3039 }
3040
3041 /// The best correlation of one channel of `got` against `want`, and the
3042 /// offset it sat at.
3043 fn align(want: &[f32], got: &[f32]) -> (f64, usize) {
3044 let (mut best, mut at) = (-2.0, 0);
3045 let window = OPUS_RATE as usize;
3046 for lag in 0..1400 {
3047 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
3048 for (x, y) in want[..window]
3049 .iter()
3050 .step_by(2)
3051 .zip(got[lag * 2..].iter().step_by(2))
3052 {
3053 num += f64::from(*x) * f64::from(*y);
3054 da += f64::from(*x) * f64::from(*x);
3055 db += f64::from(*y) * f64::from(*y);
3056 }
3057 let c = num / (da.sqrt() * db.sqrt()).max(1e-12);
3058 if c > best {
3059 (best, at) = (c, lag);
3060 }
3061 }
3062 (best, at)
3063 }
3064
3065 fn ruopus_decode(packets: &[crate::AacPacket]) -> Vec<f32> {
3066 let mut decoder = ruopus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);
3067 let mut pcm = Vec::new();
3068 for packet in packets {
3069 pcm.extend(
3070 decoder
3071 .decode_packet(&packet.bytes)
3072 .expect("a valid packet"),
3073 );
3074 }
3075 pcm
3076 }
3077
3078 /// Why [`OPUS_MAX_KBPS`] is a cap, why [`OPUS_PRE_SKIP`] is a constant and
3079 /// why [`opus_fidelity`] exists at all -- all three measured here against
3080 /// `ruopus`, the decoder this project reads every Opus file back with, and
3081 /// which matches ffmpeg's libopus decode of a libopus file to correlation
3082 /// 1.00000 on this very signal.
3083 ///
3084 /// The last third **asserts the bug**: at 256 kbps stereo `opus-rs 0.1.26`
3085 /// writes packets that only its own decoder reads back, and pinning that
3086 /// here is what makes a version bump that fixes it *fail* -- which is the
3087 /// signal to raise the cap rather than a reason to widen it quietly.
3088 #[test]
3089 fn the_opus_encoder_is_pinned_to_the_band_it_was_measured_in() {
3090 let pcm = two_tones(3);
3091 for kbps in [96, OPUS_MAX_KBPS] {
3092 let (packets, pre_skip) = encode_opus(&pcm, kbps)
3093 .expect("the encoder opens")
3094 .expect("and inside the band it passes its own round trip");
3095 assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16);
3096 assert_eq!(
3097 packets.len(),
3098 pcm.len().div_ceil(OPUS_FRAME * 2) + 2,
3099 "one packet per 20 ms frame, plus the warm-up and the flush"
3100 );
3101 let decoded = ruopus_decode(&packets);
3102 let (c, lag) = align(&pcm, &decoded);
3103 // From the first audible sample, head included -- and the head is
3104 // why this is 0.98 and not the 0.999 below: the encoder's first
3105 // audible 20 ms still comes out about 6 dB down whatever is fed in
3106 // ahead of it (a second warm-up frame changes the numbers here in
3107 // no decimal place), so that ramp is a property of `opus-rs 0.1.26`
3108 // and is stated rather than hidden behind a loose threshold.
3109 assert!(c >= 0.98, "{kbps} kbps came back at correlation {c:.4}");
3110 let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..]);
3111 assert!(
3112 settled >= 0.999,
3113 "{kbps} kbps past the first frame: correlation {settled:.4}"
3114 );
3115 // The whole point of the number in the header: drop exactly that
3116 // many samples and the sound starts where the timeline says. A lag
3117 // that is not it is a file that plays late or eats its own head.
3118 assert_eq!(
3119 lag,
3120 usize::from(pre_skip),
3121 "{kbps} kbps: the declared pre-skip is not where the sound starts"
3122 );
3123 // ...and the tail is all there: the flush frame pushed the last
3124 // samples out, so what is left after the pre-skip covers the input.
3125 assert!(
3126 decoded.len() - usize::from(pre_skip) * 2 >= pcm.len(),
3127 "{kbps} kbps: the track ends {} samples short of the timeline",
3128 (pcm.len() + usize::from(pre_skip) * 2 - decoded.len()) / 2
3129 );
3130 // The gate the export runs before it writes anything, on a track
3131 // that deserves to pass it.
3132 let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip));
3133 assert!(
3134 fidelity >= OPUS_MIN_FIDELITY,
3135 "{kbps} kbps scored {fidelity:.4} on its own round trip"
3136 );
3137 }
3138
3139 // Above the band, straight at the crate, since `encode_opus` clamps: the
3140 // packets come back as noise, and the gate says so. This is the check
3141 // that the guard actually catches the failure it is built for -- and the
3142 // one that fails, loudly, the day `opus-rs` fixes it.
3143 let mut encoder =
3144 opus_rs::OpusEncoder::new(OPUS_RATE as i32, 2, opus_rs::Application::Audio).unwrap();
3145 encoder.bitrate_bps = 256_000;
3146 encoder.complexity = 10;
3147 let mut out = vec![0u8; 1500];
3148 let packets: Vec<crate::AacPacket> = pcm
3149 .chunks_exact(OPUS_FRAME * 2)
3150 .map(|block| {
3151 let len = encoder.encode(block, OPUS_FRAME, &mut out).unwrap();
3152 crate::AacPacket {
3153 bytes: out[..len].to_vec(),
3154 samples: OPUS_FRAME as u32,
3155 }
3156 })
3157 .collect();
3158 let fidelity = opus_fidelity(&packets, &pcm, usize::from(OPUS_PRE_SKIP));
3159 assert!(
3160 fidelity < OPUS_MIN_FIDELITY,
3161 "opus-rs now encodes 256 kbps stereo that a conformant decoder reads \
3162 back (fidelity {fidelity:.4}): raise OPUS_MAX_KBPS and delete this half"
3163 );
3164 }
3165
3166 /// The one rule that keeps a picture from being converted twice: a frame the
3167 /// tone map has already brought to BT.709 is never handed the 2020 matrix as
3168 /// well, on either canvas -- and everything else about the remap is
3169 /// unchanged by the tone map existing.
3170 #[test]
3171 fn a_tone_mapped_span_is_never_matrix_remapped_too() {
3172 let hdr = ColorDescription {
3173 matrix: Matrix::Bt2020Ncl,
3174 transfer: Transfer::Pq,
3175 full_range: false,
3176 };
3177 let sdr = ColorDescription::default(); // BT.601
3178 for out in [Matrix::Bt709, Matrix::Bt601] {
3179 let toned = remap_into(Some(hdr), true, out);
3180 assert!(
3181 toned.is_none_or(|(from, _)| from == Matrix::Bt709),
3182 "tone-mapped onto a {out:?} canvas asked for {toned:?}"
3183 );
3184 // Untouched by any of this: the 2020 clip that was *not* tone-mapped
3185 // (an unreachable state today, and still the matrix answer), the
3186 // ordinary 601-on-709 reconcile, and a gap.
3187 assert_eq!(
3188 remap_into(Some(hdr), false, out),
3189 (out != Matrix::Bt2020Ncl).then_some((Matrix::Bt2020Ncl, out))
3190 );
3191 assert_eq!(
3192 remap_into(Some(sdr), false, out),
3193 (out != Matrix::Bt601).then_some((Matrix::Bt601, out))
3194 );
3195 assert_eq!(remap_into(None, false, out), None);
3196 }
3197 assert_eq!(
3198 remap_into(Some(hdr), true, Matrix::Bt601),
3199 Some((Matrix::Bt709, Matrix::Bt601)),
3200 "a tone-mapped clip below 720 lines still takes its 709 -> 601 step"
3201 );
3202 }
3203
3204 /// A track of three cues, in whichever clock `track` says: `Some(n)` is a
3205 /// track of the media file, `None` a `.srt` beside it.
3206 fn subtitles(path: &str, track: Option<u64>) -> SubtitleTrack {
3207 SubtitleTrack {
3208 path: path.into(),
3209 track,
3210 language: "eng".into(),
3211 name: String::new(),
3212 label: "eng".into(),
3213 bitmap: false,
3214 cues: vec![
3215 Cue {
3216 start_us: 500_000,
3217 end_us: 1_500_000,
3218 text: "first".into(),
3219 image: None,
3220 },
3221 Cue {
3222 start_us: 2_000_000,
3223 end_us: 3_250_000,
3224 text: "second".into(),
3225 image: None,
3226 },
3227 Cue {
3228 start_us: 4_000_000,
3229 end_us: 4_750_000,
3230 text: "third".into(),
3231 image: None,
3232 },
3233 ],
3234 refused: None,
3235 }
3236 }
3237
3238 /// A standalone subtitle file is timed against the timeline itself -- there
3239 /// is no clip to hang it on -- so a cut moves the pictures and not it. What
3240 /// it does get is the exported length: a cue past the end of the file would
3241 /// otherwise be a block after the last picture.
3242 ///
3243 /// The pair of this, the embedded clock, is measured against a real exported
3244 /// file in `tests/export_subs.rs`; both live in one function and this is the
3245 /// half that needs no encoder.
3246 #[test]
3247 fn a_subtitle_file_beside_the_media_keeps_the_timelines_own_clock() {
3248 // 5 seconds at 30, with `[0.5s, 2.5s)` cut out of it: 3 seconds left.
3249 let mut project = Project::single("/nonexistent/film.mp4", 150);
3250 let track = subtitles("/nonexistent/film.srt", None);
3251 assert!(project.ripple_delete(15, 60));
3252 assert_eq!(project.timeline_frames(), 90);
3253 let cues = timeline_cues(&project, &track, 30.0);
3254 assert_eq!(
3255 cues,
3256 vec![
3257 Cue {
3258 start_us: 500_000,
3259 end_us: 1_500_000,
3260 text: "first".into(),
3261 image: None,
3262 },
3263 // Clipped to the three seconds the export writes...
3264 Cue {
3265 start_us: 2_000_000,
3266 end_us: 3_000_000,
3267 text: "second".into(),
3268 image: None,
3269 },
3270 // ...and the one wholly past the end is not written at all.
3271 ]
3272 );
3273 // A track *of a file* the project no longer plays has no span to be
3274 // carried through either, so it falls back to the same clock rather
3275 // than exporting nothing.
3276 let orphan = subtitles("/nonexistent/other.mkv", Some(2));
3277 assert_eq!(timeline_cues(&project, &orphan, 30.0).len(), 2);
3278 }
3279
3280 /// The embedded clock, without an encoder in it: the cut moves the cues with
3281 /// the pictures, and a cue nothing clipped keeps its own microseconds.
3282 #[test]
3283 fn a_track_of_the_media_is_carried_through_the_cut() {
3284 let mut project = Project::single("/nonexistent/film.mkv", 150);
3285 let track = subtitles("/nonexistent/film.mkv", Some(2));
3286 assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out");
3287 let cues = timeline_cues(&project, &track, 30.0);
3288 assert_eq!(
3289 cues,
3290 vec![
3291 // The first cue was wholly inside the cut. The second straddled
3292 // its far edge and kept the 0.75s that is still there...
3293 Cue {
3294 start_us: 500_000,
3295 end_us: 1_250_000,
3296 text: "second".into(),
3297 image: None,
3298 },
3299 // ...and the third simply moves back the two seconds that went.
3300 Cue {
3301 start_us: 2_000_000,
3302 end_us: 2_750_000,
3303 text: "third".into(),
3304 image: None,
3305 },
3306 ]
3307 );
3308 }
3309
3310 #[test]
3311 fn bitrate_clamps_at_both_ends() {
3312 let meta = |width, height, frame_rate| VideoMeta {
3313 width,
3314 height,
3315 frame_rate,
3316 frame_count: 1,
3317 codec: crate::demux::Codec::H264,
3318 color: Default::default(),
3319 };
3320 // 1280 * 720 * 30 * 0.1
3321 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
3322 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny");
3323 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
3324 }
3325
3326 fn meta(width: u32, height: u32) -> VideoMeta {
3327 VideoMeta {
3328 width,
3329 height,
3330 frame_rate: 30.0,
3331 frame_count: 1,
3332 codec: crate::demux::Codec::H264,
3333 color: Default::default(),
3334 }
3335 }
3336
3337 /// The bitrate row a user picked, read as the quality tier it is: a higher
3338 /// row is a lower QP, the band is honoured at both ends, and the same
3339 /// picture at the same rate gets the same number whatever its size (the
3340 /// mapping is bits per *pixel*, which is what makes 720p and 1080p one
3341 /// table).
3342 #[test]
3343 fn the_quality_rows_map_onto_quantisers_that_only_go_one_way() {
3344 let at = |width, height, mbps: Option<u64>| {
3345 hevc_qp(
3346 &meta(width, height),
3347 &ExportSettings {
3348 bitrate: mbps.map(|m| m * 1_000_000),
3349 ..Default::default()
3350 },
3351 )
3352 };
3353 // 20 Mbps at 1080p30 is 0.32 bits a pixel against the 0.6 measured at
3354 // QP 27, which is just over half: five QP up, and QP is not an
3355 // arithmetic scale, so this is the number the formula gives.
3356 assert_eq!(at(1920, 1080, Some(20)), 32);
3357 // Every step down the card is a step up in QP, never sideways.
3358 let rows: Vec<i32> = [20, 12, 8, 4, 2, 1]
3359 .into_iter()
3360 .map(|mbps| at(1920, 1080, Some(mbps)))
3361 .collect();
3362 assert!(
3363 rows.windows(2).all(|w| w[0] <= w[1]),
3364 "a lower bitrate row must never code at a lower QP: {rows:?}"
3365 );
3366 assert_eq!(*rows.last().unwrap(), HEVC_QP_MAX, "the floor is clamped");
3367 // ...and the top of the range is the clamp, not an unbounded number: 20
3368 // Mbps at 320x240 is 8.7 bits a pixel, which no picture needs.
3369 assert_eq!(at(320, 240, Some(20)), HEVC_QP_MIN);
3370 // The same bits per pixel is the same quantiser at any size: 1080p at
3371 // 20 Mbps and 720p at 8.9 Mbps are one picture quality.
3372 assert_eq!(at(1920, 1080, Some(20)), at(1280, 720, Some(9)));
3373 // The automatic bitrate is 0.1 bpp at every size, so it is one QP
3374 // everywhere -- the honest end of "intra-only, large files": the file
3375 // will be bigger than the row says, and the row buys quality.
3376 assert_eq!(at(1920, 1080, None), at(1280, 720, None));
3377 }
3378
3379 /// The padding a non-%16 picture is coded with replicates the edge instead
3380 /// of filling black: the coded rows past the picture carry its last row, so
3381 /// nothing bleeds into the last real line through the intra prediction.
3382 #[test]
3383 fn the_ctb_padding_replicates_the_edge() {
3384 // 6x2 luma, values 1..=12, padded to 8x4 (CTB is 16, so this checks the
3385 // copy itself with numbers small enough to read).
3386 let y: Vec<u8> = (1..=12).collect();
3387 let u: Vec<u8> = vec![40, 41, 42];
3388 let v: Vec<u8> = vec![50, 51, 52];
3389 let (py, pu, pv) = pad_to_ctb(&y, &u, &v, 6, 2, 8, 4);
3390 assert_eq!(
3391 py,
3392 vec![
3393 1, 2, 3, 4, 5, 6, 6, 6, // the row, then its last sample twice
3394 7, 8, 9, 10, 11, 12, 12, 12, //
3395 7, 8, 9, 10, 11, 12, 12, 12, // the last row, replicated
3396 7, 8, 9, 10, 11, 12, 12, 12,
3397 ]
3398 );
3399 // Chroma is half of everything, padded the same way.
3400 assert_eq!(pu, vec![40, 41, 42, 42, 40, 41, 42, 42]);
3401 assert_eq!(pv, vec![50, 51, 52, 52, 50, 51, 52, 52]);
3402 }
3403
3404 /// An odd picture cannot be cropped back to itself in 4:2:0 -- the
3405 /// conformance window is stated in chroma samples -- so it is refused by
3406 /// name rather than written a column wider than the timeline.
3407 #[test]
3408 fn an_odd_picture_is_refused_an_hevc_export_by_name() {
3409 let settings = ExportSettings {
3410 format: Format::Hevc,
3411 ..Default::default()
3412 };
3413 let refused = Enc::open(&meta(1919, 1080), &settings)
3414 .err()
3415 .expect("an odd width has no chroma plane")
3416 .to_string();
3417 assert!(refused.contains("1919x1080"), "{refused}");
3418 assert!(refused.contains("even"), "{refused}");
3419 // ...and the even one it neighbours opens.
3420 assert!(Enc::open(&meta(1920, 1080), &settings).is_ok());
3421 }
3422}