forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa7dd4c5Tahinli3 months ago274 commits

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