forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB10cdebcTahinli3 months ago249 commits

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