forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbdcc2fbTahinli3 months ago176 commits

export.rs1415 lines, 61.8 KiBHistoryRawDownload
1//! Export: the edit list rendered back out as one mp4 or one AV1-in-Matroska —
2//! or, picture left behind, as one WAV or FLAC of the timeline's audio alone.
3//!
4//! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it
5//! is impossible — while audio is copied packet for packet wherever a copy can
6//! say what the timeline says: a copy is exact, free and never a generation of
7//! loss. Where it *cannot* — an equalized lane, which is sample math no packet
8//! copy can reach — that lane is decoded, mixed and encoded again with
9//! `rusty_aac` ([`encode_audio`]). The audio-only formats have no such split:
10//! `hound` writes PCM and `flacenc` encodes FLAC, so those are always *decoded*
11//! out of the timeline. The worker owns everything: the caller gets an
12//! [`ExportHandle`] and polls it from its render loop.
13//!
14//! A **speeded** clip splits along the same line, and for the same reason. The
15//! picture is re-encoded, so the frame walk honours a rate: it takes the source
16//! frame each timeline frame shows ([`crate::project::Speed::source_at`], the
17//! very frame preview holds there) and encodes a held one again rather than
18//! decoding it twice. The sound is *copied* unless a filter forces a decode, and
19//! a packet carries no rate -- so a speeded clip on the one audio lane an mp4
20//! copies is refused by name ([`copy_audio`]) rather than written out at 1.00x
21//! under a re-timed picture.
22//! AV1 carries no audio at all and never meets that refusal; WAV and FLAC are
23//! decoded and resampled, so they honour a rate like the picture does.
24//!
25//! Nothing partial survives a failure: the worker writes to `<out>.part` and
26//! renames it onto `out` only once the file is closed and complete, so the
27//! output either does not exist or is finished — there is no window where a
28//! half-written `.export.mp4` is sitting there looking playable. Cancel and
29//! every error path delete the `.part`. A killed *process* leaves the `.part`
30//! behind (only in-process cleanup is promised), which is an orphan a user can
31//! delete rather than a file that plays for two seconds and stops.
32
33use std::path::{Path, PathBuf};
34use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
35use std::sync::{Arc, Mutex};
36use std::thread;
37
38use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame};
39
40use flacenc::component::BitRepr;
41use flacenc::error::Verify;
42
43use crate::audio::{AudioMeta, AudioSession};
44use crate::demux::{Demuxer, VideoMeta};
45use crate::hw::{HwEncoder, HwSession};
46use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams};
47use crate::project::{LaneKind, Project};
48use crate::scale::Composer;
49
50/// Progress is reported in permille: an atomic integer the render loop can read
51/// without a lock, fine enough for any progress bar.
52const PROGRESS_SCALE: u32 = 1_000;
53
54/// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
55/// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%.
56const BITS_PER_PIXEL: f64 = 0.1;
57const MIN_BITRATE: u64 = 1_000_000;
58const MAX_BITRATE: u64 = 20_000_000;
59
60/// `rav1e`'s fastest preset. Anything slower is minutes per second of timeline
61/// on a build with no assembly, which is what this one is.
62const AV1_SPEED: u8 = 10;
63
64/// What an export writes. Four, not more: H.264-in-mp4 and AV1-in-Matroska are
65/// the only *video* pairs with both an encoder and a decoder under this
66/// project's no-install rule, and WAV and FLAC are the only *standalone* audio
67/// formats with a pure-Rust encoder at all. MP3 has one (`shine-rs`) under
68/// LGPL-2.0, which is a licensing decision this project has not taken; Vorbis
69/// and Opus have none. (AAC does -- `rusty_aac`, which is what an equalized mp4
70/// track is encoded with -- but AAC is an mp4's own audio, never a file of its
71/// own here.) HEVC and VP9 have no encoder here at all (`hevc`/`vp9` import
72/// through the plugin and stop there). A front-end says so rather than hiding
73/// the rows.
74#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
75pub enum Format {
76 /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too,
77 /// where a copy could not carry the edit (an equalized lane). Either way it
78 /// carries **one** audio lane: a timeline whose sound is spread over two is
79 /// refused by name here and mixed by the other two formats, which decode.
80 #[default]
81 Mp4,
82 /// Picture alone, AV1 in Matroska. Alone because Matroska carries no sound
83 /// this project can *write*: this engine's Matroska writer has no audio
84 /// track at all, and the copy path walks an mp4 sample table, which a
85 /// Matroska file has none of. (*Reading* one's AAC is a different question,
86 /// and since this engine gained a Matroska demuxer the answer is yes --
87 /// `audio::Track::open` does it through symphonia's mkv reader.) The sound
88 /// of an AV1 export is a WAV or FLAC beside it, which a front-end says up
89 /// front.
90 Av1,
91 /// The audio lane alone, 16-bit PCM.
92 Wav,
93 /// The audio lane alone, losslessly compressed.
94 Flac,
95}
96
97impl Format {
98 /// The extension a file of this format is named with -- a front-end builds
99 /// the destination path from it, so the name never disagrees with the bytes.
100 pub fn ext(self) -> &'static str {
101 match self {
102 Self::Mp4 => "mp4",
103 Self::Av1 => "mkv",
104 Self::Wav => "wav",
105 Self::Flac => "flac",
106 }
107 }
108
109 /// Whether this format carries the picture. The bitrate settings are video
110 /// settings and mean nothing to the audio two.
111 pub fn has_video(self) -> bool {
112 matches!(self, Self::Mp4 | Self::Av1)
113 }
114
115 /// What the format is called where a refusal names it.
116 pub fn name(self) -> &'static str {
117 match self {
118 Self::Mp4 => "an mp4",
119 Self::Av1 => "an AV1 export",
120 Self::Wav => "a WAV",
121 Self::Flac => "a FLAC",
122 }
123 }
124}
125
126/// What the caller gets to decide about the output. The codec is not among it:
127/// [`Format`] names a container *and* what goes in it, because every pair we
128/// can write is a pair we can also read back.
129#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
130pub struct ExportSettings {
131 /// Bits per second, clamped to the same sane range the automatic value uses.
132 /// `None` picks it from the picture size and frame rate. Video only.
133 pub bitrate: Option<u64>,
134 /// Skip the hardware encoder even where it is available -- an escape hatch
135 /// for a driver that encodes badly, matching the `VE_SW_ENC` env pin.
136 pub force_sw: bool,
137 /// The file to write. Defaults to [`Format::Mp4`], which is what every
138 /// caller wrote before there was a choice.
139 pub format: Format,
140}
141
142struct Shared {
143 progress: AtomicU32,
144 cancel: AtomicBool,
145 finished: AtomicBool,
146 outcome: Mutex<Option<crate::Result<()>>>,
147 /// The encoders this job really opened, published the moment they are
148 /// chosen and never changed after -- one seat for the whole file, which is
149 /// what [`Enc`] states. `None` until then.
150 encoders: Mutex<Option<String>>,
151}
152
153/// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
154/// rendered frame and take the [`result`](ExportHandle::result) when it flips;
155/// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel)
156/// does.
157pub struct ExportHandle {
158 shared: Arc<Shared>,
159}
160
161impl ExportHandle {
162 /// Fraction of the timeline written, `0.0..=1.0`.
163 pub fn progress(&self) -> f32 {
164 self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32
165 }
166
167 /// Asks the worker to stop at its next checkpoint and delete the partial
168 /// file. The outcome then reports the cancellation as an error. Checkpoints
169 /// run to the last instant before the rename, so even a cancel at full
170 /// progress leaves no output.
171 pub fn cancel(&self) {
172 self.shared.cancel.store(true, Ordering::Relaxed);
173 }
174
175 pub fn is_finished(&self) -> bool {
176 self.shared.finished.load(Ordering::Acquire)
177 }
178
179 /// What this export is encoding with -- the video seat and what the sound
180 /// is doing -- as the worker chose them, hardware fallback included.
181 /// `None` for the first instants of a job, before the encoder is open.
182 pub fn encoders(&self) -> Option<String> {
183 self.shared.encoders.lock().unwrap().clone()
184 }
185
186 /// The outcome, once — taken out of the handle, so a caller that already
187 /// reported it sees `None` afterwards. `None` while the export is running.
188 pub fn result(&self) -> Option<crate::Result<()>> {
189 self.shared.outcome.lock().unwrap().take()
190 }
191}
192
193/// Starts the worker. Failures are reported through the handle rather than
194/// returned, so a caller has exactly one place to look. The files to read are
195/// the project's own [`sources`](Project::sources) -- every clip names one --
196/// so nothing but the edit list decides what is decoded.
197pub fn start(
198 project: Project,
199 meta: VideoMeta,
200 out: &Path,
201 settings: &ExportSettings,
202) -> ExportHandle {
203 let settings = *settings;
204 let shared = Arc::new(Shared {
205 progress: AtomicU32::new(0),
206 cancel: AtomicBool::new(false),
207 finished: AtomicBool::new(false),
208 outcome: Mutex::new(None),
209 encoders: Mutex::new(None),
210 });
211 let worker = Arc::clone(&shared);
212 let out = out.to_path_buf();
213 // `<out>.part`, appended rather than substituted: the temporary of
214 // `a.export.mp4` is `a.export.mp4.part`, which no other export claims.
215 let mut part = out.clone().into_os_string();
216 part.push(".part");
217 let part = PathBuf::from(part);
218 let spawned = thread::Builder::new().name("export".into()).spawn(move || {
219 // The rename is the last step and the only one that publishes a file
220 // under the name the caller asked for; it stays on the same directory,
221 // so it is atomic.
222 //
223 // An emptied timeline is a legal project and an illegal file: no
224 // picture, no sound, and a muxer that is never created because no coded
225 // frame arrives. Refused by name here -- before the format is even
226 // looked at, so an mp4 and a WAV refuse in the same words -- rather than
227 // left to write a file of no frames that nothing opens. Every caller of
228 // `start` comes through this, the app's own door
229 // (`PlaybackSession::is_empty`) being only the first fence.
230 //
231 // An audio-only timeline is the other legal project no mp4 can be made
232 // of: every frame of it is a gap, so the file would be black picture
233 // over the sound -- minutes of encoding for a video of nothing. Refused
234 // by name, with the two formats that *are* that timeline, rather than
235 // written; the app says the same on the format row before a destination
236 // is even picked (`mp4_refusal`).
237 let written = match settings.format {
238 _ if project.timeline_frames() == 0 => {
239 Err("the timeline is empty: there is nothing to export".into())
240 }
241 format if format.has_video() && !has_picture(&project) => Err(format!(
242 "the timeline has no picture: {} would be black. Export WAV or \
243 FLAC, which are the sound itself",
244 format.name()
245 )
246 .into()),
247 Format::Mp4 | Format::Av1 => run(&project, &meta, &part, &worker, &settings),
248 format => run_audio(&project, &meta, &part, &worker, format),
249 };
250 let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
251 if result.is_err() {
252 // The muxer -- and with it the file handle -- died with `run`.
253 let _ = std::fs::remove_file(&part);
254 }
255 settle(&worker, result);
256 });
257 if let Err(e) = spawned {
258 settle(&shared, Err(e.into()));
259 }
260 ExportHandle { shared }
261}
262
263/// Whether any video lane holds anything at all -- what tells an audio-only
264/// timeline from one that merely opens on a gap. Asked of the *lanes* rather
265/// than of the sources, because a project may name a video file no clip plays
266/// from any more.
267fn has_picture(project: &Project) -> bool {
268 project
269 .lanes()
270 .into_iter()
271 .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty())
272}
273
274/// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a
275/// timeline whose export will carry sound from one whose file has none.
276fn has_sound(project: &Project) -> bool {
277 project
278 .lanes()
279 .into_iter()
280 .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty())
281}
282
283/// Whether any equalizer on the sound is doing something -- the one edit a
284/// packet copy cannot carry, so an mp4 whose lane has one is decoded and
285/// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane:
286/// the copy path has exactly one by the time it asks, and [`planned_audio`] is
287/// asked before that is settled.
288fn equalized(project: &Project) -> bool {
289 project.audio_lanes().into_iter().any(|lane| {
290 (0..project.lane(lane).len())
291 .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity()))
292 })
293}
294
295/// The bitrate an export codes at: the caller's number through the same clamp
296/// as the computed one, for the reason [`Enc::open`] states.
297fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 {
298 settings
299 .bitrate
300 .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE))
301}
302
303/// The hardware seat for these settings, opened exactly as the export opens it
304/// -- the same pins, the same AV1 opt-in, the same dimensions a driver may
305/// refuse -- or `None` where the software encoder takes the file. The single
306/// place that choice is made, which is what lets [`planned_video`] *measure* it
307/// instead of promising it.
308fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
309 if settings.force_sw || forced("VE_SW_ENC") {
310 return None;
311 }
312 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
313 let bitrate = bitrate_of(meta, settings);
314 match settings.format {
315 // Opt-in only, for the reason [`Enc::open_av1`] states in full.
316 Format::Av1 if !forced("VE_HW_AV1") => None,
317 Format::Av1 => HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate),
318 _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate),
319 }
320}
321
322/// How a front-end names a video seat: which of the two encoders has the file,
323/// and which library that is. Not the codec -- a caller shows this beside the
324/// format it picked, and `rav1e` names AV1 as `rusty_h264` names H.264. One
325/// place, so what a card says before an export and what its progress line says
326/// during one cannot drift apart.
327fn video_label(format: Format, hw: bool) -> &'static str {
328 match (format, hw) {
329 (Format::Av1, true) => "HW encode (VA-API)",
330 (Format::Av1, false) => "SW encode (rav1e)",
331 (_, true) => "HW encode (VA-API)",
332 (_, false) => "SW encode (rusty_h264)",
333 }
334}
335
336/// What the sound is written by. Every audio encoder here is software -- there
337/// is no hardware AAC, PCM or FLAC seat -- so this names *which* one, and
338/// whether an mp4 escapes encoding altogether by copying the packets it was
339/// given. Empty for AV1, which carries no audio at all: a caller joins this to
340/// a line that already says so, and repeating it would cost a line of card.
341fn audio_label(project: &Project, format: Format, sound: bool) -> &'static str {
342 match format {
343 Format::Av1 => "",
344 _ if !sound => "no sound to write",
345 Format::Mp4 if equalized(project) => "AAC · SW encode (rusty_aac)",
346 Format::Mp4 => "AAC copy",
347 Format::Wav => "PCM · SW (hound)",
348 Format::Flac => "FLAC · SW (flacenc)",
349 }
350}
351
352/// What [`start`] would write this timeline's sound with, before one is
353/// started. Pure: no probe and no file opened, so a card may ask it per repaint.
354pub fn planned_audio(project: &Project, format: Format) -> &'static str {
355 audio_label(project, format, has_sound(project))
356}
357
358/// What [`start`] would encode the picture with, probed the way the export
359/// probes it -- the very encoder is opened and closed again -- so this is a
360/// measurement and not a promise. `None` for a format that carries no picture.
361///
362/// Costs that open (~100 ms here): ask it off a render thread and keep the
363/// answer until the format, the resolution or the bitrate changes.
364pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> {
365 settings
366 .format
367 .has_video()
368 .then(|| video_label(settings.format, hw_seat(meta, settings).is_some()))
369}
370
371fn settle(shared: &Shared, result: crate::Result<()>) {
372 *shared.outcome.lock().unwrap() = Some(result);
373 // Published last: a caller that sees the flag is guaranteed the outcome.
374 shared.finished.store(true, Ordering::Release);
375}
376
377/// The timeline's one audio lane, copied packet for packet: the mp4 path's
378/// sound, and the reason that path carries only one lane of it. A lane an
379/// equalizer has been put on cannot be *copied* at all and leaves through
380/// [`encode_audio`] instead; every other timeline keeps this copy, bit for bit.
381///
382/// ponytail: this holds the whole exported AAC track in memory (~3 kB per
383/// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
384/// `copy_segments` that yields packets instead of collecting them.
385#[allow(clippy::type_complexity)]
386fn copy_audio(
387 project: &Project,
388 meta: &VideoMeta,
389) -> crate::Result<Option<(crate::AacTrackParams, Vec<crate::AacPacket>)>> {
390 // The segments name their source, and the copy carries its packet-rounding
391 // debt across a source join exactly as across a cut, so a timeline spanning
392 // files stays in sync. A source whose AAC parameters disagree with the
393 // first one is an `Err` from there -- import refuses those up front, this
394 // is the backstop -- and the caller deletes the `.part`.
395 //
396 // The stream each source is copied from is the one it plays: `audio_sources`
397 // is the same list `PlaybackSession::seek` hands the decoder, so an export
398 // of a timeline playing a file's second audio track carries *that* track.
399 //
400 // One lane, because this path *copies* AAC packets and a mix is not a copy:
401 // summing two lanes means decoding both, and only the one thing a copy
402 // cannot express at all -- an equalizer -- is decoded here today. Refused by
403 // name rather than silently exporting the first lane, which is a file
404 // missing half its sound: the one failure a user would not notice.
405 //
406 // ponytail: the ceiling is this routing, not the codec any more.
407 // [`encode_audio`] already mixes *every* audio lane (it is the WAV path's
408 // own opener), so lifting this refusal is routing a second case to it --
409 // deliberately not done here, where the change under test is the equalizer.
410 //
411 // *Which* lane is the same question `audio_segments_from` answers for
412 // playback, and it is asked here rather than assumed: the lane that holds
413 // the sound need not be `A1` (a project may leave `A1` empty and place
414 // everything on `A2`), and copying `A1`'s list in that case would write a
415 // file with no audio track at all -- silently, which is the failure this
416 // whole comment is about.
417 let lanes = project.audio_segments_from(0, meta.frame_rate);
418 let [segments] = &lanes[..] else {
419 return Err(format!(
420 "this timeline has {} audio lanes and an mp4 export copies one: \
421 export WAV or FLAC, which are mixed, or put the sound on one lane",
422 lanes.len()
423 )
424 .into());
425 };
426 // ...and the same list names *which* lane those clips sit on, which is the
427 // only way to ask what has been done to them.
428 let lane = project.audio_lanes()[0];
429 // ...and the same list decides whether any clip this would copy plays at a
430 // rate other than the one it was recorded at. A copy hands the mp4 the very
431 // AAC packets the source holds and there is no rate inside a packet to
432 // change: the picture would come out re-timed (the walk in [`run`] honours
433 // it) over sound at 1.00x, which is the drift a person finds only after the
434 // file has gone somewhere. Refused by name -- and only *here*, on the lane
435 // being copied: AV1 carries no audio at all and never reaches this, so it
436 // honours a speed like WAV and FLAC do.
437 //
438 // ponytail: the ceiling is the packet copy itself, not the rate, and the way
439 // off it is now next door -- [`encode_audio`] resamples exactly as the WAV
440 // path does, so routing a speeded lane there is the one line the equalizer
441 // below takes. Left refused because this change is the equalizer's, and a
442 // speeded export turning silently from a copy into a re-encode is a change
443 // of its own to make on purpose.
444 if let Some((at, speed)) = project
445 .lane(lane)
446 .iter()
447 .find(|c| !c.speed.is_normal())
448 .map(|c| (c.start, c.speed))
449 {
450 return Err(format!(
451 "the clip at {} plays at {speed} and an mp4 export copies AAC packets, which carry \
452 no rate: export WAV or FLAC, which are decoded and resampled, or set it back to 1.00x",
453 timecode(at, meta.frame_rate)
454 )
455 .into());
456 }
457 // ...and last, whether any clip on it carries an equalizer. An EQ is sample
458 // math and a copy never decodes, so copying such a lane would write the clip
459 // *flat*, silently -- the failure a missing audio track is. This lane is
460 // decoded, filtered, mixed and encoded again instead ([`encode_audio`]), and
461 // only this case is: a timeline nobody has equalized still leaves through
462 // the copy below, packet for packet, so no passthrough quietly becomes a
463 // generation of loss.
464 if equalized(project) {
465 return encode_audio(project, meta);
466 }
467 AudioSession::copy_multi_streams(&project.audio_sources(), segments)
468}
469
470/// The same lane, *decoded*: what a packet copy cannot carry comes out here as
471/// AAC written by this project's own encoder.
472///
473/// The samples are the very ones [`run_audio`] would put in a WAV -- the same
474/// opener with the same equalizers, the same rates and the same resize onto the
475/// timeline's own length -- so an mp4 and a WAV of one timeline are one mix,
476/// not two that could disagree.
477///
478/// AAC-LC's encoder delay is one 1024-frame block, which is exactly the priming
479/// a reader drops when the file carries no edit list (`audio::DEFAULT_PRIMING`,
480/// and [`crate::mux::Mp4Muxer`] writes none): the first packet is that delay, so
481/// the sound starts at timeline frame 0 as a copied track's does.
482///
483/// ponytail: the mix sits in memory as f32 before it is encoded (~46 MB a
484/// minute of 48 kHz stereo), for [`run_audio`]'s reason -- `rusty_aac` buffers
485/// the whole stream anyway, since it encodes its frames in parallel. Upgrade
486/// path is a chunked push once that encoder streams.
487#[allow(clippy::type_complexity)]
488fn encode_audio(
489 project: &Project,
490 meta: &VideoMeta,
491) -> crate::Result<Option<(crate::AacTrackParams, Vec<crate::AacPacket>)>> {
492 let sources = project.audio_sources();
493 let segs = project.audio_segments_from(0, meta.frame_rate);
494 let eqs = project.audio_eqs_from(0, meta.frame_rate);
495 let speeds = project.audio_speeds_from(0, meta.frame_rate);
496 let Some((audio, chunks)) =
497 AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds)?
498 else {
499 return Ok(None); // no audio to write, exactly as a copy of nothing is
500 };
501 let freq_index = rusty_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| {
502 format!(
503 "{} Hz is not an AAC sample rate: export WAV or FLAC, which write it as it is",
504 audio.sample_rate
505 )
506 })?;
507 let channels = usize::from(audio.channels.max(1));
508 // The timeline's length, not the mix's: a segment resolves its window to
509 // whole samples on its own, so the sum can miss by a sample or two and a
510 // source that ran out early would leave the track short under a picture
511 // that is not. One resize settles both, as [`run_audio`]'s does.
512 let total = (f64::from(project.timeline_frames()) / meta.frame_rate
513 * f64::from(audio.sample_rate))
514 .round() as usize
515 * channels;
516 let mut samples: Vec<f32> = Vec::with_capacity(total);
517 for chunk in chunks {
518 samples.extend(chunk.samples);
519 }
520 samples.resize(total, 0.0);
521
522 // 256 kbps, not the encoder's 128 default: this is a *second* generation of
523 // lossy coding over a source that was already AAC, and the export is a
524 // master a person edits from again, not a delivery file. Measured on the
525 // suite's fixtures, an untouched clip re-encoded here moves 0.15 dB at this
526 // rate against 0.46 dB at 128 -- and 32 KB/s beside a 2.76 Mbps picture is
527 // not a size anyone is counting.
528 let mut encoder = rusty_aac::AacEncoder::new(rusty_aac::AacEncoderConfig {
529 bitrate_bps: 256_000,
530 ..Default::default()
531 });
532 encoder.push_pcm(&samples, audio.channels.max(1), audio.sample_rate)?;
533 encoder.finish();
534 let mut packets = Vec::new();
535 // `next_packet` after `finish` yields packets until `Eof` and nothing else,
536 // so the loop ends on the only error it can see.
537 while let Ok(packet) = encoder.next_packet() {
538 packets.push(crate::AacPacket {
539 bytes: packet.data,
540 samples: packet.duration,
541 });
542 }
543 Ok(Some((
544 crate::AacTrackParams {
545 freq_index,
546 // 1 and 2 are the ISO channel configurations for mono and stereo,
547 // and the opener refuses anything wider than stereo already.
548 chan_conf: audio.channels.max(1) as u8,
549 sample_rate: audio.sample_rate,
550 },
551 packets,
552 )))
553}
554
555fn run(
556 project: &Project,
557 meta: &VideoMeta,
558 out: &Path,
559 shared: &Shared,
560 settings: &ExportSettings,
561) -> crate::Result<()> {
562 let total = project.timeline_frames();
563 let sources = project.sources();
564 // Audio first: a track has to be declared when the muxer is created, which
565 // happens as soon as the first coded picture arrives. None of it for AV1 --
566 // that one is picture only, for the reason [`Format::Av1`] states -- and no
567 // refusal of it either: a timeline with sound is exported as the video it
568 // also is, and the front-end says the sound is not in the file *before* the
569 // export starts rather than failing it here.
570 let audio = match settings.format {
571 Format::Av1 => None,
572 _ => copy_audio(project, meta)?,
573 };
574 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
575 freq_index: track.freq_index,
576 chan_conf: track.chan_conf,
577 });
578
579 let mut encoder = Enc::open(meta, settings)?;
580 // What this file is really being written by, for a progress line to name.
581 // Published *after* the seat is open, so a hardware encoder the driver
582 // refused reads as the software one that took over rather than as the hope
583 // it replaced -- and the sound says whether it was copied or encoded, which
584 // `copy_audio` decided a few lines up.
585 *shared.encoders.lock().unwrap() = Some(
586 match audio_label(project, settings.format, audio.is_some()) {
587 // AV1: no sound in the file and none to name.
588 "" => encoder.label().to_string(),
589 sound => format!("{} · {sound}", encoder.label()),
590 },
591 );
592 let mut muxer = None;
593 let mut done = 0u32;
594 let black = Black::new(meta);
595 // Spans, not clips: a gap in the video is part of the timeline and gets
596 // encoded too, as black frames. The picture count is therefore
597 // `timeline_frames` however the lanes are arranged -- and *which* lane a
598 // span comes from is `composite_spans_from`'s answer, the same one playback
599 // shows, so an export is what was watched.
600 for span in project.composite_spans_from(0) {
601 // Every clip reopens its own source file at its own in point; the
602 // encoder is *not* reopened, so the export is one continuous stream
603 // whose GOP boundaries need not line up with the cuts -- nor with the
604 // file boundaries, which are just cuts that change the path.
605 let mut pictures = match span.from {
606 Some((source, in_frame)) => {
607 let entry = sources
608 .get(source)
609 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
610 Some(ClipDecoder::open(&entry.path, in_frame)?)
611 }
612 None => None,
613 };
614 // What this span is graded by -- the same answer playback's decoder
615 // carries, so the export is the picture that was watched. `None` for a
616 // gap and for an ungraded clip, and that is the path where not a byte
617 // is touched. Scratch outside the frame loop: it is refilled per frame
618 // and its allocation survives the whole span.
619 let grade = project.composite_color_at(span.start).copied();
620 let mut graded = (Vec::new(), Vec::new(), Vec::new());
621 // ...and the canvas it is placed on, which is where a source of another
622 // resolution becomes a picture at the project's. The same `Composer`
623 // playback composes with, given the same policy, so an export is what
624 // was watched down to the letterbox; a clip already the project's size
625 // passes through it untouched.
626 let mut canvas = Composer::new(
627 meta.width,
628 meta.height,
629 project.composite_fit_at(span.start),
630 );
631 // Timeline frames, taken a *source* frame at a time: at a rate other
632 // than real time the two are not the same count, and the span says which
633 // source frame each timeline frame shows ([`Speed::source_at`]) -- the
634 // very frame playback is holding there, because the two conversions are
635 // one floor/ceil pair (`speed_maps_both_ways`). A speed-up decodes the
636 // frames it skips and drops them, because the pictures after them
637 // reference those; a slow-down encodes the picture it is holding again
638 // rather than decoding it twice. At real time `repeats` is 1 and `want`
639 // advances by one, which is the loop this always ran.
640 let mut done_here = 0u32;
641 // Source frames already taken out of this span's decoder.
642 let mut taken = 0u32;
643 while done_here < span.len {
644 cancelled(shared)?;
645 let want = span.speed.source_at(done_here);
646 let repeats = span.speed.repeats(done_here, span.len);
647 let picture = match &mut pictures {
648 Some(pictures) => {
649 let mut ran_out = false;
650 while taken < want && !ran_out {
651 ran_out = pictures.next()?.is_none();
652 taken += 1;
653 }
654 match ran_out {
655 true => None,
656 false => {
657 taken += 1;
658 pictures.next()?
659 }
660 }
661 }
662 None => Some(black.picture()),
663 };
664 let Some((y, u, v, width, height)) = picture else {
665 break; // source ran out early; the clip list outlives the file
666 };
667 // The planes are borrowed from the decoder (and `Black::picture`
668 // hands the same slice as both u and v), so a grade cannot be
669 // applied in place: it goes onto a copy, which the encoder then
670 // reads instead.
671 let (y, u, v) = match grade.filter(|p| !p.is_identity()) {
672 Some(params) => {
673 let (gy, gu, gv) = &mut graded;
674 gy.clear();
675 gy.extend_from_slice(y);
676 gu.clear();
677 gu.extend_from_slice(u);
678 gv.clear();
679 gv.extend_from_slice(v);
680 crate::color::apply_yuv(&params, gy, gu, gv);
681 (&gy[..], &gu[..], &gv[..])
682 }
683 None => (y, u, v),
684 };
685 // Grade first, place second: the grade is the clip's own pixels
686 // and the bars around them are not the clip (see `scale::Composer`).
687 let (y, u, v, width, height) = canvas.place(y, u, v, width, height);
688 // Once per timeline frame this source frame covers: one at real time
689 // and faster, more when the clip is slowed -- the picture is already
690 // graded and placed, so a held frame costs an encode and no decode.
691 for _ in 0..repeats {
692 if let Some((au, key)) = encoder.encode(y, u, v, width, height)? {
693 write_video(
694 &mut muxer,
695 out,
696 meta,
697 settings,
698 audio_params.as_ref(),
699 au,
700 key,
701 )?;
702 }
703 done += 1;
704 shared
705 .progress
706 .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);
707 }
708 done_here += repeats;
709 }
710 }
711 while let Some((au, key)) = encoder.drain()? {
712 write_video(
713 &mut muxer,
714 out,
715 meta,
716 settings,
717 audio_params.as_ref(),
718 au,
719 key,
720 )?;
721 }
722 // Progress reads 100% from here on, but nothing is published yet: draining,
723 // the audio pass and `finish` are all still cancellable.
724 cancelled(shared)?;
725
726 let Some(muxer) = muxer else {
727 return Err("export produced no coded pictures".into());
728 };
729 let muxer = match (muxer, audio) {
730 (Muxer::Mp4(mut mp4), Some((_, packets))) => {
731 for packet in packets {
732 mp4.write_audio_packet(&packet.bytes)?;
733 }
734 Muxer::Mp4(mp4)
735 }
736 (muxer, _) => muxer,
737 };
738 cancelled(shared)?;
739 muxer.finish()?;
740 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
741 Ok(())
742}
743
744/// Where a clip sits on the timeline as a person reads it: `mm:ss`, short
745/// enough to sit inside a refusal and exact enough to go and find the clip.
746/// Not the app's frame-accurate timecode -- an engine refusal is prose, and a
747/// `00:00:12:07` in the middle of a sentence is a serial number.
748fn timecode(frame: u32, fps: f64) -> String {
749 let secs = match fps.is_finite() && fps > 0.0 {
750 true => (f64::from(frame) / fps) as u32,
751 false => 0,
752 };
753 format!("{:02}:{:02}", secs / 60, secs % 60)
754}
755
756/// The audio lanes alone, summed, as a WAV or a FLAC.
757///
758/// Nothing here re-derives the edit: the play lists are
759/// [`Project::audio_segments_from`] and they are handed to the very
760/// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written
761/// is what was heard -- every lane, mixed the same way, gaps included, which
762/// arrive as real silence from that choke point rather than as a hole this would
763/// have to invent.
764///
765/// The length is the *timeline's*: each segment resolves its window to whole
766/// samples on its own, so the sum can miss the timeline by a sample or two, and
767/// a source that runs out early would leave the file short. Both are settled by
768/// one `resize` at the end -- padding with silence, trimming what overshot --
769/// so an exported file is exactly as long as what was edited.
770fn run_audio(
771 project: &Project,
772 meta: &VideoMeta,
773 out: &Path,
774 shared: &Shared,
775 format: Format,
776) -> crate::Result<()> {
777 let sources = project.audio_sources();
778 let segs = project.audio_segments_from(0, meta.frame_rate);
779 // The equalizers with them, so what is written is what is heard down to the
780 // filter: the worker applies them per segment before the lanes are summed
781 // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point
782 // playback's feeder reads from -- there is no second place here that could
783 // apply them differently.
784 let eqs = project.audio_eqs_from(0, meta.frame_rate);
785 // ...and the rates with them, for exactly the same reason: a speeded clip is
786 // resampled inside the worker playback feeds from, so a WAV of a timeline at
787 // 2x is half as long and holds the samples that were heard -- not a
788 // second pass here that could disagree with what the ear got.
789 let speeds = project.audio_speeds_from(0, meta.frame_rate);
790 let Some((audio, chunks)) =
791 AudioSession::open_mixed_streams_speed(&sources, &segs, &eqs, &speeds)?
792 else {
793 return Err("this timeline has no audio to export".into());
794 };
795 // The picture path's line, for a file that is sound alone: there is sound
796 // by the line above, so this names the encoder writing it.
797 *shared.encoders.lock().unwrap() = Some(audio_label(project, format, true).to_string());
798 let channels = usize::from(audio.channels);
799 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate
800 * f64::from(audio.sample_rate))
801 .round() as u64;
802 let total = frames as usize * channels;
803 // ponytail: the whole export sits in memory (4 bytes a sample, so ~23 MB
804 // per minute of 48 kHz stereo). `flacenc::MemSource` wants it that way and
805 // the mp4 path already collects its copied AAC track the same. Upgrade path
806 // is hound's incremental writer plus flacenc's `Source` trait.
807 let mut samples: Vec<i32> = Vec::with_capacity(total);
808 for chunk in chunks {
809 cancelled(shared)?;
810 // Already equalized: the chunks come out of the per-lane workers, which
811 // filter each segment before the mix (`open_mixed_streams_eq` above).
812 samples.extend(
813 chunk
814 .samples
815 .iter()
816 .map(|s| (s.clamp(-1.0, 1.0) * f32::from(i16::MAX)).round() as i32),
817 );
818 let done = samples.len().min(total) * PROGRESS_SCALE as usize / total.max(1);
819 shared.progress.store(done as u32, Ordering::Relaxed);
820 }
821 samples.resize(total, 0);
822 // Written in one go and still cancellable up to here, exactly as the mp4
823 // path is up to its `finish`: the `.part` is what either gets renamed or
824 // deleted.
825 cancelled(shared)?;
826 match format {
827 Format::Wav => write_wav(out, &samples, &audio)?,
828 Format::Flac => write_flac(out, &samples, &audio)?,
829 Format::Mp4 | Format::Av1 => unreachable!("the picture formats are `run`"),
830 }
831 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
832 Ok(())
833}
834
835/// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in
836/// this engine, so what the decoder handed over is what the header says.
837fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
838 let mut writer = hound::WavWriter::create(
839 out,
840 hound::WavSpec {
841 channels: audio.channels,
842 sample_rate: audio.sample_rate,
843 bits_per_sample: 16,
844 sample_format: hound::SampleFormat::Int,
845 },
846 )?;
847 for &sample in samples {
848 writer.write_sample(sample as i16)?;
849 }
850 // Not `drop`: this is what rewrites the RIFF sizes in the header, and its
851 // failure is the difference between a finished file and a truncated one.
852 writer.finalize()?;
853 Ok(())
854}
855
856/// The same samples, losslessly compressed. `flacenc`'s errors are flattened to
857/// text: they are not `Send + Sync`, and every one of them fails the export the
858/// same way.
859fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
860 let config = flacenc::config::Encoder::default()
861 .into_verified()
862 .map_err(|(_, e)| format!("flac encoder config: {e}"))?;
863 let source = flacenc::source::MemSource::from_samples(
864 samples,
865 usize::from(audio.channels),
866 16,
867 audio.sample_rate as usize,
868 );
869 let mut stream = flacenc::encode_with_fixed_block_size(&config, source, config.block_size)
870 .map_err(|e| format!("flac encode: {e}"))?;
871 // The block sizes are stated fixed, which is what the frames themselves say
872 // (they are numbered, not sample-addressed). flacenc's single-threaded path
873 // instead writes the *last* frame's length as the minimum, and a short final
874 // frame is the normal case -- a stream whose `streaminfo` then disagrees
875 // with its own blocking strategy. ffmpeg shrugs and plays it; symphonia,
876 // which is this engine's own reader, rejects every frame header and reads
877 // to EOF looking for a good one. Written this way the file reopens here,
878 // which is the only test of an export that counts. (Same value flacenc's
879 // own `par` path writes; the reference encoder does it too.)
880 stream
881 .stream_info_mut()
882 .set_block_sizes(config.block_size, config.block_size)
883 .map_err(|e| format!("flac block size: {e}"))?;
884 let mut sink = flacenc::bitsink::ByteSink::new();
885 stream
886 .write(&mut sink)
887 .map_err(|e| format!("flac write: {e}"))?;
888 std::fs::write(out, sink.as_slice())?;
889 Ok(())
890}
891
892/// The I420 planes of one black picture, allocated once for a whole export: a
893/// gap in the video lane is encoded, not skipped, or every frame after it would
894/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention
895/// [`crate::convert`] decodes with.
896struct Black {
897 y: Vec<u8>,
898 uv: Vec<u8>,
899 width: u32,
900 height: u32,
901}
902
903impl Black {
904 fn new(meta: &VideoMeta) -> Self {
905 let (w, h) = (meta.width as usize, meta.height as usize);
906 Self {
907 y: vec![16; w * h],
908 uv: vec![128; w.div_ceil(2) * h.div_ceil(2)],
909 width: meta.width,
910 height: meta.height,
911 }
912 }
913
914 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
915 (&self.y, &self.uv, &self.uv, self.width, self.height)
916 }
917}
918
919/// `Err` once a cancel has been asked for. Called at every point where the work
920/// left is more than an instant, so an `esc` at 99.9% still stops the export
921/// instead of quietly completing it.
922fn cancelled(shared: &Shared) -> crate::Result<()> {
923 if shared.cancel.load(Ordering::Relaxed) {
924 return Err("export cancelled".into());
925 }
926 Ok(())
927}
928
929/// The two containers an export writes, so the picture loop above is one loop:
930/// H.264 goes into mp4, AV1 into Matroska, and nothing else is offered.
931enum Muxer {
932 Mp4(Mp4Muxer),
933 Mkv(MkvMuxer),
934}
935
936impl Muxer {
937 fn finish(self) -> crate::Result<()> {
938 match self {
939 Self::Mp4(mp4) => mp4.finish(),
940 Self::Mkv(mkv) => mkv.finish(),
941 }
942 }
943}
944
945/// Writes one access unit, creating the file on the first one -- the parameter
946/// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once
947/// the encoder has coded something. Units with no coded slice are skipped: a
948/// software encoder may hand back an empty buffer while it buffers, and the
949/// muxer rejects a sample that would carry no picture.
950fn write_video(
951 muxer: &mut Option<Muxer>,
952 out: &Path,
953 meta: &VideoMeta,
954 settings: &ExportSettings,
955 audio: Option<&AudioParams>,
956 au: &[u8],
957 key: bool,
958) -> crate::Result<()> {
959 if settings.format == Format::Av1 {
960 let muxer = match muxer {
961 Some(Muxer::Mkv(mkv)) => mkv,
962 Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
963 none => {
964 // Every AV1 stream opens on a keyframe, and a keyframe carries
965 // the sequence header the track has to declare: an encoder that
966 // handed back neither has produced nothing a decoder can start.
967 let config = crate::mux::av1_sequence_header(au)
968 .ok_or("the first coded picture carries no AV1 sequence header")?;
969 let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create(
970 out,
971 &Av1Params {
972 width: meta.width,
973 height: meta.height,
974 frame_rate: meta.frame_rate,
975 config,
976 },
977 )?)) else {
978 unreachable!("just inserted a Matroska muxer")
979 };
980 mkv
981 }
982 };
983 return muxer.write_frame(au, key);
984 }
985 if !crate::mux::has_coded_slice(au) {
986 return Ok(());
987 }
988 let muxer = match muxer {
989 Some(Muxer::Mp4(mp4)) => mp4,
990 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
991 none => {
992 let (sps, pps) = crate::mux::parameter_sets(au)
993 .ok_or("the first coded picture carries no SPS/PPS")?;
994 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create(
995 out,
996 &VideoParams {
997 width: meta.width,
998 height: meta.height,
999 frame_rate: meta.frame_rate,
1000 sps,
1001 pps,
1002 },
1003 audio,
1004 )?)) else {
1005 unreachable!("just inserted an mp4 muxer")
1006 };
1007 mp4
1008 }
1009 };
1010 muxer.write_video_au(au)
1011}
1012
1013fn bitrate_for(meta: &VideoMeta) -> u64 {
1014 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;
1015 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)
1016}
1017
1018fn forced(var: &str) -> bool {
1019 std::env::var_os(var).is_some_and(|v| v == "1")
1020}
1021
1022/// Hardware where it is available, software everywhere else -- chosen once for
1023/// the whole export, so the stream never changes encoder mid-file. Both codecs
1024/// have both seats: an AV1 export runs on the plugin's VA-API encoder where the
1025/// GPU has one and on `rav1e` where it has not, which is the same pair H.264 has
1026/// had and the same silent fallback.
1027enum Enc {
1028 Hw(HwEncoder),
1029 Sw {
1030 encoder: Encoder,
1031 /// The last access unit; owned because `rusty_h264` hands back a `Vec`
1032 /// while the plugin lends a slice, and the two have to look alike here.
1033 au: Vec<u8>,
1034 flushed: bool,
1035 },
1036 /// AV1 on the GPU, through the same plugin the H.264 seat uses.
1037 Av1Hw(HwEncoder),
1038 Av1Sw {
1039 context: rav1e::Context<u8>,
1040 /// Temporal units the encoder has finished but the caller has not
1041 /// collected: `rav1e` reorders and may hand back several at once, while
1042 /// this interface is one picture in, one unit out (the plugin's own
1043 /// `ready` queue exists for the same reason).
1044 ready: std::collections::VecDeque<(Vec<u8>, bool)>,
1045 /// The unit currently lent out, for the same reason `Sw` owns one.
1046 au: Vec<u8>,
1047 flushed: bool,
1048 },
1049}
1050
1051impl Enc {
1052 /// Which seat this *is*, said the way [`video_label`] says it -- so the
1053 /// name a running export shows is the name the card showed, or the honest
1054 /// difference where the probe and the open disagreed.
1055 fn label(&self) -> &'static str {
1056 match self {
1057 Self::Hw(_) => video_label(Format::Mp4, true),
1058 Self::Sw { .. } => video_label(Format::Mp4, false),
1059 Self::Av1Hw(_) => video_label(Format::Av1, true),
1060 Self::Av1Sw { .. } => video_label(Format::Av1, false),
1061 }
1062 }
1063
1064 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
1065 if settings.format == Format::Av1 {
1066 return Self::open_av1(meta, settings);
1067 }
1068 // A caller's number goes through the same clamp as the computed one: a
1069 // zero bitrate switches the software encoder's lookahead on, which would
1070 // break the one-picture-per-call contract `encode` documents below.
1071 let bitrate = bitrate_of(meta, settings);
1072 // The plugin wants an exact rational, and the muxer already picks one
1073 // that is exact at every rate we can read -- `fps * 1000 / 1000` would
1074 // hand 24000/1001 over as a rounded 23.976, which is the same
1075 // truncation the container timing had.
1076 crate::mux::frame_timing(meta.frame_rate)?;
1077 if let Some(hw) = hw_seat(meta, settings) {
1078 eprintln!("export encoder: hardware (VA-API plugin)");
1079 return Ok(Self::Hw(hw));
1080 }
1081 eprintln!("export encoder: software (rusty_h264)");
1082 let mut cfg = EncoderConfig::new(meta.width as usize, meta.height as usize);
1083 cfg.framerate = meta.frame_rate as f32;
1084 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;
1085 // Two seconds between key frames, and no B-frames on either path: the
1086 // muxer times everything by duration alone, which reordering would break.
1087 cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32;
1088 cfg.bframes = 0;
1089 // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same
1090 // bitrate, so Fast is what a fallback should be.
1091 cfg.preset = Preset::Fast;
1092 let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?;
1093 Ok(Self::Sw {
1094 encoder,
1095 au: Vec::new(),
1096 flushed: false,
1097 })
1098 }
1099
1100 /// The AV1 pair. The hardware seat is the plugin's, opened by a symbol of
1101 /// its own (`vh_enc_av1_open`) so a plugin built before AV1 encode existed
1102 /// simply has none and this falls through -- the same "no" a GPU without an
1103 /// AV1 encode entrypoint gives, and the same silent fallback either way.
1104 ///
1105 /// It is **opt-in**, which is the one place this pair does not mirror the
1106 /// H.264 one: the vendored cros-codecs AV1 encoder hung the GPU on this
1107 /// project's own radeonsi box -- `engine_hw: operation failed`, then an
1108 /// amdgpu hard recovery and a lost context, measured 2026-08-10 exporting
1109 /// the 720p fixture. A software encoder that takes half a minute is a worse
1110 /// export than a hardware one; a driver reset is not an export at all. So
1111 /// the plugin's AV1 seat is wired, kept and only entered when `VE_HW_AV1=1`
1112 /// asks for it by name.
1113 ///
1114 /// ponytail: the upgrade path is a driver this was reproduced against (or a
1115 /// cros-codecs release that fixes it) plus a probe encode of one frame at
1116 /// open, after which this can prefer hardware the way H.264 does.
1117 fn open_av1(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
1118 let bitrate = bitrate_of(meta, settings);
1119 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
1120 // Two seconds between keyframes, as the H.264 seat does: a seek may only
1121 // land on one, and this is what a cluster of the Matroska file is.
1122 let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64;
1123 if let Some(hw) = hw_seat(meta, settings) {
1124 eprintln!("export encoder: hardware AV1 (VA-API plugin)");
1125 return Ok(Self::Av1Hw(hw));
1126 }
1127 eprintln!("export encoder: software AV1 (rav1e)");
1128 let mut cfg = rav1e::EncoderConfig::default();
1129 cfg.width = meta.width as usize;
1130 cfg.height = meta.height as usize;
1131 cfg.bit_depth = 8;
1132 cfg.chroma_sampling = rav1e::prelude::ChromaSampling::Cs420;
1133 // Seconds per frame, which is what `frame_timing` already has as an
1134 // exact rational -- 1001/24000 rather than a rounded 23.976.
1135 cfg.time_base = rav1e::prelude::Rational::new(u64::from(fps_den), u64::from(fps_num));
1136 cfg.min_key_frame_interval = gop;
1137 cfg.max_key_frame_interval = gop;
1138 cfg.bitrate = bitrate.min(i32::MAX as u64) as i32;
1139 // The fastest preset there is, and it is still slow: `rav1e` is built
1140 // here without its assembly (no `nasm` in this project's build), so an
1141 // export runs at a fraction of realtime. The export worker reports
1142 // progress the whole way, which is what makes that bearable rather than
1143 // hidden.
1144 cfg.speed_settings = rav1e::prelude::SpeedSettings::from_preset(AV1_SPEED);
1145 let config = rav1e::Config::new()
1146 .with_encoder_config(cfg)
1147 .with_threads(std::thread::available_parallelism().map_or(1, |n| n.get()));
1148 let context = config
1149 .new_context::<u8>()
1150 .map_err(|e| format!("software AV1 encoder: {e}"))?;
1151 Ok(Self::Av1Sw {
1152 context,
1153 ready: std::collections::VecDeque::new(),
1154 au: Vec::new(),
1155 flushed: false,
1156 })
1157 }
1158
1159 /// One picture in, at most one access unit out, and whether that unit is one
1160 /// a decoder may be started from -- which only the Matroska muxer asks, the
1161 /// mp4 one reading its own sync flag off the IDR slice.
1162 ///
1163 /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer
1164 /// when its lookahead is active, which would make this "one access unit"
1165 /// a lie and every sample duration with it. It is inactive here because
1166 /// lookahead needs a zero bitrate and this path is always CBR; a future
1167 /// constant-QP mode has to split the buffer per access unit first.
1168 fn encode(
1169 &mut self,
1170 y: &[u8],
1171 u: &[u8],
1172 v: &[u8],
1173 width: u32,
1174 height: u32,
1175 ) -> crate::Result<Option<(&[u8], bool)>> {
1176 match self {
1177 Self::Av1Hw(hw) => {
1178 let au = hw.encode(y, u, v, width, height, false)?;
1179 // What the *bitstream* says, not what was asked for: an AV1
1180 // keyframe carries the sequence header, which is the same mark
1181 // `demux` reads a sync point off. A driver that emitted one
1182 // unasked is then still a seek target, and one that skipped a
1183 // requested keyframe cannot be mistaken for a decoder's start.
1184 Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
1185 }
1186 Self::Av1Sw {
1187 context, ready, au, ..
1188 } => {
1189 let mut frame = context.new_frame();
1190 let (w, h) = (width as usize, height as usize);
1191 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
1192 frame.planes[0].copy_from_raw_u8(&y[..w * h], w, 1);
1193 frame.planes[1].copy_from_raw_u8(&u[..cw * ch], cw, 1);
1194 frame.planes[2].copy_from_raw_u8(&v[..cw * ch], cw, 1);
1195 if let Err(e) = context.send_frame(frame) {
1196 return Err(format!("software AV1 encode: {e}").into());
1197 }
1198 collect_av1(context, ready)?;
1199 Ok(pop_av1(ready, au))
1200 }
1201 Self::Hw(hw) => Ok(hw
1202 .encode(y, u, v, width, height, false)?
1203 .map(|au| (au, false))),
1204 Self::Sw { encoder, au, .. } => {
1205 let frame = YuvFrame {
1206 width: width as usize,
1207 height: height as usize,
1208 y: y.to_vec(),
1209 u: u.to_vec(),
1210 v: v.to_vec(),
1211 };
1212 *au = encoder
1213 .try_encode(&frame)
1214 .map_err(|e| format!("software encode: {e}"))?;
1215 Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty()))
1216 }
1217 }
1218 }
1219
1220 /// End of stream; call until it returns `None`.
1221 fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> {
1222 match self {
1223 Self::Av1Hw(hw) => {
1224 let au = hw.drain()?;
1225 Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
1226 }
1227 Self::Av1Sw {
1228 context,
1229 ready,
1230 au,
1231 flushed,
1232 } => {
1233 if !*flushed {
1234 *flushed = true;
1235 context.flush();
1236 collect_av1(context, ready)?;
1237 }
1238 Ok(pop_av1(ready, au))
1239 }
1240 Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))),
1241 Self::Sw {
1242 encoder,
1243 au,
1244 flushed,
1245 } => {
1246 if *flushed {
1247 return Ok(None);
1248 }
1249 *flushed = true;
1250 *au = encoder
1251 .try_flush()
1252 .map_err(|e| format!("software encoder flush: {e}"))?;
1253 Ok(Some((&au[..], false)).filter(|(au, _)| !au.is_empty()))
1254 }
1255 }
1256 }
1257}
1258
1259/// Every temporal unit `rav1e` has finished, moved into the queue in display
1260/// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is
1261/// through) are the two ways it says there is nothing more; `Encoded` means a
1262/// picture was coded but not yet packetised, which is a *keep asking* -- taking
1263/// it for an end leaves the tail of the export inside the encoder.
1264fn collect_av1(
1265 context: &mut rav1e::Context<u8>,
1266 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
1267) -> crate::Result<()> {
1268 use rav1e::prelude::{EncoderStatus, FrameType};
1269 loop {
1270 match context.receive_packet() {
1271 Ok(packet) => ready.push_back((packet.data, packet.frame_type == FrameType::KEY)),
1272 Err(EncoderStatus::Encoded) => {}
1273 Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()),
1274 Err(e) => return Err(format!("software AV1 encode: {e}").into()),
1275 }
1276 }
1277}
1278
1279/// The oldest finished unit, moved into the buffer that is lent out -- the same
1280/// "valid until the next call" contract the plugin's slice has.
1281fn pop_av1<'a>(
1282 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
1283 au: &'a mut Vec<u8>,
1284) -> Option<(&'a [u8], bool)> {
1285 let (unit, key) = ready.pop_front()?;
1286 *au = unit;
1287 Some((&au[..], key))
1288}
1289
1290/// I420 straight out of the decoder: the export never converts to BGRA and back,
1291/// which would cost two conversions and a generation of colour precision.
1292///
1293/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`,
1294/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to
1295/// software: a hardware decode that fails after the first picture fails the
1296/// export, which then deletes the half-written file.
1297enum ClipDecoder {
1298 Hw(HwSession),
1299 Sw(SwDecoder),
1300 /// A still image: one picture, handed out for as long as the span runs.
1301 /// It is decoded here rather than in `run`'s loop for the same reason the
1302 /// other two are opened there -- the span's pictures come from one place.
1303 Still(crate::decode::Still),
1304}
1305
1306impl ClipDecoder {
1307 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
1308 // Before either decoder: an image is not a stream, so `start_frame`
1309 // means nothing to it -- every frame of a still span is the same
1310 // picture, which is what playback shows for it too.
1311 if crate::is_image(path) {
1312 return Ok(Self::Still(crate::decode::Still::open(path)?));
1313 }
1314 if !forced("VE_SW")
1315 && let Some(hw) = HwSession::open_at(path, start_frame)
1316 {
1317 return Ok(Self::Hw(hw));
1318 }
1319 Ok(Self::Sw(SwDecoder::open(path, start_frame)?))
1320 }
1321
1322 /// The next picture as tightly packed I420, borrowed until the call after.
1323 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
1324 match self {
1325 Self::Still(still) => Ok(Some(still.picture())),
1326 Self::Hw(hw) => hw.next_frame(),
1327 Self::Sw(sw) => {
1328 if !sw.advance()? {
1329 return Ok(None);
1330 }
1331 let frame = sw.frame.as_ref().expect("advance stored a picture");
1332 Ok(Some((
1333 &frame.y,
1334 &frame.u,
1335 &frame.v,
1336 frame.width as u32,
1337 frame.height as u32,
1338 )))
1339 }
1340 }
1341 }
1342}
1343
1344struct SwDecoder {
1345 demuxer: Demuxer,
1346 decoder: Decoder,
1347 /// Display index of the next picture the decoder will produce. Signed: a
1348 /// sync sample inside what the edit list trims is before frame 0.
1349 index: i64,
1350 start: u32,
1351 frame: Option<YuvFrame>,
1352}
1353
1354impl SwDecoder {
1355 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
1356 let (meta, mut demuxer) = Demuxer::open(path)?;
1357 // The software decoder is H.264-only; an HEVC or VP9 source that got
1358 // this far means the plugin refused it, and the export says so instead
1359 // of handing those bytes to `rusty_h264`.
1360 if meta.codec != crate::demux::Codec::H264 {
1361 return Err(meta.codec.needs_plugin().into());
1362 }
1363 // Decoding restarts at a sync sample, so pictures between it and the in
1364 // point are decoded (the target references them) and then dropped.
1365 let index = demuxer.seek_to_sync_at_or_before(start_frame);
1366 Ok(Self {
1367 demuxer,
1368 decoder: Decoder::new(),
1369 index,
1370 start: start_frame,
1371 frame: None,
1372 })
1373 }
1374
1375 /// Decodes up to and including the next picture at or after the in point,
1376 /// leaving it in `frame`. `false` at end of stream.
1377 fn advance(&mut self) -> crate::Result<bool> {
1378 loop {
1379 let Some(au) = self.demuxer.next_access_unit()? else {
1380 return Ok(false);
1381 };
1382 let decoded = self
1383 .decoder
1384 .decode(&au)
1385 .map_err(|e| format!("decode at picture {}: {e}", self.index))?;
1386 let Some(yuv) = decoded else { continue };
1387 let wanted = self.index >= i64::from(self.start);
1388 self.index += 1;
1389 if wanted {
1390 self.frame = Some(yuv);
1391 return Ok(true);
1392 }
1393 }
1394 }
1395}
1396
1397#[cfg(test)]
1398mod tests {
1399 use super::*;
1400
1401 #[test]
1402 fn bitrate_clamps_at_both_ends() {
1403 let meta = |width, height, frame_rate| VideoMeta {
1404 width,
1405 height,
1406 frame_rate,
1407 frame_count: 1,
1408 codec: crate::demux::Codec::H264,
1409 };
1410 // 1280 * 720 * 30 * 0.1
1411 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
1412 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny");
1413 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
1414 }
1415}