forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB5530fbdTahinli3 months ago209 commits

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