forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB65ea910Tahinli3 months ago308 commits

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