forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa3e9dc2Tahinli3 months ago134 commits

export.rs839 lines, 34.4 KiBHistoryRawDownload
1//! Export: the edit list rendered back out as one mp4 — or, picture left
2//! 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, because there is no
6//! pure-Rust AAC encoder to re-encode with. The audio-only formats have no such
7//! trouble: `hound` writes PCM and `flacenc` encodes FLAC, both pure Rust, so
8//! those are *decoded* out of the timeline instead of copied. The worker owns
9//! everything: the caller gets an [`ExportHandle`] and polls it from its render
10//! loop.
11//!
12//! Nothing partial survives a failure: the worker writes to `<out>.part` and
13//! renames it onto `out` only once the file is closed and complete, so the
14//! output either does not exist or is finished — there is no window where a
15//! half-written `.export.mp4` is sitting there looking playable. Cancel and
16//! every error path delete the `.part`. A killed *process* leaves the `.part`
17//! behind (only in-process cleanup is promised), which is an orphan a user can
18//! delete rather than a file that plays for two seconds and stops.
19
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
22use std::sync::{Arc, Mutex};
23use std::thread;
24
25use rusty_h264::{Decoder, Encoder, EncoderConfig, Preset, YuvFrame};
26
27use flacenc::component::BitRepr;
28use flacenc::error::Verify;
29
30use crate::audio::{AudioMeta, AudioSession};
31use crate::demux::{Demuxer, VideoMeta};
32use crate::hw::{HwEncoder, HwSession};
33use crate::mux::{AudioParams, Mp4Muxer, VideoParams};
34use crate::project::{LaneKind, Project};
35use crate::scale::Composer;
36
37/// Progress is reported in permille: an atomic integer the render loop can read
38/// without a lock, fine enough for any progress bar.
39const PROGRESS_SCALE: u32 = 1_000;
40
41/// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
42/// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%.
43const BITS_PER_PIXEL: f64 = 0.1;
44const MIN_BITRATE: u64 = 1_000_000;
45const MAX_BITRATE: u64 = 20_000_000;
46
47/// What an export writes. Three, not more: H.264-in-mp4 is the only *video*
48/// pair with both an encoder and a decoder under this project's no-install
49/// rule, and WAV and FLAC are the only audio formats with a pure-Rust encoder
50/// at all. MP3 has one (`shine-rs`) under LGPL-2.0, which is a licensing
51/// decision this project has not taken; Vorbis, Opus and AAC have none. A
52/// front-end says so rather than hiding the rows.
53#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
54pub enum Format {
55 /// Picture and sound: video re-encoded, AAC copied. Copied, so it carries
56 /// **one** audio lane: a timeline whose sound is spread over two is refused
57 /// by name here and mixed by the other two formats, which decode.
58 #[default]
59 Mp4,
60 /// The audio lane alone, 16-bit PCM.
61 Wav,
62 /// The audio lane alone, losslessly compressed.
63 Flac,
64}
65
66impl Format {
67 /// The extension a file of this format is named with -- a front-end builds
68 /// the destination path from it, so the name never disagrees with the bytes.
69 pub fn ext(self) -> &'static str {
70 match self {
71 Self::Mp4 => "mp4",
72 Self::Wav => "wav",
73 Self::Flac => "flac",
74 }
75 }
76
77 /// Whether this format carries the picture. The bitrate settings are video
78 /// settings and mean nothing to the other two.
79 pub fn has_video(self) -> bool {
80 matches!(self, Self::Mp4)
81 }
82}
83
84/// What the caller gets to decide about the output. The codec is not among it:
85/// [`Format`] names a container *and* what goes in it, because every pair we
86/// can write is a pair we can also read back.
87#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
88pub struct ExportSettings {
89 /// Bits per second, clamped to the same sane range the automatic value uses.
90 /// `None` picks it from the picture size and frame rate. Video only.
91 pub bitrate: Option<u64>,
92 /// Skip the hardware encoder even where it is available -- an escape hatch
93 /// for a driver that encodes badly, matching the `VE_SW_ENC` env pin.
94 pub force_sw: bool,
95 /// The file to write. Defaults to [`Format::Mp4`], which is what every
96 /// caller wrote before there was a choice.
97 pub format: Format,
98}
99
100struct Shared {
101 progress: AtomicU32,
102 cancel: AtomicBool,
103 finished: AtomicBool,
104 outcome: Mutex<Option<crate::Result<()>>>,
105}
106
107/// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
108/// rendered frame and take the [`result`](ExportHandle::result) when it flips;
109/// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel)
110/// does.
111pub struct ExportHandle {
112 shared: Arc<Shared>,
113}
114
115impl ExportHandle {
116 /// Fraction of the timeline written, `0.0..=1.0`.
117 pub fn progress(&self) -> f32 {
118 self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32
119 }
120
121 /// Asks the worker to stop at its next checkpoint and delete the partial
122 /// file. The outcome then reports the cancellation as an error. Checkpoints
123 /// run to the last instant before the rename, so even a cancel at full
124 /// progress leaves no output.
125 pub fn cancel(&self) {
126 self.shared.cancel.store(true, Ordering::Relaxed);
127 }
128
129 pub fn is_finished(&self) -> bool {
130 self.shared.finished.load(Ordering::Acquire)
131 }
132
133 /// The outcome, once — taken out of the handle, so a caller that already
134 /// reported it sees `None` afterwards. `None` while the export is running.
135 pub fn result(&self) -> Option<crate::Result<()>> {
136 self.shared.outcome.lock().unwrap().take()
137 }
138}
139
140/// Starts the worker. Failures are reported through the handle rather than
141/// returned, so a caller has exactly one place to look. The files to read are
142/// the project's own [`sources`](Project::sources) -- every clip names one --
143/// so nothing but the edit list decides what is decoded.
144pub fn start(
145 project: Project,
146 meta: VideoMeta,
147 out: &Path,
148 settings: &ExportSettings,
149) -> ExportHandle {
150 let settings = *settings;
151 let shared = Arc::new(Shared {
152 progress: AtomicU32::new(0),
153 cancel: AtomicBool::new(false),
154 finished: AtomicBool::new(false),
155 outcome: Mutex::new(None),
156 });
157 let worker = Arc::clone(&shared);
158 let out = out.to_path_buf();
159 // `<out>.part`, appended rather than substituted: the temporary of
160 // `a.export.mp4` is `a.export.mp4.part`, which no other export claims.
161 let mut part = out.clone().into_os_string();
162 part.push(".part");
163 let part = PathBuf::from(part);
164 let spawned = thread::Builder::new().name("export".into()).spawn(move || {
165 // The rename is the last step and the only one that publishes a file
166 // under the name the caller asked for; it stays on the same directory,
167 // so it is atomic.
168 //
169 // An emptied timeline is a legal project and an illegal file: no
170 // picture, no sound, and a muxer that is never created because no coded
171 // frame arrives. Refused by name here -- before the format is even
172 // looked at, so an mp4 and a WAV refuse in the same words -- rather than
173 // left to write a file of no frames that nothing opens. Every caller of
174 // `start` comes through this, the app's own door
175 // (`PlaybackSession::is_empty`) being only the first fence.
176 //
177 // An audio-only timeline is the other legal project no mp4 can be made
178 // of: every frame of it is a gap, so the file would be black picture
179 // over the sound -- minutes of encoding for a video of nothing. Refused
180 // by name, with the two formats that *are* that timeline, rather than
181 // written; the app says the same on the format row before a destination
182 // is even picked (`mp4_refusal`).
183 let written = match settings.format {
184 _ if project.timeline_frames() == 0 => {
185 Err("the timeline is empty: there is nothing to export".into())
186 }
187 Format::Mp4 if !has_picture(&project) => Err("the timeline has no picture: \
188 an mp4 would be black. Export WAV or FLAC, which are the sound itself"
189 .into()),
190 Format::Mp4 => run(&project, &meta, &part, &worker, &settings),
191 format => run_audio(&project, &meta, &part, &worker, format),
192 };
193 let result = written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into));
194 if result.is_err() {
195 // The muxer -- and with it the file handle -- died with `run`.
196 let _ = std::fs::remove_file(&part);
197 }
198 settle(&worker, result);
199 });
200 if let Err(e) = spawned {
201 settle(&shared, Err(e.into()));
202 }
203 ExportHandle { shared }
204}
205
206/// Whether any video lane holds anything at all -- what tells an audio-only
207/// timeline from one that merely opens on a gap. Asked of the *lanes* rather
208/// than of the sources, because a project may name a video file no clip plays
209/// from any more.
210fn has_picture(project: &Project) -> bool {
211 project
212 .lanes()
213 .into_iter()
214 .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty())
215}
216
217fn settle(shared: &Shared, result: crate::Result<()>) {
218 *shared.outcome.lock().unwrap() = Some(result);
219 // Published last: a caller that sees the flag is guaranteed the outcome.
220 shared.finished.store(true, Ordering::Release);
221}
222
223fn run(
224 project: &Project,
225 meta: &VideoMeta,
226 out: &Path,
227 shared: &Shared,
228 settings: &ExportSettings,
229) -> crate::Result<()> {
230 let total = project.timeline_frames();
231 let sources = project.sources();
232 // Audio first: a track has to be declared when the muxer is created, which
233 // happens as soon as the first coded picture arrives.
234 //
235 // ponytail: this holds the whole exported AAC track in memory (~3 kB per
236 // 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
237 // `copy_segments` that yields packets instead of collecting them.
238 //
239 // The segments name their source, and the copy carries its packet-rounding
240 // debt across a source join exactly as across a cut, so a timeline spanning
241 // files stays in sync. A source whose AAC parameters disagree with the
242 // first one is an `Err` from there -- import refuses those up front, this
243 // is the backstop -- and the caller deletes the `.part`.
244 //
245 // The stream each source is copied from is the one it plays: `audio_sources`
246 // is the same list `PlaybackSession::seek` hands the decoder, so an export
247 // of a timeline playing a file's second audio track carries *that* track.
248 //
249 // One lane, because this path *copies* AAC packets and a mix is not a copy:
250 // summing two lanes means decoding both and encoding the result, and there
251 // is no AAC encoder here to encode it with. Refused by name rather than
252 // silently exporting the first lane -- a file missing half its sound is the
253 // one failure a user would not notice.
254 //
255 // *Which* lane is the same question `audio_segments_from` answers for
256 // playback, and it is asked here rather than assumed: the lane that holds
257 // the sound need not be `A1` (a project may leave `A1` empty and place
258 // everything on `A2`), and copying `A1`'s list in that case would write a
259 // file with no audio track at all -- silently, which is the failure this
260 // whole comment is about.
261 let lanes = project.audio_segments_from(0, meta.frame_rate);
262 let [segments] = &lanes[..] else {
263 return Err(format!(
264 "this timeline has {} audio lanes and an mp4 export copies one: \
265 there is no AAC encoder here to mix them with. Export WAV or FLAC, \
266 which are mixed, or put the sound on one lane",
267 lanes.len()
268 )
269 .into());
270 };
271 // ...and the same list decides which clips this would be copying, which is
272 // the only way to ask whether any of them carries an equalizer. An EQ is
273 // sample math and a copy never decodes: exporting it here would write the
274 // clip flat, silently -- the same failure a missing audio track is. Named by
275 // where it sits on the timeline, because "some clip" is not a thing a user
276 // can go and fix.
277 let lane = project.audio_lanes()[0];
278 if let Some((at, _)) = project
279 .lane(lane)
280 .iter()
281 .enumerate()
282 .find(|(idx, _)| project.eq_of(lane, *idx).is_some_and(|eq| !eq.is_identity()))
283 .map(|(idx, clip)| (clip.start, idx))
284 {
285 return Err(format!(
286 "the clip at {} has an equalizer and an mp4 export copies AAC packets, \
287 which no filter can reach: export WAV or FLAC, which are decoded and \
288 mixed, or clear the equalizer",
289 timecode(at, meta.frame_rate)
290 )
291 .into());
292 }
293 let audio = AudioSession::copy_multi_streams(&project.audio_sources(), segments)?;
294 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
295 freq_index: track.freq_index,
296 chan_conf: track.chan_conf,
297 });
298
299 let mut encoder = Enc::open(meta, settings)?;
300 let mut muxer = None;
301 let mut done = 0u32;
302 let black = Black::new(meta);
303 // Spans, not clips: a gap in the video is part of the timeline and gets
304 // encoded too, as black frames. The picture count is therefore
305 // `timeline_frames` however the lanes are arranged -- and *which* lane a
306 // span comes from is `composite_spans_from`'s answer, the same one playback
307 // shows, so an export is what was watched.
308 for span in project.composite_spans_from(0) {
309 // Every clip reopens its own source file at its own in point; the
310 // encoder is *not* reopened, so the export is one continuous stream
311 // whose GOP boundaries need not line up with the cuts -- nor with the
312 // file boundaries, which are just cuts that change the path.
313 let mut pictures = match span.from {
314 Some((source, in_frame)) => {
315 let entry = sources
316 .get(source)
317 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
318 Some(ClipDecoder::open(&entry.path, in_frame)?)
319 }
320 None => None,
321 };
322 // What this span is graded by -- the same answer playback's decoder
323 // carries, so the export is the picture that was watched. `None` for a
324 // gap and for an ungraded clip, and that is the path where not a byte
325 // is touched. Scratch outside the frame loop: it is refilled per frame
326 // and its allocation survives the whole span.
327 let grade = project.composite_color_at(span.start).copied();
328 let mut graded = (Vec::new(), Vec::new(), Vec::new());
329 // ...and the canvas it is placed on, which is where a source of another
330 // resolution becomes a picture at the project's. The same `Composer`
331 // playback composes with, given the same policy, so an export is what
332 // was watched down to the letterbox; a clip already the project's size
333 // passes through it untouched.
334 let mut canvas = Composer::new(
335 meta.width,
336 meta.height,
337 project.composite_fit_at(span.start),
338 );
339 for _ in 0..span.len {
340 cancelled(shared)?;
341 let picture = match &mut pictures {
342 Some(pictures) => pictures.next()?,
343 None => Some(black.picture()),
344 };
345 let Some((y, u, v, width, height)) = picture else {
346 break; // source ran out early; the clip list outlives the file
347 };
348 // The planes are borrowed from the decoder (and `Black::picture`
349 // hands the same slice as both u and v), so a grade cannot be
350 // applied in place: it goes onto a copy, which the encoder then
351 // reads instead.
352 let (y, u, v) = match grade.filter(|p| !p.is_identity()) {
353 Some(params) => {
354 let (gy, gu, gv) = &mut graded;
355 gy.clear();
356 gy.extend_from_slice(y);
357 gu.clear();
358 gu.extend_from_slice(u);
359 gv.clear();
360 gv.extend_from_slice(v);
361 crate::color::apply_yuv(&params, gy, gu, gv);
362 (&gy[..], &gu[..], &gv[..])
363 }
364 None => (y, u, v),
365 };
366 // Grade first, place second: the grade is the clip's own pixels
367 // and the bars around them are not the clip (see `scale::Composer`).
368 let (y, u, v, width, height) = canvas.place(y, u, v, width, height);
369 if let Some(au) = encoder.encode(y, u, v, width, height)? {
370 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
371 }
372 done += 1;
373 shared
374 .progress
375 .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);
376 }
377 }
378 while let Some(au) = encoder.drain()? {
379 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
380 }
381 // Progress reads 100% from here on, but nothing is published yet: draining,
382 // the audio pass and `finish` are all still cancellable.
383 cancelled(shared)?;
384
385 let Some(mut muxer) = muxer else {
386 return Err("export produced no coded pictures".into());
387 };
388 if let Some((_, packets)) = audio {
389 for packet in packets {
390 muxer.write_audio_packet(&packet.bytes)?;
391 }
392 }
393 cancelled(shared)?;
394 muxer.finish()?;
395 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
396 Ok(())
397}
398
399/// Where a clip sits on the timeline as a person reads it: `mm:ss`, short
400/// enough to sit inside a refusal and exact enough to go and find the clip.
401/// Not the app's frame-accurate timecode -- an engine refusal is prose, and a
402/// `00:00:12:07` in the middle of a sentence is a serial number.
403fn timecode(frame: u32, fps: f64) -> String {
404 let secs = match fps.is_finite() && fps > 0.0 {
405 true => (f64::from(frame) / fps) as u32,
406 false => 0,
407 };
408 format!("{:02}:{:02}", secs / 60, secs % 60)
409}
410
411/// The audio lanes alone, summed, as a WAV or a FLAC.
412///
413/// Nothing here re-derives the edit: the play lists are
414/// [`Project::audio_segments_from`] and they are handed to the very
415/// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written
416/// is what was heard -- every lane, mixed the same way, gaps included, which
417/// arrive as real silence from that choke point rather than as a hole this would
418/// have to invent.
419///
420/// The length is the *timeline's*: each segment resolves its window to whole
421/// samples on its own, so the sum can miss the timeline by a sample or two, and
422/// a source that runs out early would leave the file short. Both are settled by
423/// one `resize` at the end -- padding with silence, trimming what overshot --
424/// so an exported file is exactly as long as what was edited.
425fn run_audio(
426 project: &Project,
427 meta: &VideoMeta,
428 out: &Path,
429 shared: &Shared,
430 format: Format,
431) -> crate::Result<()> {
432 let sources = project.audio_sources();
433 let segs = project.audio_segments_from(0, meta.frame_rate);
434 // The equalizers with them, so what is written is what is heard down to the
435 // filter: the worker applies them per segment before the lanes are summed
436 // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point
437 // playback's feeder reads from -- there is no second place here that could
438 // apply them differently.
439 let eqs = project.audio_eqs_from(0, meta.frame_rate);
440 let Some((audio, chunks)) = AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs)? else {
441 return Err("this timeline has no audio to export".into());
442 };
443 let channels = usize::from(audio.channels);
444 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate
445 * f64::from(audio.sample_rate))
446 .round() as u64;
447 let total = frames as usize * channels;
448 // ponytail: the whole export sits in memory (4 bytes a sample, so ~23 MB
449 // per minute of 48 kHz stereo). `flacenc::MemSource` wants it that way and
450 // the mp4 path already collects its copied AAC track the same. Upgrade path
451 // is hound's incremental writer plus flacenc's `Source` trait.
452 let mut samples: Vec<i32> = Vec::with_capacity(total);
453 for chunk in chunks {
454 cancelled(shared)?;
455 // Already equalized: the chunks come out of the per-lane workers, which
456 // filter each segment before the mix (`open_mixed_streams_eq` above).
457 samples.extend(
458 chunk
459 .samples
460 .iter()
461 .map(|s| (s.clamp(-1.0, 1.0) * f32::from(i16::MAX)).round() as i32),
462 );
463 let done = samples.len().min(total) * PROGRESS_SCALE as usize / total.max(1);
464 shared.progress.store(done as u32, Ordering::Relaxed);
465 }
466 samples.resize(total, 0);
467 // Written in one go and still cancellable up to here, exactly as the mp4
468 // path is up to its `finish`: the `.part` is what either gets renamed or
469 // deleted.
470 cancelled(shared)?;
471 match format {
472 Format::Wav => write_wav(out, &samples, &audio)?,
473 Format::Flac => write_flac(out, &samples, &audio)?,
474 Format::Mp4 => unreachable!("the mp4 path is `run`"),
475 }
476 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
477 Ok(())
478}
479
480/// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in
481/// this engine, so what the decoder handed over is what the header says.
482fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
483 let mut writer = hound::WavWriter::create(
484 out,
485 hound::WavSpec {
486 channels: audio.channels,
487 sample_rate: audio.sample_rate,
488 bits_per_sample: 16,
489 sample_format: hound::SampleFormat::Int,
490 },
491 )?;
492 for &sample in samples {
493 writer.write_sample(sample as i16)?;
494 }
495 // Not `drop`: this is what rewrites the RIFF sizes in the header, and its
496 // failure is the difference between a finished file and a truncated one.
497 writer.finalize()?;
498 Ok(())
499}
500
501/// The same samples, losslessly compressed. `flacenc`'s errors are flattened to
502/// text: they are not `Send + Sync`, and every one of them fails the export the
503/// same way.
504fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
505 let config = flacenc::config::Encoder::default()
506 .into_verified()
507 .map_err(|(_, e)| format!("flac encoder config: {e}"))?;
508 let source = flacenc::source::MemSource::from_samples(
509 samples,
510 usize::from(audio.channels),
511 16,
512 audio.sample_rate as usize,
513 );
514 let mut stream = flacenc::encode_with_fixed_block_size(&config, source, config.block_size)
515 .map_err(|e| format!("flac encode: {e}"))?;
516 // The block sizes are stated fixed, which is what the frames themselves say
517 // (they are numbered, not sample-addressed). flacenc's single-threaded path
518 // instead writes the *last* frame's length as the minimum, and a short final
519 // frame is the normal case -- a stream whose `streaminfo` then disagrees
520 // with its own blocking strategy. ffmpeg shrugs and plays it; symphonia,
521 // which is this engine's own reader, rejects every frame header and reads
522 // to EOF looking for a good one. Written this way the file reopens here,
523 // which is the only test of an export that counts. (Same value flacenc's
524 // own `par` path writes; the reference encoder does it too.)
525 stream
526 .stream_info_mut()
527 .set_block_sizes(config.block_size, config.block_size)
528 .map_err(|e| format!("flac block size: {e}"))?;
529 let mut sink = flacenc::bitsink::ByteSink::new();
530 stream
531 .write(&mut sink)
532 .map_err(|e| format!("flac write: {e}"))?;
533 std::fs::write(out, sink.as_slice())?;
534 Ok(())
535}
536
537/// The I420 planes of one black picture, allocated once for a whole export: a
538/// gap in the video lane is encoded, not skipped, or every frame after it would
539/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention
540/// [`crate::convert`] decodes with.
541struct Black {
542 y: Vec<u8>,
543 uv: Vec<u8>,
544 width: u32,
545 height: u32,
546}
547
548impl Black {
549 fn new(meta: &VideoMeta) -> Self {
550 let (w, h) = (meta.width as usize, meta.height as usize);
551 Self {
552 y: vec![16; w * h],
553 uv: vec![128; w.div_ceil(2) * h.div_ceil(2)],
554 width: meta.width,
555 height: meta.height,
556 }
557 }
558
559 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
560 (&self.y, &self.uv, &self.uv, self.width, self.height)
561 }
562}
563
564/// `Err` once a cancel has been asked for. Called at every point where the work
565/// left is more than an instant, so an `esc` at 99.9% still stops the export
566/// instead of quietly completing it.
567fn cancelled(shared: &Shared) -> crate::Result<()> {
568 if shared.cancel.load(Ordering::Relaxed) {
569 return Err("export cancelled".into());
570 }
571 Ok(())
572}
573
574/// Writes one access unit, creating the file on the first one -- the parameter
575/// sets for `avcC` only exist once the encoder has coded something. Units with
576/// no coded slice are skipped: a software encoder may hand back an empty buffer
577/// while it buffers, and the muxer rejects a sample that would carry no picture.
578fn write_video(
579 muxer: &mut Option<Mp4Muxer>,
580 out: &Path,
581 meta: &VideoMeta,
582 audio: Option<&AudioParams>,
583 au: &[u8],
584) -> crate::Result<()> {
585 if !crate::mux::has_coded_slice(au) {
586 return Ok(());
587 }
588 let muxer = match muxer {
589 Some(muxer) => muxer,
590 none => {
591 let (sps, pps) = crate::mux::parameter_sets(au)
592 .ok_or("the first coded picture carries no SPS/PPS")?;
593 none.insert(Mp4Muxer::create(
594 out,
595 &VideoParams {
596 width: meta.width,
597 height: meta.height,
598 frame_rate: meta.frame_rate,
599 sps,
600 pps,
601 },
602 audio,
603 )?)
604 }
605 };
606 muxer.write_video_au(au)
607}
608
609fn bitrate_for(meta: &VideoMeta) -> u64 {
610 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;
611 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)
612}
613
614fn forced(var: &str) -> bool {
615 std::env::var_os(var).is_some_and(|v| v == "1")
616}
617
618/// Hardware where it is available, software everywhere else -- chosen once for
619/// the whole export, so the stream never changes encoder mid-file.
620enum Enc {
621 Hw(HwEncoder),
622 Sw {
623 encoder: Encoder,
624 /// The last access unit; owned because `rusty_h264` hands back a `Vec`
625 /// while the plugin lends a slice, and the two have to look alike here.
626 au: Vec<u8>,
627 flushed: bool,
628 },
629}
630
631impl Enc {
632 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
633 // A caller's number goes through the same clamp as the computed one: a
634 // zero bitrate switches the software encoder's lookahead on, which would
635 // break the one-picture-per-call contract `encode` documents below.
636 let bitrate = settings
637 .bitrate
638 .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE));
639 // The plugin wants an exact rational, and the muxer already picks one
640 // that is exact at every rate we can read -- `fps * 1000 / 1000` would
641 // hand 24000/1001 over as a rounded 23.976, which is the same
642 // truncation the container timing had.
643 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
644 if !settings.force_sw
645 && !forced("VE_SW_ENC")
646 && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate)
647 {
648 eprintln!("export encoder: hardware (VA-API plugin)");
649 return Ok(Self::Hw(hw));
650 }
651 eprintln!("export encoder: software (rusty_h264)");
652 let mut cfg = EncoderConfig::new(meta.width as usize, meta.height as usize);
653 cfg.framerate = meta.frame_rate as f32;
654 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;
655 // Two seconds between key frames, and no B-frames on either path: the
656 // muxer times everything by duration alone, which reordering would break.
657 cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32;
658 cfg.bframes = 0;
659 // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same
660 // bitrate, so Fast is what a fallback should be.
661 cfg.preset = Preset::Fast;
662 let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?;
663 Ok(Self::Sw {
664 encoder,
665 au: Vec::new(),
666 flushed: false,
667 })
668 }
669
670 /// One picture in, at most one access unit out.
671 ///
672 /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer
673 /// when its lookahead is active, which would make this "one access unit"
674 /// a lie and every sample duration with it. It is inactive here because
675 /// lookahead needs a zero bitrate and this path is always CBR; a future
676 /// constant-QP mode has to split the buffer per access unit first.
677 fn encode(
678 &mut self,
679 y: &[u8],
680 u: &[u8],
681 v: &[u8],
682 width: u32,
683 height: u32,
684 ) -> crate::Result<Option<&[u8]>> {
685 match self {
686 Self::Hw(hw) => hw.encode(y, u, v, width, height, false),
687 Self::Sw { encoder, au, .. } => {
688 let frame = YuvFrame {
689 width: width as usize,
690 height: height as usize,
691 y: y.to_vec(),
692 u: u.to_vec(),
693 v: v.to_vec(),
694 };
695 *au = encoder
696 .try_encode(&frame)
697 .map_err(|e| format!("software encode: {e}"))?;
698 Ok(Some(&au[..]).filter(|au| !au.is_empty()))
699 }
700 }
701 }
702
703 /// End of stream; call until it returns `None`.
704 fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
705 match self {
706 Self::Hw(hw) => hw.drain(),
707 Self::Sw {
708 encoder,
709 au,
710 flushed,
711 } => {
712 if *flushed {
713 return Ok(None);
714 }
715 *flushed = true;
716 *au = encoder
717 .try_flush()
718 .map_err(|e| format!("software encoder flush: {e}"))?;
719 Ok(Some(&au[..]).filter(|au| !au.is_empty()))
720 }
721 }
722 }
723}
724
725/// I420 straight out of the decoder: the export never converts to BGRA and back,
726/// which would cost two conversions and a generation of colour precision.
727///
728/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`,
729/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to
730/// software: a hardware decode that fails after the first picture fails the
731/// export, which then deletes the half-written file.
732enum ClipDecoder {
733 Hw(HwSession),
734 Sw(SwDecoder),
735}
736
737impl ClipDecoder {
738 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
739 if !forced("VE_SW")
740 && let Some(hw) = HwSession::open_at(path, start_frame)
741 {
742 return Ok(Self::Hw(hw));
743 }
744 Ok(Self::Sw(SwDecoder::open(path, start_frame)?))
745 }
746
747 /// The next picture as tightly packed I420, borrowed until the call after.
748 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
749 match self {
750 Self::Hw(hw) => hw.next_frame(),
751 Self::Sw(sw) => {
752 if !sw.advance()? {
753 return Ok(None);
754 }
755 let frame = sw.frame.as_ref().expect("advance stored a picture");
756 Ok(Some((
757 &frame.y,
758 &frame.u,
759 &frame.v,
760 frame.width as u32,
761 frame.height as u32,
762 )))
763 }
764 }
765 }
766}
767
768struct SwDecoder {
769 demuxer: Demuxer,
770 decoder: Decoder,
771 /// Display index of the next picture the decoder will produce. Signed: a
772 /// sync sample inside what the edit list trims is before frame 0.
773 index: i64,
774 start: u32,
775 frame: Option<YuvFrame>,
776}
777
778impl SwDecoder {
779 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
780 let (meta, mut demuxer) = Demuxer::open(path)?;
781 // The software decoder is H.264-only; an HEVC or VP9 source that got
782 // this far means the plugin refused it, and the export says so instead
783 // of handing those bytes to `rusty_h264`.
784 if meta.codec != crate::demux::Codec::H264 {
785 return Err(meta.codec.needs_plugin().into());
786 }
787 // Decoding restarts at a sync sample, so pictures between it and the in
788 // point are decoded (the target references them) and then dropped.
789 let index = demuxer.seek_to_sync_at_or_before(start_frame);
790 Ok(Self {
791 demuxer,
792 decoder: Decoder::new(),
793 index,
794 start: start_frame,
795 frame: None,
796 })
797 }
798
799 /// Decodes up to and including the next picture at or after the in point,
800 /// leaving it in `frame`. `false` at end of stream.
801 fn advance(&mut self) -> crate::Result<bool> {
802 loop {
803 let Some(au) = self.demuxer.next_access_unit()? else {
804 return Ok(false);
805 };
806 let decoded = self
807 .decoder
808 .decode(&au)
809 .map_err(|e| format!("decode at picture {}: {e}", self.index))?;
810 let Some(yuv) = decoded else { continue };
811 let wanted = self.index >= i64::from(self.start);
812 self.index += 1;
813 if wanted {
814 self.frame = Some(yuv);
815 return Ok(true);
816 }
817 }
818 }
819}
820
821#[cfg(test)]
822mod tests {
823 use super::*;
824
825 #[test]
826 fn bitrate_clamps_at_both_ends() {
827 let meta = |width, height, frame_rate| VideoMeta {
828 width,
829 height,
830 frame_rate,
831 frame_count: 1,
832 codec: crate::demux::Codec::H264,
833 };
834 // 1280 * 720 * 30 * 0.1
835 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
836 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny");
837 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
838 }
839}