forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB08af6bcTahinli3 months ago87 commits

export.rs726 lines, 28.5 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 let lanes = project.audio_segments_from(0, meta.frame_rate);
222 if lanes.len() > 1 {
223 return Err(format!(
224 "this timeline has {} audio lanes and an mp4 export copies one: \
225 there is no AAC encoder here to mix them with. Export WAV or FLAC, \
226 which are mixed, or put the sound on one lane",
227 lanes.len()
228 )
229 .into());
230 }
231 let audio = AudioSession::copy_multi_streams(
232 &project.audio_sources(),
233 &project.segments_from(0, meta.frame_rate),
234 )?;
235 let audio_params = audio.as_ref().map(|(track, _)| AudioParams {
236 freq_index: track.freq_index,
237 chan_conf: track.chan_conf,
238 });
239
240 let mut encoder = Enc::open(meta, settings)?;
241 let mut muxer = None;
242 let mut done = 0u32;
243 let black = Black::new(meta);
244 // Spans, not clips: a gap in the video is part of the timeline and gets
245 // encoded too, as black frames. The picture count is therefore
246 // `timeline_frames` however the lanes are arranged -- and *which* lane a
247 // span comes from is `composite_spans_from`'s answer, the same one playback
248 // shows, so an export is what was watched.
249 for span in project.composite_spans_from(0) {
250 // Every clip reopens its own source file at its own in point; the
251 // encoder is *not* reopened, so the export is one continuous stream
252 // whose GOP boundaries need not line up with the cuts -- nor with the
253 // file boundaries, which are just cuts that change the path.
254 let mut pictures = match span.from {
255 Some((source, in_frame)) => {
256 let entry = sources
257 .get(source)
258 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
259 Some(ClipDecoder::open(&entry.path, in_frame)?)
260 }
261 None => None,
262 };
263 for _ in 0..span.len {
264 cancelled(shared)?;
265 let picture = match &mut pictures {
266 Some(pictures) => pictures.next()?,
267 None => Some(black.picture()),
268 };
269 let Some((y, u, v, width, height)) = picture else {
270 break; // source ran out early; the clip list outlives the file
271 };
272 if let Some(au) = encoder.encode(y, u, v, width, height)? {
273 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
274 }
275 done += 1;
276 shared
277 .progress
278 .store(done * PROGRESS_SCALE / total.max(1), Ordering::Relaxed);
279 }
280 }
281 while let Some(au) = encoder.drain()? {
282 write_video(&mut muxer, out, meta, audio_params.as_ref(), au)?;
283 }
284 // Progress reads 100% from here on, but nothing is published yet: draining,
285 // the audio pass and `finish` are all still cancellable.
286 cancelled(shared)?;
287
288 let Some(mut muxer) = muxer else {
289 return Err("export produced no coded pictures".into());
290 };
291 if let Some((_, packets)) = audio {
292 for packet in packets {
293 muxer.write_audio_packet(&packet.bytes)?;
294 }
295 }
296 cancelled(shared)?;
297 muxer.finish()?;
298 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
299 Ok(())
300}
301
302/// The audio lanes alone, summed, as a WAV or a FLAC.
303///
304/// Nothing here re-derives the edit: the play lists are
305/// [`Project::audio_segments_from`] and they are handed to the very
306/// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written
307/// is what was heard -- every lane, mixed the same way, gaps included, which
308/// arrive as real silence from that choke point rather than as a hole this would
309/// have to invent.
310///
311/// The length is the *timeline's*: each segment resolves its window to whole
312/// samples on its own, so the sum can miss the timeline by a sample or two, and
313/// a source that runs out early would leave the file short. Both are settled by
314/// one `resize` at the end -- padding with silence, trimming what overshot --
315/// so an exported file is exactly as long as what was edited.
316fn run_audio(
317 project: &Project,
318 meta: &VideoMeta,
319 out: &Path,
320 shared: &Shared,
321 format: Format,
322) -> crate::Result<()> {
323 let sources = project.audio_sources();
324 let segs = project.audio_segments_from(0, meta.frame_rate);
325 let Some((audio, chunks)) = AudioSession::open_mixed_streams(&sources, &segs)? else {
326 return Err("this timeline has no audio to export".into());
327 };
328 let channels = usize::from(audio.channels);
329 let frames = (f64::from(project.timeline_frames()) / meta.frame_rate
330 * f64::from(audio.sample_rate))
331 .round() as u64;
332 let total = frames as usize * channels;
333 // ponytail: the whole export sits in memory (4 bytes a sample, so ~23 MB
334 // per minute of 48 kHz stereo). `flacenc::MemSource` wants it that way and
335 // the mp4 path already collects its copied AAC track the same. Upgrade path
336 // is hound's incremental writer plus flacenc's `Source` trait.
337 let mut samples: Vec<i32> = Vec::with_capacity(total);
338 for chunk in chunks {
339 cancelled(shared)?;
340 // ponytail: the per-segment EQ goes here -- `EqState::process` on this
341 // same interleaved f32 buffer, before the quantisation below, which is
342 // the point playback's feeder will call it from too. Not wired: the EQ
343 // slice owns that, this is only the seat kept for it.
344 samples.extend(
345 chunk
346 .samples
347 .iter()
348 .map(|s| (s.clamp(-1.0, 1.0) * f32::from(i16::MAX)).round() as i32),
349 );
350 let done = samples.len().min(total) * PROGRESS_SCALE as usize / total.max(1);
351 shared.progress.store(done as u32, Ordering::Relaxed);
352 }
353 samples.resize(total, 0);
354 // Written in one go and still cancellable up to here, exactly as the mp4
355 // path is up to its `finish`: the `.part` is what either gets renamed or
356 // deleted.
357 cancelled(shared)?;
358 match format {
359 Format::Wav => write_wav(out, &samples, &audio)?,
360 Format::Flac => write_flac(out, &samples, &audio)?,
361 Format::Mp4 => unreachable!("the mp4 path is `run`"),
362 }
363 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
364 Ok(())
365}
366
367/// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in
368/// this engine, so what the decoder handed over is what the header says.
369fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
370 let mut writer = hound::WavWriter::create(
371 out,
372 hound::WavSpec {
373 channels: audio.channels,
374 sample_rate: audio.sample_rate,
375 bits_per_sample: 16,
376 sample_format: hound::SampleFormat::Int,
377 },
378 )?;
379 for &sample in samples {
380 writer.write_sample(sample as i16)?;
381 }
382 // Not `drop`: this is what rewrites the RIFF sizes in the header, and its
383 // failure is the difference between a finished file and a truncated one.
384 writer.finalize()?;
385 Ok(())
386}
387
388/// The same samples, losslessly compressed. `flacenc`'s errors are flattened to
389/// text: they are not `Send + Sync`, and every one of them fails the export the
390/// same way.
391fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
392 let config = flacenc::config::Encoder::default()
393 .into_verified()
394 .map_err(|(_, e)| format!("flac encoder config: {e}"))?;
395 let source = flacenc::source::MemSource::from_samples(
396 samples,
397 usize::from(audio.channels),
398 16,
399 audio.sample_rate as usize,
400 );
401 let mut stream = flacenc::encode_with_fixed_block_size(&config, source, config.block_size)
402 .map_err(|e| format!("flac encode: {e}"))?;
403 // The block sizes are stated fixed, which is what the frames themselves say
404 // (they are numbered, not sample-addressed). flacenc's single-threaded path
405 // instead writes the *last* frame's length as the minimum, and a short final
406 // frame is the normal case -- a stream whose `streaminfo` then disagrees
407 // with its own blocking strategy. ffmpeg shrugs and plays it; symphonia,
408 // which is this engine's own reader, rejects every frame header and reads
409 // to EOF looking for a good one. Written this way the file reopens here,
410 // which is the only test of an export that counts. (Same value flacenc's
411 // own `par` path writes; the reference encoder does it too.)
412 stream
413 .stream_info_mut()
414 .set_block_sizes(config.block_size, config.block_size)
415 .map_err(|e| format!("flac block size: {e}"))?;
416 let mut sink = flacenc::bitsink::ByteSink::new();
417 stream
418 .write(&mut sink)
419 .map_err(|e| format!("flac write: {e}"))?;
420 std::fs::write(out, sink.as_slice())?;
421 Ok(())
422}
423
424/// The I420 planes of one black picture, allocated once for a whole export: a
425/// gap in the video lane is encoded, not skipped, or every frame after it would
426/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention
427/// [`crate::convert`] decodes with.
428struct Black {
429 y: Vec<u8>,
430 uv: Vec<u8>,
431 width: u32,
432 height: u32,
433}
434
435impl Black {
436 fn new(meta: &VideoMeta) -> Self {
437 let (w, h) = (meta.width as usize, meta.height as usize);
438 Self {
439 y: vec![16; w * h],
440 uv: vec![128; w.div_ceil(2) * h.div_ceil(2)],
441 width: meta.width,
442 height: meta.height,
443 }
444 }
445
446 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
447 (&self.y, &self.uv, &self.uv, self.width, self.height)
448 }
449}
450
451/// `Err` once a cancel has been asked for. Called at every point where the work
452/// left is more than an instant, so an `esc` at 99.9% still stops the export
453/// instead of quietly completing it.
454fn cancelled(shared: &Shared) -> crate::Result<()> {
455 if shared.cancel.load(Ordering::Relaxed) {
456 return Err("export cancelled".into());
457 }
458 Ok(())
459}
460
461/// Writes one access unit, creating the file on the first one -- the parameter
462/// sets for `avcC` only exist once the encoder has coded something. Units with
463/// no coded slice are skipped: a software encoder may hand back an empty buffer
464/// while it buffers, and the muxer rejects a sample that would carry no picture.
465fn write_video(
466 muxer: &mut Option<Mp4Muxer>,
467 out: &Path,
468 meta: &VideoMeta,
469 audio: Option<&AudioParams>,
470 au: &[u8],
471) -> crate::Result<()> {
472 if !crate::mux::has_coded_slice(au) {
473 return Ok(());
474 }
475 let muxer = match muxer {
476 Some(muxer) => muxer,
477 none => {
478 let (sps, pps) = crate::mux::parameter_sets(au)
479 .ok_or("the first coded picture carries no SPS/PPS")?;
480 none.insert(Mp4Muxer::create(
481 out,
482 &VideoParams {
483 width: meta.width,
484 height: meta.height,
485 frame_rate: meta.frame_rate,
486 sps,
487 pps,
488 },
489 audio,
490 )?)
491 }
492 };
493 muxer.write_video_au(au)
494}
495
496fn bitrate_for(meta: &VideoMeta) -> u64 {
497 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;
498 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)
499}
500
501fn forced(var: &str) -> bool {
502 std::env::var_os(var).is_some_and(|v| v == "1")
503}
504
505/// Hardware where it is available, software everywhere else -- chosen once for
506/// the whole export, so the stream never changes encoder mid-file.
507enum Enc {
508 Hw(HwEncoder),
509 Sw {
510 encoder: Encoder,
511 /// The last access unit; owned because `rusty_h264` hands back a `Vec`
512 /// while the plugin lends a slice, and the two have to look alike here.
513 au: Vec<u8>,
514 flushed: bool,
515 },
516}
517
518impl Enc {
519 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
520 // A caller's number goes through the same clamp as the computed one: a
521 // zero bitrate switches the software encoder's lookahead on, which would
522 // break the one-picture-per-call contract `encode` documents below.
523 let bitrate = settings
524 .bitrate
525 .map_or_else(|| bitrate_for(meta), |b| b.clamp(MIN_BITRATE, MAX_BITRATE));
526 // The plugin wants an exact rational, and the muxer already picks one
527 // that is exact at every rate we can read -- `fps * 1000 / 1000` would
528 // hand 24000/1001 over as a rounded 23.976, which is the same
529 // truncation the container timing had.
530 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
531 if !settings.force_sw
532 && !forced("VE_SW_ENC")
533 && let Some(hw) = HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate)
534 {
535 eprintln!("export encoder: hardware (VA-API plugin)");
536 return Ok(Self::Hw(hw));
537 }
538 eprintln!("export encoder: software (rusty_h264)");
539 let mut cfg = EncoderConfig::new(meta.width as usize, meta.height as usize);
540 cfg.framerate = meta.frame_rate as f32;
541 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;
542 // Two seconds between key frames, and no B-frames on either path: the
543 // muxer times everything by duration alone, which reordering would break.
544 cfg.gop_size = (meta.frame_rate * 2.0).round().max(1.0) as u32;
545 cfg.bframes = 0;
546 // S1 measured Fast at 1.30x realtime and Balanced at 0.46x for the same
547 // bitrate, so Fast is what a fallback should be.
548 cfg.preset = Preset::Fast;
549 let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?;
550 Ok(Self::Sw {
551 encoder,
552 au: Vec::new(),
553 flushed: false,
554 })
555 }
556
557 /// One picture in, at most one access unit out.
558 ///
559 /// ponytail: `rusty_h264` buffers a whole GOP and returns it in one buffer
560 /// when its lookahead is active, which would make this "one access unit"
561 /// a lie and every sample duration with it. It is inactive here because
562 /// lookahead needs a zero bitrate and this path is always CBR; a future
563 /// constant-QP mode has to split the buffer per access unit first.
564 fn encode(
565 &mut self,
566 y: &[u8],
567 u: &[u8],
568 v: &[u8],
569 width: u32,
570 height: u32,
571 ) -> crate::Result<Option<&[u8]>> {
572 match self {
573 Self::Hw(hw) => hw.encode(y, u, v, width, height, false),
574 Self::Sw { encoder, au, .. } => {
575 let frame = YuvFrame {
576 width: width as usize,
577 height: height as usize,
578 y: y.to_vec(),
579 u: u.to_vec(),
580 v: v.to_vec(),
581 };
582 *au = encoder
583 .try_encode(&frame)
584 .map_err(|e| format!("software encode: {e}"))?;
585 Ok(Some(&au[..]).filter(|au| !au.is_empty()))
586 }
587 }
588 }
589
590 /// End of stream; call until it returns `None`.
591 fn drain(&mut self) -> crate::Result<Option<&[u8]>> {
592 match self {
593 Self::Hw(hw) => hw.drain(),
594 Self::Sw {
595 encoder,
596 au,
597 flushed,
598 } => {
599 if *flushed {
600 return Ok(None);
601 }
602 *flushed = true;
603 *au = encoder
604 .try_flush()
605 .map_err(|e| format!("software encoder flush: {e}"))?;
606 Ok(Some(&au[..]).filter(|au| !au.is_empty()))
607 }
608 }
609 }
610}
611
612/// I420 straight out of the decoder: the export never converts to BGRA and back,
613/// which would cost two conversions and a generation of colour precision.
614///
615/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`,
616/// which only speaks BGRA. Unlike playback there is no mid-clip fallback to
617/// software: a hardware decode that fails after the first picture fails the
618/// export, which then deletes the half-written file.
619enum ClipDecoder {
620 Hw(HwSession),
621 Sw(SwDecoder),
622}
623
624impl ClipDecoder {
625 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
626 if !forced("VE_SW")
627 && let Some(hw) = HwSession::open_at(path, start_frame)
628 {
629 return Ok(Self::Hw(hw));
630 }
631 Ok(Self::Sw(SwDecoder::open(path, start_frame)?))
632 }
633
634 /// The next picture as tightly packed I420, borrowed until the call after.
635 fn next(&mut self) -> crate::Result<Option<(&[u8], &[u8], &[u8], u32, u32)>> {
636 match self {
637 Self::Hw(hw) => hw.next_frame(),
638 Self::Sw(sw) => {
639 if !sw.advance()? {
640 return Ok(None);
641 }
642 let frame = sw.frame.as_ref().expect("advance stored a picture");
643 Ok(Some((
644 &frame.y,
645 &frame.u,
646 &frame.v,
647 frame.width as u32,
648 frame.height as u32,
649 )))
650 }
651 }
652 }
653}
654
655struct SwDecoder {
656 demuxer: Demuxer,
657 decoder: Decoder,
658 /// Display index of the next picture the decoder will produce. Signed: a
659 /// sync sample inside what the edit list trims is before frame 0.
660 index: i64,
661 start: u32,
662 frame: Option<YuvFrame>,
663}
664
665impl SwDecoder {
666 fn open(path: &Path, start_frame: u32) -> crate::Result<Self> {
667 let (meta, mut demuxer) = Demuxer::open(path)?;
668 // The software decoder is H.264-only; an HEVC or VP9 source that got
669 // this far means the plugin refused it, and the export says so instead
670 // of handing those bytes to `rusty_h264`.
671 if meta.codec != crate::demux::Codec::H264 {
672 return Err(meta.codec.needs_plugin().into());
673 }
674 // Decoding restarts at a sync sample, so pictures between it and the in
675 // point are decoded (the target references them) and then dropped.
676 let index = demuxer.seek_to_sync_at_or_before(start_frame);
677 Ok(Self {
678 demuxer,
679 decoder: Decoder::new(),
680 index,
681 start: start_frame,
682 frame: None,
683 })
684 }
685
686 /// Decodes up to and including the next picture at or after the in point,
687 /// leaving it in `frame`. `false` at end of stream.
688 fn advance(&mut self) -> crate::Result<bool> {
689 loop {
690 let Some(au) = self.demuxer.next_access_unit()? else {
691 return Ok(false);
692 };
693 let decoded = self
694 .decoder
695 .decode(&au)
696 .map_err(|e| format!("decode at picture {}: {e}", self.index))?;
697 let Some(yuv) = decoded else { continue };
698 let wanted = self.index >= i64::from(self.start);
699 self.index += 1;
700 if wanted {
701 self.frame = Some(yuv);
702 return Ok(true);
703 }
704 }
705 }
706}
707
708#[cfg(test)]
709mod tests {
710 use super::*;
711
712 #[test]
713 fn bitrate_clamps_at_both_ends() {
714 let meta = |width, height, frame_rate| VideoMeta {
715 width,
716 height,
717 frame_rate,
718 frame_count: 1,
719 codec: crate::demux::Codec::H264,
720 };
721 // 1280 * 720 * 30 * 0.1
722 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
723 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny");
724 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
725 }
726}