forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

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