forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa2ebaacTahinli3 months ago107 commits

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