forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB5d650d9Tahinli16 days ago1046 commits

export.rs12218 lines, 552.1 KiBHistoryRawDownload
1//! Export: the edit list rendered back out as one mp4 (H.264, AV1 or HEVC) or
2//! one Matroska file (AV1 or HEVC) — or, picture left behind, as one WAV, FLAC,
3//! MP3 or Ogg Vorbis of the timeline's audio alone.
4//!
5//! The HEVC pair codes **I+P GOPs** by default, from `ec-h265`, the project's
6//! own pure-Rust HEVC encoder: an IDR a second and predicted pictures between
7//! them, rate-controlled when the settings carry a bitrate and at constant QP
8//! when they do not. [`ExportSettings::intra_only`] makes every picture an IDR
9//! instead -- an intraframe master in the family of ProRes and DNxHD, large
10//! files and every frame a cut point.
11//!
12//! Picture and sound are both **copied wherever a copy says exactly what the
13//! timeline says** — a copy is exact, free and never a generation of loss. For
14//! the sound that is packet for packet ([`copy_audio`]); for the picture it is
15//! block for block out of a Matroska source into a Matroska file ([`CopyPlan`]),
16//! which is what makes a cut in a two-hour film cost the reading of it rather
17//! than the re-encoding of it. The picture's copy is all-or-nothing per export,
18//! because a copied span and an encoded one cannot share one track: what it
19//! needs of a cut is that it lands on a sync point, and everything else — a
20//! grade, a speed, a gap, a source of another size or codec, an mp4 — goes
21//! through the encoder exactly as it always did. Where the *sound* cannot be
22//! copied — a second audio lane to mix in, a speeded clip, an
23//! equalized one, a source that is not AAC inside an mp4's own sample table —
24//! the sound is decoded, mixed and encoded again with `ec-aac`
25//! ([`encode_audio`]). The audio-only formats have no such split: `ec-riff` writes
26//! PCM, `ec-flac` encodes FLAC, `ec-mp3` encodes MP3 and `ec-vorbis`
27//! encodes Vorbis, so those are always *decoded* out of the timeline. The worker owns everything: the caller gets an
28//! [`ExportHandle`] and polls it from its render loop.
29//!
30//! **Every video format here carries the timeline's sound**, in whichever
31//! container: the mp4 muxer writes an AAC track and so does the Matroska one.
32//! Nothing is written picture-only and nothing is left silent without saying so
33//! — the only sound that does not come out is sound this engine cannot decode at
34//! all (Opus and AC-3 inside a Matroska file), and that is an error by name.
35//!
36//! A **speeded** clip splits along the same line, and for the same reason. The
37//! picture is re-encoded, so the frame walk honours a rate: it takes the source
38//! frame each timeline frame shows ([`crate::project::Speed::source_at`], the
39//! very frame preview holds there) and encodes a held one again rather than
40//! decoding it twice. A clip whose *file* was shot at another rate than the
41//! timeline goes through the same walk with one more conversion on the end
42//! ([`crate::project::Rate`]), so it is encoded at the speed it was shot at.
43//! The sound is *copied* unless something forces a decode, and a packet carries
44//! no rate — so a speeded lane is one of the things that forces one
45//! ([`copy_audio`]) rather than being written out at 1.00x under a re-timed
46//! picture. The audio-only formats are decoded and resampled, so they honour a
47//! rate like the picture does.
48//!
49//! Nothing partial survives a failure: the worker writes to `<out>.part` and
50//! renames it onto `out` only once the file is closed and complete, so the
51//! output either does not exist or is finished — there is no window where a
52//! half-written `.export.mp4` is sitting there looking playable. Cancel and
53//! every error path delete the `.part`. A killed *process* leaves the `.part`
54//! behind (only in-process cleanup is promised), which is an orphan a user can
55//! delete rather than a file that plays for two seconds and stops.
56
57use std::collections::VecDeque;
58use std::fs::File;
59use std::io::{BufWriter, Write};
60use std::path::{Path, PathBuf};
61use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
62use std::sync::mpsc::{Receiver, SyncSender, sync_channel};
63use std::sync::{Arc, Mutex};
64use std::thread;
65
66use ec_av1::encode::Picture as Av1Picture;
67use ec_av1::stream::decode_stream_with;
68use ec_core::frame::VideoFrame;
69use ec_core::registry::Decoder as _;
70use ec_core::registry::{AudioParameters, CodecId, CodecParameters, MediaParameters, StreamInfo};
71use ec_core::{Buf, ChannelLayout, Error as Av1Error, Muxer as _, Packet, TimeBase};
72use ec_h264::{Encoder, EncoderConfig, H264Decoder, PictureView, Preset};
73use ec_h265::encoder::{Encoder as HevcEncoder, EncoderConfig as HevcEncoderConfig, RateControl};
74use ec_h265_syntax::vui::{
75 ColourDescription as HevcColourDescription, VideoSignalType as HevcVideoSignalType,
76};
77
78use crate::audio::{AudioMeta, AudioSession};
79use crate::colorspace::{Chroma, ColorDescription, Matrix, Tags, Transfer};
80use crate::decode::{I420, Pulled, Wide};
81use crate::demux::{Codec, Demuxer, MkvDemuxer, Rotation, VideoMeta};
82use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession};
83use crate::hwproc::SeatRate;
84use crate::mux::{
85 AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams,
86};
87use crate::project::{Deinterlace, Lane, LaneKind, Project, Rate, Speed, Title};
88use crate::scale::{Composer, FitPolicy, Sample};
89use crate::subtitle::{Cue, SubtitleTrack};
90use crate::text::{Overlay, Place, TextStyle, overlay, overlay_blocks};
91use crate::titleanim::Motion;
92use crate::tonemap::{self, ToneMapper};
93use crate::transform::TransformParams;
94
95/// Progress is reported in permille: an atomic integer the render loop can read
96/// without a lock, fine enough for any progress bar.
97pub(crate) const PROGRESS_SCALE: u32 = 1_000;
98
99/// The head of the bar the *sound* owns, before a picture is written at all.
100/// The mix is decoded, encoded and measured before the muxer exists ([`run`]
101/// says why), and on a feature film that is a minute or two in which a bar
102/// pinned at zero is the only thing on screen -- which reads as an export that
103/// has hung. Small, because the picture is still nearly all of the work.
104pub(crate) const AUDIO_BAND: u32 = PROGRESS_SCALE / 20;
105
106/// Where the bar stands with `done` of `total` pictures written: the sound's
107/// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is
108/// left rather than starting again from zero.
109fn picture_progress(done: u32, total: u32) -> u32 {
110 // In `u64`: this is a picture count times a permille, and a film past
111 // ~4.5 M pictures (42 hours at 30 fps) overflowed the `u32` this used to be
112 // computed in -- a panic in debug inside the export thread, which a caller
113 // reads as `export worker panicked` on a file that was never written, and a
114 // bar that thrashed in release. The result is under the scale by
115 // construction, so the narrowing back is exact.
116 let band = u64::from(PROGRESS_SCALE - AUDIO_BAND);
117 let done = u64::from(done.min(total));
118 AUDIO_BAND + (done * band / u64::from(total.max(1))) as u32
119}
120
121/// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands
122/// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%.
123const BITS_PER_PIXEL: f64 = 0.1;
124/// The floor under a rate somebody *asked* for, and under the derived one: 100
125/// kbps, so a sub-Mbps budget -- a lo-fi delivery, a tiny picture, a
126/// phone-rate master -- is a rate this export is written at. A megabit was the
127/// old floor, and it silently rewrote every such ask. Nothing below this is
128/// worth a container: the sound's own row starts at 128 kbps.
129const MIN_BITRATE: u64 = 100_000;
130const MAX_BITRATE: u64 = 20_000_000;
131
132/// The ceiling on a bitrate somebody *asked* for, which is a different question
133/// from where the derived one stops: [`MAX_BITRATE`] is the top of the automatic
134/// figure's sane range, and a rate a person typed is not that program's guess to
135/// bound. Nothing in either encoder objects to it -- the VA-API seat takes a
136/// `u64` and the software ones a `u32`/`i32`, all of which hold this with room
137/// -- so the old shared ceiling was only ever the auto range wearing two hats.
138const MAX_EXPLICIT_BITRATE: u64 = 50_000_000;
139
140/// The rates the sound may be coded at, smallest first -- what a front-end
141/// offers and what [`ExportSettings::audio_kbps`] is clamped into. Every one of
142/// them is a legal MPEG-1 Layer III value, so the MP3 path writes the figure it
143/// was given rather than the nearest one `ec-mp3` snaps to.
144pub const AUDIO_KBPS: [u32; 4] = [128, 192, 256, 320];
145
146/// The sound rate AAC alone may be coded at, above the rows [`AUDIO_KBPS`] offers.
147pub const AAC_MAX_KBPS: u32 = 384;
148
149const QP_SOFTWARE_REFUSAL: &str = "a constant QP (qp) is written by the hardware seat and the software HEVC encoders only: pass seat hardware for this format, or bitrate_kbps for a fixed rate";
150
151/// What the sound is coded at when nobody picked: the rate this project wrote
152/// before the choice existed. 256 and not the encoders' own 128, because an
153/// export is a master a person edits from again and this is a second lossy
154/// generation over sources that may already have been one -- measured on the
155/// suite's fixtures, an untouched clip re-encoded moves 0.15 dB here against
156/// 0.46 dB at 128, and 32 KB/s beside a 2.76 Mbps picture is not a size anyone
157/// is counting.
158pub const DEFAULT_AUDIO_KBPS: u32 = 256;
159
160/// `rav1e`'s fastest preset. Anything slower is minutes per second of timeline
161/// on a build with no assembly, which is what this one is.
162const AV1_SPEED: u8 = 10;
163
164/// Tiles per software AV1 frame, the knob that spreads one picture over the
165/// cores (see `Enc::open_av1`). A power of two; `rav1e` rounds it to a legal
166/// layout for the frame size.
167const AV1_TILES: usize = 32;
168
169/// How many lane encoders the intra HEVC seat spreads frames across. Twelve
170/// is where the 2026-08-11 bench stopped scaling on this box; more lanes
171/// only holds more decoded frames in memory. The cores the lanes leave over
172/// go to the wavefront inside each lane's encoder.
173const HEVC_LANES: usize = 12;
174/// Bits per pixel an intra HEVC encoder spends at QP 27: 0.607 at 720p and
175/// 0.586 at 1080p on the old seat's bench, and `ec-h265` lands on the same
176/// 0.6 anchor. What [`hevc_qp`] maps a bitrate row through.
177const HEVC_BPP_AT_27: f64 = 0.6;
178/// The band [`hevc_qp`] is clamped into, for the reason stated there.
179const HEVC_QP_MIN: i32 = 22;
180const HEVC_QP_MAX: i32 = 40;
181/// The quantiser the I+P GOP seat codes at when no bitrate is given: its
182/// automatic quality, a constant-quality default in its own right. It is not
183/// [`hevc_qp`]: that maps the automatic *bitrate* through the intra anchor
184/// ([`HEVC_BPP_AT_27`]), which is measured on intra pictures. P pictures cost
185/// far fewer bits, so the same mapping pushed a 1080p30 GOP export to the clamp
186/// at QP 40 (652 kb/s at 31.8 dB mean PSNR on a 33 s timeline).
187///
188/// 28 is chosen so that a default is never visibly worse than the H.264 default
189/// on any source, and it matches x265's CRF 28 convention. Measured on 1080p30
190/// 10 s sources (kbps, PSNR dB against the source):
191///
192/// | source | H.264 default | QP 28 | QP 31 |
193/// |----------|---------------|----------------|----------------|
194/// | testsrc2 | 6298, 44.08 | 6390, 41.84 | 4080, 39.50 |
195/// | mandel | 6246, 35.98 | 11365, 38.37 | 6742, 36.21 |
196///
197/// At QP 28 the GOP default is 2.2 dB under H.264 on testsrc2 at equal size
198/// (+1.5%), and 2.4 dB above it on mandel at +82% bytes. QP 31 is 4.6 dB under
199/// on testsrc2, which is visibly worse on synthetic content, so it is not the
200/// default. File size is traded for never being far below H.264 quality: on
201/// natural content the GOP default is larger than the H.264 file.
202const HEVC_GOP_QP: i32 = 28;
203
204/// What an export writes. H.264-in-mp4, AV1 and HEVC -- each of the last two in
205/// Matroska or in mp4, the user's pick of container -- are the *video* pairs
206/// with both an encoder and a decoder under this project's no-install rule, and
207/// pure-Rust encoder: `ec-riff`, `ec-flac`, `ec-mp3` and `ec-vorbis`. Opus
208/// still has none as a *file* -- the Matroska seat is `ec-opus`, but a standalone
209/// `.opus` row this project does not offer.
210/// (AAC has one too -- `ec-aac`, which is what a re-encoded video track's
211/// sound leaves through -- but AAC is a container's own audio, never a file of
212/// its own here.) VP9 and VP8 are the
213/// codecs that come in through the plugin and stop there, HEVC having
214/// gained an encoder (an intra-only one, which the rows say). A front-end says
215/// so rather than hiding the row.
216///
217/// **Every video format carries sound.** Which way it carries it is the only
218/// difference: copied packet for packet where a copy can say what the timeline
219/// says, decoded and encoded again ([`encode_audio`]) where it cannot.
220#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
221pub enum Format {
222 /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too,
223 /// where a copy could not carry the edit (a second audio lane to mix in, a
224 /// speeded clip, an equalized one, a source no mp4 sample table holds).
225 #[default]
226 Mp4,
227 /// AV1 in Matroska, with the timeline's AAC beside it: this engine's
228 /// Matroska writer carries an audio track ([`crate::mux::MkvMuxer`]) and its
229 /// reader reads one back, symphonia's `mkv` reader being what
230 /// `audio::Track::open` opens it with.
231 Av1,
232 /// The same AV1 stream in an mp4, for everything that plays mp4 and not
233 /// Matroska. The sample entry `mp4 0.14` cannot write is written by hand
234 /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own,
235 /// unchanged.
236 Av1Mp4,
237 /// HEVC in Matroska: I+P GOPs from `ec-h265` ([`Enc::open_hevc`]), or with
238 /// [`ExportSettings::intra_only`] an intraframe master, every frame an IDR.
239 Hevc,
240 /// The same HEVC stream in an mp4 (`hvc1`), for everything that plays mp4
241 /// and not Matroska -- the AV1 pair's split, for the same reason.
242 HevcMp4,
243 /// AV1 in WebM, with Opus beside it: the open web's container. The same
244 /// AV1 encoder as [`Format::Av1`]; the sound is always Opus, mixed at 48 kHz
245 /// ([`start`]) because WebM carries no other audio, and the file carries no
246 /// subtitles ([`planned_subtitles`] says so). No copy path: a source's own
247 /// packets are not AV1 or Opus in general.
248 Webm,
249 /// The audio lanes alone, 16-bit PCM.
250 Wav,
251 /// The audio lanes alone, losslessly compressed.
252 Flac,
253 /// The audio lanes alone, MPEG-1 Layer III CBR (`ec-mp3`) at the rate
254 /// [`ExportSettings::audio_kbps`] asks for.
255 Mp3,
256 /// The audio lanes alone, Vorbis I in an Ogg container -- `ec-vorbis`
257 /// encoding, `ec-ogg` paging. Quality-coded and not rate-coded, which
258 /// is why [`audio_rate_refusal`] takes the Sound row away here: see
259 /// [`VORBIS_QUALITY`] for the operating point and how it was measured.
260 Ogg,
261 /// The audio lanes alone as AAC in an mp4 box with the `M4A ` brand -- the
262 /// file a player picks an audio parser for. The same track an mp4 of a
263 /// timeline with no picture carries ([`run_aac`]), which is an [`Format::Mp4`]
264 /// and not this one: the difference is the brand alone.
265 M4a,
266 /// The audio lanes alone as Opus in Ogg (RFC 7845), mixed at 48 kHz and
267 /// coded by `ec-opus` at [`ExportSettings::audio_kbps`]
268 /// ([`crate::opus_write`]).
269 Opus,
270 /// Apple ProRes in a QuickTime `.mov`, the profile in
271 /// [`ExportSettings::prores_profile`]: always 10-bit, software (`ec-prores`),
272 /// every frame a key frame, progressive, no alpha. The sound is 16-bit
273 /// little-endian PCM (`sowt`) at the timeline's rate, not AAC. See
274 /// [`crate::prores_out`] for the chroma upsampling the 4:2:0 compositor needs.
275 ProRes,
276 /// A numbered run of PNG pictures, one per timeline frame of the range (or the
277 /// whole timeline): `<folder name>_00001.png` onward, written into the folder the
278 /// export names. No sound. Each picture is the project's own size, with titles and
279 /// burnt captions as the export draws them ([`compose_at_with`]).
280 PngSequence,
281 /// One PNG picture: the frame at the start of the range (frame 0 without one), at
282 /// the project's own size. The poster frame. No sound.
283 Still,
284 /// An animated GIF of the range, at [`ExportSettings::gif`]. Not written yet: the
285 /// GIF encoder is still to come, so this format refuses by name ([`GifWriter`]).
286 Gif,
287}
288
289impl Format {
290 /// The extension a file of this format is named with -- a front-end builds
291 /// the destination path from it, so the name never disagrees with the bytes.
292 pub fn ext(self) -> &'static str {
293 match self {
294 Self::Mp4 | Self::Av1Mp4 | Self::HevcMp4 => "mp4",
295 Self::Av1 | Self::Hevc => "mkv",
296 Self::Webm => "webm",
297 Self::Wav => "wav",
298 Self::Flac => "flac",
299 Self::Mp3 => "mp3",
300 Self::Ogg => "ogg",
301 Self::M4a => "m4a",
302 Self::Opus => "opus",
303 Self::ProRes => "mov",
304 Self::PngSequence | Self::Still => "png",
305 Self::Gif => "gif",
306 }
307 }
308
309 /// Whether this format carries the picture. The bitrate settings are video
310 /// settings and mean nothing to the audio-only ones.
311 pub fn has_video(self) -> bool {
312 matches!(
313 self,
314 Self::Mp4 | Self::Av1 | Self::Av1Mp4 | Self::Hevc | Self::HevcMp4 | Self::Webm | Self::ProRes
315 )
316 }
317
318 /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs
319 /// and which of the two AV1 containers is being written are separate
320 /// questions, and this is the first.
321 pub fn is_av1(self) -> bool {
322 matches!(self, Self::Av1 | Self::Av1Mp4 | Self::Webm)
323 }
324
325 /// The same question for HEVC, and the same answer for both its containers:
326 /// one encoder, two boxes to put its stream in.
327 pub fn is_hevc(self) -> bool {
328 matches!(self, Self::Hevc | Self::HevcMp4)
329 }
330
331 /// Whether the file is an mp4 box file (mp4, hevc-mp4, av1-mp4 or m4a), which is what faststart lays out.
332 pub fn is_mp4_family(self) -> bool {
333 matches!(self, Self::Mp4 | Self::HevcMp4 | Self::Av1Mp4 | Self::M4a)
334 }
335
336 /// Whether the picture is ProRes in a QuickTime file ([`Format::ProRes`]).
337 pub fn is_prores(self) -> bool {
338 self == Self::ProRes
339 }
340
341 /// Whether the file is a Matroska one. Only that container carries this
342 /// project's Opus track ([`encode_opus`]): an mp4 may hold Opus by spec, but
343 /// the crate that writes the mp4s here has no sample entry for it, so the
344 /// mp4 formats stay on AAC and say so.
345 fn is_mkv(self) -> bool {
346 matches!(self, Self::Av1 | Self::Hevc | Self::Webm)
347 }
348
349 /// What the format is called where a refusal names it.
350 pub fn name(self) -> &'static str {
351 match self {
352 Self::Mp4 => "an mp4",
353 Self::Webm => "a WebM",
354 Self::Av1 => "an AV1 Matroska",
355 Self::Av1Mp4 => "an AV1 mp4",
356 Self::Hevc => "an HEVC Matroska",
357 Self::HevcMp4 => "an HEVC mp4",
358 Self::Wav => "a WAV",
359 Self::Flac => "a FLAC",
360 Self::Mp3 => "an MP3",
361 Self::Ogg => "an Ogg Vorbis",
362 Self::M4a => "an M4A",
363 Self::Opus => "an Ogg Opus",
364 Self::ProRes => "a ProRes QuickTime",
365 Self::PngSequence => "a PNG sequence",
366 Self::Still => "a PNG still",
367 Self::Gif => "an animated GIF",
368 }
369 }
370}
371
372/// Which encoder writes the picture, as a person picks it on a card. Three
373/// discrete choices and not a switch, because "whatever is best" and "the GPU,
374/// and say so if there is none" are different answers: a driver that encodes
375/// badly wants [`Software`](Self::Software), and a person who *needs* the GPU
376/// (a long delivery, a machine whose CPU is doing something else) wants to be
377/// told when it is not there rather than to wait out a silent fallback.
378#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
379pub enum EncoderSeat {
380 /// Hardware where this machine has a seat for the picked codec, software
381 /// everywhere else -- what every export did before there was a choice, and
382 /// still what an unpicked project does.
383 #[default]
384 Auto,
385 /// The GPU or nothing: no silent fallback, and [`Enc::open`] refuses in
386 /// words before a byte is written. The only way to the plugin's AV1 seat,
387 /// which [`Auto`](Self::Auto) will not enter (see [`Enc::open_av1`]).
388 Hardware,
389 /// The software encoder even where a seat exists -- for a driver that
390 /// encodes badly, and for the AV1 pair, where it is what `Auto` picks too.
391 Software,
392}
393
394impl EncoderSeat {
395 pub const ALL: [EncoderSeat; 3] = [Self::Auto, Self::Hardware, Self::Software];
396
397 /// What a card row and a project file call it. The file's keyword too, so
398 /// the two can never drift ([`crate::edith`]).
399 pub fn name(self) -> &'static str {
400 match self {
401 Self::Auto => "auto",
402 Self::Hardware => "hardware",
403 Self::Software => "software",
404 }
405 }
406
407 /// Reads one back. `None` for anything else, which a project file refuses
408 /// by name rather than silently exporting on another seat.
409 pub fn from_name(name: &[u8]) -> Option<Self> {
410 Self::ALL.into_iter().find(|s| s.name().as_bytes() == name)
411 }
412}
413
414/// The six ProRes profiles ([`Format::ProRes`]). The first four code 4:2:2, the
415/// last two 4:4:4; the encoder's rate is Apple's nominal one for the profile and
416/// the picture size, so a profile *is* the quality row ([`ExportSettings::bitrate`]
417/// means nothing to ProRes).
418#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
419pub enum ProResProfile {
420 Proxy,
421 Lt,
422 Standard,
423 #[default]
424 Hq,
425 P4444,
426 P4444Xq,
427}
428
429impl ProResProfile {
430 pub const ALL: [ProResProfile; 6] =
431 [Self::Proxy, Self::Lt, Self::Standard, Self::Hq, Self::P4444, Self::P4444Xq];
432
433 /// What a card row calls it.
434 pub fn name(self) -> &'static str {
435 match self {
436 Self::Proxy => "ProRes 422 Proxy",
437 Self::Lt => "ProRes 422 LT",
438 Self::Standard => "ProRes 422",
439 Self::Hq => "ProRes 422 HQ",
440 Self::P4444 => "ProRes 4444",
441 Self::P4444Xq => "ProRes 4444 XQ",
442 }
443 }
444
445 /// Whether the profile codes full-resolution chroma (4:4:4).
446 pub fn is_444(self) -> bool {
447 matches!(self, Self::P4444 | Self::P4444Xq)
448 }
449
450 fn codec(self) -> ec_prores::Profile {
451 match self {
452 Self::Proxy => ec_prores::Profile::Proxy,
453 Self::Lt => ec_prores::Profile::Lt,
454 Self::Standard => ec_prores::Profile::Standard,
455 Self::Hq => ec_prores::Profile::Hq,
456 Self::P4444 => ec_prores::Profile::P4444,
457 Self::P4444Xq => ec_prores::Profile::P4444Xq,
458 }
459 }
460}
461
462/// The HDR transfer an HEVC export is written on ([`HdrOutput::transfer`]).
463#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
464pub enum HdrTransfer {
465 /// No HDR: the export is SDR as it always was (tone-mapped from HDR sources).
466 #[default]
467 Sdr,
468 /// SMPTE ST 2084 (HDR10): BT.2020 primaries and matrix, limited range, 10-bit.
469 Pq,
470 /// ARIB STD-B67 (HLG): BT.2020 primaries and matrix, limited range, 10-bit.
471 Hlg,
472}
473
474impl HdrTransfer {
475 pub const ALL: [HdrTransfer; 3] = [Self::Sdr, Self::Pq, Self::Hlg];
476
477 pub fn name(self) -> &'static str {
478 match self {
479 Self::Sdr => "SDR",
480 Self::Pq => "PQ (HDR10)",
481 Self::Hlg => "HLG",
482 }
483 }
484
485 fn colour(self) -> Option<ColorDescription> {
486 let transfer = match self {
487 Self::Sdr => return None,
488 Self::Pq => Transfer::Pq,
489 Self::Hlg => Transfer::Hlg,
490 };
491 Some(ColorDescription { matrix: Matrix::Bt2020Ncl, transfer, full_range: false })
492 }
493}
494
495/// A SMPTE ST 2086 mastering display, in the units the SEI states: chromaticities
496/// in 0.00002 steps, luminance in 0.0001 cd/m2.
497#[derive(Debug, Clone, Copy, PartialEq, Eq)]
498pub struct MasteringDisplay {
499 /// Green, blue, red `(x, y)`, in that order (the SEI's).
500 pub primaries: [(u16, u16); 3],
501 pub white_point: (u16, u16),
502 /// Peak luminance, 0.0001 cd/m2 (1000 nits = 10_000_000).
503 pub max_luminance: u32,
504 /// Black level, 0.0001 cd/m2 (0.005 nits = 50).
505 pub min_luminance: u32,
506}
507
508impl MasteringDisplay {
509 /// A BT.2020-primaries, D65 display with the given peak and black, in nits.
510 pub fn bt2020(max_nits: f32, min_nits: f32) -> Self {
511 Self {
512 primaries: [(8500, 39850), (6550, 2300), (35400, 14600)],
513 white_point: (15635, 16450),
514 max_luminance: (max_nits * 10_000.0).round() as u32,
515 min_luminance: (min_nits * 10_000.0).round() as u32,
516 }
517 }
518
519 /// A DCI-P3 (D65) display, the usual HDR10 grading monitor, with the given
520 /// peak and black in nits.
521 pub fn p3_d65(max_nits: f32, min_nits: f32) -> Self {
522 Self {
523 primaries: [(13250, 34500), (7500, 3000), (34000, 16000)],
524 white_point: (15635, 16450),
525 max_luminance: (max_nits * 10_000.0).round() as u32,
526 min_luminance: (min_nits * 10_000.0).round() as u32,
527 }
528 }
529}
530
531/// HDR output of an HEVC export ([`ExportSettings::hdr`]). The default is none:
532/// every export that does not set it is the SDR file it always was.
533///
534/// With a transfer set the file is 10-bit (an explicit
535/// [`ExportSettings::video_bit_depth`] of 8 is refused), tagged BT.2020 primaries
536/// and matrix with that transfer in the bitstream VUI, the mp4 `colr` box or the
537/// Matroska `Colour` element, and the HDR sources are *not* tone-mapped.
538#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
539pub struct HdrOutput {
540 pub transfer: HdrTransfer,
541 /// Written as a mastering display colour volume SEI (in the bitstream).
542 pub mastering_display: Option<MasteringDisplay>,
543 /// MaxCLL in cd/m2, with `max_fall`, written as a content light level SEI.
544 pub max_cll: Option<u16>,
545 /// MaxFALL in cd/m2.
546 pub max_fall: Option<u16>,
547}
548
549/// What the caller gets to decide about the output. The codec is not among it:
550/// [`Format`] names a container *and* what goes in it, because every pair we
551/// can write is a pair we can also read back.
552#[derive(Debug, Clone, Default, PartialEq)]
553pub struct ExportSettings {
554 /// Bits per second, clamped to the same sane range the automatic value uses.
555 /// `None` picks it from the picture size and frame rate. Video only.
556 pub bitrate: Option<u64>,
557 /// A constant quantiser (0..51 for H.264 and HEVC) instead of a bitrate.
558 pub qp: Option<u32>,
559 /// Which encoder writes the picture ([`EncoderSeat`]). Was a `force_sw`
560 /// flag, which could say "not the GPU" and never "the GPU or say so".
561 /// [`EncoderSeat::Software`] is what the `VE_SW_ENC` env pin still forces
562 /// on every export of a run.
563 pub seat: EncoderSeat,
564 /// The file to write. Defaults to [`Format::Mp4`], which is what every
565 /// caller wrote before there was a choice.
566 pub format: Format,
567 /// The sample depth an AV1 software export is written at: `Some(8)` or
568 /// `Some(10)`, and `None` follows the source -- 10 where any video source of
569 /// the timeline is 10-bit. AV1 and software HEVC (H.264 stays 8-bit, and so do
570 /// the hardware AV1 and HEVC seats, which the 10-bit seats do not take). An HDR
571 /// transfer ([`ExportSettings::hdr`]) and ProRes are always 10-bit.
572 ///
573 /// A 10-bit export is decoded at 10 bits and encoded from its 16-bit planes
574 /// ([`Enc::encode_wide`]) wherever the span passes its picture through
575 /// untouched. A picture composed on the way (a grade, a transform, a fade, a
576 /// dissolve, a caption, a tone map, a layer) is composed at 8 bits as it always
577 /// was and shifted up to the file's depth, so the file is 10-bit either way.
578 pub video_bit_depth: Option<u8>,
579 /// What the *sound* is coded at, in kbps, wherever an encoder writes it --
580 /// the AAC of a video export as much as an MP3. `None` is
581 /// [`DEFAULT_AUDIO_KBPS`], which is what every caller wrote before there
582 /// was a choice, so a settings value nobody touched writes the same bytes
583 /// it used to. Means nothing to WAV and FLAC, which code no rate, and
584 /// nothing to a *copied* AAC track, which carries its source's.
585 pub audio_kbps: Option<u32>,
586 /// Code the sound at [`ExportSettings::audio_kbps`] even where its packets could be copied.
587 pub reencode_audio: bool,
588 /// Bits per sample of the PCM sound in a ProRes `.mov`: 16 or 24. `None` (and
589 /// anything else) is 24. No other format reads it.
590 pub audio_bit_depth: Option<u8>,
591 /// Which of the project's subtitle tracks travel with the file: indices into
592 /// [`Project::subtitles`], which is the same list a front-end picks rows of.
593 /// As many as the timeline holds, in the order given -- the file declares
594 /// them in that order and a player's subtitle menu lists them in it. Empty
595 /// writes none -- what every caller wrote before there was a choice, so an
596 /// export of a timeline without subtitles is the file it always was, byte
597 /// for byte.
598 ///
599 /// Every container that carries picture carries them: Matroska as
600 /// `S_TEXT/UTF8` blocks, an mp4 as a `tx3g` timed-text track
601 /// ([`crate::mux::Mp4Muxer::write_subtitles`]). A Matroska block names its
602 /// track in one byte, so a Matroska file carries at most
603 /// [`crate::mux::MAX_SUB_TRACKS`] of them and asking for more is refused by
604 /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has
605 /// no such ceiling.
606 pub subtitles: Vec<usize>,
607 /// Writes no soft subtitle track at all -- not the lanes, not the picks. The
608 /// captions a file carries are then only the ones [`burn_subtitles`] drew
609 /// into its picture. `false` is what every caller wrote before there was a
610 /// choice, so the lanes and the picks decide as they always did.
611 ///
612 /// [`burn_subtitles`]: ExportSettings::burn_subtitles
613 pub no_soft_subtitles: bool,
614 /// Code every picture as a key frame a decoder may be started from: no
615 /// frame references another, the file is an intraframe master in the shape
616 /// of ProRes, and a seek to any frame at all is one decode.
617 ///
618 /// Bigger files for that, so it is off for delivery and on for the
619 /// stand-ins [`crate::proxy`] makes, which exist precisely to be seeked
620 /// through. This is the switch of the H.264 and HEVC pairs; on HEVC the
621 /// software seat then codes every picture an IDR ([`Enc::open_hevc`]) and
622 /// the hardware seat is already intra. AV1 has no such switch.
623 pub intra_only: bool,
624 /// Captions drawn into the picture: the track at this index in
625 /// [`Project::subtitles`] (the index [`ExportSettings::subtitles`] and
626 /// [`crate::PlaybackSession::timeline_cues`] take), its cue on screen at
627 /// each timeline frame, drawn in this style ([`crate::text`]). `None` writes
628 /// the picture as it is -- what every caller wrote before there was a
629 /// choice.
630 ///
631 /// A burned-in picture is never copied out of its source: it is decoded,
632 /// drawn and encoded, so [`exact_refusal`] names the copy it gives up. The
633 /// cues are the ones the timeline plays, so a rippled edit captions what it
634 /// shows, the way the soft track does.
635 pub burn_subtitles: Option<(usize, TextStyle)>,
636 /// Write the picture in the space its **source** declares -- no tone map to
637 /// SDR, no matrix conversion -- and tag the file with it, instead of
638 /// converting everything into the space the output height implies.
639 ///
640 /// For a preview file and nothing else ([`crate::proxy`]): it makes the
641 /// stand-in a smaller copy of the film rather than a rendition of it, so
642 /// the screen tone-maps it live with whatever preset the project is set to
643 /// -- and it takes the per-frame conversion off the *source's* full
644 /// resolution, which on a 4K HDR film was 48 ms a frame and the whole of a
645 /// proxy's cost (measured 2026-08-13).
646 ///
647 /// A delivery export must leave it off: an mp4 in BT.2020 PQ is a file for
648 /// this editor to read back, not one to hand anybody.
649 pub keep_source_colour: bool,
650 /// Half-open `[start, end)` in timeline frames, or `None` for the whole
651 /// timeline -- what every caller wrote before there was a choice, so an
652 /// export nobody has marked in or out on writes the same bytes it always
653 /// did. Session state, like the mark itself: never saved to a `.edith`.
654 pub range: Option<(u32, u32)>,
655 /// The Exact quality row: this file must be the source's own coded
656 /// picture, copied wherever [`CopyPlan`] already says a copy is exactly
657 /// what the timeline says. `bitrate` and `seat` mean nothing to a copied
658 /// track, but a fallback re-encode (a cut off a sync point, a grade, a
659 /// speed, a transform) still honours them, so a copy-minded caller sends
660 /// `bitrate: None` beside this and gets the automatic figure rather than
661 /// a preset's.
662 ///
663 /// [`exact_refusal`] is the gate a front-end asks before the button is
664 /// pressed; [`run`] asks it again, which is what makes this a setting a
665 /// worker can trust rather than one only the card checked.
666 pub exact: bool,
667 /// The picture's size in pixels for this export alone, `(width, height)`:
668 /// the canvas the file is drawn and encoded at, in place of the project's
669 /// resolution. The project itself is not touched -- [`start`] applies it to
670 /// the export's own copy of the settings, and every clip refits on that
671 /// canvas by its fit mode, as it does when the project's resolution changes.
672 /// `None` is the project's own size, as every caller wrote before there was
673 /// a choice. Each side must be a picture size ([`crate::is_resolution`]) and
674 /// even, which the caller checks: a size here is trusted as given.
675 pub size: Option<(u32, u32)>,
676 /// Chapter marks the file carries, `(start in ns, title)` each, sorted by start. An mp4 gets
677 /// them as a Nero `chpl` and a QuickTime chapter track, a Matroska file as a `Chapters`
678 /// element. Empty writes none, which is what every caller wrote before there was a choice.
679 pub chapters: Vec<(u64, String)>,
680 /// Level the mixed sound to this integrated loudness under this true-peak ceiling before it
681 /// is coded ([`LoudnessTarget`]). `None` writes the mix at the level it was heard at, which
682 /// is what every caller wrote before there was a choice. A track is never *copied* when this
683 /// is set: a packet copy carries no gain.
684 pub loudness: Option<LoudnessTarget>,
685 /// The ProRes profile of a [`Format::ProRes`] export; means nothing to any
686 /// other format. Defaults to [`ProResProfile::Hq`].
687 pub prores_profile: ProResProfile,
688 /// HDR output of an HEVC export ([`Format::Hevc`], [`Format::HevcMp4`]); see
689 /// [`HdrOutput`]. Refused for every other format. The default is none.
690 pub hdr: HdrOutput,
691 /// Speed preset of the software HEVC encoder ([`Format::Hevc`], [`Format::HevcMp4`]); means
692 /// nothing to any other format. `None` is [`HevcSpeed::Default`], the encoder's own search,
693 /// bit-identical to every export written before there was a choice.
694 pub hevc_speed: Option<HevcSpeed>,
695 /// What a GIF asks for beyond the picture ([`Format::Gif`]); means nothing to any other format.
696 pub gif: GifSettings,
697 /// Seconds between key frames of a video export's H.264, HEVC or AV1 picture, `None` for the
698 /// encoder's own. Refused with [`ExportSettings::intra_only`], which codes every picture a key frame.
699 pub keyframe_s: Option<f64>,
700 /// Lays an mp4 out `ftyp`, `moov`, `mdat` so it can start playing before its end. Means
701 /// something only to [`Format::Mp4`], [`Format::HevcMp4`], [`Format::Av1Mp4`] and [`Format::M4a`].
702 pub faststart: bool,
703}
704
705/// The settings of an animated GIF ([`Format::Gif`]): its width in pixels (the height follows
706/// the project's aspect), its frame rate, and whether it loops. The default is the size and rate
707/// a GIF is usually shared at: 480 pixels wide, 15 frames a second, looping forever.
708#[derive(Debug, Clone, Copy, PartialEq, Eq)]
709pub struct GifSettings {
710 pub width: u32,
711 pub fps: u32,
712 pub loop_forever: bool,
713}
714
715impl Default for GifSettings {
716 fn default() -> Self {
717 Self { width: 480, fps: 15, loop_forever: true }
718 }
719}
720
721/// Speed preset of the software HEVC encoder (`ec-h265`'s `Preset`). `Fast` costs about 0-3%
722/// BD-rate for 1.2-1.6x speed, `Faster` up to 27% for about 1.5-2x.
723#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
724pub enum HevcSpeed {
725 #[default]
726 Default,
727 Fast,
728 Faster,
729}
730
731impl HevcSpeed {
732 fn preset(self) -> ec_h265::encoder::Preset {
733 match self {
734 Self::Default => ec_h265::encoder::Preset::Default,
735 Self::Fast => ec_h265::encoder::Preset::Fast,
736 Self::Faster => ec_h265::encoder::Preset::Faster,
737 }
738 }
739}
740
741/// An export-time loudness normalisation: one gain over the whole mix, from
742/// [`crate::loudness::gain_to_target`], so the integrated loudness lands on `lufs` and the true
743/// peak is held at or under `true_peak_dbtp` (the gain is cut back, never a limiter).
744#[derive(Debug, Clone, Copy, PartialEq)]
745pub struct LoudnessTarget {
746 pub lufs: f64,
747 pub true_peak_dbtp: f64,
748}
749
750// Plain finite figures, never NaN: the settings that hold one are `Eq`.
751impl Eq for LoudnessTarget {}
752
753/// Measures `samples` (interleaved) and scales them by the gain that reaches `target`.
754fn level_to_target(samples: &mut [f32], rate: u32, channels: u16, target: LoudnessTarget) {
755 let mut meter = crate::loudness::Meter::new(rate, channels);
756 meter.push(samples);
757 let gain = crate::loudness::gain_to_target(&meter.finish(), target.lufs, target.true_peak_dbtp);
758 if gain != 0.0 {
759 let g = 10f32.powf(gain as f32 / 20.0);
760 for s in samples.iter_mut() {
761 *s *= g;
762 }
763 }
764}
765
766/// The export's picture size: the project's canvas, or the [`ExportSettings::size`]
767/// this export is asked to draw at. Everything that decides what the file's picture
768/// is (the encoder's seat, the copy's gate, the colour matrix) asks it through here,
769/// so the answer each gives is the one the file has.
770pub fn output_meta(meta: &VideoMeta, settings: &ExportSettings) -> VideoMeta {
771 match settings.size {
772 // The coded size goes with the drawn one: a copy's gate compares the coded pair with its
773 // source's, and a picture drawn at another size is not a copy of anything.
774 Some((width, height)) => VideoMeta {
775 width,
776 height,
777 coded_width: width,
778 coded_height: height,
779 ..*meta
780 },
781 None => *meta,
782 }
783}
784
785/// What [`fit_picture_clips`] did: the full-frame clips it put on the policy, per lane (a lane
786/// with none is left out), and how many transformed overlays it left on their own fit.
787#[derive(Debug, Clone, PartialEq, Eq, Default)]
788pub struct FitOutcome {
789 pub lanes: Vec<(Lane, usize)>,
790 pub overlays: usize,
791}
792
793/// Puts every full-frame picture clip of `project` on `fit`, in place. Meant for the export's own
794/// copy of the timeline ([`start`] takes it by value), so the project a user edits keeps its
795/// clips' fit modes. A clip refits on the export's canvas by its fit mode, so this is how an
796/// export asks for `fit` on the pictures that fill the frame.
797///
798/// A clip placed by a transform (moved, scaled, cropped, faded or animated) is an overlay and
799/// keeps its own fit: `fill` would crop it to the canvas's shape, so a logo would lose its
800/// aspect on a vertical canvas. Its size stays relative to the canvas width, as in the project.
801/// The whole change is one undo step on the copy, which nothing reads.
802pub fn fit_picture_clips(project: &mut Project, fit: FitPolicy) -> FitOutcome {
803 let videos: Vec<Lane> = project.lanes().into_iter().filter(|l| l.kind == LaneKind::Video).collect();
804 project.begin_batch();
805 let mut outcome = FitOutcome::default();
806 for lane in videos {
807 let mut count = 0;
808 for idx in 0..project.lane(lane).len() {
809 if is_placed(project, lane, idx) {
810 outcome.overlays += 1;
811 } else {
812 project.set_fit(lane, idx, fit);
813 count += 1;
814 }
815 }
816 if count > 0 {
817 outcome.lanes.push((lane, count));
818 }
819 }
820 project.end_batch();
821 outcome
822}
823
824/// Whether the clip at `idx` of `lane` is placed by a transform that is not the identity, or has
825/// a placement animation: the overlays [`fit_picture_clips`] leaves alone.
826fn is_placed(project: &Project, lane: Lane, idx: usize) -> bool {
827 project.transform_of(lane, idx).is_some_and(|t| !t.is_identity())
828 || !project.transform_keys_of(lane, idx).is_empty()
829}
830
831/// The first moment a burned caption and a title show together in the same place. `cues` are the
832/// burn's cues ([`burn_cues`]) and `place` the burn's own place; a title sits where its
833/// `style.place` says, so a clash is a caption and a title with the same place on screen at once.
834/// Returns the moment in seconds and the index into `titles` of the title, the earliest such
835/// moment; `None` when no caption and title clash.
836pub fn caption_title_clash(cues: &[Cue], titles: &[Title], place: Place, fps: f64) -> Option<(f64, usize)> {
837 let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64;
838 let mut first: Option<(i64, usize)> = None;
839 for (i, t) in titles.iter().enumerate().filter(|(_, t)| t.style.place == place) {
840 let (start, end) = (us(t.start), us(t.end()));
841 for c in cues.iter().filter(|c| c.image.is_none() && !c.text.trim().is_empty()) {
842 let lo = c.start_us.max(start);
843 if lo < c.end_us.min(end) && first.is_none_or(|(f, _)| lo < f) {
844 first = Some((lo, i));
845 }
846 }
847 }
848 first.map(|(lo, i)| (lo as f64 / 1e6, i))
849}
850
851/// The lowest H.264 level (Table A-1) whose frame size and macroblock rate
852/// hold `width`x`height` at `fps_num/fps_den`, as the `level_idc` byte; 62
853/// past the table. One table for both seats: the software encoder writes it
854/// into its SPS (its default is 3.0, which is out of spec above 720p30) and
855/// the plugin hands it to the driver.
856pub fn h264_level_idc(width: u32, height: u32, fps_num: u32, fps_den: u32) -> u8 {
857 const LEVELS: [(u8, u64, u64); 17] = [
858 (10, 1485, 99),
859 (11, 3000, 396),
860 (12, 6000, 396),
861 (13, 11880, 396),
862 (20, 11880, 396),
863 (21, 19800, 792),
864 (22, 20250, 1620),
865 (30, 40500, 1620),
866 (31, 108000, 3600),
867 (32, 216000, 5120),
868 (40, 245760, 8192),
869 (41, 245760, 8192),
870 (42, 522240, 8704),
871 (50, 589824, 22080),
872 (51, 983040, 36864),
873 (52, 2073600, 36864),
874 (60, 4177920, 139264),
875 ];
876 let frame_mbs = u64::from(width.div_ceil(16)) * u64::from(height.div_ceil(16));
877 let fps = f64::from(fps_num.max(1)) / f64::from(fps_den.max(1));
878 let mbps = (frame_mbs as f64 * fps).ceil() as u64;
879 LEVELS
880 .iter()
881 .find(|&&(_, max_mbps, max_fs)| mbps <= max_mbps && frame_mbs <= max_fs)
882 .map_or(62, |&(idc, ..)| idc)
883}
884
885struct Shared {
886 /// Fraction of the job done, in [`PROGRESS_SCALE`]ths.
887 ///
888 /// **Every stage that can run beside another writes this with `fetch_max`,
889 /// never `store`.** The sound and the picture are two threads publishing
890 /// two bands of one bar ([`AUDIO_BAND`]): a `store` from the lower band
891 /// pulls the bar backwards every time the other thread has already moved
892 /// it on, which is what a person sees as a progress bar that stutters
893 /// backwards -- 5,458 backward steps over one film export before this rule
894 /// was written down. A `store` is only correct where nothing else can be
895 /// publishing at all, which now means the terminal [`PROGRESS_SCALE`] and
896 /// the audio-only export ([`run_audio`]) that has no second thread. The
897 /// rule outlives one attempt at the file: an export rerun in software
898 /// because the hardware seat died writes this same atomic, and the bar
899 /// holds where the dead seat left it rather than starting again.
900 progress: AtomicU32,
901 cancel: AtomicBool,
902 finished: AtomicBool,
903 outcome: Mutex<Option<crate::Result<()>>>,
904 /// The encoders this job really opened, published the moment they are
905 /// chosen and never changed after -- one seat for the whole file, which is
906 /// what [`Enc`] states. `None` until then. The one thing that joins it
907 /// afterwards is how much of the edit never got a picture
908 /// ([`Shared::truncated`]), and [`ExportHandle::encoders`] does that
909 /// joining, so a notice cannot land on the line twice.
910 encoders: Mutex<Option<String>>,
911 /// Timeline frames of the edit the walk could not write because a file ran
912 /// out before its clip did ([`run`]'s break). The bar reaches its end
913 /// whatever happens, so without this a truncated file reads as a whole one.
914 /// Published the moment the walk gives up and read by
915 /// [`ExportHandle::encoders`] beside the seat line.
916 truncated: AtomicU32,
917 /// A stage that runs before a span can encode -- a stabilised clip's shake
918 /// being measured ([`crate::stabilise::ensure`]) -- as `1 +` its thousandths
919 /// done, `0` while none runs. Its own fraction, beside [`Shared::progress`]
920 /// rather than in it, which holds still meanwhile ([`ExportHandle::stage`]).
921 measuring: AtomicU32,
922 /// [`ExportSettings::loudness`], for the audio stages that only see `Shared`.
923 loudness: Option<LoudnessTarget>,
924}
925
926/// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
927/// rendered frame and take the [`result`](ExportHandle::result) when it flips;
928/// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel)
929/// does.
930pub struct ExportHandle {
931 shared: Arc<Shared>,
932 /// The length of the file this export writes, in seconds: the range's, or the
933 /// picture and sound's end for a whole-timeline export. Known before the first frame.
934 length_secs: f64,
935}
936
937impl ExportHandle {
938 /// Fraction of the timeline written, `0.0..=1.0`.
939 pub fn progress(&self) -> f32 {
940 self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32
941 }
942
943 /// The length of the file this export writes, in seconds: the frames it holds at the
944 /// canvas's frame rate, which is the file's duration as a player shows it (a range is
945 /// cut to the picture's end the same way the encoder cuts it).
946 pub fn length_secs(&self) -> f64 {
947 self.length_secs
948 }
949
950 /// Asks the worker to stop at its next checkpoint and delete the partial
951 /// file. The outcome then reports the cancellation as an error. Checkpoints
952 /// run to the last instant before the rename, so even a cancel at full
953 /// progress leaves no output.
954 pub fn cancel(&self) {
955 self.shared.cancel.store(true, Ordering::Relaxed);
956 }
957
958 /// Whether [`cancel`](Self::cancel) was asked: the worker has not yet reached its
959 /// next checkpoint, so the export is still running though it is going to stop.
960 pub fn is_cancelling(&self) -> bool {
961 self.shared.cancel.load(Ordering::Relaxed)
962 }
963
964 pub fn is_finished(&self) -> bool {
965 self.shared.finished.load(Ordering::Acquire)
966 }
967
968 /// What this export is encoding with -- the video seat and what the sound
969 /// is doing -- as the worker chose them, hardware fallback included.
970 /// `None` for the first instants of a job, before the encoder is open.
971 ///
972 /// ...and, where a file ran out under its clip, how much of the edit never
973 /// got a picture. Composed here rather than written into the stored line,
974 /// because that line is published more than once on a rerun (a hardware
975 /// seat that died) and a notice appended at the write site lands twice.
976 pub fn encoders(&self) -> Option<String> {
977 let line = self.shared.encoders.lock().unwrap().clone()?;
978 Some(match self.shared.truncated.load(Ordering::Relaxed) {
979 0 => line,
980 past => format!("{line} · {past} frames of the edit past the last picture"),
981 })
982 }
983
984 /// The stage the export is in when it is not encoding: its name and its own
985 /// fraction done, `0.0..=1.0` -- `("Measuring shake", 0.4)` while a stabilised
986 /// clip with no finished analysis is measured. `None` while it encodes, when
987 /// [`progress`](Self::progress) is the one to show.
988 pub fn stage(&self) -> Option<(&'static str, f32)> {
989 match self.shared.measuring.load(Ordering::Relaxed) {
990 0 => None,
991 n => Some((MEASURING_SHAKE, ((n - 1) as f32 / 1000.0).clamp(0.0, 1.0))),
992 }
993 }
994
995 /// The outcome, once — taken out of the handle, so a caller that already
996 /// reported it sees `None` afterwards. `None` while the export is running.
997 pub fn result(&self) -> Option<crate::Result<()>> {
998 self.shared.outcome.lock().unwrap().take()
999 }
1000}
1001
1002/// Starts the worker. Failures are reported through the handle rather than
1003/// returned, so a caller has exactly one place to look. The files to read are
1004/// the project's own [`sources`](Project::sources) -- every clip names one --
1005/// so nothing but the edit list decides what is decoded.
1006pub fn start(
1007 project: Project,
1008 meta: VideoMeta,
1009 out: &Path,
1010 settings: &ExportSettings,
1011 sample_rate: Option<u32>,
1012) -> ExportHandle {
1013 let settings = settings.clone();
1014 // The canvas this export draws at: the project's, unless the settings name another.
1015 let meta = output_meta(&meta, &settings);
1016 let media = project.media_frames();
1017 let frames = match settings.range {
1018 Some((from, to)) => to.min(media).saturating_sub(from),
1019 None => media,
1020 };
1021 let length_secs = f64::from(frames) / meta.frame_rate;
1022 let shared = Arc::new(Shared {
1023 progress: AtomicU32::new(0),
1024 cancel: AtomicBool::new(false),
1025 finished: AtomicBool::new(false),
1026 outcome: Mutex::new(None),
1027 encoders: Mutex::new(None),
1028 truncated: AtomicU32::new(0),
1029 measuring: AtomicU32::new(0),
1030 loudness: settings.loudness,
1031 });
1032 let worker = Arc::clone(&shared);
1033 // A second handle to the same slot, held outside the caught body below --
1034 // what settles it if that body never gets to its own [`settle`] call at
1035 // all, because a codec parser deep inside `run` panicked instead of
1036 // returning the parse error it should have. Without this a panic there
1037 // strands the slot: [`ExportHandle::is_finished`] never flips, and a
1038 // proxy or export that hit a malformed frame sits in "Making" forever.
1039 let panic_worker = Arc::clone(&worker);
1040 let out = out.to_path_buf();
1041 // `<out>.part`, appended rather than substituted: the temporary of
1042 // `a.export.mp4` is `a.export.mp4.part`, which no other export claims.
1043 let mut part = out.clone().into_os_string();
1044 part.push(".part");
1045 let part = PathBuf::from(part);
1046 let spawned = thread::Builder::new().name("export".into()).spawn(move || {
1047 let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1048 // Every file this export will read, named before a byte of one is.
1049 // These are the project's own sources and can be nothing else: a
1050 // stand-in ([`crate::proxy`]) is a substitution playback makes when it
1051 // opens a span, and nothing here knows such a thing exists. Printed so
1052 // that "the delivery came off the film itself" is a grep rather than a
1053 // belief.
1054 for source in project.sources() {
1055 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export source: {}", source.path.display()); }
1056 }
1057 // The rename is the last step and the only one that publishes a file
1058 // under the name the caller asked for; it stays on the same directory,
1059 // so it is atomic.
1060 //
1061 // An emptied timeline is a legal project and an illegal file: no
1062 // picture, no sound, and a muxer that is never created because no coded
1063 // frame arrives. Refused by name here -- before the format is even
1064 // looked at, so an mp4 and a WAV refuse in the same words -- rather than
1065 // left to write a file of no frames that nothing opens. Every caller of
1066 // `start` comes through this, the app's own door
1067 // (`PlaybackSession::is_empty`) being only the first fence.
1068 //
1069 // An audio-only timeline has no picture to give a file, and an mp4 of
1070 // it would be black picture over the sound -- minutes of encoding for a
1071 // video of nothing. So an mp4 of it is written as the sound alone, the
1072 // same AAC track in an mp4 with no picture entry ([`run_aac`]); the
1073 // Matroska and WebM containers, which have no such form, are refused by
1074 // name. The app says the same on the format row before a destination
1075 // is even picked (`mp4_refusal`).
1076 let written = match settings.format {
1077 _ if project.timeline_frames() == 0 => {
1078 Err("the timeline is empty: there is nothing to export".into())
1079 }
1080 Format::PngSequence | Format::Still | Format::Gif if !has_picture(&project) => Err(format!(
1081 "the timeline has no picture: {} would be black. Export an mp4, an \
1082 M4A, WAV, FLAC, MP3, Ogg or Opus, which are the sound itself",
1083 settings.format.name()
1084 )
1085 .into()),
1086 // The pictures are composed one timeline frame at a time, with no sound.
1087 Format::PngSequence => run_png_sequence(&project, &meta, &out, &worker, &settings),
1088 Format::Still => run_still(&project, &meta, &part, &settings),
1089 Format::Gif => run_gif(&project, &meta, &part, &worker, &settings),
1090 format if format.ext() == "mp4" && !has_picture(&project) => {
1091 run_aac(&project, &meta, &part, &worker, &settings, sample_rate)
1092 }
1093 format if format.has_video() && !has_picture(&project) => Err(format!(
1094 "the timeline has no picture: {} would be black. Export an mp4, an \
1095 M4A, WAV, FLAC, MP3, Ogg or Opus, which are the sound itself",
1096 format.name()
1097 )
1098 .into()),
1099 format if format.has_video() => {
1100 let first = run(&project, &meta, &part, &worker, &settings, sample_rate);
1101 match first {
1102 // The hardware encoder's *process* died under the driver
1103 // ([`crate::hwproc`]) -- the editor is still here, and the
1104 // file is still owed. Written again by the software encoder
1105 // for this codec, from the first frame: the pictures the
1106 // dead seat coded are not ones this one may continue from.
1107 //
1108 // Not where a person picked the GPU by name: that export
1109 // refuses in words, the same answer [`hw_seat`] already
1110 // gives a machine with no seat at all, rather than quietly
1111 // spending an hour in an encoder nobody chose.
1112 Err(e)
1113 if crate::hwproc::is_lost(&e)
1114 && settings.seat != EncoderSeat::Hardware =>
1115 {
1116 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export video: {e}; writing it again in software"); }
1117 let _ = std::fs::remove_file(&part);
1118 // The bar is *not* put back to zero: the rerun writes
1119 // it with `fetch_max` like everything else
1120 // ([`Shared::progress`]), so it holds where the dead
1121 // seat left it and moves again once the software
1122 // encoder passes that mark. A person whose GPU has just
1123 // died is the last one who should also watch the bar
1124 // run backwards.
1125 let mut software = settings.clone();
1126 software.seat = EncoderSeat::Software;
1127 run(&project, &meta, &part, &worker, &software, sample_rate)
1128 }
1129 other => other,
1130 }
1131 }
1132 Format::M4a => run_aac(&project, &meta, &part, &worker, &settings, sample_rate),
1133 // Opus codes at 48 kHz and nothing else, so the mix is made there.
1134 Format::Opus => run_audio(&project, &meta, &part, &worker, &settings, Some(OPUS_RATE)),
1135 _ => run_audio(&project, &meta, &part, &worker, &settings, sample_rate),
1136 };
1137 let result = match settings.format {
1138 // A run of pictures is written into the folder it was asked for, which has no
1139 // temporary of its own to publish.
1140 Format::PngSequence => written,
1141 _ => written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)),
1142 };
1143 if result.is_err() {
1144 // The muxer -- and with it the file handle -- died with `run`.
1145 let _ = std::fs::remove_file(&part);
1146 }
1147 settle(&worker, result);
1148 }));
1149 if let Err(payload) = caught {
1150 // The body above panicked before it could settle its own slot --
1151 // the panic message becomes the outcome, so a caller sees a
1152 // failure and a notice rather than a bar that never moves again.
1153 let message = payload
1154 .downcast_ref::<&str>()
1155 .map(ToString::to_string)
1156 .or_else(|| payload.downcast_ref::<String>().cloned())
1157 .unwrap_or_else(|| "unknown panic".to_string());
1158 if !panic_worker.finished.load(Ordering::Acquire) {
1159 // ...and the `.part` the body left behind is deleted here: the
1160 // module promises every failure path removes it, and the only
1161 // path that did was the body's own `result.is_err()` arm, which
1162 // a panic never reaches. Done inside this branch only -- a body
1163 // that *did* settle has already renamed or deleted the file.
1164 let _ = std::fs::remove_file(&part);
1165 settle(
1166 &panic_worker,
1167 Err(format!("export worker panicked: {message}").into()),
1168 );
1169 }
1170 }
1171 });
1172 if let Err(e) = spawned {
1173 settle(&shared, Err(e.into()));
1174 }
1175 ExportHandle { shared, length_secs }
1176}
1177
1178/// Whether any video lane holds anything at all -- what tells an audio-only
1179/// timeline from one that merely opens on a gap. Asked of the *lanes* rather
1180/// than of the sources, because a project may name a video file no clip plays
1181/// from any more.
1182fn has_picture(project: &Project) -> bool {
1183 // A title is a picture of its own: a timeline of nothing but a title card
1184 // over black is a picture, not a black one.
1185 !project.titles().is_empty()
1186 || project
1187 .lanes()
1188 .into_iter()
1189 .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty())
1190}
1191
1192/// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a
1193/// timeline whose export will carry sound from one whose file has none.
1194fn has_sound(project: &Project) -> bool {
1195 project
1196 .lanes()
1197 .into_iter()
1198 .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty())
1199}
1200
1201/// Whether any equalizer on the sound is doing something -- the one edit a
1202/// packet copy cannot carry, so an mp4 whose lane has one is decoded and
1203/// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane:
1204/// the copy path has exactly one by the time it asks, and [`planned_audio`] is
1205/// asked before that is settled.
1206fn equalized(project: &Project) -> bool {
1207 project.audio_lanes().into_iter().any(|lane| {
1208 (0..project.lane(lane).len())
1209 .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity()))
1210 })
1211}
1212
1213/// How many timeline frames before a ranged export's start the mix is opened, so the voice
1214/// chain's envelopes and the noise reduction's overlap are warm when the range begins
1215/// instead of starting from silence ([`voice`](crate::voice)). Half a second, as far back as
1216/// the timeline goes; none when no lane has a processor on. [`warm_up_samples`] is how much
1217/// of the mix's front that is, taken off again.
1218fn warm_up(project: &Project, offset: u32, fps: f64) -> u32 {
1219 if offset == 0 || !project.audio_voices().iter().any(crate::voice::VoiceFx::is_active) {
1220 return 0;
1221 }
1222 offset.min((fps * 0.5).ceil() as u32)
1223}
1224
1225/// How many interleaved samples the `pre` frames of [`warm_up`] before `range_start` are:
1226/// the samples the timeline's mix puts between the two frames, counted with the mixer's own
1227/// rounding ([`timeline_sample`](crate::audio::timeline_sample)), so the range starts on the
1228/// same sample a full export has there. Rounding the pre-roll's own length instead can miss
1229/// by one at 29.97 or 23.976 fps.
1230fn warm_up_samples(range_start: u32, pre: u32, fps: f64, rate: u32, channels: usize) -> usize {
1231 let at = |frame: u32| crate::audio::timeline_sample(f64::from(frame) / fps, rate);
1232 (at(range_start) - at(range_start - pre)) as usize * channels
1233}
1234
1235/// Whether the *mix* is doing something -- a lane turned off unity, a lane
1236/// ducked under another, or a limiter in circuit. [`equalized`]'s pair, and a
1237/// copy cannot carry any of them: all live where the lanes are summed
1238/// ([`AudioSession::open_mixed_streams_master`]), and a copied packet was never
1239/// summed at all. An mp4 whose timeline is mixed is decoded and re-encoded.
1240fn mastered(project: &Project) -> bool {
1241 project.limiter().is_active()
1242 || project.audio_gains().iter().any(|&g| g != 1.0)
1243 || project.audio_ducks().iter().any(|lane| !lane.is_empty())
1244 || project.audio_voices().iter().any(crate::voice::VoiceFx::is_active)
1245}
1246
1247/// Whether any audio clip has a fade -- [`equalized`]'s pair again: a fade is
1248/// gain math on decoded samples ([`crate::project::Fade::apply`]), and a
1249/// packet copy carries neither an equalizer nor a fade. An mp4 whose timeline
1250/// has one is decoded and re-encoded so the fade actually reaches the file.
1251fn faded(project: &Project) -> bool {
1252 project.audio_lanes().into_iter().any(|lane| {
1253 project
1254 .lane(lane)
1255 .iter()
1256 .any(|c| c.fade_in > 0 || c.fade_out > 0)
1257 })
1258}
1259
1260/// The bitrate an export codes at: the caller's number clamped into what an
1261/// asked-for rate may be ([`MIN_BITRATE`]..[`MAX_EXPLICIT_BITRATE`]), the
1262/// derived one where there was none. Clamped rather than refused, for the
1263/// reason [`Enc::open`] states.
1264fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 {
1265 settings.bitrate.map_or_else(
1266 || bitrate_for(meta),
1267 |b| b.clamp(MIN_BITRATE, MAX_EXPLICIT_BITRATE),
1268 )
1269}
1270
1271fn rate_of(meta: &VideoMeta, settings: &ExportSettings) -> SeatRate {
1272 match settings.qp {
1273 Some(qp) => SeatRate::ConstantQp(qp),
1274 None => SeatRate::Bitrate(bitrate_of(meta, settings)),
1275 }
1276}
1277
1278/// The pictures between key frames the caller asked for, `None` for the encoder's own.
1279fn gop_frames(meta: &VideoMeta, settings: &ExportSettings) -> Option<u32> {
1280 settings.keyframe_s.map(|s| (meta.frame_rate * s).round().max(1.0) as u32)
1281}
1282
1283/// The rate the sound codes at: the caller's pick clamped into the offered
1284/// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused,
1285/// for [`bitrate_of`]'s reason -- a number out of range is a caller's slip and
1286/// not a file worth failing.
1287fn audio_kbps_of(settings: &ExportSettings) -> u32 {
1288 // 384 is above the offered rows, which a preset asks for (YouTube's AAC); MP3 has no such rate.
1289 let ceiling = if settings.format == Format::Mp3 { AUDIO_KBPS[3] } else { AAC_MAX_KBPS };
1290 settings.audio_kbps.map_or(DEFAULT_AUDIO_KBPS, |k| k.clamp(AUDIO_KBPS[0], ceiling))
1291}
1292
1293/// The hardware seat for these settings, opened exactly as the export opens it
1294/// -- the same pins, the same dimensions a driver may refuse -- or `None` where
1295/// the software encoder takes the file. The single place that choice is made,
1296/// which is what lets [`planned_video`] *measure* it instead of promising it.
1297///
1298/// `Err` is the one answer the software encoder does **not** take over from:
1299/// [`EncoderSeat::Hardware`] asked for the GPU by name and this machine has no
1300/// seat for the codec, so the export refuses in words rather than falling back
1301/// to an encoder nobody picked. Every caller is before a file exists
1302/// ([`Enc::open`] runs ahead of the muxer), which is what makes the refusal
1303/// free.
1304fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Option<HwEncoder>> {
1305 if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") {
1306 return Ok(None);
1307 }
1308 let opened = open_hw_seat(meta, settings);
1309 if opened.is_none() && settings.seat == EncoderSeat::Hardware {
1310 return Err(format!(
1311 "hardware encoding was asked for and this machine has no VA-API seat for {}: \
1312 pick Auto or Software on the export card",
1313 settings.format.name()
1314 )
1315 .into());
1316 }
1317 Ok(opened)
1318}
1319
1320/// The plugin half of [`hw_seat`]: what the driver gives for this codec and
1321/// this picture, with no policy in it but the AV1 one.
1322fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
1323 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
1324 let rate = rate_of(meta, settings);
1325 match settings.format {
1326 // Both HEVC formats sit on the plugin's HEVC seat, GOP or intra as the
1327 // export asks. `None` here is the plugin's own "no" -- no entrypoint, or
1328 // a picture under the driver's 384x384 floor -- and the software seat
1329 // takes it. The colour goes in at the open, from the same
1330 // [`ColorDescription::output`] rule the software seat's VUI and both
1331 // containers' tags come from, so the file cannot say one thing in its
1332 // bitstream and another in its header.
1333 format if format.is_hevc() && settings.intra_only => HwEncoder::open_hevc_intra(
1334 meta.width,
1335 meta.height,
1336 fps_num,
1337 fps_den,
1338 rate,
1339 ColorDescription::output_sized(meta.width, meta.height),
1340 ),
1341 format if format.is_hevc() => HwEncoder::open_hevc(
1342 meta.width,
1343 meta.height,
1344 fps_num,
1345 fps_den,
1346 rate,
1347 ColorDescription::output_sized(meta.width, meta.height),
1348 gop_frames(meta, settings),
1349 ),
1350 // Asked for by name only, for the reason [`Enc::open_av1`] states in
1351 // full: `Auto` takes the software encoder here and nowhere else. Both
1352 // AV1 formats sit on it: the container is not the encoder's business.
1353 format if format.is_av1() && settings.seat != EncoderSeat::Hardware => None,
1354 format if format.is_av1() => {
1355 HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, rate, gop_frames(meta, settings))
1356 }
1357 // An intra-only H.264 file is a *different seat*, not the same seat with
1358 // a flag on the pictures: asking this one for a key frame every time
1359 // gets I slices that are not IDRs and carry no parameter sets, which is
1360 // a file with one starting point in it however many I pictures it holds
1361 // (measured: a 60-frame hardware proxy, 1 sync point of 60). `None`
1362 // where the plugin is older than that seat, and then the software
1363 // encoder takes the file -- its `gop_size = 1` writes what was asked
1364 // for, slowly, which is the only honest fallback here.
1365 //
1366 // Only H.264 reaches this arm: the arms above take every HEVC and AV1 format.
1367 _ if settings.intra_only => {
1368 HwEncoder::open_intra(meta.width, meta.height, fps_num, fps_den, rate)
1369 }
1370 _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, rate, gop_frames(meta, settings)),
1371 }
1372}
1373
1374/// True when an Annex B HEVC access unit holds an IRAP picture (NAL types 16..=23).
1375fn hevc_irap(au: &[u8]) -> bool {
1376 au.windows(4)
1377 .any(|w| w[0] == 0 && w[1] == 0 && w[2] == 1 && (16..=23).contains(&((w[3] >> 1) & 0x3F)))
1378}
1379
1380/// What a hardware encode is called wherever one is named -- the card's line
1381/// before the export and the progress line during it.
1382const HW_LABEL: &str = "HW encode (VA-API)";
1383
1384/// ...and what a card says instead where [`EncoderSeat::Hardware`] was picked
1385/// and there is no seat: the export's own refusal in the width of a card row,
1386/// shown *before* the button is pressed rather than a minute into a file.
1387pub const NO_HW_SEAT: &str = "no HW seat here — pick Auto or Software";
1388
1389/// How a front-end names a video seat: which of the two encoders has the file,
1390/// and which library that is. Not the codec -- a caller shows this beside the
1391/// format it picked, and `rav1e` names AV1 as `ec-h264` names H.264. One
1392/// place, so what a card says before an export and what its progress line says
1393/// during one cannot drift apart.
1394fn video_label(format: Format, hw: bool, intra: bool) -> &'static str {
1395 match (format, hw) {
1396 (_, true) => HW_LABEL,
1397 (Format::Hevc | Format::HevcMp4, false) if intra => "SW encode (ec-h265 intra)",
1398 (Format::Hevc | Format::HevcMp4, false) => "SW encode (ec-h265 GOP)",
1399 (Format::Av1 | Format::Av1Mp4 | Format::Webm, false) => "SW encode (rav1e)",
1400 (Format::ProRes, false) => "SW encode (ec-prores)",
1401 (_, false) => "SW encode (ec-h264)",
1402 }
1403}
1404
1405/// Whether the *edit* has touched the samples a copy would carry out: the one
1406/// predicate both copy-or-encode decisions ask, with `lanes` the sound's own
1407/// list as the caller has it -- every audio lane for the question a card asks
1408/// before the button ([`forces_encode`]), and the single lane the segments have
1409/// already narrowed a copy to ([`copy_audio`]).
1410///
1411/// One function and not two lists of the same conditions, which is what they
1412/// were: `faded` reached [`forces_encode`] and not [`copy_audio`]'s gate, so an
1413/// mp4 whose lane carried a fade wrote the source's own packets with the fade
1414/// nowhere, while the card had promised a re-encode -- and the WAV, FLAC and
1415/// MP3 exports of the same project applied it. Two gates that cannot be given
1416/// two answers is the fix; the drift was the defect.
1417fn sample_altered(project: &Project, lanes: &[Lane]) -> bool {
1418 // Two lanes are a mix and a mix is not a copy; a speeded lane is resampled;
1419 // an equalizer, a fade and the mix itself are gain math on decoded samples
1420 // ([`equalized`], [`faded`], [`mastered`]). None of them is inside a packet.
1421 lanes.len() > 1
1422 || lanes
1423 .iter()
1424 .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal() || !c.speed_keys.is_empty() || c.reversed))
1425 || equalized(project)
1426 || mastered(project)
1427 || faded(project)
1428}
1429
1430/// The cheap half of "does this timeline's sound have to be re-encoded": what
1431/// the *edit* says, with no file opened ([`sample_altered`], asked of every
1432/// audio lane). The other half -- whether the sources can be copied out of at
1433/// all -- costs a file open each and belongs to [`copy_audio`], which may
1434/// re-encode where this says copy.
1435fn forces_encode(project: &Project, ranged: bool) -> bool {
1436 // A ranged export needs an exact offset and an exact length, which a copy
1437 // of the source's own packets cannot give it ([`copy_audio`]) -- so a
1438 // range marked at all always encodes, whatever the lanes look like.
1439 ranged || sample_altered(project, &project.audio_lanes())
1440}
1441
1442/// What the sound is written by. Every audio encoder here is software -- there
1443/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and
1444/// whether a container escapes encoding altogether by copying the packets it was
1445/// given. Both AV1 formats are in it like the mp4: an AV1 export carries the
1446/// timeline's sound too, so leaving it unnamed would be the old lie.
1447///
1448/// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a
1449/// card asking before the export has no way to know (a source that cannot be
1450/// copied out of is only found by opening it). `None` predicts from the edit
1451/// alone.
1452fn audio_label(
1453 project: &Project,
1454 format: Format,
1455 sound: bool,
1456 copied: Option<bool>,
1457 ranged: bool,
1458 reencode: bool,
1459) -> &'static str {
1460 if !sound {
1461 return "no sound to write";
1462 }
1463 match format {
1464 Format::Wav => "PCM · SW (ec-riff)",
1465 Format::Flac => "FLAC · SW (ec-flac)",
1466 Format::Mp3 => "MP3 · SW (ec-mp3)",
1467 Format::Ogg => "Vorbis · SW (ec-vorbis)",
1468 Format::Opus => "Opus · SW (ec-opus)",
1469 Format::ProRes => "PCM · SW (16-bit, mov)",
1470 // Never a copy: WebM carries Opus, and the sound is mixed and encoded
1471 // for it at 48 kHz ([`start`], [`encode_audio`]).
1472 Format::Webm => "Opus · SW encode (ec-opus)",
1473 _ => match copied.unwrap_or(!(reencode || forces_encode(project, ranged))) {
1474 true => "AAC copy",
1475 // A Matroska file gets Opus where the mix allows it -- 48 kHz and
1476 // stereo, which is every Opus source and most of everything else --
1477 // and AAC where it does not ([`encode_audio`]). Which of the two it
1478 // will be cannot be known here: both answers need a source opened,
1479 // and this function may be asked per repaint. So the card names the
1480 // codec it will nearly always be, as a prediction like the copy above
1481 // it, and the line the export publishes while it runs is the measured
1482 // one ([`run`]) -- it says AAC when the fallback took it, so the
1483 // fallback is visible rather than silent.
1484 //
1485 // It is one line and 76 characters wide (`summary_head` in the app
1486 // has the test), which is why the condition is in this comment
1487 // instead of in the string.
1488 false if format.is_mkv() => "Opus · SW encode (ec-opus)",
1489 false => "AAC · SW encode (ec-aac)",
1490 },
1491 }
1492}
1493
1494/// What the export *did* to the sound, for the line it publishes while it runs:
1495/// [`audio_label`]'s words with the one thing no prediction can know filled in
1496/// -- whether the Opus seat took the track or handed it back
1497/// ([`encode_opus`]'s gate).
1498///
1499/// `sound` is `Some(copied)` for a track and `None` for a file with no sound.
1500/// Naming Opus for *every* Matroska encode is what made that fallback
1501/// invisible: a track the gate refused was written as AAC and the line still
1502/// said Opus, on the one path where the difference is audible.
1503fn measured_audio_label(
1504 project: &Project,
1505 format: Format,
1506 sound: Option<bool>,
1507 opus: bool,
1508) -> &'static str {
1509 match (sound, opus) {
1510 (_, true) => "Opus · SW encode (ec-opus)",
1511 // Encoded, into a container that would have carried Opus, and it is not
1512 // Opus: the fidelity gate sent it to AAC ([`OPUS_MIN_FIDELITY`]), or
1513 // the mix was not 48 kHz at a width the seat is measured in.
1514 (Some(false), false) if format.is_mkv() => "AAC · SW encode (ec-aac)",
1515 // `sound` is already what happened, not a prediction, so `copied` is
1516 // filled in and `ranged` never reaches the branch that reads it.
1517 _ => audio_label(project, format, sound.is_some(), sound, false, false),
1518 }
1519}
1520
1521/// What [`start`] would write this timeline's sound with, before one is
1522/// started. Pure: no probe and no file opened, so a card may ask it per
1523/// repaint. `ranged` is whether the export a card is describing is bounded to
1524/// a marked range -- a copy needs the source's own packets to *be* the file,
1525/// which a range's exact offset and length rule out ([`copy_audio`]).
1526pub fn planned_audio(project: &Project, format: Format, ranged: bool) -> &'static str {
1527 audio_label(project, format, has_sound(project), None, ranged, false)
1528}
1529
1530/// Why the sound's rate is nothing this timeline can be asked about in this
1531/// format, or `None` where it is a real choice: there is no sound to write, the
1532/// format codes the samples themselves, or the packets are the source's own and
1533/// carry the rate *it* was coded at. Pure, like [`planned_audio`], and a
1534/// prediction in the same way -- a copy that turns out impossible (a source no
1535/// mp4 sample table holds) falls through to [`encode_audio`], which codes at
1536/// [`ExportSettings::audio_kbps`] like every other encode. So the value travels
1537/// even where this refuses; what it cannot do is silently write a rate nobody
1538/// picked.
1539pub fn audio_rate_refusal(project: &Project, format: Format, ranged: bool, reencode: bool) -> Option<&'static str> {
1540 match format {
1541 _ if !has_sound(project) => Some("no sound to write"),
1542 Format::Wav | Format::Flac | Format::ProRes => Some("lossless — the samples themselves, at no rate"),
1543 // Vorbis is written at one measured operating point ([`VORBIS_QUALITY`]
1544 // + [`VORBIS_TARGET_BPS`]), not at a rate a user may pick: its actual
1545 // landing moves with the content around that target (124-134 kbps
1546 // across this suite's bench inputs), so a live rate row would print a
1547 // figure the file does not hold -- the one thing this card is built
1548 // not to do.
1549 Format::Ogg => Some("quality-coded — Vorbis holds no rate to pick"),
1550 // The bitrate is the one choice WebM leaves: Opus at the rate picked.
1551 Format::Mp3 | Format::Webm | Format::Opus => None,
1552 _ if reencode || forces_encode(project, ranged) => None,
1553 _ => Some("the source's own packets are copied — at the rate they hold"),
1554 }
1555}
1556
1557/// The soft subtitle tracks an export carries: the lanes the timeline places, each
1558/// as its placement (the lanes a pick reaches), then every picked track no lane
1559/// places, whole. Empty where it carries none: no pick and no placement, a pick
1560/// nothing answers, a track that could not be read, one with no cue left on the
1561/// exported timeline -- and every format that is the sound alone, which has
1562/// nowhere to put them. Filtered *per track*, so one unusable pick costs its own
1563/// row and not the others.
1564///
1565/// Both containers, since the mp4 muxer gained its `tx3g` track: what the two
1566/// do with the very same [`SubParams`] is theirs to say
1567/// ([`crate::mux::Mp4Muxer::write_subtitles`], [`MkvMuxer`]), and nothing here
1568/// asks which one is being written.
1569fn export_subtitles(
1570 project: &Project,
1571 meta: &VideoMeta,
1572 settings: &ExportSettings,
1573) -> Vec<SubParams> {
1574 // WebM has no subtitle track this writer can state: [`planned_subtitles`]
1575 // says so on the card, and nothing is written.
1576 if !settings.format.has_video() || matches!(settings.format, Format::Webm | Format::ProRes) || !has_picture(project) {
1577 return Vec::new();
1578 }
1579 // Burned captions are the only ones this file carries: a soft track of the
1580 // same words would show them twice.
1581 if settings.no_soft_subtitles {
1582 return Vec::new();
1583 }
1584 // Words placed on a lane are written through the lanes, at their placement
1585 // (`lane_subtitle`; none when nothing is placed). A picked track that no lane
1586 // places is written whole beside them, as it always was: the palette's pick
1587 // is the only say it has in the file, so it must not be dropped for a lane
1588 // elsewhere. A placed track is never written twice. The tracks go in the
1589 // order the caller gave them ([`soft_order`]), placed or not.
1590 let lanes = placed_lanes(project);
1591 let mut subs = Vec::new();
1592 for entry in soft_order(project, &lanes, &settings.subtitles) {
1593 match entry {
1594 SoftEntry::Lane(lane) => subs.extend(lane_subtitle(
1595 project,
1596 lane,
1597 meta.frame_rate,
1598 settings.range,
1599 &settings.subtitles,
1600 )),
1601 SoftEntry::Track(pick) => subs.extend(whole_track(project, meta, settings, pick)),
1602 }
1603 }
1604 subs
1605}
1606
1607/// Whether a track has a cue the file would carry: any cue at all on the whole timeline, or one
1608/// left inside `range` (on the clock the range is cut to, as [`written_cues`] cuts it).
1609fn track_has_cues(project: &Project, track: &SubtitleTrack, range: Option<(u32, u32)>, fps: f64) -> bool {
1610 match range {
1611 None => !track.cues.is_empty(),
1612 Some(_) => !written_cues(timeline_cues(project, track, fps), range, fps, project.media_frames()).is_empty(),
1613 }
1614}
1615
1616/// The reason a track with nothing to carry is dropped, in the card's words.
1617fn no_cues_word(range: Option<(u32, u32)>) -> &'static str {
1618 if range.is_some() { "no cues in range" } else { "no cues" }
1619}
1620
1621/// The labels of the written soft tracks whose styling the file drops: a standalone ASS or SSA
1622/// script whose lines carry override blocks (`{\i1}`, `{\an8}`), which a cue's plain text does not
1623/// keep. An embedded ASS track is not read here, so it is not named. Empty when none is.
1624pub fn stripped_styling(project: &Project, picks: &[usize]) -> Vec<String> {
1625 let lanes = placed_lanes(project);
1626 let placed = placed_tracks(project);
1627 let mut used: std::collections::BTreeSet<usize> = picks.iter().copied().filter(|p| !placed.contains(p)).collect();
1628 for &lane in &lanes {
1629 let on_lane = project.sub_lane(lane);
1630 if picked(on_lane, picks) {
1631 used.extend(on_lane.iter().map(|s| s.track));
1632 }
1633 }
1634 used.into_iter()
1635 .filter_map(|i| project.subtitles().get(i))
1636 .filter(|t| t.refused.is_none() && !t.is_bitmap() && t.track.is_none() && has_override_blocks(&t.path))
1637 .map(|t| t.label.clone())
1638 .collect()
1639}
1640
1641/// Whether `path` is an ASS or SSA script with an override block in it.
1642fn has_override_blocks(path: &Path) -> bool {
1643 let ass = path
1644 .extension()
1645 .and_then(|e| e.to_str())
1646 .is_some_and(|e| e.eq_ignore_ascii_case("ass") || e.eq_ignore_ascii_case("ssa"));
1647 ass && std::fs::read_to_string(path).is_ok_and(|text| text.contains("{\\"))
1648}
1649
1650/// One soft track of the file: a subtitle lane (written through its placements) or a picked
1651/// track no lane places (written whole).
1652#[derive(Clone, Copy, Debug, PartialEq)]
1653enum SoftEntry {
1654 Lane(Lane),
1655 Track(usize),
1656}
1657
1658/// The soft tracks the file writes, in the order the file declares them. With picks, that is
1659/// the order the caller gave them: a lane goes where the first pick that reaches it sits, and a
1660/// pick no lane places goes whole in its own place. Without picks, every placed lane in lane
1661/// order and no whole track.
1662fn soft_order(project: &Project, lanes: &[Lane], picks: &[usize]) -> Vec<SoftEntry> {
1663 if picks.is_empty() {
1664 return lanes.iter().map(|&l| SoftEntry::Lane(l)).collect();
1665 }
1666 let placed = placed_tracks(project);
1667 let mut out: Vec<SoftEntry> = Vec::new();
1668 for &pick in picks {
1669 let entry = if placed.contains(&pick) {
1670 match lanes.iter().find(|&&l| project.sub_lane(l).iter().any(|s| s.track == pick)) {
1671 Some(&lane) => SoftEntry::Lane(lane),
1672 None => continue,
1673 }
1674 } else {
1675 SoftEntry::Track(pick)
1676 };
1677 if !out.contains(&entry) {
1678 out.push(entry);
1679 }
1680 }
1681 out
1682}
1683
1684/// One picked track written whole, on the timeline's clock and clipped to the range
1685/// and the picture. `None` for a track that writes nothing: no row for the pick, a
1686/// track that could not be read, a picture track (the muxer writes words), or no cue
1687/// left in the file.
1688fn whole_track(
1689 project: &Project,
1690 meta: &VideoMeta,
1691 settings: &ExportSettings,
1692 pick: usize,
1693) -> Option<SubParams> {
1694 let track = project.subtitles().get(pick)?;
1695 // A picture is not a line: the muxer writes an `S_TEXT/UTF8` track and a PGS cue
1696 // has no words to put in one. `planned_subtitles` says so before the button is
1697 // pressed rather than the file coming out short.
1698 if track.refused.is_some() || track.is_bitmap() {
1699 return None;
1700 }
1701 let cues = written_cues(
1702 timeline_cues(project, track, meta.frame_rate),
1703 settings.range,
1704 meta.frame_rate,
1705 project.media_frames(),
1706 );
1707 // The container's own two fields, carried as two
1708 // ([`SubtitleTrack::language`]): a `TrackEntry` with no `Language` means `eng`
1709 // by spec, so a French track that arrives here as one flattened string leaves
1710 // as an English one.
1711 (!cues.is_empty()).then(|| SubParams {
1712 language: track.language.clone(),
1713 name: subtitle_title(track),
1714 cues,
1715 })
1716}
1717
1718/// The title a soft subtitle track is written under. An embedded track keeps the
1719/// title its container gave it; a standalone file has none of its own, so it is
1720/// titled with its language's name (`French`) or left untitled -- never with its
1721/// file name.
1722fn subtitle_title(track: &SubtitleTrack) -> String {
1723 match track.track {
1724 Some(_) => track.name.clone(),
1725 None => crate::subtitle::language_name(&track.language).unwrap_or_default().to_string(),
1726 }
1727}
1728
1729/// The indices of the tracks some placement on a subtitle lane names. Those tracks
1730/// are written through their lanes, so a pick of one of them is not written whole.
1731fn placed_tracks(project: &Project) -> std::collections::BTreeSet<usize> {
1732 project
1733 .subtitle_lanes()
1734 .into_iter()
1735 .flat_map(|lane| project.sub_lane(lane).iter().map(|s| s.track))
1736 .collect()
1737}
1738
1739/// The labels of the soft subtitle tracks this export writes whose cues overlap. An mp4
1740/// writes an overlap as one stretch with both lines in it (`mux`'s `timed_text`), so the
1741/// cue times the timeline holds are not the file's; an mkv keeps every cue. Empty when
1742/// nothing is written or no two cues of a written track overlap.
1743pub fn overlapping_subtitles(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Vec<String> {
1744 export_subtitles(project, meta, settings)
1745 .into_iter()
1746 .filter(|t| {
1747 let mut spans: Vec<(i64, i64)> = t.cues.iter().map(|c| (c.start_us, c.end_us)).collect();
1748 spans.sort_unstable();
1749 let mut reach = i64::MIN;
1750 spans.iter().any(|&(start, end)| {
1751 let overlap = start < reach;
1752 reach = reach.max(end);
1753 overlap
1754 })
1755 })
1756 .map(|t| match (t.name.is_empty(), t.language.is_empty()) {
1757 (false, _) => t.name,
1758 (true, false) => t.language,
1759 (true, true) => "an unnamed track".to_string(),
1760 })
1761 .collect()
1762}
1763
1764/// Whether a lane with these placements is in the file: an empty pick list is
1765/// every lane, otherwise the lane must hold at least one placement of a picked
1766/// track ([`Project::subtitles`] index, as [`ExportSettings::subtitles`] gives).
1767fn picked(placed: &[crate::project::SubClip], picks: &[usize]) -> bool {
1768 picks.is_empty() || placed.iter().any(|s| picks.contains(&s.track))
1769}
1770
1771/// The project's subtitle lanes in display order, and empty where **nothing is
1772/// placed on any of them** -- an empty list is what the export and the card both
1773/// read as "this project does not use lanes yet", so a project holding a bare
1774/// `S1` nobody dropped a caption on still exports by the pick list.
1775fn placed_lanes(project: &Project) -> Vec<Lane> {
1776 let lanes = project.subtitle_lanes();
1777 match lanes.iter().any(|&l| !project.sub_lane(l).is_empty()) {
1778 true => lanes,
1779 false => Vec::new(),
1780 }
1781}
1782
1783/// One track per subtitle *lane*, in lane order -- so the file declares them
1784/// top-down as the timeline shows them and a player's subtitle menu lists them
1785/// in that order.
1786///
1787/// The cues are [`Project::sub_lane_cues`]: each placement's window of its
1788/// palette track, on the timeline's own clock. Clipped again here to what the
1789/// export *writes*, which ends with the last picture or sound
1790/// ([`Project::media_frames`]) -- a caption hanging past both holds the
1791/// timeline open ([`Project::timeline_frames`]) but there is no picture under
1792/// it to write, so a cue out there is dropped and one straddling the end keeps
1793/// the half that is inside. [`planned_subtitles`] says so before the button is
1794/// pressed.
1795///
1796/// A lane is dropped whole -- no track at all in the file -- where any
1797/// placement on it is a picture ([`SubtitleTrack::is_bitmap`]), a track that
1798/// could not be read, or a palette row that has since gone: the muxers write
1799/// words, and half a lane's cues under the other half's name would be worse
1800/// than none. Its language and title are the lane's *first* placement's track,
1801/// which is the one thing the whole lane is named by.
1802///
1803/// `picks` narrows the lanes the same way [`ExportSettings::subtitles`] does: a
1804/// lane is kept when it holds a placement of a picked track ([`picked`]), and an
1805/// empty list keeps every lane.
1806#[cfg(test)]
1807fn lane_subtitles(
1808 project: &Project,
1809 fps: f64,
1810 range: Option<(u32, u32)>,
1811 picks: &[usize],
1812) -> Vec<SubParams> {
1813 placed_lanes(project)
1814 .into_iter()
1815 .filter_map(|lane| lane_subtitle(project, lane, fps, range, picks))
1816 .collect()
1817}
1818
1819/// One lane written as its track ([`lane_subtitles`] for a single lane); `None` where the
1820/// lane is not in the file (see there for the reasons).
1821fn lane_subtitle(
1822 project: &Project,
1823 lane: Lane,
1824 fps: f64,
1825 range: Option<(u32, u32)>,
1826 picks: &[usize],
1827) -> Option<SubParams> {
1828 let end = (f64::from(project.media_frames()) / fps * 1e6).round() as i64;
1829 let placed = project.sub_lane(lane);
1830 if !picked(placed, picks) {
1831 return None;
1832 }
1833 let first = placed.first()?;
1834 let writable = |track: usize| {
1835 project
1836 .subtitles()
1837 .get(track)
1838 .filter(|t| t.refused.is_none() && !t.is_bitmap())
1839 };
1840 let named = writable(first.track)?;
1841 if placed.iter().any(|s| writable(s.track).is_none()) {
1842 return None;
1843 }
1844 let cues: Vec<Cue> = written_cues(
1845 project
1846 .sub_lane_cues(lane, fps)
1847 .into_iter()
1848 .filter_map(|cue| {
1849 let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end));
1850 (end_us > start_us).then_some(Cue {
1851 start_us,
1852 end_us,
1853 text: cue.text,
1854 image: cue.image,
1855 words: Vec::new(),
1856 karaoke: Vec::new(),
1857 })
1858 })
1859 .collect(),
1860 range,
1861 fps,
1862 project.media_frames(),
1863 );
1864 (!cues.is_empty()).then(|| SubParams {
1865 language: named.language.clone(),
1866 name: subtitle_title(named),
1867 cues,
1868 })
1869}
1870
1871/// `cues` on the clock the export *writes*, for a range-relative file.
1872///
1873/// A cue is timed on the timeline; a ranged export's file starts its own clock
1874/// at zero where the range starts, so every cue moves back by the range's start.
1875/// What falls before the range is dropped, what falls after it is dropped, and a
1876/// cue straddling either edge keeps the half inside. The window is the range
1877/// clamped to the media, the same clamp [`export_spans`] makes, so the cues stop
1878/// where the pictures do. Both ends are whole microseconds of the same
1879/// frame-to-time mapping the cues were timed with, so the only rounding left is
1880/// the container's own tick.
1881///
1882/// Unranged, the cues come back as they were.
1883fn written_cues(
1884 cues: Vec<Cue>,
1885 range: Option<(u32, u32)>,
1886 fps: f64,
1887 media_frames: u32,
1888) -> Vec<Cue> {
1889 let Some((r_start, r_end)) = range else {
1890 return cues;
1891 };
1892 let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64;
1893 let from = us(r_start);
1894 let to = us(r_end.min(media_frames).max(r_start));
1895 cues.into_iter()
1896 .filter_map(|cue| {
1897 let start_us = cue.start_us.max(from);
1898 let end_us = cue.end_us.min(to);
1899 (end_us > start_us).then_some(Cue {
1900 start_us: start_us - from,
1901 end_us: end_us - from,
1902 text: cue.text,
1903 image: cue.image,
1904 words: Vec::new(),
1905 karaoke: Vec::new(),
1906 })
1907 })
1908 .collect()
1909}
1910
1911/// The composite spans an export *writes*: [`Project::composite_spans_from`]
1912/// cut to where the media runs out ([`Project::media_frames`]), and, with
1913/// `range` set, to that window too.
1914///
1915/// The walk itself is the timeline's ([`Project::timeline_frames`]), because a
1916/// caption placed past the last picture holds the timeline open under it and
1917/// playback parks on that tail -- but there is nothing to *write* out there, so
1918/// an unbounded walk encoded and muxed black frames past the end of the media
1919/// and padded the sound to match. This is the one place that end is decided:
1920/// the frame count [`run`] publishes, the cues [`lane_subtitles`] clips and the
1921/// blocks [`CopyPlan`] copies are then the same number by construction, which
1922/// is what makes [`planned_lanes`]' "cut off there" true of the file.
1923///
1924/// `span.start` stays the *project's* own timeline coordinate throughout --
1925/// what [`Project::composite_color_at`] and its fit sibling are keyed on -- so
1926/// a caller writing a range-relative output shifts it at the one place that
1927/// actually emits a position (`CopyPlan`'s own region, since the encode loop
1928/// counts pictures rather than reading `span.start` for its output clock).
1929/// Trimming the left edge mid-span moves `from`'s source frame by
1930/// [`Speed::source_at`], the same mapping a legal cut is placed by.
1931fn export_spans(project: &Project, range: Option<(u32, u32)>) -> Vec<crate::project::Span> {
1932 let end = project.media_frames();
1933 let mut spans = stack_spans_from(project, 0);
1934 spans.retain(|span| span.start < end);
1935 for span in &mut spans {
1936 span.len = span.len.min(end - span.start);
1937 }
1938 // A title past the last clip is picture: the frames up to its end are black
1939 // under it, a gap like any other. Only titles extend the picture here; a
1940 // sound that runs on still does not, as it never did.
1941 let title_end = project
1942 .titles()
1943 .iter()
1944 .map(Title::end)
1945 .max()
1946 .unwrap_or(0)
1947 .min(end);
1948 let covered = spans.last().map_or(0, crate::project::Span::end);
1949 if covered < title_end {
1950 spans.push(crate::project::Span {
1951 ramp: None,
1952 start: covered,
1953 len: title_end - covered,
1954 from: None,
1955 speed: Speed::NORMAL,
1956 reverse: false,
1957 pitch: 0.0,
1958 });
1959 }
1960 let Some((r_start, r_end)) = range else {
1961 return spans;
1962 };
1963 let r_end = r_end.min(end).max(r_start);
1964 spans.retain(|span| span.start < r_end && span.start + span.len > r_start);
1965 for span in &mut spans {
1966 if span.start < r_start {
1967 let cut = r_start - span.start;
1968 if let Some((source, in_frame)) = span.from {
1969 span.from = Some((source, span.source_at(in_frame, cut)));
1970 }
1971 // A ramp's offsets are counted from the span's start, which has moved.
1972 span.ramp = span.ramp.map(|r| r.advanced(cut));
1973 span.len -= cut;
1974 span.start = r_start;
1975 }
1976 span.len = span.len.min(r_end - span.start);
1977 }
1978 spans
1979}
1980
1981/// The visible video lanes, bottom first: the last one is the topmost, the order
1982/// [`Project::composite_clip_at`] counts in.
1983fn visible_video_lanes(project: &Project) -> Vec<Lane> {
1984 project
1985 .lanes()
1986 .into_iter()
1987 .filter(|lane| lane.kind == LaneKind::Video && !project.lane_hidden(*lane))
1988 .collect()
1989}
1990
1991/// Every visible video clip covering `frame`, bottom first: the stack the
1992/// picture is composed from. One entry is the single-clip picture every path
1993/// has always drawn; two or more are a layered picture ([`layered_at`]), where
1994/// each clip is drawn over the ones beneath it.
1995pub(crate) fn stack_at(project: &Project, frame: u32) -> Vec<(Lane, usize)> {
1996 visible_video_lanes(project)
1997 .into_iter()
1998 .filter_map(|lane| Some((lane, project.lane_clip_at(lane, frame)?)))
1999 .collect()
2000}
2001
2002/// Whether `frame` is a layered picture: more than one visible clip covers it.
2003pub(crate) fn layered_at(project: &Project, frame: u32) -> bool {
2004 let stack = stack_at(project, frame);
2005 stack.len() >= 2 || animated_at(project, frame) || generated_at(project, &stack)
2006}
2007
2008/// Whether a clip covering `frame` is an adjustment layer or an animated generator
2009/// ([`crate::generate`]): neither is a picture the single-clip path draws.
2010fn generated_at(project: &Project, stack: &[(Lane, usize)]) -> bool {
2011 stack.iter().any(|&(lane, idx)| {
2012 let src = project.sources().get(project.lane(lane)[idx].source);
2013 src.and_then(|s| crate::generate::Gen::parse(&s.path)).is_some_and(|g| g.animated() || g.is_adjust() || g.has_alpha())
2014 })
2015}
2016
2017/// The one clip covering `frame` when its only animation is colour keys or an
2018/// effects stack and nothing dissolves out of it: a 10-bit export keeps such a
2019/// clip on the single-clip path, grading each picture by [`clip_color_at`] and
2020/// drawing its effects at 10 bits ([`crate::effects`]), rather than composing it
2021/// layered at 8 bits.
2022fn color_keyed_alone_at(project: &Project, frame: u32) -> Option<&crate::project::Clip> {
2023 let [(lane, idx)] = stack_at(project, frame)[..] else {
2024 return None;
2025 };
2026 let clip = &project.lane(lane)[idx];
2027 ((!clip.color_keys.is_empty() || crate::effects::active(&clip.effects))
2028 && clip.transform_keys.is_empty()
2029 && clip.opacity_keys.is_empty()
2030 && cross_window(project, lane, idx).is_none())
2031 .then_some(clip)
2032}
2033
2034/// Whether the picture at `frame` is one a single clip cannot show: the clip on
2035/// top has placement keys, or its dissolve partner does. A keyed picture is
2036/// composed as a layered one, which places each frame's own placement
2037/// ([`LayerFeed::advance`]), so a single clip's span-long transform never has
2038/// to stand in for a moving one.
2039fn animated_at(project: &Project, frame: u32) -> bool {
2040 visible_video_lanes(project).into_iter().any(|lane| {
2041 let Some(idx) = project.lane_clip_at(lane, frame) else {
2042 return false;
2043 };
2044 if crate::project::clip_animated(&project.lane(lane)[idx]) {
2045 return true;
2046 }
2047 matches!(
2048 cross_window(project, lane, idx),
2049 Some((window, start)) if frame >= start && frame - start < window
2050 ) && project.lane(lane).get(idx + 1).is_some_and(crate::project::clip_animated)
2051 })
2052}
2053
2054/// [`Project::composite_span_at`] over the stack. The topmost covering clip
2055/// supplies `from` and `speed`, and the span runs until any visible video lane
2056/// changes what covers the frame -- a clip there starts or ends. With one
2057/// covering clip that is exactly the composite's own span; across a stack it
2058/// also cuts where a lower lane changes beneath the picture on top, since the
2059/// picture under it is then a different one.
2060pub(crate) fn stack_span_at(project: &Project, frame: u32) -> Option<crate::project::Span> {
2061 let total = project.timeline_frames();
2062 if frame >= total {
2063 return None;
2064 }
2065 let mut until = total;
2066 for lane in visible_video_lanes(project) {
2067 let clips = project.lane(lane);
2068 match project.lane_clip_at(lane, frame) {
2069 Some(idx) => until = until.min(clips[idx].end()),
2070 None => {
2071 if let Some(next) = clips.iter().find(|c| c.start > frame) {
2072 until = until.min(next.start);
2073 }
2074 }
2075 }
2076 }
2077 let (from, speed, ramp, reverse) = match stack_at(project, frame).pop() {
2078 Some((lane, idx)) => {
2079 let clip = &project.lane(lane)[idx];
2080 let (speed, ramp) = crate::project::span_speed_of(clip, frame);
2081 (
2082 Some((clip.source, clip_source_frame(clip, frame))),
2083 speed,
2084 ramp,
2085 clip.reversed,
2086 )
2087 }
2088 None => (None, Speed::NORMAL, None, false),
2089 };
2090 Some(crate::project::Span {
2091 start: frame,
2092 len: until - frame,
2093 from,
2094 speed,
2095 ramp,
2096 reverse,
2097 pitch: 0.0,
2098 })
2099}
2100
2101/// [`Project::composite_spans_from`] over the stack: every span from `frame` on.
2102pub(crate) fn stack_spans_from(project: &Project, frame: u32) -> Vec<crate::project::Span> {
2103 let mut out = Vec::new();
2104 let mut t = frame;
2105 while let Some(span) = stack_span_at(project, t) {
2106 t = span.end();
2107 out.push(span);
2108 }
2109 out
2110}
2111
2112/// Which source frame a clip plays at timeline `frame` -- the project's own
2113/// rule, clamped inside the clip's range.
2114fn clip_source_frame(clip: &crate::project::Clip, frame: u32) -> u32 {
2115 (crate::project::source_pos(clip, frame - clip.start).floor() as u32).min(clip.out_frame - 1)
2116}
2117
2118/// One clip of a layered picture, open for the span: its decoder, read forward
2119/// as the picture advances, and the canvas its picture lands on -- the same
2120/// placement a single clip gets ([`place_picture`]).
2121struct LayerFeed {
2122 clip: crate::project::Clip,
2123 info: Placed,
2124 meta: VideoMeta,
2125 grade: Option<crate::color::ColorParams>,
2126 /// The grade the current picture was graded with, so a colour-keyed clip is
2127 /// graded again the frame its grade moves, even on the same source frame.
2128 graded_with: Option<crate::color::ColorParams>,
2129 /// The clip's base placement ([`Clip::transform`] resolved); its keys, when
2130 /// it has any, are read from `clip` at each frame ([`clip_transform_at`]).
2131 transform: TransformParams,
2132 /// The placement the current picture was placed with, so a keyed clip is
2133 /// placed again the frame its placement moves, even on the same source frame.
2134 placed_with: TransformParams,
2135 /// The clip's own opacity ([`TransformParams::opacity`]), applied as its
2136 /// coverage over the layers beneath rather than in its placement.
2137 opacity: f32,
2138 fit_canvas: Composer,
2139 rotated: Planes,
2140 stretched: Planes,
2141 graded: Planes,
2142 transformed: Planes,
2143 /// The decoder, and the file frame its next picture is.
2144 decoder: Option<(ClipDecoder, u32)>,
2145 /// The placed picture, and the file frame it is of.
2146 current: Option<(u32, Planes)>,
2147 /// The same picture composed at 10 bits ([`LayerStack::picture16`]), and the
2148 /// scratch only that path uses.
2149 current16: Option<(u32, Planes16)>,
2150 scratch16: Scratch16,
2151 widened: Planes16,
2152 steadied16: Planes16,
2153 adjusted16: Planes16,
2154 fx16: crate::effects::Scratch<u16>,
2155 /// Luma-sized coverage of the placed picture on the canvas: 255 where the
2156 /// clip's own pixels are, 0 in the letterbox bars and off the canvas. A
2157 /// layer above lets the one beneath show wherever this is 0.
2158 cover: Option<Vec<u8>>,
2159 matrix: Matrix,
2160 /// The dissolve this clip's tail owes the clip after it on its lane, when
2161 /// one is set and adjacent ([`cross_window`]).
2162 cross: Option<Box<LayerCross>>,
2163 /// The effects stack's scratch, and what it made of the current picture: its
2164 /// coverage (the placed footprint times the keys and masks) where it has any,
2165 /// and the mode it is laid down in ([`crate::effects`]).
2166 fx: crate::effects::Scratch<u8>,
2167 fx_cover: Option<Vec<u8>>,
2168 fx_mode: crate::effects::BlendMode,
2169 /// The clip's stabilisation, once its analysis is cached
2170 /// ([`crate::stabilise::correction`]): applied to the decoded picture, by its
2171 /// file frame, before anything else is.
2172 steady: Option<std::sync::Arc<crate::stabilise::Correction>>,
2173 steadied: Planes,
2174 /// The clip's deinterlace setting as it applies to its file. `Field` makes
2175 /// `info.rate` count fields; stabilisation is measured per file frame, so a
2176 /// field takes its frame's correction.
2177 deint: Deinterlace,
2178 /// An adjustment layer ([`crate::generate`]): no picture, its grade and effects act on the
2179 /// layers beneath ([`LayerFeed::adjust_over`]).
2180 adjust: bool,
2181 /// An adjustment layer's scratch, kept between frames like `steadied`: the placed and
2182 /// effected copy of the layers beneath, and its coverage.
2183 adjusted: Planes,
2184 adjust_cover: Vec<u8>,
2185 /// A generator with a transparent background ([`crate::generate::Gen::has_alpha`]) and its
2186 /// alpha at the size last asked for, kept so the mask is drawn once, not per coverage.
2187 alpha_gen: Option<crate::generate::Gen>,
2188 alpha_mask: Option<(u32, u32, Vec<u8>)>,
2189}
2190
2191/// The clip a layer's tail dissolves into: its own feed, and the window of
2192/// timeline frames the blend runs over, from `start` for `window` frames.
2193struct LayerCross {
2194 next: LayerFeed,
2195 window: u32,
2196 start: u32,
2197}
2198
2199/// The dissolve window a clip's tail owes its successor, as [`dissolve_window`]
2200/// reads it -- without the span rules, which a layered picture does not have:
2201/// it blends wherever its lane is on the clip, whatever is above it. `None` for
2202/// a hard cut, a stale transition out (the clips are no longer adjacent), or an
2203/// empty window. `(window, start)` in timeline frames.
2204fn cross_window(project: &Project, lane: Lane, idx: usize) -> Option<(u32, u32)> {
2205 let clips = project.lane(lane);
2206 let a = clips.get(idx)?;
2207 if a.transition_out == 0 {
2208 return None;
2209 }
2210 let b = clips.get(idx + 1)?;
2211 if a.end() != b.start {
2212 return None;
2213 }
2214 let window = a.transition_out.min(a.frames()).min(b.frames());
2215 (window > 0).then_some((window, a.end() - window))
2216}
2217
2218impl LayerFeed {
2219 /// The feed for clip `idx` of `lane`, with the dissolve it owes its
2220 /// successor opened beside it. `paths`, when given, is the file each source
2221 /// is decoded from in place of its own (a proxy stand-in), by source index.
2222 /// `measure`, when given, is the cancel flag a stabilised clip's missing
2223 /// analysis is run under before this returns ([`crate::stabilise::ensure`])
2224 /// and the stage it reports to ([`Shared::measuring`]); `None` takes only a
2225 /// finished one (the viewer, which shows the analysis's progress and redraws
2226 /// when it lands).
2227 fn open(
2228 project: &Project,
2229 meta: &VideoMeta,
2230 lane: Lane,
2231 idx: usize,
2232 matrix: Matrix,
2233 paths: Option<&[PathBuf]>,
2234 measure: Option<Measure<'_>>,
2235 ) -> crate::Result<Self> {
2236 let mut feed = Self::plain(project, meta, lane, idx, matrix, paths, measure)?;
2237 if let Some((window, start)) = cross_window(project, lane, idx) {
2238 let next = Self::plain(project, meta, lane, idx + 1, matrix, paths, measure)?;
2239 feed.cross = Some(Box::new(LayerCross {
2240 next,
2241 window,
2242 start,
2243 }));
2244 }
2245 Ok(feed)
2246 }
2247
2248 fn plain(
2249 project: &Project,
2250 meta: &VideoMeta,
2251 lane: Lane,
2252 idx: usize,
2253 matrix: Matrix,
2254 paths: Option<&[PathBuf]>,
2255 measure: Option<Measure<'_>>,
2256 ) -> crate::Result<Self> {
2257 let Some(clip) = project.lane(lane).get(idx).cloned() else {
2258 return Err("a layer names a clip that is not there".into());
2259 };
2260 let mut info = placed_info(project, meta, clip.source)?;
2261 if let Some(path) = paths.and_then(|paths| paths.get(clip.source)) {
2262 info.path = path.clone();
2263 }
2264 // Smoothed at the timeline's rate, as the viewer smooths it, over every
2265 // file frame the clip plays: an export measures what is missing rather
2266 // than write the clip unstabilised.
2267 let steady = match (clip.stabilise, project.sources().get(clip.source)) {
2268 (Some(st), Some(source)) => {
2269 let (lo, hi) = crate::stabilise::file_range(&clip, info.rate);
2270 match measure {
2271 Some((cancel, stage)) => {
2272 let mut tell = |f: f32| stage.store(1 + (f.clamp(0.0, 1.0) * 1000.0) as u32, Ordering::Relaxed);
2273 let c = crate::stabilise::ensure(&source.path, lo, hi, st, meta.frame_rate, &mut tell, cancel);
2274 stage.store(0, Ordering::Relaxed);
2275 Some(c?)
2276 }
2277 None => crate::stabilise::correction_or_start(&source.path, lo, hi, st, meta.frame_rate),
2278 }
2279 }
2280 _ => None,
2281 };
2282 let deint = crate::deinterlace::effective(clip.deinterlace, &info.path);
2283 info.rate = crate::deinterlace::counted_rate(deint, info.rate);
2284 Ok(Self {
2285 steady,
2286 steadied: Default::default(),
2287 deint,
2288 adjust: crate::generate::is_adjust(&info.path),
2289 adjusted: Default::default(),
2290 adjust_cover: Vec::new(),
2291 alpha_gen: crate::generate::Gen::parse(&info.path).filter(|g| g.has_alpha()),
2292 alpha_mask: None,
2293 info,
2294 meta: *meta,
2295 grade: project.color_of(lane, idx).copied(),
2296 graded_with: None,
2297 // The layer's opacity is its coverage in [`LayerStack::picture`], so
2298 // the placement below runs at opacity 1: a placed mask at opacity
2299 // below 1 would fade the coverage it is read for.
2300 transform: {
2301 let whole = project.transform_of(lane, idx).copied().unwrap_or_default();
2302 TransformParams {
2303 opacity: 1.0,
2304 ..whole
2305 }
2306 },
2307 opacity: project
2308 .transform_of(lane, idx)
2309 .map_or(1.0, |t| t.opacity),
2310 fit_canvas: Composer::new(meta.width, meta.height, project.fit_of(lane, idx)),
2311 clip,
2312 rotated: Default::default(),
2313 stretched: Default::default(),
2314 graded: Default::default(),
2315 transformed: Default::default(),
2316 decoder: None,
2317 current: None,
2318 current16: None,
2319 scratch16: Default::default(),
2320 widened: Default::default(),
2321 steadied16: Default::default(),
2322 adjusted16: Default::default(),
2323 fx16: Default::default(),
2324 cover: None,
2325 placed_with: TransformParams::default(),
2326 matrix,
2327 cross: None,
2328 fx: Default::default(),
2329 fx_cover: None,
2330 fx_mode: Default::default(),
2331 })
2332 }
2333
2334 /// The dissolve picture this clip shows at timeline `frame` while its tail
2335 /// blends into the next clip on its lane: the two placed pictures mixed by
2336 /// [`dissolve_weight`], and the coverage between the two clips' footprints
2337 /// mixed the same way. `None` outside the window, and where the next clip's
2338 /// file ends first -- then this clip's own picture stands, as a single
2339 /// clip's does. The next clip is read forward as this one is.
2340 fn cross_at(&mut self, frame: u32) -> crate::Result<Option<(Planes, Vec<u8>)>> {
2341 let Some(cross) = self.cross.as_mut() else {
2342 return Ok(None);
2343 };
2344 if frame < cross.start || frame - cross.start >= cross.window {
2345 return Ok(None);
2346 }
2347 // The next clip shows its own picture from its first frame on, as the
2348 // single clip's dissolve reads it ([`compose_at_with`]): window frame k
2349 // is its frame k, not the timeline frame, which is before its start.
2350 let k = frame - cross.start;
2351 if !cross.next.advance(cross.next.clip.start + k)? {
2352 return Ok(None);
2353 }
2354 let t = dissolve_weight(k, cross.window);
2355 let a_cover = self.fx_cover.as_deref().or(self.cover.as_deref());
2356 let (Some((_, a)), Some(a_cover)) = (self.current.as_ref(), a_cover) else {
2357 return Ok(None);
2358 };
2359 let b_cover = cross.next.fx_cover.as_deref().or(cross.next.cover.as_deref());
2360 let (Some((_, b)), Some(b_cover)) = (cross.next.current.as_ref(), b_cover)
2361 else {
2362 return Ok(None);
2363 };
2364 let planes = crate::transitions::blend_planes(
2365 self.clip.transition_kind,
2366 (&a.0, &a.1, &a.2),
2367 (&b.0, &b.1, &b.2),
2368 t,
2369 self.meta.width as usize,
2370 self.meta.height as usize,
2371 );
2372 let cover = a_cover
2373 .iter()
2374 .zip(b_cover)
2375 .map(|(&x, &y)| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8)
2376 .collect();
2377 Ok(Some((planes, cover)))
2378 }
2379
2380 /// [`LayerFeed::cross_at`] at 10 bits.
2381 fn cross_at16(&mut self, frame: u32) -> crate::Result<Option<(Planes16, Vec<u8>)>> {
2382 let Some(cross) = self.cross.as_mut() else {
2383 return Ok(None);
2384 };
2385 if frame < cross.start || frame - cross.start >= cross.window {
2386 return Ok(None);
2387 }
2388 let k = frame - cross.start;
2389 if !cross.next.advance16(cross.next.clip.start + k)? {
2390 return Ok(None);
2391 }
2392 let t = dissolve_weight(k, cross.window);
2393 let a_cover = self.fx_cover.as_deref().or(self.cover.as_deref());
2394 let (Some((_, a)), Some(a_cover)) = (self.current16.as_ref(), a_cover) else {
2395 return Ok(None);
2396 };
2397 let b_cover = cross.next.fx_cover.as_deref().or(cross.next.cover.as_deref());
2398 let (Some((_, b)), Some(b_cover)) = (cross.next.current16.as_ref(), b_cover) else {
2399 return Ok(None);
2400 };
2401 let planes = crate::transitions::blend_planes(
2402 self.clip.transition_kind,
2403 (&a.0, &a.1, &a.2),
2404 (&b.0, &b.1, &b.2),
2405 t,
2406 self.meta.width as usize,
2407 self.meta.height as usize,
2408 );
2409 let cover = a_cover
2410 .iter()
2411 .zip(b_cover)
2412 .map(|(&x, &y)| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8)
2413 .collect();
2414 Ok(Some((planes, cover)))
2415 }
2416
2417 /// Makes the placed picture for timeline `frame` the current one, reading
2418 /// the decoder forward to it. `false` when the file ends first.
2419 fn advance(&mut self, frame: u32) -> crate::Result<bool> {
2420 self.advance_as(frame, false)
2421 }
2422
2423 /// [`LayerFeed::advance`] at 10 bits: the placed picture lands in `current16`.
2424 fn advance16(&mut self, frame: u32) -> crate::Result<bool> {
2425 self.advance_as(frame, true)
2426 }
2427
2428 fn advance_as(&mut self, frame: u32, wide: bool) -> crate::Result<bool> {
2429 let want = self.info.rate.source_at(clip_source_frame(&self.clip, frame));
2430 // Coverage is the layer's own (see `LayerFeed::picture`), so the placement
2431 // runs at opacity 1 whatever the keys say.
2432 let tf = TransformParams {
2433 opacity: 1.0,
2434 ..crate::project::clip_transform_at(&self.clip, self.transform, frame)
2435 };
2436 // A colour-keyed clip's grade moves with the frame ([`clip_color_at`]).
2437 let grade = match self.clip.color_keys.is_empty() {
2438 true => self.grade,
2439 false => Some(crate::project::clip_color_at(
2440 &self.clip,
2441 self.grade.unwrap_or_default(),
2442 frame,
2443 )),
2444 };
2445 let have = match wide {
2446 true => self.current16.as_ref().map(|(at, _)| *at),
2447 false => self.current.as_ref().map(|(at, _)| *at),
2448 };
2449 if have == Some(want)
2450 && self.placed_with == tf
2451 && self.graded_with == grade
2452 && !crate::effects::animated(&self.clip.effects)
2453 {
2454 return Ok(true);
2455 }
2456 // A decoder that has read past the picture wanted is reopened at it;
2457 // playback and export only ever move forward through a span -- down it,
2458 // for a reversed clip, whose decoder counts the file frame it is on
2459 // downwards.
2460 let backwards = self.clip.reversed;
2461 let behind = matches!(&self.decoder, Some((_, pos)) if match backwards {
2462 true => *pos < want,
2463 false => *pos > want,
2464 });
2465 if self.decoder.is_none() || behind {
2466 let path = self.info.path.clone();
2467 let flags = self.clip.visualizer;
2468 let decoder = if crate::is_audio(&path) || flags & 1 != 0 {
2469 ClipDecoder::visualizer(
2470 &path,
2471 self.info.stream,
2472 want,
2473 (self.meta.width, self.meta.height),
2474 self.meta.frame_rate,
2475 flags,
2476 self.clip.viz_paint,
2477 )?
2478 } else if backwards && !crate::is_image(&path) {
2479 ClipDecoder::reversed(&path, want, self.info.rate.source_at(self.clip.in_frame), self.deint)
2480 } else {
2481 ClipDecoder::open_with(&path, want, None, None, wide, self.deint)?
2482 };
2483 self.decoder = Some((decoder, want));
2484 }
2485 let (decoder, pos) = self.decoder.as_mut().expect("opened above");
2486 while match backwards {
2487 true => *pos > want,
2488 false => *pos < want,
2489 } {
2490 if decoder.next()?.is_none() {
2491 return Ok(false);
2492 }
2493 *pos = if backwards { *pos - 1 } else { *pos + 1 };
2494 }
2495 let Some(picture) = decoder.next()? else {
2496 return Ok(false);
2497 };
2498 *pos = if backwards { pos.saturating_sub(1) } else { *pos + 1 };
2499 if wide {
2500 let (y, u, v, w, h): (&[u16], &[u16], &[u16], u32, u32) = match picture {
2501 Frame::Wide(y, u, v, w, h) => (y, u, v, w, h),
2502 Frame::Pixels(y, u, v, w, h) => {
2503 widen_into(y, &mut self.widened.0);
2504 widen_into(u, &mut self.widened.1);
2505 widen_into(v, &mut self.widened.2);
2506 (&self.widened.0[..], &self.widened.1[..], &self.widened.2[..], w, h)
2507 }
2508 Frame::Dma(_) => return Err("a layer's decoder produced no pixels".into()),
2509 };
2510 let (y, u, v) = match &self.steady {
2511 Some(c) => {
2512 let m = c.at(crate::deinterlace::file_frame(self.deint, &self.info.path, want), w).ok_or_else(|| -> crate::Error {
2513 format!("stabilise: file frame {want} lies before the measured range").into()
2514 })?;
2515 crate::stabilise::warp_i420(y, u, v, w, h, m, &mut self.steadied16);
2516 (&self.steadied16.0[..], &self.steadied16.1[..], &self.steadied16.2[..])
2517 }
2518 None => (y, u, v),
2519 };
2520 let remap = remap_into(Some(self.info.color), self.info.mapper.is_some(), self.matrix);
2521 let (py, pu, pv, pw, ph) = place_picture16(
2522 y,
2523 u,
2524 v,
2525 w,
2526 h,
2527 self.info.rotation,
2528 self.info.pixel_aspect,
2529 grade,
2530 tf,
2531 remap,
2532 self.info.mapper.as_ref(),
2533 &mut self.scratch16,
2534 &mut self.fit_canvas,
2535 );
2536 let mut planes = (py.to_vec(), pu.to_vec(), pv.to_vec());
2537 if self.cover.is_none() || self.placed_with != tf {
2538 self.cover = Some(self.coverage(w, h, tf));
2539 }
2540 debug_assert_eq!((pw, ph), (self.meta.width, self.meta.height), "a placed layer is canvas-sized");
2541 let secs = f64::from(frame) / self.meta.frame_rate;
2542 let src = crate::project::key_sample_pos(&self.clip, frame);
2543 let (mode, fx_cover) = layer_effects(
2544 &self.clip.effects,
2545 &mut planes,
2546 (pw, ph),
2547 secs,
2548 src,
2549 self.matrix,
2550 &mut self.fx16,
2551 self.cover.as_deref().expect("set above"),
2552 );
2553 self.fx_mode = mode;
2554 self.fx_cover = fx_cover;
2555 self.placed_with = tf;
2556 self.graded_with = grade;
2557 self.current16 = Some((want, planes));
2558 return Ok(true);
2559 }
2560 let Frame::Pixels(y, u, v, w, h) = picture else {
2561 return Err("a layer's decoder produced no pixels".into());
2562 };
2563 let (y, u, v) = match &self.steady {
2564 Some(c) => {
2565 let m = c.at(crate::deinterlace::file_frame(self.deint, &self.info.path, want), w).ok_or_else(|| -> crate::Error {
2566 format!("stabilise: file frame {want} lies before the measured range").into()
2567 })?;
2568 crate::stabilise::warp_i420(y, u, v, w, h, m, &mut self.steadied);
2569 (&self.steadied.0[..], &self.steadied.1[..], &self.steadied.2[..])
2570 }
2571 None => (y, u, v),
2572 };
2573 let remap = remap_into(
2574 Some(self.info.color),
2575 self.info.mapper.is_some(),
2576 self.matrix,
2577 );
2578 let (py, pu, pv, pw, ph) = place_picture(
2579 y,
2580 u,
2581 v,
2582 w,
2583 h,
2584 self.info.rotation,
2585 self.info.pixel_aspect,
2586 grade,
2587 tf,
2588 remap,
2589 self.info.mapper.as_ref(),
2590 &mut self.rotated,
2591 &mut self.stretched,
2592 &mut self.graded,
2593 &mut self.transformed,
2594 &mut self.fit_canvas,
2595 );
2596 let mut planes = (py.to_vec(), pu.to_vec(), pv.to_vec());
2597 if self.cover.is_none() || self.placed_with != tf {
2598 self.cover = Some(self.coverage(w, h, tf));
2599 }
2600 // The effects stack, on the placed picture: its filters rewrite the
2601 // samples, and its keys and masks narrow the footprint it lands with.
2602 debug_assert_eq!((pw, ph), (self.meta.width, self.meta.height), "a placed layer is canvas-sized");
2603 let secs = f64::from(frame) / self.meta.frame_rate;
2604 let src = crate::project::key_sample_pos(&self.clip, frame);
2605 let (mode, fx_cover) = layer_effects(
2606 &self.clip.effects,
2607 &mut planes,
2608 (pw, ph),
2609 secs,
2610 src,
2611 self.matrix,
2612 &mut self.fx,
2613 self.cover.as_deref().expect("set above"),
2614 );
2615 self.fx_mode = mode;
2616 self.fx_cover = fx_cover;
2617 self.placed_with = tf;
2618 self.graded_with = grade;
2619 self.current = Some((want, planes));
2620 Ok(true)
2621 }
2622
2623 /// The layers composed so far, `base`, with this adjustment layer's grade, placement and
2624 /// effects applied to them, at strength `k` (its fade times its opacity).
2625 ///
2626 /// The clip's transform moves the composite below it (as Motion on an adjustment layer does
2627 /// in Premiere), so what the placement uncovers -- a shrunk, shifted or rotated composite --
2628 /// goes black. Crop is different: the layer only reaches where its crop footprint
2629 /// ([`LayerFeed::coverage`], placement left out) is, so a cropped-away region keeps the base.
2630 fn adjust_over(&mut self, base: Planes, k: f32, frame: u32) -> Planes {
2631 let (w, h) = (self.meta.width, self.meta.height);
2632 let grade = match self.clip.color_keys.is_empty() {
2633 true => self.grade,
2634 false => Some(crate::project::clip_color_at(&self.clip, self.grade.unwrap_or_default(), frame)),
2635 };
2636 let tf = TransformParams { opacity: 1.0, ..crate::project::clip_transform_at(&self.clip, self.transform, frame) };
2637 let (py, pu, pv, _, _) = place_picture(
2638 &base.0, &base.1, &base.2, w, h, Rotation::None, crate::demux::PixelAspect::SQUARE, grade, tf, None, None,
2639 &mut self.rotated, &mut self.stretched, &mut self.graded, &mut self.transformed, &mut self.fit_canvas,
2640 );
2641 let mut adjusted = std::mem::take(&mut self.adjusted);
2642 for (dst, src) in [(&mut adjusted.0, py), (&mut adjusted.1, pu), (&mut adjusted.2, pv)] {
2643 dst.clear();
2644 dst.extend_from_slice(src);
2645 }
2646 let mut cover = std::mem::take(&mut self.adjust_cover);
2647 cover.clear();
2648 // Only the crop limits the layer: the placement moved the composite itself, and
2649 // what it uncovers is the black of its own fit bars.
2650 // With crop and a transform together the crop footprint stays at the identity
2651 // position while the picture moves: the crop limits where the layer acts, not what moves.
2652 let crop = TransformParams { crop_l: tf.crop_l, crop_r: tf.crop_r, crop_t: tf.crop_t, crop_b: tf.crop_b, ..TransformParams::default() };
2653 match crop == TransformParams::default() {
2654 true => cover.resize(w as usize * h as usize, 255),
2655 false => cover.extend(self.coverage(w, h, crop)),
2656 }
2657 if crate::effects::active(&self.clip.effects) {
2658 let out = crate::effects::apply(
2659 &self.clip.effects,
2660 (&mut adjusted.0, &mut adjusted.1, &mut adjusted.2),
2661 w as usize,
2662 h as usize,
2663 f64::from(frame) / self.meta.frame_rate,
2664 crate::project::key_sample_pos(&self.clip, frame),
2665 self.matrix,
2666 &mut self.fx,
2667 );
2668 if let Some(alpha) = out.alpha {
2669 for (c, a) in cover.iter_mut().zip(alpha) {
2670 *c = ((u32::from(*c) * u32::from(a) + 127) / 255) as u8;
2671 }
2672 }
2673 }
2674 let mut result = base;
2675 layer_over(&mut result, &adjusted, &cover, k, w as usize, h as usize);
2676 self.adjusted = adjusted;
2677 self.adjust_cover = cover;
2678 result
2679 }
2680
2681 /// [`LayerFeed::adjust_over`] at 10 bits.
2682 fn adjust_over16(&mut self, base: Planes16, k: f32, frame: u32) -> Planes16 {
2683 let (w, h) = (self.meta.width, self.meta.height);
2684 let grade = match self.clip.color_keys.is_empty() {
2685 true => self.grade,
2686 false => Some(crate::project::clip_color_at(&self.clip, self.grade.unwrap_or_default(), frame)),
2687 };
2688 let tf = TransformParams { opacity: 1.0, ..crate::project::clip_transform_at(&self.clip, self.transform, frame) };
2689 let (py, pu, pv, _, _) = place_picture16(
2690 &base.0, &base.1, &base.2, w, h, Rotation::None, crate::demux::PixelAspect::SQUARE, grade, tf, None, None,
2691 &mut self.scratch16, &mut self.fit_canvas,
2692 );
2693 let mut adjusted = std::mem::take(&mut self.adjusted16);
2694 for (dst, src) in [(&mut adjusted.0, py), (&mut adjusted.1, pu), (&mut adjusted.2, pv)] {
2695 dst.clear();
2696 dst.extend_from_slice(src);
2697 }
2698 let mut cover = std::mem::take(&mut self.adjust_cover);
2699 cover.clear();
2700 let crop = TransformParams { crop_l: tf.crop_l, crop_r: tf.crop_r, crop_t: tf.crop_t, crop_b: tf.crop_b, ..TransformParams::default() };
2701 match crop == TransformParams::default() {
2702 true => cover.resize(w as usize * h as usize, 255),
2703 false => cover.extend(self.coverage(w, h, crop)),
2704 }
2705 if crate::effects::active(&self.clip.effects) {
2706 let out = crate::effects::apply(
2707 &self.clip.effects,
2708 (&mut adjusted.0, &mut adjusted.1, &mut adjusted.2),
2709 w as usize,
2710 h as usize,
2711 f64::from(frame) / self.meta.frame_rate,
2712 crate::project::key_sample_pos(&self.clip, frame),
2713 self.matrix,
2714 &mut self.fx16,
2715 );
2716 if let Some(alpha) = out.alpha {
2717 for (c, a) in cover.iter_mut().zip(alpha) {
2718 *c = ((u32::from(*c) * u32::from(a) + 127) / 255) as u8;
2719 }
2720 }
2721 }
2722 let mut result = base;
2723 layer_over(&mut result, &adjusted, &cover, k, w as usize, h as usize);
2724 self.adjusted16 = adjusted;
2725 self.adjust_cover = cover;
2726 result
2727 }
2728
2729 /// Where a `w` x `h` picture of this clip lands on the canvas, as luma: the
2730 /// same placement, run on a picture that is white everywhere, so the cover
2731 /// is exactly the placed picture's footprint -- transform, crop, fit bars
2732 /// and all -- without a second copy of that geometry to keep in step.
2733 fn coverage(&mut self, w: u32, h: u32, transform: TransformParams) -> Vec<u8> {
2734 // A generator with a transparent background ([`crate::generate::Gen::has_alpha`]) places
2735 // its alpha as the luma (limited range, so the fit bars are 0) and is covered by degree.
2736 // The mask is drawn at the picture's own size, so a canvas that is not the generator's
2737 // still gets a shape, not the full frame. It reaches `place_picture` as plain luma with
2738 // no grade, remap or tonemap (all `None` below): only geometry and resampling touch it.
2739 if let Some(g) = self.alpha_gen
2740 && !matches!(&self.alpha_mask, Some((mw, mh, _)) if (*mw, *mh) == (w, h))
2741 {
2742 let mask = crate::generate::Gen::new(g.kind, w, h).alpha().expect("an alpha generator has a mask");
2743 self.alpha_mask = Some((w, h, mask));
2744 }
2745 let alpha = self.alpha_gen.and(self.alpha_mask.as_ref()).map(|(_, _, m)| m);
2746 let ones: Vec<u8> = match alpha {
2747 Some(a) => a.iter().map(|&v| 16 + (u32::from(v) * 219 / 255) as u8).collect(),
2748 None => vec![255u8; w as usize * h as usize],
2749 };
2750 let chroma = vec![128u8; w.div_ceil(2) as usize * h.div_ceil(2) as usize];
2751 let (cy, _, _, _, _) = place_picture(
2752 &ones,
2753 &chroma,
2754 &chroma,
2755 w,
2756 h,
2757 self.info.rotation,
2758 self.info.pixel_aspect,
2759 None,
2760 transform,
2761 None,
2762 None,
2763 &mut self.rotated,
2764 &mut self.stretched,
2765 &mut self.graded,
2766 &mut self.transformed,
2767 &mut self.fit_canvas,
2768 );
2769 match alpha.is_some() {
2770 true => cy.iter().map(|&p| ((u32::from(p.clamp(16, 235)) - 16) * 255 / 219) as u8).collect(),
2771 false => cy.iter().map(|&p| if p >= 128 { 255 } else { 0 }).collect(),
2772 }
2773 }
2774}
2775
2776/// A layer's effects stack drawn on its placed picture `planes` (a canvas of `size`): the
2777/// blend mode it lands in and the coverage its keys and masks leave of `cover`, `None` where
2778/// it has no effects (or none that cut the footprint). Generic over the sample so the 8-bit
2779/// and the 10-bit layer paths draw one stack the same way.
2780#[allow(clippy::too_many_arguments)]
2781fn layer_effects<T: crate::scale::Sample>(
2782 effects: &[crate::effects::Effect],
2783 planes: &mut Planes<T>,
2784 size: (u32, u32),
2785 secs: f64,
2786 src: f64,
2787 matrix: Matrix,
2788 scratch: &mut crate::effects::Scratch<T>,
2789 cover: &[u8],
2790) -> (crate::effects::BlendMode, Option<Vec<u8>>) {
2791 if !crate::effects::active(effects) {
2792 return (Default::default(), None);
2793 }
2794 let out = crate::effects::apply(
2795 effects,
2796 (&mut planes.0, &mut planes.1, &mut planes.2),
2797 size.0 as usize,
2798 size.1 as usize,
2799 secs,
2800 src,
2801 matrix,
2802 scratch,
2803 );
2804 let fx_cover = out.alpha.map(|alpha| {
2805 debug_assert_eq!(cover.len(), alpha.len(), "the cover and the effects' alpha are one size");
2806 cover
2807 .iter()
2808 .zip(alpha)
2809 .map(|(&c, a)| ((u32::from(c) * u32::from(a) + 127) / 255) as u8)
2810 .collect()
2811 });
2812 (out.mode, fx_cover)
2813}
2814
2815/// A layered picture's clips, open together: read forward by timeline frame and
2816/// composed bottom to top ([`LayerStack::picture`]).
2817pub(crate) struct LayerStack {
2818 feeds: Vec<LayerFeed>,
2819 width: usize,
2820 height: usize,
2821}
2822
2823impl LayerStack {
2824 /// The clips of `stack` ([`stack_at`]) on a `meta`-sized canvas, colour
2825 /// converted with `matrix`, decoded from `paths` where given (see
2826 /// [`LayerFeed::open`]). Nothing is decoded until a frame is asked for.
2827 pub(crate) fn open(
2828 project: &Project,
2829 meta: &VideoMeta,
2830 stack: &[(Lane, usize)],
2831 matrix: Matrix,
2832 paths: Option<&[PathBuf]>,
2833 measure: Option<Measure<'_>>,
2834 ) -> crate::Result<Self> {
2835 let feeds = stack
2836 .iter()
2837 .map(|&(lane, idx)| LayerFeed::open(project, meta, lane, idx, matrix, paths, measure))
2838 .collect::<crate::Result<Vec<_>>>()?;
2839 Ok(Self {
2840 feeds,
2841 width: meta.width as usize,
2842 height: meta.height as usize,
2843 })
2844 }
2845
2846 /// The composed I420 picture at timeline `frame`, or `None` once a clip's
2847 /// file ends before it. The bottom clip is drawn exactly as a single clip
2848 /// is (its bars black); each clip above lands on it where its own picture
2849 /// covers, at its own fade -- so a fade on a picture on top shows the one
2850 /// beneath through it, rather than fading the whole frame. A clip whose
2851 /// tail is dissolving into the next clip on its lane shows the blend of the
2852 /// two over the window ([`LayerFeed::cross_at`]), and the layers above
2853 /// composite over that -- so a dissolve under a picture-in-picture blends
2854 /// the same as one without it.
2855 pub(crate) fn picture(&mut self, frame: u32) -> crate::Result<Option<Planes>> {
2856 let (w, h) = (self.width, self.height);
2857 let mut out: Option<Planes> = None;
2858 for feed in &mut self.feeds {
2859 if !feed.adjust && !feed.advance(frame)? {
2860 return Ok(None);
2861 }
2862 // The fade and the opacity both scale this layer's coverage.
2863 let opacity = crate::project::clip_transform_at(
2864 &feed.clip,
2865 TransformParams {
2866 opacity: feed.opacity,
2867 ..TransformParams::default()
2868 },
2869 frame,
2870 )
2871 .opacity;
2872 let opacity = crate::project::clip_opacity_at(&feed.clip, opacity, frame);
2873 let k = clip_fade(&feed.clip, frame).unwrap_or(1.0) * opacity;
2874 // An adjustment layer with nothing beneath it is a no-op. Adjacent adjustment clips
2875 // hard-cut: `cross_at` is skipped for them, so a dissolve between two does nothing.
2876 if feed.adjust {
2877 out = out.take().map(|base| feed.adjust_over(base, k, frame));
2878 continue;
2879 }
2880 let blended = feed.cross_at(frame)?;
2881 let (planes, cover): (&Planes, &[u8]) = match blended.as_ref() {
2882 Some((planes, cover)) => (planes, cover.as_slice()),
2883 None => {
2884 let Some((_, planes)) = feed.current.as_ref() else {
2885 return Ok(None);
2886 };
2887 let cover = feed.fx_cover.as_deref().or(feed.cover.as_deref());
2888 (planes, cover.expect("set with the picture"))
2889 }
2890 };
2891 // A clip whose effects key, mask or blend it is laid over what is
2892 // beneath -- black, at the bottom -- by [`crate::effects::blend_over`].
2893 let mode = feed.fx_mode;
2894 if feed.fx_cover.is_some() || mode != crate::effects::BlendMode::Normal {
2895 let base = out.get_or_insert_with(|| crate::scale::black_i420(w, h));
2896 crate::effects::blend_over(
2897 (&mut base.0, &mut base.1, &mut base.2),
2898 borrow_planes(planes),
2899 cover,
2900 k,
2901 mode,
2902 feed.matrix,
2903 w,
2904 h,
2905 );
2906 continue;
2907 }
2908 // A picture with a transparent background lands on black, as the bottom layer does.
2909 if out.is_none() && feed.alpha_gen.is_some() {
2910 out = Some(crate::scale::black_i420(w, h));
2911 }
2912 match out.as_mut() {
2913 // The bottom layer sits on black, as a single clip does.
2914 None => {
2915 out = Some(match k < 1.0 {
2916 true => fade_planes(borrow_planes(planes), k),
2917 false => planes.clone(),
2918 });
2919 }
2920 Some(base) => layer_over(base, planes, cover, k, w, h),
2921 }
2922 }
2923 // Nothing drew (a stack of adjustment layers alone) is a gap: black.
2924 Ok(Some(out.unwrap_or_else(|| crate::scale::black_i420(w, h))))
2925 }
2926
2927 /// [`LayerStack::picture`] at 10 bits: 10-bit layers keep every sample, 8-bit ones are
2928 /// widened where they meet, and the grade, the placement, the blends and the effects all
2929 /// run on 10-bit codes.
2930 pub(crate) fn picture16(&mut self, frame: u32) -> crate::Result<Option<Planes16>> {
2931 let (w, h) = (self.width, self.height);
2932 let mut out: Option<Planes16> = None;
2933 for feed in &mut self.feeds {
2934 if !feed.adjust && !feed.advance16(frame)? {
2935 return Ok(None);
2936 }
2937 let opacity = crate::project::clip_transform_at(
2938 &feed.clip,
2939 TransformParams {
2940 opacity: feed.opacity,
2941 ..TransformParams::default()
2942 },
2943 frame,
2944 )
2945 .opacity;
2946 let opacity = crate::project::clip_opacity_at(&feed.clip, opacity, frame);
2947 let k = clip_fade(&feed.clip, frame).unwrap_or(1.0) * opacity;
2948 if feed.adjust {
2949 out = out.take().map(|base| feed.adjust_over16(base, k, frame));
2950 continue;
2951 }
2952 let blended = feed.cross_at16(frame)?;
2953 let (planes, cover): (&Planes16, &[u8]) = match blended.as_ref() {
2954 Some((planes, cover)) => (planes, cover.as_slice()),
2955 None => {
2956 let Some((_, planes)) = feed.current16.as_ref() else {
2957 return Ok(None);
2958 };
2959 let cover = feed.fx_cover.as_deref().or(feed.cover.as_deref());
2960 (planes, cover.expect("set with the picture"))
2961 }
2962 };
2963 let mode = feed.fx_mode;
2964 if feed.fx_cover.is_some() || mode != crate::effects::BlendMode::Normal {
2965 let base = out.get_or_insert_with(|| crate::scale::black_i420_wide(w, h));
2966 crate::effects::blend_over(
2967 (&mut base.0, &mut base.1, &mut base.2),
2968 borrow_planes(planes),
2969 cover,
2970 k,
2971 mode,
2972 feed.matrix,
2973 w,
2974 h,
2975 );
2976 continue;
2977 }
2978 if out.is_none() && feed.alpha_gen.is_some() {
2979 out = Some(crate::scale::black_i420_wide(w, h));
2980 }
2981 match out.as_mut() {
2982 None => {
2983 out = Some(match k < 1.0 {
2984 true => fade_planes(borrow_planes(planes), k),
2985 false => planes.clone(),
2986 });
2987 }
2988 Some(base) => layer_over(base, planes, cover, k, w, h),
2989 }
2990 }
2991 Ok(Some(out.unwrap_or_else(|| crate::scale::black_i420_wide(w, h))))
2992 }
2993}
2994
2995/// `top` laid over `base` where `cover` says the picture is, at strength `k`
2996/// (its fade times 1). Luma takes each sample's own coverage; chroma takes the
2997/// coverage of the luma sample at its block's top left.
2998fn layer_over<T: crate::scale::Sample>(base: &mut Planes<T>, top: &Planes<T>, cover: &[u8], k: f32, w: usize, h: usize) {
2999 let mix = |b: T, t: T, a: f32| {
3000 let (b, t) = (b.code() as f32, t.code() as f32);
3001 T::from_f32(b + (t - b) * a)
3002 };
3003 for (i, (b, &t)) in base.0.iter_mut().zip(&top.0).enumerate() {
3004 let a = f32::from(cover[i]) / 255.0 * k;
3005 if a > 0.0 {
3006 *b = mix(*b, t, a);
3007 }
3008 }
3009 let cw = w.div_ceil(2);
3010 for i in 0..cw * h.div_ceil(2) {
3011 let (cx, cy) = (i % cw, i / cw);
3012 let a = f32::from(cover[2 * cy * w + 2 * cx]) / 255.0 * k;
3013 if a > 0.0 {
3014 base.1[i] = mix(base.1[i], top.1[i], a);
3015 base.2[i] = mix(base.2[i], top.2[i], a);
3016 }
3017 }
3018}
3019
3020/// A layered span as a playback stream: its composed frames, one per picture
3021/// change, decoded on a thread of their own. Each is `view`-sized and numbered
3022/// the way a decoder numbers its pictures -- the span's first source frame plus
3023/// the speed's step -- so the playback clock maps it like any other clip.
3024pub(crate) fn layered_stream(
3025 project: Project,
3026 view: VideoMeta,
3027 out_color: ColorDescription,
3028 span: crate::project::Span,
3029 paths: Option<Vec<PathBuf>>,
3030) -> crate::decode::FrameStream {
3031 let stack = stack_at(&project, span.start);
3032 let base = span.from.map_or(0, |(_, in_frame)| in_frame);
3033 crate::decode::DecodeSession::spawn_stream(
3034 "layers",
3035 crate::decode::Backend::Software,
3036 move |tx, cancel| {
3037 let Ok(mut layers) =
3038 LayerStack::open(&project, &view, &stack, out_color.matrix, paths.as_deref(), None)
3039 else {
3040 return;
3041 };
3042 let mut last = None;
3043 for offset in 0..span.len {
3044 if cancel.load(Ordering::Relaxed) {
3045 return;
3046 }
3047 // One picture per source step, as a decoder yields one per frame:
3048 // a slowed clip's repeats are held by the clock, not decoded again.
3049 let step = span.source_offset(offset);
3050 if last == Some(step) {
3051 continue;
3052 }
3053 last = Some(step);
3054 let Ok(Some((y, u, v))) = layers.picture(span.start + offset) else {
3055 return;
3056 };
3057 let bgra = crate::convert::i420_to_bgra(
3058 &out_color,
3059 &y,
3060 &u,
3061 &v,
3062 view.width as usize,
3063 view.height as usize,
3064 );
3065 let frame = crate::decode::Frame {
3066 index: base + step,
3067 width: view.width,
3068 height: view.height,
3069 bgra,
3070 };
3071 if tx.send(frame).is_err() {
3072 return;
3073 }
3074 }
3075 },
3076 )
3077}
3078
3079/// The cross-dissolve this span's tail owes its successor, or `None` for a
3080/// hard cut. `(b_source, b_in_frame, window, b_start)`: which source and
3081/// source frame the dissolve's B side starts reading, how many *output*
3082/// frames the blend ramps across, and where B sits on the timeline (which is
3083/// what its own grade and fit are keyed on, [`Project::composite_color_at`]
3084/// and [`Project::composite_fit_at`]).
3085///
3086/// [`Clip::transition_out`] is trusted only after adjacency is checked again
3087/// here: a trim or a split since it was set leaves the stored number in
3088/// place but not its meaning, so a stale one plays as the hard cut it now
3089/// is rather than as a dissolve into a clip that no longer follows.
3090pub(crate) fn dissolve_window(
3091 project: &Project,
3092 span: &crate::project::Span,
3093) -> Option<(usize, u32, u32, u32)> {
3094 // A layered picture is composed beneath its top clip, and a dissolve of that
3095 // clip would blend a picture of one clip alone -- the layers are not blended.
3096 if layered_at(project, span.start) {
3097 return None;
3098 }
3099 let (source, _) = span.from?;
3100 let (lane, idx) = project.composite_clip_at(span.start)?;
3101 let clips = project.lane(lane);
3102 let a = clips.get(idx)?;
3103 if a.source != source || a.transition_out == 0 {
3104 return None;
3105 }
3106 let b = clips.get(idx + 1)?;
3107 if a.end() != b.start {
3108 return None; // trimmed or split apart since the dissolve was set
3109 }
3110 // The span must run uninterrupted all the way to A's own end: a higher
3111 // video lane taking over before that means there is no tail of A left
3112 // here to blend into anything.
3113 if span.start + span.len != a.end() {
3114 return None;
3115 }
3116 let window = a
3117 .transition_out
3118 .min(a.frames())
3119 .min(b.frames())
3120 .min(span.len);
3121 (window > 0).then_some((b.source, b.in_frame, window, b.start))
3122}
3123
3124/// `B`'s weight in [`crate::scale::blend_i420`] at output frame `idx_in_window` of `window`
3125/// (`idx_in_window < window`): a ramp from just above 0 to just below 1 that
3126/// never actually reaches either end, so the first blended frame still shows
3127/// a trace of A and the last still a trace of B -- the cut a hard transition
3128/// would have made lands one frame *after* the window, at full B, rather than
3129/// inside it.
3130pub(crate) fn dissolve_weight(idx_in_window: u32, window: u32) -> f32 {
3131 (idx_in_window + 1) as f32 / (window + 1) as f32
3132}
3133
3134/// The picture's black fade at timeline `frame`: the share of the picture that
3135/// survives, `None` where no fade reaches it. The clip on screen
3136/// ([`Project::composite_clip_at`]) owns its own fades -- [`Clip::fade_in`] ramps
3137/// from black on its first frame to the whole picture at `fade_in`, and
3138/// [`Clip::fade_out`] ramps back to black over its last `fade_out` frames, the
3139/// same edges [`crate::project::Fade`] ramps the sound on. A linear ramp: the
3140/// first frame of a fade-in is pure black and the frame a fade-out ends on is
3141/// one step short of it, so nothing shows the picture at full strength while
3142/// the ramp is still running.
3143pub(crate) fn picture_fade_at(project: &Project, frame: u32) -> Option<f32> {
3144 let (lane, idx) = project.composite_clip_at(frame)?;
3145 clip_fade(project.lane(lane).get(idx)?, frame)
3146}
3147
3148/// [`picture_fade_at`] for one clip: the share of its picture that survives at
3149/// `frame`. A layered picture asks it of each clip, so a fade belongs to the
3150/// clip it is on.
3151fn clip_fade(clip: &crate::project::Clip, frame: u32) -> Option<f32> {
3152 if clip.fade_in == 0 && clip.fade_out == 0 {
3153 return None;
3154 }
3155 let pos = frame.checked_sub(clip.start)?;
3156 let total = clip.frames();
3157 let mut k = 1.0f32;
3158 if clip.fade_in > 0 && pos < clip.fade_in {
3159 k = pos as f32 / clip.fade_in as f32;
3160 }
3161 if clip.fade_out > 0 && pos >= total.saturating_sub(clip.fade_out) {
3162 k = k.min((total - pos) as f32 / clip.fade_out as f32);
3163 }
3164 (k < 1.0).then_some(k)
3165}
3166
3167/// Whether any frame of `span` is inside a picture fade ([`picture_fade_at`]):
3168/// the span's pixels then have to be touched, which a zero-copy span never is.
3169fn picture_faded_in(project: &Project, span: &crate::project::Span) -> bool {
3170 (span.start..span.start.saturating_add(span.len))
3171 .any(|frame| picture_fade_at(project, frame).is_some())
3172}
3173
3174/// Whether any video clip on the timeline has a picture fade -- the
3175/// picture-side twin of [`faded`], which asks the same of sound: a fade is
3176/// pixel math, so a stream copy cannot carry one.
3177fn picture_faded(project: &Project) -> bool {
3178 project
3179 .lanes()
3180 .into_iter()
3181 .filter(|lane| lane.kind == LaneKind::Video)
3182 .any(|lane| {
3183 project
3184 .lane(lane)
3185 .iter()
3186 .any(|c| c.fade_in > 0 || c.fade_out > 0)
3187 })
3188}
3189
3190/// `planes` drawn toward black by `k` ([`picture_fade_at`]): luma moves toward
3191/// 16 and chroma toward 128, the black a gap is composed as, so a faded frame
3192/// and a gap agree on what black is.
3193fn fade_planes<T: Sample>(planes: (&[T], &[T], &[T]), k: f32) -> Planes<T> {
3194 let toward = |s: &[T], black: T| -> Vec<T> {
3195 s.iter()
3196 .map(|&p| {
3197 let (black, p) = (black.code() as f32, p.code() as f32);
3198 T::from_f32(black + (p - black) * k)
3199 })
3200 .collect()
3201 };
3202 (
3203 toward(planes.0, T::BLACK),
3204 toward(planes.1, T::NEUTRAL),
3205 toward(planes.2, T::NEUTRAL),
3206 )
3207}
3208
3209/// A dissolve's B side, open beside A's own decoder for this span's tail:
3210/// its own decoder, and everything [`place_picture`] needs to put its frames
3211/// on the same canvas, in the same space, graded the way B is graded rather
3212/// than the way A is -- [`Project::composite_color_at`]/`composite_fit_at`
3213/// asked at B's own start, not at the timeline position the blend writes to,
3214/// which is still inside A's span.
3215struct Dissolve<'a> {
3216 /// How many output frames the blend ramps across.
3217 window: u32,
3218 kind: crate::transitions::TransitionKind,
3219 /// The first output frame of this span's tail that is inside the window.
3220 tail_start: u32,
3221 decoder: ClipDecoder,
3222 mapper: Option<&'a ToneMapper>,
3223 remap: Option<Remap>,
3224 grade: Option<crate::color::ColorParams>,
3225 transform: TransformParams,
3226 /// B's own file's display-matrix turn, [`place_picture`]'s first stage;
3227 /// B is a different file and may be turned differently from A.
3228 rotation: Rotation,
3229 /// B's own file's sample aspect, [`place_picture`]'s second stage, for
3230 /// the same reason the turn is per file.
3231 pixel_aspect: crate::demux::PixelAspect,
3232 canvas: Composer,
3233 /// The turn's, the grade's and the transform's scratch, exactly as A's
3234 /// span keeps them: refilled per picture, allocated once.
3235 rotated: (Vec<u8>, Vec<u8>, Vec<u8>),
3236 /// The stretch's own scratch, [`place_picture`]'s second stage -- the
3237 /// pixel aspect's, beside the turn's.
3238 stretched: (Vec<u8>, Vec<u8>, Vec<u8>),
3239 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
3240 transformed: (Vec<u8>, Vec<u8>, Vec<u8>),
3241 /// The 10-bit scratch of B's placement, for a 10-bit export.
3242 scratch16: Scratch16,
3243}
3244
3245/// The Videos folder a default export lands in: the user's own (`XDG_VIDEOS_DIR`,
3246/// else the one `~/.config/user-dirs.dirs` names, else `~/Videos`), then the
3247/// project's folder, never the media's own folder by default.
3248pub fn default_export_folder(project: &Path) -> PathBuf {
3249 let home = std::env::var_os("HOME").map(PathBuf::from);
3250 let xdg = std::env::var_os("XDG_VIDEOS_DIR").map(PathBuf::from).or_else(|| {
3251 let home = home.as_ref()?;
3252 let text = std::fs::read_to_string(home.join(".config/user-dirs.dirs")).ok()?;
3253 let line = text.lines().find_map(|l| l.trim().strip_prefix("XDG_VIDEOS_DIR="))?;
3254 let value = line.trim().trim_matches('"');
3255 Some(PathBuf::from(value.replace("$HOME", &home.to_string_lossy())))
3256 });
3257 let videos = xdg.filter(|d| d.is_dir()).or_else(|| home.map(|h| h.join("Videos")).filter(|d| d.is_dir()));
3258 videos
3259 .or_else(|| project.parent().filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf))
3260 .unwrap_or_else(|| PathBuf::from("."))
3261}
3262
3263/// The track's cues where the *exported* timeline puts them, which is the only
3264/// clock the file has: the export writes timeline frame 0 onwards and nothing
3265/// else, exactly as the sound is mixed from frame 0 and resized to the
3266/// timeline's own length ([`encode_audio`]).
3267///
3268/// Which clock the cues arrive in is what the track itself says:
3269///
3270/// * a track out of a *file* (`SubtitleTrack::track`) is timed against that
3271/// file, so each cue is carried through the spans that play it -- a cue over
3272/// a stretch that was cut out is gone, one straddling a cut keeps the half
3273/// that is still there, and one after a rippled delete moves back with the
3274/// picture it belongs to. The *edges* a cut clips to are frames -- that is
3275/// what a cut is -- but a cue nothing clipped keeps its own microseconds, so
3276/// an untouched timeline exports the times the source states.
3277/// * a *standalone* file (`subs.srt`) is timed against nothing else -- there is
3278/// no clip to hang it on and no offset in the project to shift it by -- so it
3279/// is the timeline's own clock, which is where it was drawn while editing
3280/// (`Player::subtitle_overlay`). Clipped to the exported length and no more.
3281///
3282/// This is also what the *preview* draws: the plate over the picture and the
3283/// timeline strip both ask it through
3284/// [`PlaybackSession::timeline_cues`](crate::PlaybackSession::timeline_cues), so
3285/// what a rippled timeline shows and what its export writes are one answer by
3286/// construction rather than two maps kept in step by hand.
3287///
3288/// Pure and cheap enough to ask per repaint (a walk of the spans and of the
3289/// cues, no file opened), which is how a front-end asks it.
3290pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<Cue> {
3291 let frames = project.timeline_frames();
3292 let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64;
3293 let end = us(frames);
3294 // The file the cues are timed against, when there is one on this timeline.
3295 // A track whose media has since been dropped from the project has no span
3296 // to be carried through and falls back to the timeline's clock, which is
3297 // what it was drawn on.
3298 //
3299 // Through the same `canonical` a source is indexed by, or the two spellings
3300 // of one file (an argv `../assets/film.mkv`, a symlinked folder) would read
3301 // as two files and the cues would quietly fall back to the timeline's clock.
3302 let source = track.track.and_then(|_| {
3303 let path = crate::project::canonical(&track.path);
3304 project.sources().iter().position(|s| s.path == path)
3305 });
3306 let Some(source) = source else {
3307 return track
3308 .cues
3309 .iter()
3310 .filter_map(|cue| {
3311 let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end));
3312 (end_us > start_us).then_some(Cue {
3313 start_us,
3314 end_us,
3315 text: cue.text.clone(),
3316 image: cue.image.clone(),
3317 words: crate::subtitle::map_words(&cue.words, (start_us, end_us), (start_us, end_us)),
3318 karaoke: crate::subtitle::map_karaoke(&cue.karaoke, (start_us, end_us), (start_us, end_us)),
3319 })
3320 })
3321 .collect();
3322 };
3323 let mut out = Vec::new();
3324 for span in stack_spans_from(project, 0) {
3325 let Some((_, in_frame)) = span.from.filter(|&(from, _)| from == source) else {
3326 continue;
3327 };
3328 // What of the file this span plays, as *time in the file*: a clip counts
3329 // the timeline's frames whatever its file was shot at ([`Rate`]), which
3330 // is what makes those frames the same seconds a cue is timed in.
3331 let (first, last) = match span.source_window() {
3332 Some((_, lo, hi)) => (us(lo), us(hi)),
3333 None => (us(in_frame), us(in_frame + span.source_len())),
3334 };
3335 // Where that lands, and how fast: a cue is carried by the same factor
3336 // the pictures under it are, so a slowed clip stretches its subtitles
3337 // with it instead of leaving them behind.
3338 let start = us(span.start);
3339 // `rel` is the time since the span's head in the file's own direction of play:
3340 // forwards from `first`, and for a reversed clip back from `last` (the cue
3341 // [s, e] is mirrored to [last - e, last - s]).
3342 let onto = |rel: i64| {
3343 let Some(_) = span.ramp else {
3344 return start + (rel as f64 / span.speed.as_f64()).round() as i64;
3345 };
3346 // A ramp has no one factor: carry the cue through the ramp's own
3347 // inverse (`Span::timeline_at`), interpolating between whole frames.
3348 let f = (rel as f64 / 1e6 * fps).max(0.0);
3349 let (lo, hi) = (f.floor() as u32, f.ceil() as u32);
3350 let at = |s: u32| f64::from(span.timeline_at(in_frame + s).min(span.start + span.len) - span.start);
3351 let (a, b) = (at(lo), at(hi));
3352 let frames = if hi == lo { b } else { a + (b - a) * (f - f64::from(lo)) };
3353 start + (frames / fps * 1e6).round() as i64
3354 };
3355 for cue in &track.cues {
3356 let (a, b) = (cue.start_us.max(first), cue.end_us.min(last));
3357 if b <= a {
3358 continue; // wholly outside what this span kept
3359 }
3360 let (from, to) = if span.reverse { (last - b, last - a) } else { (a - first, b - first) };
3361 out.push(Cue {
3362 start_us: onto(from),
3363 end_us: onto(to).min(end),
3364 text: cue.text.clone(),
3365 image: cue.image.clone(),
3366 // Each word through the same mapping as the cue, so a ramp places it where
3367 // its own sound plays; a reversed clip keeps none, its cue shown whole.
3368 words: if span.reverse {
3369 Vec::new()
3370 } else {
3371 cue.words
3372 .iter()
3373 .filter(|(s, _, _)| *s < b)
3374 .map(|(s, e, w)| {
3375 let at = |t: i64| onto(t.clamp(a, b) - first).min(end);
3376 (at(*s), at(*e), w.clone())
3377 })
3378 .collect()
3379 },
3380 karaoke: if span.reverse {
3381 Vec::new()
3382 } else {
3383 cue.karaoke
3384 .iter()
3385 .filter(|k| k.start_us < b)
3386 .map(|k| {
3387 let at = |t: i64| onto(t.clamp(a, b) - first).min(end);
3388 crate::subtitle::Syllable { start_us: at(k.start_us), end_us: at(k.end_us), ..k.clone() }
3389 })
3390 .collect()
3391 },
3392 });
3393 }
3394 }
3395 // The spans come in timeline order but a cue's *own* order across them does
3396 // not: a Matroska muxer writes blocks as they come up.
3397 out.sort_by_key(|cue| cue.start_us);
3398 out
3399}
3400
3401/// What [`start`] would do about the subtitles, in the words a card shows: what
3402/// travels, and the reason beside every pick that does not. Pure, like
3403/// [`planned_audio`]: no file is opened, so it may be asked per repaint.
3404///
3405/// `picks` is any run of indices into [`Project::subtitles`] -- an
3406/// [`ExportSettings::subtitles`] list (`picks.iter().copied()`) as much as a
3407/// single `Some(row)`, which is what a front-end holding one row still hands it.
3408pub fn planned_subtitles(
3409 project: &Project,
3410 format: Format,
3411 picks: impl IntoIterator<Item = usize>,
3412) -> String {
3413 planned_subtitles_in(project, format, picks, None, 0.0)
3414}
3415
3416/// [`planned_subtitles`] for an export of `range` (the frames a ranged file keeps) at `fps`: a
3417/// track or lane with no cue left in the range is named as dropped for that reason, since the
3418/// file would carry it empty. `None` is the whole timeline, and `fps` is then not read.
3419pub fn planned_subtitles_in(
3420 project: &Project,
3421 format: Format,
3422 picks: impl IntoIterator<Item = usize>,
3423 range: Option<(u32, u32)>,
3424 fps: f64,
3425) -> String {
3426 let picks: Vec<usize> = picks.into_iter().collect();
3427 let lanes = placed_lanes(project);
3428 // WebM is the one container that names no subtitle track here, placed or
3429 // picked: said first and once, as the reason nothing travels.
3430 if format == Format::Webm && (!picks.is_empty() || !lanes.is_empty()) {
3431 return "none — a WebM file carries no subtitles".into();
3432 }
3433 if format == Format::ProRes && (!picks.is_empty() || !lanes.is_empty()) {
3434 return "none — a ProRes QuickTime file carries no subtitles".into();
3435 }
3436 // An mp4 of a timeline with no picture is the sound alone too: no track of
3437 // either kind is written, placed or picked ([`export_subtitles`]).
3438 if format.ext() == "mp4" && !has_picture(project) {
3439 return "none — a timeline with no picture is the sound alone".into();
3440 }
3441 // One statement about the *file*, said before any about a track: a format
3442 // that is the sound alone has nowhere to put a single one of them, and the
3443 // reason a pick would not have travelled anyway (a picture track, no cues)
3444 // is not the reason it does not travel here. Nothing picked is "none" --
3445 // there is nothing to say a container cannot carry.
3446 if !format.has_video() && (!picks.is_empty() || !lanes.is_empty()) {
3447 return "none — this format is the sound alone".into();
3448 }
3449 // The lanes are the words placed on the timeline and go as they are placed
3450 // ([`export_subtitles`]); each picked track no lane places is written whole,
3451 // beside them. The clauses go in the order the file writes the tracks
3452 // ([`soft_order`]), which is the order the caller gave them.
3453 let (mut embedded, mut dropped) = (Vec::new(), Vec::new());
3454 let (mut lane_count, mut trailing) = (0, false);
3455 for entry in soft_order(project, &lanes, &picks) {
3456 let pick = match entry {
3457 SoftEntry::Lane(lane) => {
3458 let (e, d, t) = planned_lanes(project, &[lane], &picks, range, fps);
3459 lane_count += e.len();
3460 embedded.extend(e);
3461 dropped.extend(d);
3462 trailing |= t;
3463 continue;
3464 }
3465 SoftEntry::Track(pick) => pick,
3466 };
3467 // A pick the project has no row for: a caller holding an index the list
3468 // no longer has (a removed row shifts every later one down). Every other
3469 // reason a pick does not travel is named on this card, so this one is
3470 // too -- a bug that says nothing is a bug found in the finished file.
3471 let Some(track) = project.subtitles().get(pick) else {
3472 dropped.push(format!("#{pick} — no such track"));
3473 continue;
3474 };
3475 if let Some(why) = &track.refused {
3476 dropped.push(format!("{} — {why}", track.label));
3477 } else if track.is_bitmap() {
3478 // Drawn over the picture, written into no file: the exported track
3479 // is text and these cues are bitmaps. Said whatever the format,
3480 // because it is the track and not the container that cannot be
3481 // carried.
3482 dropped.push(format!("{} — pictures; drawn, not written", track.label));
3483 } else if !track_has_cues(project, track, range, fps) {
3484 dropped.push(format!("{} — {}", track.label, no_cues_word(range)));
3485 } else {
3486 // Whichever container: a Matroska carries the track as
3487 // `S_TEXT/UTF8` blocks and an mp4 as a `tx3g` timed-text track, and
3488 // a pick travels either way. There is no container refusal left on
3489 // this card -- the sound-alone one above is about the *file* and the
3490 // ones beside it about the *track*.
3491 embedded.push(track.label.clone());
3492 }
3493 }
3494 // Lanes only are named as lanes; a picked track in the mix makes them tracks.
3495 let noun = if lane_count == embedded.len() { "lanes" } else { "tracks" };
3496 // A Matroska block numbers its track in one byte, so a file carries at most
3497 // MAX_SUB_TRACKS of them, placed or picked; the muxer refuses more again.
3498 if format.is_mkv() && embedded.len() > crate::mux::MAX_SUB_TRACKS {
3499 return format!(
3500 "{} subtitle {noun}: a Matroska block writes its track number in one byte, so one file \
3501 carries at most {}",
3502 embedded.len(),
3503 crate::mux::MAX_SUB_TRACKS
3504 );
3505 }
3506 let mut parts = match embedded.len() {
3507 0 => Vec::new(),
3508 1 => vec![format!("{} → embedded", embedded[0])],
3509 n => vec![format!("{n} {noun} → embedded ({})", embedded.join(", "))],
3510 };
3511 parts.extend(dropped);
3512 if trailing {
3513 parts.push("cues past the last picture are cut off there".into());
3514 }
3515 match parts.is_empty() {
3516 true => "none".into(),
3517 false => parts.join("; "),
3518 }
3519}
3520
3521/// [`planned_subtitles`] for a timeline that *places* its words: one clause per
3522/// subtitle lane, named by the lane and by the palette row it shows, in the
3523/// order the file will declare them ([`lane_subtitles`]).
3524///
3525/// Every reason a lane does not travel is said here rather than found in the
3526/// file: a picture track placed on it, a track that could not be read, a palette
3527/// row that has since gone, a lane sitting entirely past the last picture, and
3528/// -- before a byte is written -- more lanes than a Matroska block can number
3529/// ([`crate::mux::MAX_SUB_TRACKS`], which the muxer refuses again).
3530fn planned_lanes(
3531 project: &Project,
3532 lanes: &[Lane],
3533 picks: &[usize],
3534 range: Option<(u32, u32)>,
3535 fps: f64,
3536) -> (Vec<String>, Vec<String>, bool) {
3537 let end = project.media_frames();
3538 let (mut embedded, mut dropped, mut trailing) = (Vec::new(), Vec::new(), false);
3539 for &lane in lanes {
3540 let placed = project.sub_lane(lane);
3541 // An empty lane is a lane nobody has used yet, not a refusal. A lane no
3542 // pick reaches is not in this file at all, so it is not named either.
3543 let Some(first) = placed.first() else {
3544 continue;
3545 };
3546 if !picked(placed, picks) {
3547 continue;
3548 }
3549 let row = |s: &crate::project::SubClip| project.subtitles().get(s.track);
3550 let (label, head) = (lane.label(), row(first));
3551 let name = head.map_or_else(String::new, |t| format!("{} ", t.label));
3552 if let Some(gone) = placed.iter().find(|s| row(s).is_none()) {
3553 dropped.push(format!("{label} — #{} is no longer a track", gone.track));
3554 } else if let Some((t, why)) = placed
3555 .iter()
3556 .find_map(|s| row(s).and_then(|t| t.refused.as_ref().map(|why| (t, why))))
3557 {
3558 dropped.push(format!("{label} {} — {why}", t.label));
3559 } else if let Some(t) = placed.iter().find_map(|s| row(s).filter(|t| t.is_bitmap())) {
3560 // Drawn over the picture, written into no file -- the same sentence
3561 // a picked track gets, because it is the track and not the lane that
3562 // cannot be carried.
3563 dropped.push(format!(
3564 "{label} {} — pictures; drawn, not written",
3565 t.label
3566 ));
3567 } else if first.start >= end {
3568 dropped.push(format!("{label} {name}— past the last picture"));
3569 } else if range.is_some() && lane_subtitle(project, lane, fps, range, picks).is_none() {
3570 dropped.push(format!("{label} {name}— {}", no_cues_word(range)));
3571 } else {
3572 embedded.push(format!("{label} {}", name.trim_end()));
3573 // Something on it hangs past the end of the media: the timeline is
3574 // held open under it ([`Project::timeline_frames`]) but the file
3575 // stops with the last picture, so those cues are cut off there.
3576 trailing |= placed.last().is_some_and(|s| s.end() > end);
3577 }
3578 }
3579 (embedded, dropped, trailing)
3580}
3581
3582/// What [`start`] would encode the picture with, probed the way the export
3583/// probes it -- the very encoder is opened and closed again -- so this is a
3584/// measurement and not a promise. `None` for a format that carries no picture.
3585///
3586/// Costs that open (~100 ms here): ask it off a render thread and keep the
3587/// answer until the format, the resolution or the bitrate changes.
3588pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> {
3589 settings
3590 .format
3591 .has_video()
3592 .then(|| match hw_seat(meta, settings) {
3593 Ok(hw) => video_label(settings.format, hw.is_some(), settings.intra_only),
3594 // The seat the settings demand and this machine has not: the very
3595 // refusal [`start`] would settle with, said on the card instead.
3596 Err(_) => NO_HW_SEAT,
3597 })
3598}
3599
3600/// What [`start`] would open for *this* timeline: the picture's seat -- or the
3601/// copy that means there is no encoder at all -- and the sound's, asked of the
3602/// very gates the export asks ([`CopyPlan::of`] and [`copy_audio`]'s) rather
3603/// than of the format alone.
3604///
3605/// This exists because the card and the running export used to disagree in both
3606/// directions on the same file: the card named a software HEVC encode for a cut
3607/// the engine copied, and named an AAC copy for a Matroska source whose sound
3608/// no sample table holds and which therefore always re-encodes. A prediction
3609/// that is not the decision is worse than no prediction, because a person plans
3610/// their evening around it.
3611///
3612/// Costs what [`planned_video`] costs (an encoder opened and closed) plus a
3613/// header read per source and, once per file, its cluster walk: ask it off a
3614/// render thread and keep the answer until the timeline or the settings change.
3615pub fn planned_seats(
3616 project: &Project,
3617 meta: &VideoMeta,
3618 settings: &ExportSettings,
3619) -> (Option<&'static str>, &'static str) {
3620 // The canvas the file is drawn at, which is what the seat and the copy gate are about.
3621 let meta = &output_meta(meta, settings);
3622 let video = settings.format.has_video().then(|| {
3623 match CopyPlan::of(project, meta, settings).is_some() {
3624 true => "copy (source packets)",
3625 false => planned_video(meta, settings).unwrap_or(NO_HW_SEAT),
3626 }
3627 });
3628 // The half [`audio_label`] cannot know from the format: a copy is a *sample
3629 // table's* packets ([`copy_audio`] hands them to `copy_multi_streams`), and
3630 // a Matroska file has none -- so every mkv source re-encodes, however
3631 // untouched its lane is. Extension only, which is what `is_matroska`
3632 // reads, so this costs nothing beyond what is already open. A standalone
3633 // audio file (mp3, wav, flac...) has no sample table either: its sound is
3634 // decoded and encoded again, as [`copy_multi_streams`] refusing it sends it.
3635 let copyable = !settings.reencode_audio
3636 && !forces_encode(project, settings.range.is_some())
3637 && !project.sources().iter().any(|source|
3638 {
3639 crate::demux::is_matroska(&source.path)
3640 || crate::demux::is_mpeg_system(&source.path)
3641 || crate::is_audio(&source.path)
3642 });
3643 let sound = match undecodable_sound(project) {
3644 Some(label) if has_sound(project) => label,
3645 // A Matroska file that is encoded (not copied) takes Opus or AAC as the mix decides, so
3646 // the card names the one this mix will get, read from the sources' headers.
3647 None if has_sound(project)
3648 && !copyable
3649 && settings.format.is_mkv()
3650 && settings.format != Format::Webm =>
3651 {
3652 match mkv_mix_is_opus(project, meta.frame_rate) {
3653 true => "Opus · SW encode (ec-opus)",
3654 false => "AAC · SW encode (ec-aac)",
3655 }
3656 }
3657 _ => audio_label(
3658 project,
3659 settings.format,
3660 has_sound(project),
3661 Some(copyable),
3662 settings.range.is_some(),
3663 settings.reencode_audio,
3664 ),
3665 };
3666 (video, sound)
3667}
3668
3669/// Whether the mix a Matroska export encodes would be written as Opus: the rule
3670/// [`encode_audio`] applies after the mix is open -- 48 kHz, mono or stereo -- worked
3671/// out from the lanes' sources' headers instead ([`AudioSession::probe`]), since no mix
3672/// is opened to ask. The mix runs at the highest source rate, 48 kHz when every source
3673/// is below 44.1 kHz ([`crate::audio`]'s `mix_rate`), and as wide as the widest source.
3674/// The fidelity gate that can still hand the track back to AAC is measured only once
3675/// the encode has run, so this is the prediction the export's own line corrects.
3676fn mkv_mix_is_opus(project: &Project, fps: f64) -> bool {
3677 let sources = project.audio_sources();
3678 let mut rates = Vec::new();
3679 let mut channels = 0u16;
3680 for lane in project.audio_segments_from(0, fps) {
3681 for (source, ..) in lane {
3682 let Some((path, stream)) = source.and_then(|i| sources.get(i)) else {
3683 continue;
3684 };
3685 if crate::is_image(path) {
3686 continue;
3687 }
3688 if let Ok(Some(probe)) = AudioSession::probe(path, *stream) {
3689 rates.push(probe.sample_rate);
3690 channels = channels.max(probe.channels);
3691 }
3692 }
3693 }
3694 let rate = rates.into_iter().max().map(|r| if r < 44_100 { OPUS_RATE } else { r });
3695 rate == Some(OPUS_RATE) && (1..=2).contains(&channels)
3696}
3697
3698/// The sound a timeline's sources cannot give: `Some(label)` when every source
3699/// on the audio lanes is one [`AudioSession::unsupported`] names as undecodable,
3700/// which is what the export's own open answers with no sound at all ("no audio
3701/// to write"). `None` when any source decodes, or when a source has no sound
3702/// this question can name.
3703fn undecodable_sound(project: &Project) -> Option<&'static str> {
3704 let reasons: Vec<Option<String>> = project
3705 .audio_sources()
3706 .iter()
3707 .map(|(path, _)| AudioSession::unsupported(path).ok().flatten())
3708 .collect();
3709 if reasons.is_empty() || reasons.iter().any(Option::is_none) {
3710 return None;
3711 }
3712 // The reason's first words name the codec: a Matroska file by its codec id
3713 // ("the A_DTS track ..."), an mp4 by its media type ("the dts audio track
3714 // ..."). Only DTS is named by name; any other codec this engine cannot decode
3715 // gets the general words.
3716 let dts = reasons.iter().flatten().all(|reason| {
3717 let reason = reason.to_ascii_lowercase();
3718 reason.starts_with("the a_dts ") || reason.starts_with("the dts ")
3719 });
3720 Some(match dts {
3721 true => "none — DTS can't be decoded",
3722 false => "none — this codec can't be decoded",
3723 })
3724}
3725
3726/// The tone map a picture export puts on its HDR sources, as a sentence for the
3727/// start line and the plan: the picture is written 8-bit BT.709 SDR, so a PQ or
3728/// HLG source is tone-mapped down silently otherwise. `None` where no picture
3729/// is tone-mapped -- a sound-only format, a preview that keeps its source's
3730/// curve ([`ExportSettings::keep_source_colour`]), or no HDR source in the
3731/// project. Asked of every source, as [`planned_seats`] asks its sound.
3732///
3733/// Header reads only, one per source, the same colour the export's own tone map
3734/// is built from ([`source_rate`]).
3735pub fn planned_tone(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<String> {
3736 if !settings.format.has_video() || settings.keep_source_colour {
3737 return None;
3738 }
3739 // The matrix the file is tagged with: the one [`start`] writes for this canvas
3740 // ([`ColorDescription::output_sized`]), so the words name what the file says.
3741 let out = output_meta(meta, settings);
3742 let matrix = match ColorDescription::output_sized(out.width, out.height).matrix {
3743 Matrix::Bt601 => "BT.601",
3744 _ => "BT.709",
3745 };
3746 let mut transfers = project.sources().iter().filter_map(|source| {
3747 if crate::is_image(&source.path) || crate::is_audio(&source.path) {
3748 return None;
3749 }
3750 Demuxer::open(&source.path).ok().map(|(meta, _)| meta.color.transfer)
3751 });
3752 transfers.find_map(|transfer| match transfer {
3753 Transfer::Pq => Some(format!("HDR (PQ) source tone-mapped to SDR {matrix}")),
3754 Transfer::Hlg => Some(format!("HDR (HLG) source tone-mapped to SDR {matrix}")),
3755 Transfer::Sdr => None,
3756 })
3757}
3758
3759fn settle(shared: &Shared, result: crate::Result<()>) {
3760 *shared.outcome.lock().unwrap() = Some(result);
3761 // Published last: a caller that sees the flag is guaranteed the outcome.
3762 shared.finished.store(true, Ordering::Release);
3763}
3764
3765/// The audio track an export writes, and how it was made -- a copy is the
3766/// source's own packets, bit for bit, and anything else is this project's
3767/// encoder over the decoded mix. [`run`] publishes which of the two really
3768/// happened, so the encoder line a user reads is measured and not promised.
3769pub(crate) struct ExportAudio {
3770 pub params: crate::AacTrackParams,
3771 pub packets: Vec<crate::AacPacket>,
3772 /// Whether those packets are the source's, untouched.
3773 pub copied: bool,
3774 /// The track's pre-skip in samples where those packets are **Opus** and not
3775 /// AAC ([`encode_opus`]), which is what the Matroska track entry states in
3776 /// its `OpusHead` and its `CodecDelay`. `None` is an AAC track, which is
3777 /// every copy and every mp4.
3778 pub opus_pre_skip: Option<u16>,
3779 /// The language the track is tagged with ([`audio_language`]), `None` for
3780 /// `und`. Set once where the track is made, from the project it came from.
3781 pub language: Option<String>,
3782 /// The sound's length in PCM frames per channel, where the packets were
3783 /// encoded from a mix of exactly that many: the count the encoder was fed,
3784 /// not the packets' sum, which runs on past it by the encoder's priming and
3785 /// the last frame's padding. `None` for a copy, whose length is the
3786 /// source's own packets.
3787 pub pcm_frames: Option<u64>,
3788}
3789
3790/// The timeline's audio track for a file that carries picture: copied packet for
3791/// packet where a copy says exactly what the timeline says, and decoded, mixed
3792/// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane,
3793/// a speeded clip, an equalizer, a source that is not AAC inside an mp4 sample
3794/// table. Nothing is refused for being uncopyable any more; the only refusals
3795/// left below the copy are about sound this engine cannot *decode* either, and
3796/// those come out of the decode path by name.
3797///
3798/// The copy is still the default and still bit-exact: a timeline nobody has
3799/// touched leaves as the very packets its source holds.
3800///
3801/// corner-cut: this holds the whole exported AAC track in memory (~3 kB per
3802/// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
3803/// `copy_segments` that yields packets instead of collecting them.
3804#[allow(clippy::too_many_arguments)]
3805fn copy_audio(
3806 project: &Project,
3807 meta: &VideoMeta,
3808 kbps: u32,
3809 mkv: bool,
3810 webm: bool,
3811 reencode: bool,
3812 shared: &Shared,
3813 sample_rate: Option<u32>,
3814 range: Option<(u32, u32)>,
3815) -> crate::Result<Option<ExportAudio>> {
3816 // WebM's sound is Opus, which no source's packets are: always the mix. A loudness target is a
3817 // gain over the mix, which a copied packet cannot carry. A rate the caller chose is a re-encode.
3818 if webm || reencode || shared.loudness.is_some() {
3819 return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, range);
3820 }
3821 // A ranged export needs an exact offset and an exact length, which a
3822 // packet copy cannot give -- it carries whole segments named by
3823 // `audio_segments_from(0, ..)`, not an arbitrary window into them. The
3824 // decoded path already resamples per segment, so it is the one that can
3825 // start and stop anywhere; this falls to it exactly as a speeded or
3826 // equalized lane already does.
3827 if range.is_some() {
3828 return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, range);
3829 }
3830 // The segments name their source, and the copy carries its packet-rounding
3831 // debt across a source join exactly as across a cut, so a timeline spanning
3832 // files stays in sync. A source whose AAC parameters disagree with the
3833 // first one is an `Err` from there -- import refuses those up front, this
3834 // is the backstop -- and the caller deletes the `.part`.
3835 //
3836 // The stream each source is copied from is the one it plays: `audio_sources`
3837 // is the same list `PlaybackSession::seek` hands the decoder, so an export
3838 // of a timeline playing a file's second audio track carries *that* track.
3839 //
3840 // One lane is the only shape a *copy* has: summing two means decoding both,
3841 // and a sum is not a copy. Two or more go to [`encode_audio`], which is the
3842 // very mix the WAV path writes -- it used to be a refusal, and a refusal is
3843 // what a file missing half its sound deserves, not what a mix does.
3844 //
3845 // *Which* lane is the same question `audio_segments_from` answers for
3846 // playback, and it is asked here rather than assumed: the lane that holds
3847 // the sound need not be `A1` (a project may leave `A1` empty and place
3848 // everything on `A2`), and copying `A1`'s list in that case would write a
3849 // file with no audio track at all -- silently, which is the failure this
3850 // whole comment is about.
3851 let mut lanes = project.audio_segments_from(0, meta.frame_rate);
3852 // ...cut to what the picture writes ([`export_spans`]). The play list is
3853 // the *timeline's* ([`Project::timeline_frames`]), so a caption hanging past
3854 // the last picture ends every audio lane with a trailing gap -- silence this
3855 // path would copy out past the last frame, three seconds of it on the film
3856 // this was found on. Only a gap can be out there (`media_frames` is the last
3857 // clip's own end), and the mixed paths already resize to the same length
3858 // ([`encode_audio`]); a copy carries source packets and has no resize.
3859 let over = f64::from(project.timeline_frames() - project.media_frames()) / meta.frame_rate;
3860 for lane in &mut lanes {
3861 match lane.last_mut() {
3862 Some((None, _, len)) if *len > over => *len -= over,
3863 Some((None, _, _)) if over > 0.0 => {
3864 lane.pop();
3865 }
3866 _ => {}
3867 }
3868 }
3869 let [segments] = &lanes[..] else {
3870 return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None);
3871 };
3872 // ...and the same list names *which* lane those clips sit on, which is the
3873 // only way to ask what has been done to them.
3874 let lane = project.audio_lanes()[0];
3875 // ...and the same list decides whether any clip this would copy plays at a
3876 // rate other than the one it was recorded at. A copy hands the muxer the
3877 // very AAC packets the source holds and there is no rate inside a packet to
3878 // change: the picture would come out re-timed (the walk in [`run`] honours
3879 // it) over sound at 1.00x, which is the drift a person finds only after the
3880 // file has gone somewhere. Decoded and resampled instead, by the same worker
3881 // playback feeds from.
3882 //
3883 // ...and whether any clip on it carries an equalizer, which is sample math a
3884 // copy never reaches: copying such a lane would write the clip *flat*,
3885 // silently.
3886 //
3887 // A frame *rate* of its own is not one of those, and that is deliberate: do
3888 // not "fix" this into a re-encode. A clip counts the **timeline's** frames
3889 // whatever its file was shot at ([`crate::project::Rate`]), so the window
3890 // this copy trims a source's sound to is `start..end` in whole timeline
3891 // frames -- exactly the seconds the picture covers -- and the file is read
3892 // at the pitch it was recorded at, which is what playing at the rate it was
3893 // shot at means. There is no per-clip stretch to express, so the packets are
3894 // already the right sound in the right place; re-encoding a conformed lane
3895 // would buy nothing and cost a generation of loss on every mixed-rate export
3896 // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot`
3897 // measures the copied sound against the picture). A *speed* is different
3898 // because it resamples, which is why it leaves through the re-encode above.
3899 //
3900 // Only these: a timeline nobody has touched still leaves through the copy
3901 // below, packet for packet, so no passthrough quietly becomes a generation
3902 // of loss.
3903 // ...and whether the mix itself does anything a packet never went through:
3904 // a lane volume is applied at the sum and a limiter over it, so copying
3905 // such a lane would write it at unity and unlimited, silently.
3906 // ...asked as the very predicate [`forces_encode`] is, over the one lane
3907 // the segments came off, so what a card predicted and what this decides are
3908 // one answer. `lane` here is that lane, and not `A1` by assumption:
3909 // [`Project::audio_lanes`] is the list built for, and filtered by, these
3910 // very segments.
3911 if sample_altered(project, &[lane]) {
3912 return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None);
3913 }
3914 // What is left is a copy the *sources* may still not be able to give: AAC
3915 // inside a Matroska file (readable, but not out of a sample table this walks
3916 // -- there is none), an mp3 or a wav on the timeline, an AC-3 track, two
3917 // sources whose AAC parameters disagree. Every one of them decodes, and what
3918 // decodes can be encoded again, so the copy's refusal is now a route: the
3919 // error a *decode* cannot get past -- Opus or AC-3 inside a Matroska file,
3920 // which symphonia has no decoder for at any version -- is the one that comes
3921 // back, by name, from [`encode_audio`].
3922 match AudioSession::copy_multi_streams(&project.audio_sources(), segments) {
3923 Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio {
3924 params,
3925 packets,
3926 copied: true,
3927 // A copy is the source's own AAC packets: there is no Opus copy
3928 // path here, since the packets an mkv source holds never reach this
3929 // (they are not in a sample table) and every one of them re-encodes.
3930 opus_pre_skip: None,
3931 language: None,
3932 pcm_frames: None,
3933 })),
3934 Err(_) => encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None),
3935 }
3936}
3937
3938/// The picture's half of [`copy_audio`]: a Matroska export whose every span is
3939/// its source's own coded blocks, written back out without a decoder or an
3940/// encoder anywhere in the path.
3941///
3942/// **When.** A copy is entered only where it says *exactly* what the timeline
3943/// says, which is the audio gate's rule and not a looser one: the file this
3944/// export writes is Matroska, the source's codec is the one that file would
3945/// carry ([`Format::Hevc`] over HEVC, [`Format::Av1`] over AV1), and nothing on
3946/// the way has touched a sample -- no grade, no speed, no rate conversion, no
3947/// gap to fill with black, no source of another size to place on the canvas,
3948/// no `ContentEncodings` packing to undo. Anything else re-encodes exactly as
3949/// it always did; there is no half-copied file.
3950///
3951/// **All or nothing, per export.** A copied span and an encoded one cannot
3952/// share one track: this project's encoders write 8-bit SDR streams whose
3953/// parameter sets are their own, so splicing them into (say) a Main 10 HDR
3954/// source would change bit depth and colour mid-track, and a container states
3955/// its configuration record once. So the head and tail fragments of a cut that
3956/// lands mid-GOP are *not* re-encoded into the copy -- they are what makes the
3957/// whole export fall back to the encoder. What a copy needs instead is that
3958/// every span begins on a sync point and ends where the next one begins, which
3959/// is what a cut placed on a keyframe gives it.
3960///
3961/// **What a cut costs.** An open-GOP source (x265's default) writes leading
3962/// pictures after a sync point that are shown *before* it and reference the
3963/// group before it. At the start of a copied region those references are not in
3964/// the file, so they are dropped -- the picture before the cut is held for those
3965/// few frames (four at this film's B-depth, a sixth of a second) rather than
3966/// being written as pictures that cannot decode. The region still starts at the
3967/// timeline frame it owns, so the sound never drifts.
3968///
3969/// corner-cut: mp4 is not copied (its `hvc1` sample entry forbids in-band
3970/// parameter sets, and the mp4 muxer here writes its sample table from a frame
3971/// counter), and neither is H.264, which this project only writes into mp4. The
3972/// upgrade path for both is a sample-table writer that takes explicit
3973/// timestamps, which is what [`MkvMuxer::write_block`] already is for Matroska.
3974struct CopyPlan {
3975 /// Every source a region reads, by the index the project names it with;
3976 /// `None` for a source no clip plays from.
3977 sources: Vec<Option<MkvDemuxer>>,
3978 regions: Vec<CopyRegion>,
3979 codec_id: &'static [u8],
3980 /// The `CodecPrivate` every region's source agrees on -- a track is declared
3981 /// once, so two sources that disagree about their parameter sets are not one
3982 /// copy.
3983 private: Vec<u8>,
3984 /// The picture's language as the first source states it ([`video_language`]), which the
3985 /// copied track declares.
3986 language: Option<String>,
3987 /// The container's colour tags exactly as the source wrote them, which the
3988 /// copied track declares: a field the source left out stays left out, and
3989 /// nothing is resolved in its place ([`MkvDemuxer::colour_tags`]).
3990 colour: Tags,
3991 /// The coded shape the copied track declares: the samples under it are the
3992 /// source's own, so the header names what they are stored at -- not the
3993 /// shape they are drawn at.
3994 width: u32,
3995 height: u32,
3996 /// The aspect the copied samples are drawn at, written into the file as
3997 /// display metadata ([`CopyParams::pixel_aspect`]): square for every
3998 /// ordinary source, so the header gains nothing.
3999 pixel_aspect: crate::demux::PixelAspect,
4000}
4001
4002/// A run of source blocks copied in one piece: what a cut leaves behind, and
4003/// what two spans that continue each other in the same file merge back into.
4004struct CopyRegion {
4005 source: usize,
4006 /// Blocks of that source, in the file's own decode order.
4007 blocks: std::ops::Range<usize>,
4008 /// The *output* frame the region's first picture is shown at -- the
4009 /// project's own timeline frame less the range's own start, since a
4010 /// ranged export's file starts a fresh clock at zero.
4011 start: u32,
4012}
4013
4014/// Why [`ExportSettings::exact`] cannot be honoured for this project right
4015/// now, or `None` where [`CopyPlan`] already carries the whole file. A state
4016/// report, not an instruction: it says what the file *is* rather than what to
4017/// pick instead.
4018///
4019/// Two shapes of reason, told apart because only one of them is permanent.
4020/// **The container cannot carry the source's own codec at all** -- Exact was
4021/// asked of an mp4, or of a Matroska file whose codec is not the source's own
4022/// -- which is [`CopyPlan`]'s own corner-cut (mp4 copies nothing yet) and
4023/// [`CopyPlan::of`]'s codec check, so it is checked here the same way rather
4024/// than duplicated with different words. **The edit is what stops it** -- a
4025/// cut off a sync point, a grade, a speed, a dissolve, a moved or scaled
4026/// clip -- which the same format would carry exactly if the edit let it, so
4027/// those six [`CopyPlan::of`] gates are named together rather than picked
4028/// apart into six different sentences.
4029pub fn exact_refusal(
4030 project: &Project,
4031 meta: &VideoMeta,
4032 settings: &ExportSettings,
4033) -> Option<String> {
4034 if !settings.exact || CopyPlan::of(project, meta, settings).is_some() {
4035 return None;
4036 }
4037 // An anamorphic source asked of a format that cannot state the aspect: the
4038 // blocks would copy, but the sample entry this writer produces has no
4039 // `pasp` box to carry it in, and a header that declares the coded pair
4040 // while the pixels are drawn 4/3 wide is a file that lies about its own
4041 // shape. Refused by name -- the sentence a reader is owed -- before the
4042 // container's codec question, because this is the *nearer* reason: a
4043 // Matroska copy needs no refusal at all (its track carries the aspect
4044 // beside the blocks, [`CopyParams::pixel_aspect`], which is ffmpeg's own
4045 // copy behaviour), so an anamorphic source's Exact row only ever dies on
4046 // this for an mp4.
4047 if settings.burn_subtitles.is_some() {
4048 return Some(
4049 "captions are drawn into the picture, so it is decoded and encoded again rather \
4050 than copied byte for byte"
4051 .to_string(),
4052 );
4053 }
4054 if !project.titles().is_empty() {
4055 return Some(
4056 "titles are drawn into the picture, so it is decoded and encoded again rather \
4057 than copied byte for byte"
4058 .to_string(),
4059 );
4060 }
4061 if picture_faded(project) {
4062 return Some(
4063 "a picture fade is pixel math, so it is decoded and encoded again rather than \
4064 copied byte for byte"
4065 .to_string(),
4066 );
4067 }
4068 if !settings.format.is_mkv() {
4069 let anamorphic = project.sources().iter().any(|source| {
4070 Demuxer::open(&source.path)
4071 .ok()
4072 .is_some_and(|(source_meta, _)| !source_meta.pixel_aspect.is_square())
4073 });
4074 if anamorphic {
4075 return Some(
4076 "a copy would lose the pixel aspect — this format cannot state it beside the \
4077 coded picture, so the export re-encodes it into the square pixels it is drawn at"
4078 .to_string(),
4079 );
4080 }
4081 }
4082 let codec = match settings.format {
4083 Format::Hevc => Codec::Hevc,
4084 Format::Av1 => Codec::Av1,
4085 _ => {
4086 return Some(format!(
4087 "{} cannot carry a source's own coded picture byte for byte — pick an HEVC or AV1 Matroska to copy it exactly",
4088 settings.format.name()
4089 ));
4090 }
4091 };
4092 // The turn-baking corner-cut (a copied packet is the source's own coded
4093 // picture; this export bakes a display-matrix turn into the pixels) and
4094 // the rest of the reasons a copy says something other than what the
4095 // timeline says are [`CopyPlan::of`]'s own gates, so the container and
4096 // edit sentences below are checked the same way rather than duplicated
4097 // with different words.
4098 let carries = project.sources().iter().all(|source| {
4099 crate::demux::is_matroska(&source.path)
4100 && Demuxer::open(&source.path)
4101 .ok()
4102 .is_some_and(|(source_meta, _)| source_meta.codec == codec)
4103 });
4104 Some(match carries {
4105 false => format!(
4106 "{} cannot carry the source's own codec byte for byte",
4107 settings.format.name()
4108 ),
4109 true => "the edit does not let this file copy the source exactly — a cut off a sync \
4110 point, a grade, a speed, a transform or a canvas the source is not forces a \
4111 re-encode"
4112 .to_string(),
4113 })
4114}
4115
4116impl CopyPlan {
4117 /// The plan for this timeline, or `None` where anything at all makes a copy
4118 /// say something other than what the timeline says -- in which case the
4119 /// caller encodes, which is what it always did.
4120 fn of(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<Self> {
4121 // Burned-in captions and titles are drawn into pixels, which a copy
4122 // never has.
4123 if settings.burn_subtitles.is_some()
4124 || !project.titles().is_empty()
4125 || picture_faded(project)
4126 {
4127 return None;
4128 }
4129 // An explicit picture depth is a request for samples the source may not
4130 // have (8 bits from a 10-bit HEVC, say), which a copy would silently
4131 // keep: the picture is re-encoded at the depth asked for.
4132 if settings.video_bit_depth.is_some() {
4133 return None;
4134 }
4135 // An HDR transfer is a statement the encoder writes into its own stream
4136 // (VUI, SEIs); a copy carries the source's.
4137 if settings.hdr.transfer != HdrTransfer::Sdr {
4138 return None;
4139 }
4140 let (codec_id, codec): (&'static [u8], Codec) = match settings.format {
4141 Format::Hevc => (b"V_MPEGH/ISO/HEVC", Codec::Hevc),
4142 Format::Av1 => (b"V_AV1", Codec::Av1),
4143 _ => return None,
4144 };
4145 let entries = project.sources();
4146 let mut sources: Vec<Option<MkvDemuxer>> = (0..entries.len()).map(|_| None).collect();
4147 // The DRAWN pair each source is displayed at, kept beside its demuxer:
4148 // the fit gate below asks what a clip's policy does with this source's
4149 // picture on this canvas, and the picture the encoder places is the
4150 // drawn one ([`VideoMeta::width`]/`height`] -- the coded one with the
4151 // file's turn and its pixel aspect already applied), not the pair the
4152 // samples are stored at. A non-square source at its own displayed size
4153 // is therefore the identity again, which is what a copy of one is: the
4154 // aspect travels beside the track in the `Display*` elements rather
4155 // than being resampled into it.
4156 let mut drawn: Vec<Option<(u32, u32)>> = (0..entries.len()).map(|_| None).collect();
4157 let mut declared: Option<(Vec<u8>, Tags, crate::demux::PixelAspect)> = None;
4158 let mut regions: Vec<CopyRegion> = Vec::new();
4159 let r_start = settings.range.map_or(0, |(s, _)| s);
4160 for span in export_spans(project, settings.range) {
4161 let out_start = span.start - r_start;
4162 // A gap is black frames, which only an encoder makes.
4163 let (source, in_frame) = span.from?;
4164 if !span.speed.is_normal() || span.ramp.is_some() || span.reverse {
4165 return None;
4166 }
4167 // A layered picture is composed from more than one clip; no packet
4168 // of one of them is the picture.
4169 if layered_at(project, span.start) {
4170 return None;
4171 }
4172 // A copied packet is the source's own picture, never a blend: a
4173 // live dissolve on this span's tail forces the whole video track
4174 // through the encoder, exactly as a grade or a speed does below.
4175 //
4176 // corner-cut: the whole file falls back rather than only the
4177 // clips either side of the dissolve -- [`CopyPlan`] is already
4178 // all-or-nothing per export ([`CopyPlan`]'s own doc comment
4179 // states why), so one dissolve on a two-hour film re-encodes all
4180 // of it. Upgrade path: splice a re-encoded region between two
4181 // copied ones, which needs the sample-table writer that doc
4182 // comment already names as the cost of a finer copy.
4183 if dissolve_window(project, &span).is_some() {
4184 return None;
4185 }
4186 // The grade playback shows, which a copied packet never went
4187 // through. `None` and the identity are the same untouched picture.
4188 if project
4189 .composite_color_at(span.start)
4190 .is_some_and(|params| !params.is_identity())
4191 {
4192 return None;
4193 }
4194 // A moved, scaled, rotated or cropped clip is a different picture
4195 // than the source's own packets, exactly as a grade is.
4196 if project
4197 .composite_transform_at(span.start)
4198 .is_some_and(|params| !params.is_identity())
4199 {
4200 return None;
4201 }
4202 let path = &entries.get(source)?.path;
4203 if sources.get(source)?.is_none() {
4204 if !crate::demux::is_matroska(path) {
4205 return None;
4206 }
4207 let (source_meta, demuxer) = Demuxer::open(path).ok()?;
4208 let Demuxer::Mkv(demuxer) = demuxer else {
4209 return None;
4210 };
4211 // The stream this file would carry, at the size and the rate the
4212 // timeline is in: anything else is a picture that has to be
4213 // coded again to become this file's.
4214 //
4215 // A source whose display matrix asks for a turn is one of
4216 // those: a copied packet is the source's own coded picture, and
4217 // this export bakes the turn into the pixels -- so a copy would
4218 // ship the file sideways. Re-encoding is the only honest
4219 // answer here.
4220 //
4221 // The size the copy declares is the source's *coded* pair, so
4222 // that is what the comparison asks: coded to coded. A display
4223 // comparison would refuse every anamorphic source that happens
4224 // to sit at the project's displayed shape and then write a
4225 // track that lies about its own samples -- and a square
4226 // source's coded pair is its display pair, so this asks nothing
4227 // new of the ordinary file.
4228 //
4229 // A source whose samples are not square is the *other* kind of
4230 // picture a copy cannot carry here: the blocks are its own
4231 // coded pixels and this engine's Matroska writer can now state
4232 // the aspect beside them -- but only this engine's
4233 // ([`MkvMuxer::create_copy`] writes the `Display*` elements),
4234 // and the copy's declared shape must stay the coded one. The
4235 // aspect travels with the track instead of being baked in,
4236 // which is ffmpeg's own copy behaviour, so an anamorphic
4237 // source is copyable *into Matroska* and nowhere else.
4238 if !source_meta.rotation.is_none()
4239 || source_meta.codec != codec
4240 || source_meta.coded_width != meta.coded_width
4241 || source_meta.coded_height != meta.coded_height
4242 || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()?
4243 != Rate::REAL_TIME
4244 || !demuxer.plain_blocks()
4245 {
4246 return None;
4247 }
4248 // Two sources that disagree about their pixel aspect are two
4249 // displayed pictures under one track; the copy declares one
4250 // aspect or none.
4251 let declares = (
4252 demuxer.codec_private().to_vec(),
4253 demuxer.colour_tags(),
4254 source_meta.pixel_aspect,
4255 );
4256 if declared.get_or_insert(declares.clone()) != &declares {
4257 return None;
4258 }
4259 sources[source] = Some(*demuxer);
4260 drawn[source] = Some((source_meta.width, source_meta.height));
4261 }
4262 let demuxer = sources.get_mut(source)?.as_mut()?;
4263 // **The canvas gate** -- the condition this path was missing, and
4264 // the one that decides whether a copy can state the project's size.
4265 //
4266 // A copied packet is the source's own coded picture; the file this
4267 // export writes has to be the size the *project* is, and those are
4268 // two different pairs held in two different fields:
4269 //
4270 // * `meta.coded_width`/`coded_height` is the pair a *copied* track
4271 // declares -- what the samples are stored at, and what the check
4272 // above compares every source against. Only a *source* ever moves
4273 // it.
4274 // * `meta.width`/`meta.height` is the canvas -- what a person chose
4275 // with [`crate::playback::PlaybackSession::set_resolution`],
4276 // which writes those two and leaves the coded pair exactly where
4277 // it was. The encode door sizes everything from it
4278 // ([`Composer`]), so this is the size the file must have.
4279 //
4280 // ...and the two meet in the *drawn* pair: what this span is
4281 // composed from is the source's picture as a decoder delivers it,
4282 // turn and pixel aspect already applied
4283 // ([`VideoMeta::width`]/`height`]), which is what the check below is
4284 // asked about.
4285 //
4286 // A canvas that differs from the source's drawn pair means every
4287 // span is a picture the export has to *place onto* that canvas, and
4288 // there is no resampler on this path at all -- so a copy would ship
4289 // the source's frame size under the project's name, with the seat
4290 // line reading "copy · …" all the way out. That is the defect: not
4291 // a wrong rate or a wrong codec but the wrong geometry, silently,
4292 // on the one door that is supposed to be exact.
4293 //
4294 // Asked as a *placement* rather than as two separate conditions --
4295 // is this clip's policy the identity for this source on this canvas
4296 // -- because that is the one thing a condition has to mean here:
4297 // [`fit_is_identity`] computes it from [`scale::fit_rect`] itself,
4298 // so it holds for `Fill` on a canvas the size of the picture the
4299 // source draws at (there is nothing to crop there) and refuses a
4300 // canvas of another size under *every* policy, and a
4301 // [`crate::scale::FitPolicy`] added later is judged by what it
4302 // places rather than by being absent from a list here.
4303 if !fit_is_identity(
4304 drawn.get(source).copied().flatten()?,
4305 (meta.width, meta.height),
4306 project.composite_fit_at(span.start),
4307 ) {
4308 return None;
4309 }
4310 // The window this span reads, in the blocks the whole engine counts
4311 // a source's frames in. It has to *be* whole groups of pictures: a
4312 // copy that began between two sync points would hand a decoder
4313 // pictures whose references are not in the file, and one that ended
4314 // between them would drop a reference the pictures before it need.
4315 let (start, end) = (in_frame as usize, in_frame as usize + span.len as usize);
4316 if end > demuxer.block_count()
4317 || !demuxer.is_sync(start)
4318 || (end < demuxer.block_count() && !demuxer.is_sync(end))
4319 {
4320 return None;
4321 }
4322 // Two spans that continue each other in one file are one region:
4323 // nothing was cut between them, so the leading pictures across that
4324 // boundary still have every reference they need.
4325 match regions.last_mut() {
4326 Some(last)
4327 if last.source == source
4328 && last.blocks.end == start
4329 && last.start + (last.blocks.end - last.blocks.start) as u32
4330 == out_start =>
4331 {
4332 last.blocks.end = end;
4333 }
4334 _ => regions.push(CopyRegion {
4335 source,
4336 blocks: start..end,
4337 start: out_start,
4338 }),
4339 }
4340 }
4341 let (private, colour, pixel_aspect) = declared?;
4342 Some(Self {
4343 sources,
4344 regions,
4345 codec_id,
4346 private,
4347 language: video_language(project),
4348 colour,
4349 // The track the copy declares is the source's coded shape -- the
4350 // samples under it are the source's own -- with the aspect beside
4351 // it as the display metadata ([`CopyParams::pixel_aspect`]).
4352 width: meta.coded_width,
4353 height: meta.coded_height,
4354 pixel_aspect,
4355 })
4356 }
4357
4358 /// The file itself: one Matroska muxer, every region's blocks through it in
4359 /// the order and at the timing their source states.
4360 #[allow(
4361 clippy::too_many_arguments,
4362 reason = "the copy's one run: its inputs are passed positionally at its one call site, and a struct would only rename them"
4363 )]
4364 fn run(
4365 mut self,
4366 out: &Path,
4367 meta: &VideoMeta,
4368 shared: &Shared,
4369 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
4370 subs: Vec<SubParams>,
4371 total: u32,
4372 chapters: &[(u64, String)],
4373 ) -> crate::Result<()> {
4374 let mut muxer = MkvMuxer::create_copy(
4375 out,
4376 &CopyParams {
4377 width: self.width,
4378 height: self.height,
4379 frame_rate: meta.frame_rate,
4380 codec_id: self.codec_id,
4381 codec_private: &self.private,
4382 colour: self.colour,
4383 pixel_aspect: self.pixel_aspect,
4384 language: self.language.clone(),
4385 },
4386 audio,
4387 subs,
4388 )?;
4389 muxer.set_chapters(chapters)?;
4390 // Nanoseconds a timeline frame lasts, which is what a region's own
4391 // position on the timeline is measured in.
4392 let frame_ns = 1e9 / meta.frame_rate;
4393 let mut done = 0u32;
4394 for region in &self.regions {
4395 let demuxer = self.sources[region.source]
4396 .as_mut()
4397 .ok_or("a copied region names a source that was never opened")?;
4398 let base = (f64::from(region.start) * frame_ns).round() as i64;
4399 // When the region's first picture is shown on its source's clock;
4400 // everything after it is written that far along from `base`.
4401 let mut origin: Option<i64> = None;
4402 for index in region.blocks.clone() {
4403 cancelled(shared)?;
4404 let Some(block) = demuxer.coded_block(index)? else {
4405 break;
4406 };
4407 let origin = *origin.get_or_insert(block.ts_ns);
4408 // The leading pictures of the group this region opens on: shown
4409 // before it, coded against the group before it, and that group
4410 // is not in this file. Dropped rather than written as pictures
4411 // no decoder can put back together.
4412 if block.ts_ns < origin {
4413 continue;
4414 }
4415 muxer.write_block(block.bytes, block.key, base + block.ts_ns - origin)?;
4416 done += 1;
4417 shared
4418 .progress
4419 .fetch_max(picture_progress(done, total), Ordering::Relaxed);
4420 }
4421 }
4422 // Everything up to here is still cancellable, exactly as the encoded
4423 // path is up to its own `finish`.
4424 cancelled(shared)?;
4425 muxer.finish()?;
4426 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
4427 Ok(())
4428 }
4429}
4430
4431/// Whether `policy` places the picture `source` is DRAWN at onto this `canvas`
4432/// without touching a sample: the whole picture, at the whole canvas, 1:1.
4433///
4434/// The 1:1 is the half the rects cannot state: a source scaled onto a canvas
4435/// of another aspect is placed whole and cropped nowhere, which is a resize
4436/// and not an identity -- so the pairs themselves are compared first.
4437///
4438/// The pair asked about is the **drawn** one ([`VideoMeta::width`]/`height`]),
4439/// never the coded one: what the fit is composed against is what a decoder
4440/// hands the canvas after the file's turn and its pixel aspect have been
4441/// applied, so a 1440x1080 file with a 4:3 sample aspect is a 1920x1080
4442/// picture, and a project at 1920x1080 is copying it exactly. The coded pair
4443/// has its own question -- what a copied track *declares* -- and the coded-to-
4444/// coded check in [`CopyPlan::of`] already asks that one; asking it twice, in
4445/// the geometry's stead, refuses a copy main performs byte for byte.
4446///
4447/// Asked from [`scale::fit_rect`] -- the one function that *is* a fit policy's
4448/// meaning -- rather than from the policy itself, which is what makes this
4449/// canvas-aware twice over: `Fill` on a canvas the size of the source's own
4450/// samples is the identity (nothing is cropped, because there is nothing to
4451/// crop), while `Fit` on a canvas of another aspect is not (it bars or crops).
4452/// A policy added to [`FitPolicy`] later is judged by what it places, not by
4453/// being absent from a list here.
4454fn fit_is_identity(
4455 source: (u32, u32),
4456 canvas: (u32, u32),
4457 policy: crate::scale::FitPolicy,
4458) -> bool {
4459 // The pairs themselves: a picture is the canvas only when it *is* the
4460 // canvas, and the rects below cannot say so -- a source scaled onto a
4461 // canvas of another aspect is still placed whole and still cropped
4462 // nowhere, which is a resize, and a resize is exactly what a copied packet
4463 // cannot be.
4464 if source != canvas {
4465 return false;
4466 }
4467 let (placed, cropped) = crate::scale::fit_rect(source.0, source.1, canvas.0, canvas.1, policy);
4468 placed
4469 == crate::scale::Rect {
4470 x: 0,
4471 y: 0,
4472 w: canvas.0,
4473 h: canvas.1,
4474 }
4475 && cropped
4476 == crate::scale::Rect {
4477 x: 0,
4478 y: 0,
4479 w: source.0,
4480 h: source.1,
4481 }
4482}
4483
4484/// The same lane, *decoded*: what a packet copy cannot carry comes out here as
4485/// AAC written by this project's own encoder.
4486///
4487/// The samples are the very ones [`run_audio`] would put in a WAV -- the same
4488/// opener with the same equalizers, the same rates and the same resize onto the
4489/// timeline's own length -- so an mp4 and a WAV of one timeline are one mix,
4490/// not two that could disagree.
4491///
4492/// AAC-LC's encoder delay is one 1024-frame block, which is exactly the priming
4493/// a reader drops when the file carries no edit list (`audio::DEFAULT_PRIMING`,
4494/// and [`crate::mux::Mp4Muxer`] writes none): the first packet is that delay, so
4495/// the sound starts at timeline frame 0 as a copied track's does.
4496///
4497/// corner-cut: the mix sits in memory as f32 before it is encoded (~46 MB a
4498/// minute of 48 kHz stereo), for [`run_audio`]'s reason -- sizing the track
4499/// against the timeline, publishing the mix third of the bar as it goes and
4500/// answering a cancel before the encode are whole-mix concerns here. The
4501/// upgrade path is a chunked push: `ec_aac`'s encoder itself streams.
4502#[allow(clippy::too_many_arguments)]
4503fn encode_audio(
4504 project: &Project,
4505 meta: &VideoMeta,
4506 kbps: u32,
4507 mkv: bool,
4508 webm: bool,
4509 shared: &Shared,
4510 sample_rate: Option<u32>,
4511 range: Option<(u32, u32)>,
4512) -> crate::Result<Option<ExportAudio>> {
4513 let sources = project.audio_sources();
4514 let range_start = range.map_or(0, |(s, _)| s);
4515 let pre = warm_up(project, range_start, meta.frame_rate);
4516 let offset = range_start - pre;
4517 let segs = project.audio_segments_from(offset, meta.frame_rate);
4518 let eqs = project.audio_eqs_from(offset, meta.frame_rate);
4519 let speeds = project.audio_speeds_from(offset, meta.frame_rate);
4520 let fades = project.audio_fades_from(offset, meta.frame_rate);
4521 // Coarse stage timers, in the same voice as `export video: copy` below: an
4522 // export of a feature film spends minutes in here before a byte of picture
4523 // is written, and which minutes went where is the first question asked of a
4524 // slow export. Three lines an export, so they stay on.
4525 let mixed = std::time::Instant::now();
4526 let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade(
4527 &sources,
4528 &segs,
4529 &eqs,
4530 &speeds,
4531 &fades,
4532 meta.frame_rate,
4533 &project.audio_gains(),
4534 &project.audio_ducks(),
4535 &project.audio_voices(),
4536 project.limiter(),
4537 sample_rate,
4538 )?
4539 else {
4540 return Ok(None); // no audio to write, exactly as a copy of nothing is
4541 };
4542 let freq_index = ec_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| {
4543 format!(
4544 "{} Hz is not an AAC sample rate: export WAV, FLAC, MP3 or OGG, which write it as \
4545 it is",
4546 audio.sample_rate
4547 )
4548 })?;
4549 let channels = usize::from(audio.channels.max(1));
4550 // The timeline's length, not the mix's: a segment resolves its window to
4551 // whole samples on its own, so the sum can miss by a sample or two and a
4552 // source that ran out early would leave the track short under a picture
4553 // that is not. One resize settles both, as [`run_audio`]'s does.
4554 let out_frames = range.map_or(project.media_frames(), |(s, e)| {
4555 e.min(project.media_frames()).saturating_sub(s)
4556 });
4557 let total = (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round()
4558 as usize
4559 * channels;
4560 let skip = warm_up_samples(range_start, pre, meta.frame_rate, audio.sample_rate, channels);
4561 let mut samples: Vec<f32> = Vec::with_capacity(total + skip);
4562 for chunk in chunks {
4563 // The only place a cancelled export can be answered before the whole
4564 // timeline has been mixed. This pass runs on a thread of its own now
4565 // ([`run`]), so without this a cancel left it mixing a feature film
4566 // for minutes behind a job nobody is waiting for any more, writing
4567 // into a `Shared` whose outcome was already settled.
4568 cancelled(shared)?;
4569 samples.extend(chunk.samples);
4570 // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of
4571 // the three stages and the only one that can be counted as it goes.
4572 //
4573 // `fetch_max` and not `store`, for the reason [`Shared::progress`]
4574 // states: this runs on the audio thread while the picture publishes
4575 // numbers above [`AUDIO_BAND`] from the other, and a `store` of this
4576 // small one pulled the bar backwards 5,458 times over one film export.
4577 shared.progress.fetch_max(
4578 (samples.len().saturating_sub(skip).min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32,
4579 Ordering::Relaxed,
4580 );
4581 // The range is in: the mix past its end would only be cut off below.
4582 if samples.len() >= skip + total {
4583 break;
4584 }
4585 }
4586 samples.drain(..skip.min(samples.len()));
4587 samples.resize(total, 0.0);
4588 if let Some(target) = shared.loudness {
4589 level_to_target(&mut samples, audio.sample_rate, audio.channels.max(1), target);
4590 }
4591 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!(
4592 "export audio: mixed {:.1} s of sound in {:.1} s",
4593 total as f64 / f64::from(audio.sample_rate.max(1)) / channels as f64,
4594 mixed.elapsed().as_secs_f64()
4595 ); }
4596
4597 // Opus where the container carries it and the mix is inside the envelope
4598 // this encoder is *measured* correct in ([`encode_opus`]): a Matroska file,
4599 // 48 kHz, mono or stereo. An Opus source edited into an mkv export
4600 // therefore leaves as Opus instead of being turned into AAC on the way
4601 // out, which is the one generation of loss an all-Opus timeline used to
4602 // pay for being cut.
4603 //
4604 // Everything else falls through to the AAC below and is unchanged by this:
4605 // every mp4, a 44.1 kHz timeline. The rate is the mix's own -- there is no
4606 // resampler on this path, and inventing one to reach 48 kHz would resample
4607 // a whole timeline to satisfy a codec, which is a bigger change to the
4608 // sound than the codec is.
4609 // ...and again before either encoder is entered: both of them run to the
4610 // end of the mix without a checkpoint of their own, so this is the last
4611 // moment a cancel costs seconds rather than the whole encode.
4612 cancelled(shared)?;
4613 if mkv
4614 && audio.sample_rate == OPUS_RATE
4615 && (1..=2).contains(&channels)
4616 && let Some((packets, pre_skip)) = encode_opus(&samples, kbps, channels)?
4617 {
4618 return Ok(Some(ExportAudio {
4619 params: crate::AacTrackParams {
4620 freq_index,
4621 chan_conf: channels as u8,
4622 sample_rate: OPUS_RATE,
4623 },
4624 packets,
4625 copied: false,
4626 opus_pre_skip: Some(pre_skip),
4627 language: None,
4628 pcm_frames: Some(samples.len() as u64 / channels as u64),
4629 }));
4630 }
4631
4632 // A WebM file carries Opus or nothing: a track the gate handed back is named
4633 // here rather than written as AAC into a file no WebM reader will open.
4634 if webm {
4635 return Err(
4636 "the sound could not be coded as Opus, the only sound a WebM file \
4637 carries: export a Matroska instead"
4638 .into(),
4639 );
4640 }
4641 // The caller's rate, never the encoder's own 128 default -- see
4642 // [`DEFAULT_AUDIO_KBPS`] for why the untouched figure is 256.
4643 let mut encoder = ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig {
4644 bitrate_bps: kbps * 1_000,
4645 ..Default::default()
4646 });
4647 encoder.push_pcm(&samples, audio.channels.max(1), audio.sample_rate)?;
4648 encoder.finish();
4649 let mut packets = Vec::new();
4650 // `next_packet` after `finish` yields packets until `Eof` and nothing else,
4651 // so the loop ends on the only error it can see.
4652 while let Ok(packet) = encoder.next_packet() {
4653 cancelled(shared)?;
4654 packets.push(crate::AacPacket {
4655 bytes: packet.data,
4656 samples: packet.duration,
4657 });
4658 }
4659 Ok(Some(ExportAudio {
4660 params: crate::AacTrackParams {
4661 freq_index,
4662 // 1 and 2 are the ISO channel configurations for mono and stereo,
4663 // and what the opener hands the timeline is one of those whatever
4664 // the source carried ([`crate::audio::downmix`]).
4665 chan_conf: audio.channels.max(1) as u8,
4666 sample_rate: audio.sample_rate,
4667 },
4668 packets,
4669 copied: false,
4670 opus_pre_skip: None,
4671 language: None,
4672 pcm_frames: Some(samples.len() as u64 / channels as u64),
4673 }))
4674}
4675
4676/// The one rate Opus codes at. The container may state another one in its
4677/// `OpusHead` and every decoder still runs at 48 kHz (RFC 7845 §5.1), so a
4678/// timeline at any other rate is not "encoded at its own rate" here -- it is
4679/// resampled or it is not Opus, and [`encode_audio`] picks the second.
4680pub(crate) const OPUS_RATE: u32 = 48_000;
4681
4682/// 20 ms at [`OPUS_RATE`], the frame every Opus muxer in the wild writes:
4683/// long enough that the per-packet overhead is nothing, short enough that a
4684/// Matroska block timestamp in whole milliseconds is exact.
4685const OPUS_FRAME: usize = 960;
4686
4687/// The most this project asks of the Opus encoder, in kbps, and why it is a cap
4688/// rather than the four rates the Sound row offers.
4689///
4690/// History, because the number moved once already and the reason it could is
4691/// part of the record. Under `opus-rs 0.1.26` the ceiling was 128: that encoder
4692/// fell off a cliff at a rate that depended on the *content*, and above it a
4693/// conformant decoder got noise back. Measured on three one-second spans of a
4694/// real 5.1 Opus film, encoded there and decoded with `ruopus` -- which was not
4695/// the suspect, since it decoded ffmpeg's own libopus at 256 kbps to
4696/// correlation 1.00000 on the same material:
4697///
4698/// ```text
4699/// kbps 120 128 136 144 152 160
4700/// span A 0.945 0.937 0.452 0.206 0.223 0.163
4701/// span B 0.986 0.989 0.697 0.153 0.114 0.149
4702/// span C 0.999 0.994 0.951 0.335 0.266 0.326
4703/// libopus 0.997 0.998 -- -- -- 0.996 (same spans, control)
4704/// ```
4705///
4706/// So: usable to 128, ruined by 136 on real film sound -- and mono worse, at
4707/// every rate, which is why a mono mix kept the AAC path entirely. `ec-opus`
4708/// has no such cliff: its own suite holds every rate of the format's table to
4709/// the reference decoders, mono, stereo and 5.1 alike, and this project
4710/// re-measures the high band and the mono path where the old encoder failed
4711/// (`the_opus_encoder_is_pinned_to_the_band_it_was_measured_in`).
4712///
4713/// It is still not *trusted*: every track is decoded again and measured before
4714/// it is written ([`opus_fidelity`]), because a rate nobody measured on *your*
4715/// sound is not something a constant can be safe against on its own.
4716/// The ceiling is the Sound row's ([`AUDIO_KBPS`]), not the format's 510 kbps:
4717/// a rate nothing in the product can ask for is a rate nothing here measures.
4718/// 320 covers the row honestly, including the 256 default
4719/// ([`DEFAULT_AUDIO_KBPS`]) the old cap silently halved on a Matroska export.
4720pub(crate) const OPUS_MAX_KBPS: u32 = 320;
4721
4722/// How well a track has to survive its own round trip to be written as Opus:
4723/// the correlation between the mix and the decode of what was encoded from it.
4724/// A good encoder scores 0.98-0.999 on this material (libopus, measured above);
4725/// the failure mode is not subtle at all, scoring 0.1-0.7. 0.95 sits in the gap
4726/// with room on both sides, and what fails it is written as AAC -- the export's
4727/// own encoder line then says AAC, so the fallback is visible rather than
4728/// silent.
4729const OPUS_MIN_FIDELITY: f64 = 0.95;
4730
4731/// The encoder's lookahead at [`OPUS_RATE`] in the mode this envelope always
4732/// selects (CELT-only: 2.5 ms). The pre-skip a file states is this *plus* the
4733/// warm-up frame [`encode_opus`] throws away. Measured by
4734/// cross-correlating the decode against the source, not taken from the crate --
4735/// it exposes no lookahead getter -- and asserted at both ends of the rate band
4736/// in `tests/opus_export.rs`, which is what catches a version that changes it.
4737const OPUS_PRE_SKIP: u16 = 120;
4738
4739/// The mix as Opus packets, one per [`OPUS_FRAME`], plus the pre-skip that has
4740/// to be declared in front of them. Mono or stereo, at [`OPUS_RATE`] -- the
4741/// caller checks all of it, because outside that envelope this encoder is not
4742/// one this project is willing to write files with ([`OPUS_MAX_KBPS`]).
4743///
4744/// The tail frame is padded with silence rather than dropped: Opus codes whole
4745/// frames and a track a few milliseconds short under a picture that is not is
4746/// the drift every other path here is written to avoid. The pre-skip trims the
4747/// front; the container's duration trims the back.
4748fn encode_opus(
4749 samples: &[f32],
4750 kbps: u32,
4751 channels: usize,
4752) -> crate::Result<Option<(Vec<crate::AacPacket>, u16)>> {
4753 let mut encoder = ec_opus::Encoder::new(OPUS_RATE, channels, ec_opus::Application::Audio)
4754 .map_err(|e| format!("the Opus encoder refused 48 kHz {channels}-channel sound: {e}"))?;
4755 // CBR, the crate's default: every packet exactly the rate's size. The old
4756 // seat ran opus-rs's VBR; the gate below measures either, and a fixed
4757 // packet size is the friendlier neighbour to a muxer's block budget.
4758 encoder.set_bitrate(kbps.min(OPUS_MAX_KBPS) * 1_000);
4759 // No complexity knob on this crate: the reference's default (9) is baked
4760 // into its rate arithmetic, one percent of equiv rate away from the 10 the
4761 // old encoder was asked for.
4762 let mut packets = Vec::new();
4763 let mut frame = vec![0f32; OPUS_FRAME * channels];
4764 // 1275 bytes is the most one Opus frame may weigh (RFC 6716 §3.2); this is
4765 // that with room for the TOC and a padded frame, so `encode_float` never
4766 // has to refuse for want of a buffer.
4767 let mut out = vec![0u8; 1500];
4768 // The head, coded **twice**. An encoder's very first frame has no history
4769 // behind it and comes out ramped and out of phase -- measured on a 440 Hz
4770 // fixture, the first 20 ms of the export correlated 0.09 with the source
4771 // where every later window correlated 0.9997 -- and 20 ms of wrong sound at
4772 // the head of a file is the kind of thing nobody hears in a test and
4773 // everybody hears in the first frame of a cut. So the first frame is fed in
4774 // once to warm the encoder, and thrown away again by the pre-skip: exactly
4775 // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet.
4776 let coded = std::time::Instant::now();
4777 let warm = samples.len().min(OPUS_FRAME * channels);
4778 // ...and one silent frame after the sound, for the same delay seen from the
4779 // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so
4780 // without a frame to push them out the last 2.5 ms of the timeline stay
4781 // inside it and the track ends short under a picture that does not.
4782 let blocks = std::iter::once(&samples[..warm])
4783 .chain(samples.chunks(OPUS_FRAME * channels))
4784 .chain(std::iter::once(&samples[..0]));
4785 for block in blocks {
4786 frame[..block.len()].copy_from_slice(block);
4787 frame[block.len()..].fill(0.0);
4788 let len = encoder
4789 .encode_float(&frame, OPUS_FRAME, &mut out)
4790 .map_err(|e| format!("Opus encode failed: {e}"))?;
4791 packets.push(crate::AacPacket {
4792 bytes: out[..len].to_vec(),
4793 samples: OPUS_FRAME as u32,
4794 });
4795 }
4796 // ...and now the part that is not optimism: what was just written is
4797 // decoded again and measured against what went in, and a track that does
4798 // not come back is not written at all ([`OPUS_MIN_FIDELITY`]). The caller
4799 // falls through to AAC, which is exactly where it stood before this seat
4800 // existed -- a worse codec is a fair trade for a track that is the sound.
4801 //
4802 // corner-cut: this costs one Opus decode of the whole track (a minute of
4803 // sound in a few hundred milliseconds, against a video encode that is
4804 // minutes). Upgrade path is deleting it, the day this encoder can be
4805 // trusted at the rate it is asked for.
4806 let encoded = coded.elapsed().as_secs_f64();
4807 let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16;
4808 let measured = std::time::Instant::now();
4809 let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip), channels);
4810 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!(
4811 "export audio: Opus encode {encoded:.1} s, fidelity {fidelity:.4} measured in {:.1} s",
4812 measured.elapsed().as_secs_f64()
4813 ); }
4814 Ok((fidelity >= OPUS_MIN_FIDELITY).then_some((packets, pre_skip)))
4815}
4816
4817/// Packets one sampled window listens to: 5 s at [`OPUS_FRAME`].
4818const FIDELITY_WINDOW: usize = 250;
4819
4820/// How many of them a long track is judged on -- a minute of sound, wherever
4821/// the track's length puts them, and a constant cost rather than one that grows
4822/// with the film ([`opus_fidelity`]).
4823const FIDELITY_WINDOWS: usize = 12;
4824
4825/// Packets decoded into a window and thrown away before it is measured. CELT
4826/// predicts across frames, so a decoder started cold mid-stream is behind its
4827/// own history for a few frames; 100 ms is far more than it needs and is not
4828/// worth counting.
4829const FIDELITY_WARMUP: usize = 5;
4830
4831/// How much sound a window must carry before its correlation means anything:
4832/// mean square per sample. A window of digital silence -- the head of a film,
4833/// the gap between a feature and its credits -- correlates with nothing, and
4834/// failing a track for it would send perfectly good sound to AAC.
4835const FIDELITY_FLOOR: f64 = 1e-9;
4836
4837/// The correlation between `samples` and the decode of `packets` with the first
4838/// `pre_skip` frames dropped: 1.0 is the same waveform, and this codec's failure
4839/// mode lands near 0.1. Streamed packet by packet -- the decode is never held,
4840/// only three running sums -- because the mix behind it is already the biggest
4841/// thing in an export ([`encode_audio`]'s corner-cut).
4842///
4843/// A packet the decoder refuses is 0.0 and no argument: a track this project
4844/// cannot read is exactly what this is here to catch.
4845///
4846/// **Sampled above a minute of sound, and the median window is the answer.**
4847/// This decode was the whole cost of exporting a feature film under the
4848/// previous decoder: `ruopus` ran its inverse MDCT at 0.2x real time (measured,
4849/// 24.2 s for 121.5 s of stereo; `ec-opus`, the decoder here now, is far
4850/// quicker, and the sampling survives it because it costs almost nothing to
4851/// keep),
4852/// so judging every packet of a two-and-a-half-hour film costs half an hour
4853/// before a byte of picture is written -- which is what it did, and what made a
4854/// copy export that has no encoding to do at all sit at zero for twenty minutes.
4855/// [`FIDELITY_WINDOWS`] windows spread evenly across the track cost the same
4856/// minute of decode whatever the film's length, and what they are looking for
4857/// survives sampling: [`OPUS_MAX_KBPS`]'s cliff is a *rate* the encoder falls
4858/// off everywhere that rate is used, not a defect of one bar of music.
4859///
4860/// The **median** and not the worst, and that is measured rather than cautious.
4861/// Forty five-second windows of a real 5.1 film's mix, encoded here at 128 kbps
4862/// and decoded back, in order:
4863///
4864/// ```text
4865/// 0.803 0.835 0.938 0.940 0.960 0.987 0.994 ... median 0.998 ... 0.999
4866/// ```
4867///
4868/// Five of the thirty-nine that carried sound sit under [`OPUS_MIN_FIDELITY`] on
4869/// a track that is *good* -- which is the same thing the table in
4870/// [`OPUS_MAX_KBPS`] shows, where a span scoring 0.937 at 128 kbps is inside the
4871/// usable band. A worst-window rule at 0.95 therefore refuses films this encoder
4872/// handles perfectly well, while the failure it exists for is the opposite
4873/// shape: at 136 kbps the same three measured spans read 0.452, 0.697, 0.951,
4874/// and at 256 kbps the whole track correlates 0.06. Half a track cannot be
4875/// ruined without the middle of the list moving, so the median separates the two
4876/// by a margin no single window can (0.998 against under 0.7) -- and a track
4877/// under a minute is one window, where median and whole-track correlation are
4878/// the same number the gate always used.
4879fn opus_fidelity(
4880 packets: &[crate::AacPacket],
4881 samples: &[f32],
4882 pre_skip: usize,
4883 channels: usize,
4884) -> f64 {
4885 // Short enough to hear all of: every fixture, every unit test, and any
4886 // track under a minute. There is nothing to sample from.
4887 let all = FIDELITY_WINDOW * FIDELITY_WINDOWS;
4888 if packets.len() <= all {
4889 return window_fidelity(packets, samples, pre_skip, channels, 0, 0, packets.len())
4890 .unwrap_or(1.0);
4891 }
4892 // Evenly spread, first window at the head: the head is where an encoder's
4893 // own warm-up would show, and the last starts a window short of the end so
4894 // no window runs past the packets.
4895 let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);
4896 let mut scores: Vec<f64> = Vec::with_capacity(FIDELITY_WINDOWS);
4897 for w in 0..FIDELITY_WINDOWS {
4898 let at = w * step;
4899 let from = at.saturating_sub(FIDELITY_WARMUP);
4900 let Some(fidelity) = window_fidelity(
4901 packets,
4902 samples,
4903 pre_skip,
4904 channels,
4905 from,
4906 at,
4907 at + FIDELITY_WINDOW,
4908 ) else {
4909 continue; // silence: nothing to correlate, and not a failure
4910 };
4911 scores.push(fidelity);
4912 }
4913 // Every window silent is a silent track, which this codec writes as silence.
4914 if scores.is_empty() {
4915 return 1.0;
4916 }
4917 scores.sort_by(f64::total_cmp);
4918 scores[scores.len() / 2]
4919}
4920
4921/// [`opus_fidelity`] over `packets[measure..to]`, with `packets[from..measure]`
4922/// -- the warm-up -- decoded for its state and thrown away. `None` where the
4923/// source window carries no sound worth correlating ([`FIDELITY_FLOOR`]).
4924fn window_fidelity(
4925 packets: &[crate::AacPacket],
4926 samples: &[f32],
4927 pre_skip: usize,
4928 channels: usize,
4929 from: usize,
4930 measure: usize,
4931 to: usize,
4932) -> Option<f64> {
4933 let (streams, coupled, mapping) = match channels {
4934 1 => (1, 0, vec![0u8]),
4935 // One coupled stream: the stereo shape every fixture and every mix
4936 // here decodes back through.
4937 _ => (1, 1, vec![0, 1]),
4938 };
4939 let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, streams, coupled, &mapping);
4940 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
4941 // Where in the mix this window's first decoded sample lands: every packet
4942 // is [`OPUS_FRAME`] long, and the pre-skip is what the front of the stream
4943 // owes before the first of them is the timeline's frame 0.
4944 let mut at = (from * OPUS_FRAME * channels).saturating_sub(pre_skip * channels);
4945 let mut drop = (pre_skip * channels).saturating_sub(from * OPUS_FRAME * channels);
4946 let mut counted = 0usize;
4947 for (index, packet) in packets.iter().enumerate().take(to).skip(from) {
4948 let Ok(pcm) = decoder.decode_packet(&packet.bytes) else {
4949 return Some(0.0);
4950 };
4951 let pcm = &pcm[drop.min(pcm.len())..];
4952 drop = drop.saturating_sub(packet.samples as usize * channels);
4953 // The warm-up is decoded for its state and not for its numbers.
4954 if index < measure {
4955 at += pcm.len();
4956 continue;
4957 }
4958 for (want, got) in samples[at.min(samples.len())..].iter().zip(pcm) {
4959 let (x, y) = (f64::from(*want), f64::from(*got));
4960 num += x * y;
4961 da += x * x;
4962 db += y * y;
4963 at += 1;
4964 counted += 1;
4965 }
4966 }
4967 (da / counted.max(1) as f64 > FIDELITY_FLOOR).then(|| num / (da.sqrt() * db.sqrt()).max(1e-12))
4968}
4969
4970/// The audio pass, running beside the picture: what [`run`] holds while it
4971/// encodes and joins where the file it is writing needs the track.
4972type AudioJob = thread::JoinHandle<crate::Result<Option<ExportAudio>>>;
4973
4974/// The pass while [`run`] holds it, joined however that function leaves --
4975/// including through a `?`.
4976///
4977/// A [`JoinHandle`](thread::JoinHandle) that is merely dropped *detaches* its
4978/// thread, and the one error that matters here is the hardware encoder's
4979/// process dying ([`crate::hwproc`]): the whole export is then written again by
4980/// [`start`], which starts an audio pass of its own. The abandoned one would go
4981/// on mixing and encoding the same sound beside it -- two passes of a feature
4982/// film's audio at once, on the machine that has just lost its GPU. Joined
4983/// instead, so an export has one audio pass at a time and none outlives it.
4984struct AudioPass(Option<AudioJob>);
4985
4986impl AudioPass {
4987 /// Whether the pass has landed, so the picture loop may collect it without
4988 /// waiting.
4989 fn is_finished(&self) -> bool {
4990 self.0.as_ref().is_some_and(thread::JoinHandle::is_finished)
4991 }
4992
4993 /// Whether a pass is still to be collected -- which is what "the sound is
4994 /// still being worked out" means on the encoder line.
4995 fn running(&self) -> bool {
4996 self.0.is_some()
4997 }
4998
4999 /// The handle, for the one caller that is about to join it itself.
5000 fn take(&mut self) -> Option<AudioJob> {
5001 self.0.take()
5002 }
5003}
5004
5005impl Drop for AudioPass {
5006 fn drop(&mut self) {
5007 if let Some(job) = self.0.take() {
5008 let _ = job.join();
5009 }
5010 }
5011}
5012
5013/// The pass's answer, or the failure that is the export's failure. A panicked
5014/// audio thread reads as an error rather than as silence: an export that wrote
5015/// its picture and quietly no sound is the one outcome this must not have.
5016fn join_audio(job: AudioJob) -> crate::Result<Option<ExportAudio>> {
5017 job.join()
5018 .map_err(|_| crate::Error::from("the audio pass stopped without a picture or a reason"))?
5019}
5020
5021/// The encoder line a running export shows: the seat the picture is really
5022/// being written by, and what the sound is -- or that the sound is still being
5023/// worked out, which an overlapped audio pass is until it is collected.
5024fn publish_seats(
5025 shared: &Shared,
5026 seat: &str,
5027 project: &Project,
5028 settings: &ExportSettings,
5029 sound: Option<bool>,
5030 opus: bool,
5031 waiting: bool,
5032) {
5033 let audio = match waiting {
5034 // Still mixing on the other thread. The same half-line the copied-
5035 // picture path has always shown, and for the same reason: what is
5036 // published is never a codec that did not run.
5037 true => "working out the sound…",
5038 false => measured_audio_label(project, settings.format, sound, opus),
5039 };
5040 *shared.encoders.lock().unwrap() = Some(format!("{seat} · {audio}"));
5041}
5042
5043/// Hands a mix that finished mixing early to the mp4 it belongs in, the
5044/// moment both exist: `late` may land before the first coded picture has
5045/// opened `muxer` at all, so this is tried both right where the mix lands
5046/// and after every picture written afterwards, and does nothing once
5047/// `*fed` says an earlier try already succeeded. Declaring the track and
5048/// queuing its packets here is what lets [`crate::mux::Mp4Muxer`]'s own
5049/// hold interleave them under the pictures still to come, rather than the
5050/// track landing all at once after the picture is done.
5051fn feed_late_audio(
5052 muxer: &mut Option<Muxer>,
5053 late: &Option<ExportAudio>,
5054 fed: &mut bool,
5055) -> crate::Result<()> {
5056 if *fed {
5057 return Ok(());
5058 }
5059 let (Some(track), Some(Muxer::Mp4(mp4))) = (late.as_ref(), muxer.as_mut()) else {
5060 return Ok(());
5061 };
5062 mp4.add_audio_track(&params_of(track))?;
5063 for packet in &track.packets {
5064 mp4.write_audio_packet(&packet.bytes)?;
5065 }
5066 *fed = true;
5067 Ok(())
5068}
5069
5070/// The language the timeline's sound is in, for the export to tag its audio track with: the one
5071/// language every audio clip's stream states. `None` when the clips disagree, when one of them
5072/// states none (`und`), or when there are no audio clips, and the track stays `und`.
5073pub(crate) fn audio_language(project: &Project) -> Option<String> {
5074 let sources = project.sources();
5075 shared_language(
5076 project
5077 .audio_lanes()
5078 .into_iter()
5079 .flat_map(|lane| project.lane(lane).iter())
5080 .map(|clip| sources.get(clip.source).and_then(|src| stream_language(&src.path, src.audio_stream))),
5081 )
5082}
5083
5084/// The one language every stream in `langs` states, or `None` when there are none, when one
5085/// states none, or when they differ.
5086fn shared_language(langs: impl IntoIterator<Item = Option<String>>) -> Option<String> {
5087 let mut shared: Option<String> = None;
5088 for lang in langs {
5089 let lang = lang?;
5090 match &shared {
5091 None => shared = Some(lang),
5092 Some(s) if *s == lang => {}
5093 Some(_) => return None,
5094 }
5095 }
5096 shared
5097}
5098
5099/// The language audio stream `audio_stream` of `path` states in its header, with `und` (none
5100/// stated) as `None`. Read from the header alone.
5101fn stream_language(path: &Path, audio_stream: usize) -> Option<String> {
5102 crate::probe_media(path)
5103 .streams
5104 .into_iter()
5105 .find(|s| s.kind == crate::StreamKind::Audio && s.index == audio_stream)?
5106 .language
5107 .filter(|l| l != "und")
5108}
5109
5110/// The language the picture is tagged with, for the Matroska video track to state: the first
5111/// source's picture track, the one the export takes its picture from ([`source_colour_tags`]).
5112/// `None` where that track states none (`und`), or no source can be read.
5113fn video_language(project: &Project) -> Option<String> {
5114 let path = &project.sources().first()?.path;
5115 crate::probe_media(path)
5116 .streams
5117 .into_iter()
5118 .find(|s| s.kind == crate::StreamKind::Video && s.index == 0)?
5119 .language
5120 .filter(|l| l != "und")
5121}
5122
5123/// The colour tags of the first source, exactly as its container states them:
5124/// what a file that keeps its source's colour declares, unspecified fields left
5125/// unspecified. Nothing when no source can be read, which declares nothing.
5126fn source_colour_tags(project: &Project) -> Tags {
5127 project
5128 .sources()
5129 .first()
5130 .and_then(|source| crate::demux::Demuxer::open(&source.path).ok())
5131 .map(|(_, demuxer)| demuxer.colour_tags())
5132 .unwrap_or_default()
5133}
5134
5135fn params_of(track: &ExportAudio) -> AudioParams {
5136 AudioParams {
5137 freq_index: track.params.freq_index,
5138 chan_conf: track.params.chan_conf,
5139 sample_rate: track.params.sample_rate,
5140 opus_pre_skip: track.opus_pre_skip,
5141 language: track.language.clone(),
5142 }
5143}
5144
5145fn run(
5146 project: &Project,
5147 meta: &VideoMeta,
5148 out: &Path,
5149 shared: &Arc<Shared>,
5150 settings: &ExportSettings,
5151 sample_rate: Option<u32>,
5152) -> crate::Result<()> {
5153 // The media's length and not the timeline's: a caption placed past the last
5154 // picture holds the *timeline* open ([`Project::timeline_frames`]) and there
5155 // is nothing to write under it -- the picture loop walks the composite spans
5156 // and stops with them, so a file padded to the caption's end would be
5157 // trailing silence over a frozen last frame. The export ends with the last
5158 // picture or sound, the cues are cut off there ([`lane_subtitles`]), and
5159 // [`planned_subtitles`] says so before the button is pressed.
5160 // The range's own length where one is marked, the media's otherwise --
5161 // `export_spans` walks the same window, so `done` ends on this `total`
5162 // exactly as it always did.
5163 let total = settings.range.map_or(project.media_frames(), |(s, e)| {
5164 e.min(project.media_frames()).saturating_sub(s)
5165 });
5166 // The two preview switches are the H.264 mp4 pair's alone. Only that
5167 // container carries a colour of its own back out ([`write_video`] tags it
5168 // there), so asking any other for a source-space file would write pictures
5169 // in one space and a header in another; and only that codec's seats honour
5170 // `intra_only` -- the H.264 and HEVC pairs do, and an AV1 one would quietly
5171 // write the long-GOP file it always did.
5172 if settings.keep_source_colour && settings.format != Format::Mp4 {
5173 return Err(format!(
5174 "{} cannot be written in its source's colour space",
5175 settings.format.name()
5176 )
5177 .into());
5178 }
5179 if settings.intra_only && !matches!(settings.format, Format::Mp4 | Format::Hevc | Format::HevcMp4) {
5180 return Err(format!("{} cannot be written intra-only", settings.format.name()).into());
5181 }
5182 if settings.keyframe_s.is_some() && settings.intra_only {
5183 return Err("keyframe_s sets the key frame interval, and intra_only codes every picture a key frame: pass one".into());
5184 }
5185 if settings.faststart && !settings.format.is_mp4_family() {
5186 return Err(format!("faststart lays out an mp4 file, and {} is not one", settings.format.name()).into());
5187 }
5188 if let Some(why) = exact_refusal(project, meta, settings) {
5189 return Err(why.into());
5190 }
5191 let hdr_colour = hdr_colour_of(settings)?;
5192 let sources = project.sources();
5193 // The picture's decision first, before a sample of sound is touched: it is
5194 // the answer that decides what the whole export *is*, it costs one header
5195 // read per source, and it is what the line on screen has been missing --
5196 // an export that copies its picture used to say nothing at all for as long
5197 // as its sound took, which on a feature film was minutes. Half a line now,
5198 // completed by the measured codec once the sound is known below: what is
5199 // published is never a codec that did not run.
5200 let plan = CopyPlan::of(project, meta, settings);
5201 if plan.is_some() {
5202 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export video: copy (source packets)"); }
5203 *shared.encoders.lock().unwrap() = Some("copy · working out the sound…".into());
5204 }
5205 // ...then the audio, on a thread of its own, started before anything is
5206 // opened for the picture.
5207 //
5208 // Where it is *waited* for is the whole of this: a Matroska file interleaves
5209 // its audio into the clusters from the header on, so that path needs every
5210 // packet before the first coded picture and there is nothing to overlap. An
5211 // mp4 writes its audio track after the whole picture -- and now declares it
5212 // there too ([`MkvMuxer`]'s opposite, `Mp4Muxer::add_audio_track`) -- so the
5213 // picture's loop needs nothing at all from this until it has finished, and
5214 // the mix, its encode and the encode of every frame run at once. An export
5215 // used to cost the sound *plus* the picture; an mp4 one now costs the longer
5216 // of the two. On this project's own film that is 168 s of AC-3 that no
5217 // longer stands in front of 733 s of hardware H.264.
5218 // What a file keeping its source's colour declares, read once: the picture
5219 // is written in that space, so the tags are the source's own, not resolved.
5220 let source_colour = match settings.keep_source_colour {
5221 true => source_colour_tags(project),
5222 false => Tags::default(),
5223 };
5224 // The picture's language, which the Matroska video track states (`und` where none).
5225 let source_language = video_language(project);
5226 // A ProRes file's sound is PCM (24-bit unless asked for 16) mixed on a thread of its own and written
5227 // after the picture ([`PcmPass`]); no AAC pass runs beside it.
5228 let bits = prores_audio_bits(settings);
5229 let pcm_job = match settings.format.is_prores() {
5230 true => {
5231 let (project, meta, settings, shared) =
5232 (project.clone(), *meta, settings.clone(), Arc::clone(shared));
5233 PcmPass(Some(
5234 thread::Builder::new()
5235 .name("export-pcm".into())
5236 .spawn(move || mix_pcm16(&project, &meta, &shared, &settings, sample_rate, bits))?,
5237 ))
5238 }
5239 false => PcmPass(None),
5240 };
5241 let audio_job = if settings.format.is_prores() { None } else { Some({
5242 let (project, meta, settings, shared) =
5243 (project.clone(), *meta, settings.clone(), Arc::clone(shared));
5244 thread::Builder::new()
5245 .name("export-audio".into())
5246 .spawn(move || {
5247 let track = copy_audio(
5248 &project,
5249 &meta,
5250 audio_kbps_of(&settings),
5251 settings.format.is_mkv(),
5252 settings.format == Format::Webm,
5253 settings.reencode_audio,
5254 &shared,
5255 // WebM's sound is mixed at the rate Opus codes at, so the
5256 // one encoder path it takes is the one that resamples.
5257 match settings.format {
5258 Format::Webm => Some(OPUS_RATE),
5259 _ => sample_rate,
5260 },
5261 settings.range,
5262 )?;
5263 // The language the sound is in, on the copy and the mix alike:
5264 // the one tag the whole track carries.
5265 Ok(track.map(|track| ExportAudio {
5266 language: audio_language(&project),
5267 ..track
5268 }))
5269 })?
5270 }) };
5271 // A Matroska file (and a copied one, whose muxer is the same) collects it
5272 // here; an mp4 leaves it running and collects it under the picture below.
5273 // Held in a guard from here on, so no way out of this function leaves the
5274 // pass running behind it ([`AudioPass`]).
5275 let mut audio_job = AudioPass(audio_job);
5276 // The condition is the *format*, and the copied-picture path below relies
5277 // on that covering it too: `plan` hands its packets straight to a Matroska
5278 // muxer, so it may only exist where this has already collected them --
5279 // which holds because [`CopyPlan::of`] returns `None` for every format
5280 // that is not `Hevc` or `Av1`, both of which are `is_mkv`. Said out loud
5281 // because a copy plan for an mp4 would otherwise reach `plan.run` with the
5282 // sound still being mixed on the other thread.
5283 debug_assert!(
5284 settings.format.is_mkv() || plan.is_none(),
5285 "a copy plan outside Matroska would run before its sound is collected"
5286 );
5287 let mut pcm_job = pcm_job;
5288 let audio = match settings.format.is_mkv() {
5289 true => join_audio(audio_job.take().expect("the job was just made"))?,
5290 false => None,
5291 };
5292 let audio_params = audio.as_ref().map(params_of);
5293 // What the track *is*, kept before the packets are handed to a muxer: the
5294 // encoder line names a copy or an encode and only `copy_audio` knows which.
5295 // `None` on the mp4 path until the pass is collected -- the line says it is
5296 // still working the sound out, which is what it is doing.
5297 let mut sound = audio.as_ref().map(|track| track.copied);
5298 // ...and *which* encoder, for the same line: the card predicts Opus from the
5299 // format alone and cannot know the mix's rate or width ([`audio_label`]),
5300 // while this is after the mix was opened, so it is the measured answer.
5301 let mut opus = audio
5302 .as_ref()
5303 .is_some_and(|track| track.opus_pre_skip.is_some());
5304 // Taken by the Matroska muxer at creation; the mp4 one writes its track
5305 // after the picture, so for that path this is filled in at the end.
5306 let mut packets = audio.map(|track| track.packets);
5307 // ...and the cues with them, for the same reason: the subtitle track is
5308 // declared in the header and its blocks are interleaved into the clusters,
5309 // so the muxer needs the lot before the first picture is written.
5310 let mut subs = export_subtitles(project, meta, settings);
5311 // Whatever the sound has reached, the picture's share starts here
5312 // ([`AUDIO_BAND`]) -- and the bar only ever moves forwards, which is what
5313 // `fetch_max` below keeps true while an audio pass is still publishing its
5314 // own third of that band from the other thread.
5315 shared.progress.fetch_max(AUDIO_BAND, Ordering::Relaxed);
5316
5317 // Before an encoder is opened at all: a timeline nobody has touched, whose
5318 // sources this file can hold as they are, is written by copying their coded
5319 // blocks -- the picture's half of what `copy_audio` just did for the sound,
5320 // and the difference between an export bounded by the *edited* spans and one
5321 // that re-encodes a whole film to change a cut. [`CopyPlan`] states the
5322 // whole rule; anything at all outside it falls through to the walk below.
5323 if let Some(plan) = plan {
5324 *shared.encoders.lock().unwrap() = Some(format!(
5325 "copy · {}",
5326 // The measured codec, exactly as the encoder path below publishes
5327 // it: the mix has been opened by now, so a line that fell back to
5328 // AAC says AAC. Naming the prediction here would make the fallback
5329 // invisible on precisely the exports that are over in seconds.
5330 measured_audio_label(project, settings.format, sound, opus)
5331 ));
5332 return plan.run(
5333 out,
5334 meta,
5335 shared,
5336 audio_params.as_ref().zip(packets.take()),
5337 std::mem::take(&mut subs),
5338 total,
5339 &settings.chapters,
5340 );
5341 }
5342
5343 // One header parse per source, before any of them is decoded: what rate
5344 // each file was shot at against the timeline's ([`Rate`]), which is how the
5345 // clip's timeline frames below become frames of the file, and what its
5346 // samples *mean* ([`ColorDescription`]), which is what decides whether they
5347 // are remapped on the way in. Real time for a still, a song and a
5348 // single-rate project, where every conversion below is the identity.
5349 let rates: Vec<(
5350 Rate,
5351 ColorDescription,
5352 Option<f32>,
5353 Rotation,
5354 crate::demux::PixelAspect,
5355 )> = sources
5356 .iter()
5357 .map(|source| source_rate(&source.path, meta.frame_rate))
5358 .collect();
5359 // ...and, for a source on an HDR curve, the tone map that brings its samples
5360 // down to the SDR this file is written in ([`crate::tonemap`]). Once per
5361 // source stream: the table costs a couple of milliseconds to build and a
5362 // span reopens its file, so building it here rather than in the loop below
5363 // is the difference between paying that once and paying it per cut. An SDR
5364 // source -- the whole of an ordinary project -- builds no table at all.
5365 //
5366 // Through the project's own preset ([`tonemap::Preset`]) and each source's
5367 // own declared peak, which is the pair playback's decode funnel builds its
5368 // tables with: preview and export are the same rendition of the same film
5369 // because they are told the same two things, not because two numbers happen
5370 // to agree.
5371 let preset = project.tone();
5372 let tone: Vec<Option<ToneMapper>> = rates
5373 .iter()
5374 .map(|(_, color, peak, _, _)| match color.transfer {
5375 // A preview file keeps the film's own curve and is tone-mapped when
5376 // it is *shown* ([`ExportSettings::keep_source_colour`]), which is
5377 // both cheaper and the only way the preset can still be changed
5378 // after the stand-in was made.
5379 _ if settings.keep_source_colour => None,
5380 // An HDR export keeps the HDR sources' own curve: no tone map to SDR
5381 // ([`ExportSettings::hdr`], [`hdr_colour_of`] refuses a curve change).
5382 _ if hdr_colour.is_some() => None,
5383 Transfer::Sdr => None,
5384 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)),
5385 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)),
5386 })
5387 .collect();
5388 // ...and the one space they are all written in, the same rule a reader with
5389 // no tags to read would apply to this file's height -- or, for a preview
5390 // file, the source's own, which is what makes every remap below the
5391 // identity and the file's `colr` box its film's.
5392 // The software seat's depth ([`wide_ten_bit`]): a 10-bit timeline is
5393 // decoded and encoded at 10 bits wherever its pictures pass through untouched.
5394 for (_, color, ..) in &rates {
5395 let clash = hdr_colour.is_some_and(|out| color.transfer != Transfer::Sdr && color.transfer != out.transfer);
5396 if clash {
5397 let out = hdr_colour.expect("a clash needs an HDR output");
5398 return Err(format!(
5399 "a source is {} and this export is {}: converting one HDR curve to the other is not done here, so pick the export's transfer to match, or SDR to tone-map",
5400 transfer_name(color.transfer),
5401 transfer_name(out.transfer)
5402 )
5403 .into());
5404 }
5405 }
5406 let ten_bit = wide_ten_bit(settings, || {
5407 sources
5408 .iter()
5409 .any(|s| Demuxer::open(&s.path).is_ok_and(|(_, d)| d.bit_depth() >= 10))
5410 })?;
5411 // The colour a 10-bit SDR export declares: its sources' own matrix, where every
5412 // clip is SDR in one matrix ([`source_sdr_colour`]). Every other export keeps the
5413 // output rule, and so does the encoder's declared colour when there is no such one.
5414 let source_sdr = match ten_bit && !settings.keep_source_colour {
5415 // An HDR export declares its own colour, whatever the sources are.
5416 true if hdr_colour.is_some() => hdr_colour,
5417 true => source_sdr_colour(&rates.iter().map(|(_, c, ..)| *c).collect::<Vec<_>>()),
5418 false => None,
5419 };
5420 let rule = ColorDescription::output_sized(meta.width, meta.height);
5421 let out_color = match settings.keep_source_colour {
5422 true => meta.color,
5423 false => source_sdr.unwrap_or(rule),
5424 };
5425 let container_colour = source_sdr.map_or(source_colour, Tags::of);
5426
5427 // The captions drawn into each picture, if the export burns any in ([`Burn`]).
5428 let mut burn = Burn::new(project, settings, meta.frame_rate, out_color.full_range)?;
5429 let mut encoder = Enc::open(meta, settings, ten_bit, source_sdr.unwrap_or(rule))?;
5430 // What this file is really being written by, for a progress line to name.
5431 // Published *after* the seat is open, so a hardware encoder the driver
5432 // refused reads as the software one that took over rather than as the hope
5433 // it replaced -- and the sound says whether it was copied or encoded, which
5434 // only `copy_audio` knows and, on the overlapped path, does not know yet.
5435 let seat = encoder.label();
5436 publish_seats(
5437 shared,
5438 seat,
5439 project,
5440 settings,
5441 sound,
5442 opus,
5443 audio_job.running(),
5444 );
5445 // When the picture started, so the stage line below can say where under it
5446 // the sound landed -- the one number that says whether the two passes
5447 // really overlapped, in the same voice as `encode_audio`'s own timers.
5448 let picture_started = std::time::Instant::now();
5449 // The sound, once the pass beside this one has finished with it: joined
5450 // here the moment it lands rather than only after the picture, so
5451 // `feed_late_audio` below can hand it to the muxer while pictures are
5452 // still being coded and let `Mp4Muxer`'s own hold interleave the two
5453 // ([`crate::mux::Mp4Muxer`]).
5454 let mut late: Option<ExportAudio> = None;
5455 // Set once `late`'s track has been handed to the muxer -- so the final
5456 // join below, which still exists for a mix that never lands mid-picture,
5457 // knows not to declare the track or write its packets a second time.
5458 let mut audio_fed = false;
5459 let mut muxer = None;
5460 // A ProRes file is declared up front: the encoder knows its own sample entry.
5461 if let Some(params) = encoder.prores_params() {
5462 muxer = Some(Muxer::Mov(crate::prores_out::MovWriter::create(
5463 out,
5464 params,
5465 crate::mux::frame_timing(meta.frame_rate)?,
5466 )?));
5467 }
5468 let mut done = 0u32;
5469 // ...and how many of the edit's frames a file could not give, summed over
5470 // the spans that ran out under their clip ([`Shared::truncated`]).
5471 let mut skipped = 0u32;
5472 let black = Black::new(meta);
5473 // Software decoders that spans leave behind for the next span of the same
5474 // file to continue (see [`Parked`]).
5475 let parked = Arc::new(Parked::default());
5476 // Spans, not clips: a gap in the video is part of the timeline and gets
5477 // encoded too, as black frames. The picture count is therefore
5478 // `media_frames` however the lanes are arranged -- [`export_spans`] is that
5479 // walk cut to it, so `done` ends on the `total` above instead of running
5480 // past it under a trailing caption -- and *which* lane a span comes from is
5481 // `composite_spans_from`'s answer, the same one playback shows, so an
5482 // export is what was watched.
5483 for span in export_spans(project, settings.range) {
5484 // Every clip reopens its own source file at its own in point; the
5485 // encoder is *not* reopened, so the export is one continuous stream
5486 // whose GOP boundaries need not line up with the cuts -- nor with the
5487 // file boundaries, which are just cuts that change the path.
5488 // Whether this span's tail dissolves into its successor -- decided
5489 // before A's own decoder is opened, because it is what decides
5490 // whether A may take the DMA fast path at all: the blend below needs
5491 // A's pixels on the CPU, so a dissolving span never asks for a GPU
5492 // buffer, not even outside its own window.
5493 //
5494 // A layered span (two or more clips on the stack, [`layered_at`]) takes
5495 // no decoder of its own: its pictures are composed by a [`LayerStack`]
5496 // opened beside it, placed and faded per clip, so it never dissolves,
5497 // never takes the DMA path and never runs the single-clip placement.
5498 let keyed_color = color_keyed_alone_at(project, span.start).filter(|_| ten_bit);
5499 let layered_here = layered_at(project, span.start) && keyed_color.is_none();
5500 let dissolve = dissolve_window(project, &span);
5501 let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) =
5502 match span.from.filter(|_| !layered_here) {
5503 Some((source, in_frame)) => {
5504 let entry = sources
5505 .get(source)
5506 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
5507 let (rate, color, _peak, rotation, pixel_aspect) = rates[source];
5508 // A field-mode clip of an interlaced file counts fields, two a frame.
5509 let deint = span_deint(project, span.start, &entry.path);
5510 let rate = crate::deinterlace::counted_rate(deint, rate);
5511 let mapper = tone[source].as_ref();
5512 // Nothing on the way from this span's decoder to the encoder
5513 // touches a sample: no tone map, no matrix remap, no grade --
5514 // which is what lets the *decoded buffer itself* be encoded,
5515 // never read back and never written out again. The canvas is
5516 // the fourth thing that would touch it, and the decoder answers
5517 // that one: a picture of another size than this file's is one
5518 // the plugin hands back as pixels ([`HwSession::next_frame_dma`]).
5519 let untouched = mapper.is_none()
5520 && keyed_color.is_none()
5521 && burn.is_none()
5522 && remap_into(Some(color), false, out_color.matrix).is_none()
5523 && project
5524 .composite_color_at(span.start)
5525 .is_none_or(|params| params.is_identity())
5526 && project
5527 .composite_transform_at(span.start)
5528 .is_none_or(|params| params.is_identity())
5529 // A file whose display matrix asks for a turn is *not*
5530 // untouched, whatever else the timeline says: its pictures
5531 // have to be turned, which is a read-back no GPU buffer
5532 // survives. The sample aspect is the same refusal one
5533 // stage later: its pictures have to be stretched to the
5534 // square-pixel raster before an encoder sees them, which
5535 // is the same kind of touch.
5536 && rotation.is_none()
5537 && pixel_aspect.is_square()
5538 && dissolve.is_none()
5539 && !picture_faded_in(project, &span);
5540 let want = untouched.then(|| encoder.dma_want(meta)).flatten();
5541 // Opened at the file's own frame, which is the only place the
5542 // file's numbering is used -- the span's are the timeline's.
5543 let flags = project.composite_visualizer_at(span.start);
5544 let pictures = if crate::is_audio(&entry.path) || flags & 1 != 0 {
5545 ClipDecoder::visualizer(
5546 &entry.path,
5547 entry.audio_stream,
5548 rate.source_at(in_frame),
5549 (meta.width, meta.height),
5550 meta.frame_rate,
5551 flags,
5552 project.composite_viz_paint_at(span.start),
5553 )?
5554 } else if span.reverse && !crate::is_image(&entry.path) {
5555 // Played backwards: from the file frame the span starts on, down
5556 // to the lowest it reads. The loop below counts the pictures it
5557 // takes off the decoder, which is how it reads a forward one.
5558 let lo = span.source_window().map_or(0, |(_, lo, _)| rate.source_at(lo));
5559 ClipDecoder::reversed(&entry.path, rate.source_at(in_frame), lo, deint)
5560 } else {
5561 ClipDecoder::open_with(&entry.path, rate.source_at(in_frame), want, Some(&parked), ten_bit, deint)?
5562 };
5563 (
5564 Some(pictures),
5565 rate,
5566 in_frame,
5567 Some(color),
5568 mapper,
5569 rotation,
5570 pixel_aspect,
5571 )
5572 }
5573 // A gap's black is 16/128/128, which is black in every matrix here
5574 // and on every curve: nothing to remap and nothing to tone-map,
5575 // which is what `None` says. A gap is no file either, so nothing
5576 // turns it.
5577 None => (
5578 None,
5579 Rate::REAL_TIME,
5580 0,
5581 None,
5582 None,
5583 Rotation::None,
5584 crate::demux::PixelAspect::SQUARE,
5585 ),
5586 };
5587 // Mixed spaces on one timeline: a clip coded against another matrix than
5588 // the one this file declares is rewritten into it, *after* the grade --
5589 // playback grades in the source's own space and converts for the screen
5590 // ([`crate::decode`]), so a grade applied to remapped samples is a
5591 // different picture than the one the canvas showed. Same-space clips --
5592 // the whole of an ordinary project -- take `None` and not a byte is
5593 // touched.
5594 //
5595 // ...and what the samples mean when that remap sees them is not always
5596 // what the file said, which is [`remap_into`]'s whole question.
5597 let remap = remap_into(color, mapper.is_some(), out_color.matrix);
5598 // What this span is graded by -- the same answer playback's decoder
5599 // carries, so the export is the picture that was watched. `None` for a
5600 // gap and for an ungraded clip, and that is the path where not a byte
5601 // is touched. Scratch outside the frame loop: it is refilled per frame
5602 // and its allocation survives the whole span.
5603 // A layered span's clips carry their own grades and transforms, in the
5604 // [`LayerStack`] that composes them; the top clip's do not apply here.
5605 let grade = match layered_here {
5606 true => None,
5607 false => project.composite_color_at(span.start).copied(),
5608 };
5609 let transform = match layered_here {
5610 true => TransformParams::default(),
5611 false => project
5612 .composite_transform_at(span.start)
5613 .copied()
5614 .unwrap_or_default(),
5615 };
5616 // The composing stack for a layered span, open for the whole span.
5617 let mut layers = match layered_here {
5618 true => Some(LayerStack::open(
5619 project,
5620 meta,
5621 &stack_at(project, span.start),
5622 out_color.matrix,
5623 None,
5624 Some((&shared.cancel, &shared.measuring)),
5625 )?),
5626 false => None,
5627 };
5628 // A 10-bit export composes a layered picture at 10 bits too ([`LayerStack::picture16`]).
5629 let layered_wide = ten_bit && layers.is_some();
5630 let mut graded = (Vec::new(), Vec::new(), Vec::new());
5631 let mut transformed = (Vec::new(), Vec::new(), Vec::new());
5632 // The 10-bit scratch of A's placement, and the 10-bit copies of an 8-bit
5633 // picture (or of B's) that composes at 10 bits ([`widen_into`]).
5634 let mut scratch16 = Scratch16::default();
5635 let mut widened_a: Planes16 = Planes16::default();
5636 let mut widened_b: Planes16 = Planes16::default();
5637 // A lone clip's effects stack on this path draws on copies of its placed
5638 // picture, at whichever depth it was placed ([`color_keyed_alone_at`]).
5639 let fx_clip = keyed_color.filter(|clip| crate::effects::active(&clip.effects));
5640 let (mut fx8, mut fx16): (Planes, Planes16) = Default::default();
5641 let mut fx_scratch8 = crate::effects::Scratch::<u8>::default();
5642 let mut fx_scratch16 = crate::effects::Scratch::<u16>::default();
5643 // ...and one more for the file's own display-matrix turn, which happens
5644 // before all of those (see [`place_picture`]): empty for every source
5645 // that states no turn. `stretched` is its twin for the pixel aspect,
5646 // which happens right after it.
5647 let mut rotated = (Vec::new(), Vec::new(), Vec::new());
5648 let mut stretched = (Vec::new(), Vec::new(), Vec::new());
5649 // ...and the canvas it is placed on, which is where a source of another
5650 // resolution becomes a picture at the project's. The same `Composer`
5651 // playback composes with, given the same policy, so an export is what
5652 // was watched down to the letterbox; a clip already the project's size
5653 // passes through it untouched.
5654 let mut canvas = Composer::new(
5655 meta.width,
5656 meta.height,
5657 project.composite_fit_at(span.start),
5658 );
5659 // The 10-bit canvas: its own composer, because the 8-bit placement above
5660 // borrows `canvas` in the same frame. It places the same fit.
5661 let mut canvas16 = Composer::new(
5662 meta.width,
5663 meta.height,
5664 project.composite_fit_at(span.start),
5665 );
5666 // Scratch for the 8-bit composition of a 10-bit picture ([`narrowed`]),
5667 // one for A's picture and one for B's.
5668 let mut narrow_a: [Vec<u8>; 3] = Default::default();
5669 let mut narrow_b: [Vec<u8>; 3] = Default::default();
5670 // B's own decoder, opened beside A's: the two streams come off their
5671 // files together for exactly the frames the tail below blends, and
5672 // nothing else in this span ever touches it.
5673 let mut b = dissolve
5674 .map(
5675 |(b_source, b_in_frame, window, b_start)| -> crate::Result<_> {
5676 let entry = sources.get(b_source).ok_or_else(|| {
5677 format!("clip names source {b_source} of {}", sources.len())
5678 })?;
5679 let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source];
5680 // The blended tail of a dissolve takes one picture per timeline
5681 // frame, so it never counts fields: `Field` is its `Frame`.
5682 let b_deint = frame_counting(span_deint(project, b_start, &entry.path));
5683 let b_rate = crate::deinterlace::counted_rate(b_deint, b_rate);
5684 let b_mapper = tone[b_source].as_ref();
5685 let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix);
5686 Ok(Dissolve {
5687 window,
5688 kind: crate::transitions::kind_at(project, span.start),
5689 tail_start: span.len - window,
5690 decoder: if crate::is_audio(&entry.path)
5691 || project.composite_visualizer_at(b_start) & 1 != 0
5692 {
5693 ClipDecoder::visualizer(
5694 &entry.path,
5695 entry.audio_stream,
5696 b_rate.source_at(b_in_frame),
5697 (meta.width, meta.height),
5698 meta.frame_rate,
5699 project.composite_visualizer_at(b_start),
5700 project.composite_viz_paint_at(b_start),
5701 )?
5702 } else {
5703 ClipDecoder::open_with(&entry.path, b_rate.source_at(b_in_frame), None, Some(&parked), ten_bit, b_deint)?
5704 },
5705 mapper: b_mapper,
5706 remap: b_remap,
5707 grade: project.composite_color_at(b_start).copied(),
5708 transform: project
5709 .composite_transform_at(b_start)
5710 .copied()
5711 .unwrap_or_default(),
5712 rotation: b_rotation,
5713 pixel_aspect: b_pixel_aspect,
5714 canvas: Composer::new(
5715 meta.width,
5716 meta.height,
5717 project.composite_fit_at(b_start),
5718 ),
5719 rotated: (Vec::new(), Vec::new(), Vec::new()),
5720 stretched: (Vec::new(), Vec::new(), Vec::new()),
5721 graded: (Vec::new(), Vec::new(), Vec::new()),
5722 transformed: (Vec::new(), Vec::new(), Vec::new()),
5723 scratch16: Scratch16::default(),
5724 })
5725 },
5726 )
5727 .transpose()?;
5728 // Timeline frames, taken a *source* frame at a time: at a rate other
5729 // than real time the two are not the same count, and the span says which
5730 // source frame each timeline frame shows ([`Speed::source_at`]) -- the
5731 // very frame playback is holding there, because the two conversions are
5732 // one floor/ceil pair (`speed_maps_both_ways`). A speed-up decodes the
5733 // frames it skips and drops them, because the pictures after them
5734 // reference those; a slow-down encodes the picture it is holding again
5735 // rather than decoding it twice. At real time `repeats` is 1 and `want`
5736 // advances by one, which is the loop this always ran.
5737 let mut done_here = 0u32;
5738 // Source frames already taken out of this span's decoder.
5739 let mut taken = 0u32;
5740 // The whole of the mapping, in the order it composes: the speed says
5741 // which of the clip's (timeline-rate) frames a timeline frame shows,
5742 // and the rate says which frame of the *file* that is -- counted from
5743 // the one the decoder was opened at. At real time and at the timeline's
5744 // own rate this is `Speed::source_at` and nothing else, which is the
5745 // walk a single-rate project has always taken.
5746 let opened_at = rate.source_at(in_frame);
5747 let source_at =
5748 |offset: u32| rate.source_at(in_frame + span.source_offset(offset)) - opened_at;
5749 while done_here < span.len {
5750 cancelled(shared)?;
5751 // The sound's failure is the export's, and it is heard the moment
5752 // it happens rather than after the last frame: a mix this engine
5753 // cannot decode used to refuse in seconds, before any picture was
5754 // encoded, and an overlapped pass that reported only at the end
5755 // would spend the whole encode first. Also where its measured
5756 // codec reaches the line on screen.
5757 if audio_job.is_finished() {
5758 late = join_audio(audio_job.take().expect("just seen to be there"))?;
5759 sound = late.as_ref().map(|track| track.copied);
5760 opus = late
5761 .as_ref()
5762 .is_some_and(|track| track.opus_pre_skip.is_some());
5763 publish_seats(shared, seat, project, settings, sound, opus, false);
5764 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!(
5765 "export audio: done {:.1} s into the picture",
5766 picture_started.elapsed().as_secs_f64()
5767 ); }
5768 feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
5769 }
5770 let want = source_at(done_here);
5771 // A colour-keyed clip on the 10-bit path: this picture's grade is the
5772 // keys' value at its first timeline frame (a slowed picture repeated
5773 // over several frames keeps it).
5774 let grade = match keyed_color {
5775 Some(clip) => Some(crate::project::clip_color_at(
5776 clip,
5777 grade.unwrap_or_default(),
5778 span.start + done_here,
5779 )),
5780 None => grade,
5781 };
5782 // How many timeline frames from here show that same picture: one at
5783 // real time, more when the clip is slowed or its file is slower
5784 // than the timeline. Encoded again rather than decoded twice.
5785 // A layered span composes every timeline frame, so it never repeats one.
5786 // ...nor does a lone clip whose effects move from frame to frame (a
5787 // shake); a static stack is drawn once and its picture held like any other.
5788 let repeats = match layered_here || fx_clip.is_some_and(|c| crate::effects::animated(&c.effects)) {
5789 true => 1,
5790 false => (done_here..span.len)
5791 .take_while(|&offset| source_at(offset) == want)
5792 .count() as u32,
5793 };
5794 // The composed picture of a layered span, owned for this frame.
5795 let mut composed: Option<Planes> = None;
5796 let mut composed16: Option<Planes16> = None;
5797 let picture = match (&mut layers, &mut pictures) {
5798 (Some(stack), _) if layered_wide => match stack.picture16(span.start + done_here)? {
5799 Some(planes) => {
5800 let planes = composed16.insert(planes);
5801 Some(Frame::Wide(
5802 &planes.0[..],
5803 &planes.1[..],
5804 &planes.2[..],
5805 meta.width,
5806 meta.height,
5807 ))
5808 }
5809 None => None,
5810 },
5811 (Some(stack), _) => match stack.picture(span.start + done_here)? {
5812 Some(planes) => {
5813 let planes = composed.insert(planes);
5814 Some(Frame::Pixels(
5815 &planes.0[..],
5816 &planes.1[..],
5817 &planes.2[..],
5818 meta.width,
5819 meta.height,
5820 ))
5821 }
5822 None => None,
5823 },
5824 (None, Some(pictures)) => {
5825 let mut ran_out = false;
5826 while taken < want && !ran_out {
5827 ran_out = pictures.next()?.is_none();
5828 taken += 1;
5829 }
5830 match ran_out {
5831 true => None,
5832 false => {
5833 taken += 1;
5834 pictures.next()?
5835 }
5836 }
5837 }
5838 (None, None) => {
5839 let (y, u, v, width, height) = black.picture();
5840 Some(Frame::Pixels(y, u, v, width, height))
5841 }
5842 };
5843 let Some(frame) = picture else {
5844 // The file ran out before its clip did: this span's tail never
5845 // gets a picture -- and *only* this span's tail, because the
5846 // span loop this break sits in carries on with the spans after
5847 // it and writes every picture they have. Counted, not
5848 // swallowed: the bar reaches its end whatever happens, so
5849 // without this a truncated file reads as a whole one. The same
5850 // sentence `planned_subtitles` gives cues that hang past the
5851 // last picture, said after the fact here because how many
5852 // pictures a *file* holds is only known by opening it.
5853 //
5854 // `span.len > done_here` holds by the loop's own condition, and
5855 // the sum over every break is exactly `total - done` at the end
5856 // of the walk: the spans are disjoint and cover the whole edit.
5857 skipped += span.len - done_here;
5858 break; // source ran out early; the clip list outlives the file
5859 };
5860 // A picture still on the GPU has nothing waiting for it here: the
5861 // span was opened that way only where none of what follows would
5862 // have touched a sample of it, so it is placed by nobody and goes
5863 // into the encoder as the buffer the decoder wrote.
5864 // A 10-bit picture goes to the encoder whole only where nothing on the
5865 // way touches a sample: no layer, dissolve, tone map, remap, grade,
5866 // transform, turn, stretch, caption or fade. Anything else composes at
5867 // 8 bits as it always did, narrowed here.
5868 let untouched = ten_bit
5869 && !layered_here
5870 && b.is_none()
5871 && mapper.is_none()
5872 && remap.is_none()
5873 && grade.is_none()
5874 && transform == TransformParams::default()
5875 && matches!(rotation, Rotation::None)
5876 && pixel_aspect.is_square()
5877 && burn
5878 .as_ref()
5879 .is_none_or(|b| b.cues.is_empty() && b.titles.is_empty())
5880 && (done_here..done_here + repeats)
5881 .all(|off| picture_fade_at(project, span.start + off).is_none());
5882 // A 10-bit export composes at 10 bits wherever the picture is touched at
5883 // all. The exceptions stay at 8 bits: a tone map (HDR), a turn or a
5884 // stretch, and a layered picture (composed per clip).
5885 let wide16 = ten_bit
5886 && (layered_wide || !layered_here)
5887 && !untouched;
5888 let frame = match frame {
5889 Frame::Wide(_, _, _, width, height)
5890 if !wide16 && !(untouched && width == meta.width && height == meta.height) =>
5891 {
5892 narrowed(frame, &mut narrow_a)
5893 }
5894 other => other,
5895 };
5896 // The picture at 10 bits, composed: a 10-bit one as it is, an 8-bit one widened.
5897 let placed16 = match (wide16, &frame) {
5898 (true, Frame::Wide(y, u, v, width, height)) => Some(place_picture16(
5899 y,
5900 u,
5901 v,
5902 *width,
5903 *height,
5904 rotation,
5905 pixel_aspect,
5906 grade,
5907 transform,
5908 remap.filter(|_| !layered_here),
5909 mapper,
5910 &mut scratch16,
5911 &mut canvas16,
5912 )),
5913 (true, Frame::Pixels(y, u, v, width, height)) => {
5914 widen_into(y, &mut widened_a.0);
5915 widen_into(u, &mut widened_a.1);
5916 widen_into(v, &mut widened_a.2);
5917 Some(place_picture16(
5918 &widened_a.0[..],
5919 &widened_a.1[..],
5920 &widened_a.2[..],
5921 *width,
5922 *height,
5923 rotation,
5924 pixel_aspect,
5925 grade,
5926 transform,
5927 remap.filter(|_| !layered_here),
5928 mapper,
5929 &mut scratch16,
5930 &mut canvas16,
5931 ))
5932 }
5933 _ => None,
5934 };
5935 let placed = match frame {
5936 Frame::Dma(_) => None,
5937 // Encoded whole below, at 10 bits.
5938 Frame::Wide(..) => None,
5939 // Composed at 10 bits above.
5940 Frame::Pixels(..) if wide16 => None,
5941 // A layered picture is composed already, per clip: nothing here
5942 // places it again.
5943 Frame::Pixels(y, u, v, width, height) if layered_here => {
5944 Some((y, u, v, width, height))
5945 }
5946 Frame::Pixels(y, u, v, width, height) => Some(place_picture(
5947 y,
5948 u,
5949 v,
5950 width,
5951 height,
5952 rotation,
5953 pixel_aspect,
5954 grade,
5955 transform,
5956 remap,
5957 mapper,
5958 &mut rotated,
5959 &mut stretched,
5960 &mut graded,
5961 &mut transformed,
5962 &mut canvas,
5963 )),
5964 };
5965 // A lone clip's effects, drawn on its placed picture and laid over black.
5966 let (placed16, placed) = match fx_clip {
5967 None => (placed16, placed),
5968 Some(clip) => {
5969 let secs = f64::from(span.start + done_here) / meta.frame_rate;
5970 let src = crate::project::key_sample_pos(clip, span.start + done_here);
5971 let placed16 = placed16.map(|(y, u, v, w, h)| {
5972 fx16 = (y.to_vec(), u.to_vec(), v.to_vec());
5973 effected(&clip.effects, &mut fx16, w, h, secs, src, out_color.matrix, &mut fx_scratch16);
5974 (&fx16.0[..], &fx16.1[..], &fx16.2[..], w, h)
5975 });
5976 let placed = placed.map(|(y, u, v, w, h)| {
5977 fx8 = (y.to_vec(), u.to_vec(), v.to_vec());
5978 effected(&clip.effects, &mut fx8, w, h, secs, src, out_color.matrix, &mut fx_scratch8);
5979 (&fx8.0[..], &fx8.1[..], &fx8.2[..], w, h)
5980 });
5981 (placed16, placed)
5982 }
5983 };
5984 // Once per timeline frame this source frame covers: one at real time
5985 // and faster, more when the clip is slowed -- the picture is already
5986 // graded and placed, so a held frame costs an encode and no decode.
5987 for r in 0..repeats {
5988 // Inside the window every *output* frame gets its own B
5989 // picture -- decoded fresh here rather than once for the
5990 // whole held A frame -- which is what makes a slowed A's
5991 // tail still ramp one weight per frame shown rather than one
5992 // per source frame.
5993 let in_window = b.as_ref().is_some_and(|d| done_here + r >= d.tail_start);
5994 let coded = match (&mut b, in_window) {
5995 (Some(d), true) if placed16.is_some() => {
5996 let (ay, au, av, aw, ah) = placed16.expect("checked by the guard");
5997 let t = dissolve_weight(done_here + r - d.tail_start, d.window);
5998 let blended: Option<Planes16> = match d.decoder.next()? {
5999 // B's file ran out inside the window: A's own picture carries the frame.
6000 None => None,
6001 Some(b) => {
6002 // B at 10 bits: a 10-bit picture as it is, an 8-bit one widened.
6003 let (by, bu, bv, bw, bh): (&[u16], &[u16], &[u16], u32, u32) = match b {
6004 Frame::Wide(y, u, v, w, h) => (y, u, v, w, h),
6005 Frame::Pixels(y, u, v, w, h) => {
6006 widen_into(y, &mut widened_b.0);
6007 widen_into(u, &mut widened_b.1);
6008 widen_into(v, &mut widened_b.2);
6009 (&widened_b.0[..], &widened_b.1[..], &widened_b.2[..], w, h)
6010 }
6011 Frame::Dma(_) => unreachable!("b's decoder is never a DMA buffer"),
6012 };
6013 let (y, u, v, _, _) = place_picture16(
6014 by,
6015 bu,
6016 bv,
6017 bw,
6018 bh,
6019 d.rotation,
6020 d.pixel_aspect,
6021 d.grade,
6022 d.transform,
6023 d.remap,
6024 d.mapper,
6025 &mut d.scratch16,
6026 &mut d.canvas,
6027 );
6028 Some(crate::transitions::blend_planes(
6029 d.kind,
6030 (ay, au, av),
6031 (y, u, v),
6032 t,
6033 aw as usize,
6034 ah as usize,
6035 ))
6036 }
6037 };
6038 let frame_at = span.start + done_here + r;
6039 let (y, u, v) = match &blended {
6040 Some(p) => borrow_planes(p),
6041 None => (ay, au, av),
6042 };
6043 let faded = picture_fade_at(project, frame_at).map(|k| fade_planes((y, u, v), k));
6044 let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes);
6045 let painted = burned16(&mut burn, frame_at, aw, ah, (y, u, v));
6046 let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes);
6047 encoder.encode_wide(y, u, v, aw, ah)?
6048 }
6049 (Some(d), true) => {
6050 let (ay, au, av, aw, ah) =
6051 placed.expect("a dissolving span always decodes to pixels");
6052 match d.decoder.next()?.map(|f| narrowed(f, &mut narrow_b)) {
6053 // B's file ran out inside the window: A's own
6054 // picture carries the frame rather than the
6055 // export losing it.
6056 None => {
6057 let frame_at = span.start + done_here + r;
6058 let faded = picture_fade_at(project, frame_at)
6059 .map(|k| fade_planes((ay, au, av), k));
6060 let (ay, au, av) =
6061 faded.as_ref().map_or((ay, au, av), borrow_planes);
6062 let painted = burned(&mut burn, frame_at, aw, ah, (ay, au, av));
6063 let (ay, au, av) = painted.as_ref().map_or((ay, au, av), borrow_planes);
6064 encoder.encode(ay, au, av, aw, ah, settings.intra_only)?
6065 }
6066 Some(Frame::Dma(_) | Frame::Wide(..)) => {
6067 unreachable!("b's decoder was opened with no DMA want and is narrowed")
6068 }
6069 Some(Frame::Pixels(by, bu, bv, bw, bh)) => {
6070 let (by, bu, bv, _, _) = place_picture(
6071 by,
6072 bu,
6073 bv,
6074 bw,
6075 bh,
6076 d.rotation,
6077 d.pixel_aspect,
6078 d.grade,
6079 d.transform,
6080 d.remap,
6081 d.mapper,
6082 &mut d.rotated,
6083 &mut d.stretched,
6084 &mut d.graded,
6085 &mut d.transformed,
6086 &mut d.canvas,
6087 );
6088 let idx_in_window = done_here + r - d.tail_start;
6089 let t = dissolve_weight(idx_in_window, d.window);
6090 let (y, u, v) = crate::transitions::blend_planes(
6091 d.kind,
6092 (ay, au, av),
6093 (by, bu, bv),
6094 t,
6095 aw as usize,
6096 ah as usize,
6097 );
6098 let frame_at = span.start + done_here + r;
6099 let faded = picture_fade_at(project, frame_at)
6100 .map(|k| fade_planes((&y[..], &u[..], &v[..]), k));
6101 let (y, u, v) =
6102 faded.as_ref().map_or((&y[..], &u[..], &v[..]), borrow_planes);
6103 let painted =
6104 burned(&mut burn, frame_at, aw, ah, (y, u, v));
6105 let (y, u, v) =
6106 painted.as_ref().map_or((y, u, v), borrow_planes);
6107 encoder.encode(y, u, v, aw, ah, settings.intra_only)?
6108 }
6109 }
6110 }
6111 _ => match (&frame, placed16) {
6112 (_, Some((y, u, v, width, height))) => {
6113 let frame_at = span.start + done_here + r;
6114 // A layered picture's fades were applied per clip in its stack.
6115 let faded = picture_fade_at(project, frame_at)
6116 .filter(|_| !layered_here)
6117 .map(|k| fade_planes((y, u, v), k));
6118 let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes);
6119 let painted = burned16(&mut burn, frame_at, width, height, (y, u, v));
6120 let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes);
6121 encoder.encode_wide(y, u, v, width, height)?
6122 }
6123 (Frame::Dma(dma), None) => encoder.encode_dma(dma, settings.intra_only)?,
6124 (Frame::Wide(y, u, v, width, height), None) => {
6125 encoder.encode_wide(y, u, v, *width, *height)?
6126 }
6127 (Frame::Pixels(..), None) => {
6128 let (y, u, v, width, height) =
6129 placed.expect("a picture with pixels was placed");
6130 let frame_at = span.start + done_here + r;
6131 // A layered picture's fades were applied per clip in
6132 // its stack; the top clip's does not fade the frame.
6133 let faded = picture_fade_at(project, frame_at)
6134 .filter(|_| !layered_here)
6135 .map(|k| fade_planes((y, u, v), k));
6136 let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes);
6137 let painted = burned(&mut burn, frame_at, width, height, (y, u, v));
6138 let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes);
6139 encoder.encode(y, u, v, width, height, settings.intra_only)?
6140 }
6141 },
6142 };
6143 if let Some((au, key)) = coded {
6144 write_video(
6145 &mut muxer,
6146 out,
6147 meta,
6148 settings,
6149 container_colour,
6150 source_language.as_deref(),
6151 audio_params.as_ref(),
6152 &mut packets,
6153 &mut subs,
6154 au,
6155 key,
6156 ten_bit,
6157 )?;
6158 // Retried here rather than only where the mix lands: the
6159 // very first coded picture is what creates `muxer`, and a
6160 // mix that lands before it (a short film, or a slow first
6161 // frame) has nothing to hand it to until now.
6162 feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
6163 inject_export_test_panic(out);
6164 }
6165 done += 1;
6166 // Forwards only: an audio pass still running beside this one
6167 // publishes its own share of [`AUDIO_BAND`], and a bar that
6168 // went backwards every time it did would be worse than one
6169 // that stood still.
6170 shared
6171 .progress
6172 .fetch_max(picture_progress(done, total), Ordering::Relaxed);
6173 }
6174 done_here += repeats;
6175 }
6176 }
6177 // The whole walk is over, so what it could not write is known to the frame
6178 // and is published once. `fetch_max` and not `fetch_add`, because a
6179 // hardware seat that died has the *whole* walk run again from its first
6180 // frame ([`start`]): the same project and the same picture counts, so a
6181 // second run must not double a number that is already on the line.
6182 shared.truncated.fetch_max(skipped, Ordering::Relaxed);
6183 while let Some((au, key)) = encoder.drain()? {
6184 write_video(
6185 &mut muxer,
6186 out,
6187 meta,
6188 settings,
6189 container_colour,
6190 source_language.as_deref(),
6191 audio_params.as_ref(),
6192 &mut packets,
6193 &mut subs,
6194 au,
6195 key,
6196 ten_bit,
6197 )?;
6198 }
6199 // Progress reads 100% from here on, but nothing is published yet: draining,
6200 // the audio pass and `finish` are all still cancellable.
6201 cancelled(shared)?;
6202
6203 let Some(muxer) = muxer else {
6204 return Err("export produced no coded pictures".into());
6205 };
6206 // The mp4's audio and subtitle tracks after its picture -- the Matroska one
6207 // interleaved its own as it went and left `packets` and `subs` empty behind
6208 // it. The text last, so its samples are written knowing how long the picture
6209 // turned out to be.
6210 let muxer = match muxer {
6211 Muxer::Mp4(mut mp4) => {
6212 // The sound, collected where this file first needs it: it has been
6213 // mixing and encoding under the whole picture, and an mp4 declares
6214 // its audio track here rather than at the open precisely so that
6215 // could happen ([`Mp4Muxer::add_audio_track`]).
6216 let track = match audio_job.take() {
6217 Some(job) => {
6218 let track = join_audio(job)?;
6219 // The picture finished first and this waited for the
6220 // sound: the pair of stage lines is what says which of the
6221 // two an export is really bounded by.
6222 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!(
6223 "export audio: waited for after {:.1} s of picture",
6224 picture_started.elapsed().as_secs_f64()
6225 ); }
6226 // ...and the line on screen finished with it. The loop above
6227 // publishes the measured codec the moment the pass lands
6228 // under the picture, but a picture that outran the mix never
6229 // reaches that branch -- and "working out the sound…" would
6230 // then be the last thing the card ever said about a track it
6231 // had long since written.
6232 publish_seats(
6233 shared,
6234 seat,
6235 project,
6236 settings,
6237 track.as_ref().map(|track| track.copied),
6238 track
6239 .as_ref()
6240 .is_some_and(|track| track.opus_pre_skip.is_some()),
6241 false,
6242 );
6243 track
6244 }
6245 // `late` was already handed to `mp4` inside the picture loop
6246 // ([`feed_late_audio`]) unless the mix never landed there, in
6247 // which case it is still `None` and there was nothing to feed.
6248 None if audio_fed => None,
6249 None => late,
6250 };
6251 if let Some(track) = &track {
6252 mp4.add_audio_track(&params_of(track))?;
6253 }
6254 for packet in track.into_iter().flat_map(|track| track.packets) {
6255 mp4.write_audio_packet(&packet.bytes)?;
6256 }
6257 mp4.set_faststart(settings.faststart);
6258 mp4.set_chapters(&settings.chapters)?;
6259 mp4.write_subtitles(&subs)?;
6260 Muxer::Mp4(mp4)
6261 }
6262 Muxer::Mov(mut mov) => {
6263 // The sound, PCM at the asked width, laid to the picture's length.
6264 if let Some(job) = pcm_job.take()
6265 && let Some((mut samples, rate, channels)) = join_pcm(job)?
6266 {
6267 let want = (f64::from(done) / meta.frame_rate * f64::from(rate)).round() as usize
6268 * usize::from(channels.max(1));
6269 samples.resize(want, 0);
6270 mov.write_sound(&samples, rate, channels, prores_audio_bits(settings))?;
6271 }
6272 Muxer::Mov(mov)
6273 }
6274 muxer => muxer,
6275 };
6276 cancelled(shared)?;
6277 muxer.finish()?;
6278 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
6279 Ok(())
6280}
6281
6282/// The cues a burn of track `pick` draws, on this timeline's clock: what the
6283/// screen shows. Once a track is placed on a subtitle lane, its placements are
6284/// the answer -- a cut sentence is gone, a trimmed or moved one sits where it
6285/// was put, and a hidden lane draws nothing -- with each cue's words read from
6286/// its palette track, so a retyped cue burns retyped. A track no lane places is
6287/// drawn as the export writes it whole ([`timeline_cues`]), whatever else is
6288/// placed, so a burn and a soft track of the same pick never disagree.
6289///
6290/// `Err` for a pick that is not a track of the project.
6291pub fn burn_cues(project: &Project, pick: usize, fps: f64) -> crate::Result<Vec<Cue>> {
6292 let track = project
6293 .subtitles()
6294 .get(pick)
6295 .ok_or_else(|| format!("burn_subtitles: no subtitle track {pick} in this project"))?;
6296 if !placed_tracks(project).contains(&pick) {
6297 return Ok(timeline_cues(project, track, fps));
6298 }
6299 let mut cues: Vec<Cue> = project
6300 .subtitle_lanes()
6301 .into_iter()
6302 .flat_map(|lane| project.sub_lane_cue_spans(lane, fps))
6303 .filter(|s| s.track == pick)
6304 .filter_map(|s| {
6305 let c = track.cues.get(s.cue)?;
6306 Some(Cue {
6307 start_us: s.start_us,
6308 end_us: s.end_us,
6309 text: c.text.clone(),
6310 image: c.image.clone(),
6311 words: crate::subtitle::map_words(&c.words, s.window, (s.start_us, s.end_us)),
6312 karaoke: crate::subtitle::map_karaoke(&c.karaoke, s.window, (s.start_us, s.end_us)),
6313 })
6314 })
6315 .collect();
6316 cues.sort_by_key(|c| c.start_us);
6317 Ok(cues)
6318}
6319
6320/// The index of the cue on screen at timeline frame `frame`, if one is: a cue
6321/// is shown from the instant of its start up to, not including, its end, read
6322/// off the frame's own start time the way [`timeline_cues`] times the frames.
6323/// Cues with no text (a picture track's, or a blank line) show nothing.
6324pub fn cue_on_screen(cues: &[Cue], frame: u32, fps: f64) -> Option<usize> {
6325 let t = (f64::from(frame) / fps * 1e6).round() as i64;
6326 cues.iter().position(|c| {
6327 c.image.is_none() && c.start_us <= t && t < c.end_us && !c.text.trim().is_empty()
6328 })
6329}
6330
6331/// The indices of every cue on screen at timeline frame `frame`, in the order
6332/// `cues` lists them (start order from [`burn_cues`]). The same test as
6333/// [`cue_on_screen`], for a burn that draws all the cues up at once.
6334pub fn cues_on_screen(cues: &[Cue], frame: u32, fps: f64) -> Vec<usize> {
6335 let t = (f64::from(frame) / fps * 1e6).round() as i64;
6336 cues.iter()
6337 .enumerate()
6338 .filter(|(_, c)| {
6339 c.image.is_none() && c.start_us <= t && t < c.end_us && !c.text.trim().is_empty()
6340 })
6341 .map(|(i, _)| i)
6342 .collect()
6343}
6344
6345/// Three planes of one picture, owned: what a burned-in frame is encoded from.
6346type Planes<T = u8> = (Vec<T>, Vec<T>, Vec<T>);
6347
6348/// A picture at 10 bits a sample ([`Enc::encode_wide`]).
6349type Planes16 = Planes<u16>;
6350
6351fn borrow_planes<T>(p: &Planes<T>) -> (&[T], &[T], &[T]) {
6352 (&p.0, &p.1, &p.2)
6353}
6354
6355/// What one export draws into its pictures: the titles, then the captions
6356/// ([`ExportSettings::burn_subtitles`]). The overlay of the cue last drawn is
6357/// kept, so a caption on screen for a second is laid out once rather than once
6358/// a frame, and each title's overlay is kept the same way.
6359struct Burn {
6360 cues: Vec<Cue>,
6361 style: TextStyle,
6362 fps: f64,
6363 full_range: bool,
6364 /// The cues drawn last, by index, with the size, the animation state
6365 /// ([`crate::captionanim::blocks_key`]) and the stacked overlay.
6366 last: Option<(Vec<usize>, u32, u32, u64, Overlay)>,
6367 titles: Vec<Title>,
6368 /// One per title, the overlay it was last drawn as, with what made it ([`TitleKey`]).
6369 title_last: Vec<Option<(TitleKey, Overlay)>>,
6370}
6371
6372/// What a title's overlay is made from: a frame's size, how much of its text shows and its
6373/// motion. A title that does not move keeps the same key, so it is laid out once.
6374#[derive(Clone, Debug, PartialEq)]
6375struct TitleKey {
6376 width: u32,
6377 height: u32,
6378 size: u32,
6379 dx: i32,
6380 dy: i32,
6381 /// The letters drawn, or `None` for all of them.
6382 shown: Option<usize>,
6383}
6384
6385/// What a title draws at one frame, as a key: its size, where it is moved and how much of its
6386/// text shows, for a `width` x `height` picture. Preview and export both draw a title from this
6387/// same motion ([`Title::motion_at`]), so the animation reads the same in both.
6388fn title_key(title: &Title, motion: &Motion, width: u32, height: u32) -> TitleKey {
6389 let size = ((title.style.size as f32 * motion.scale).round() as u32)
6390 .clamp(crate::text::SIZE_RANGE.0, crate::text::SIZE_RANGE.1);
6391 TitleKey {
6392 width,
6393 height,
6394 size,
6395 dx: (motion.dx * width as f32).round() as i32,
6396 dy: (motion.dy * height as f32).round() as i32,
6397 shown: motion.revealed(&title.text).map(|s| s.ink),
6398 }
6399}
6400
6401/// The overlay a title's key stands for: the whole text laid out in the key's size and moved,
6402/// with the letters past its reveal left out of the drawing but not out of the layout.
6403fn title_overlay(title: &Title, key: &TitleKey) -> Overlay {
6404 let style = TextStyle { size: key.size, ..title.style.clone() };
6405 let lines: Vec<String> = title.text.split('\n').map(str::to_string).collect();
6406 let mut ov = match key.shown {
6407 None => overlay(&style, key.width, key.height, &lines),
6408 Some(ink) => crate::text::overlay_revealed(&style, key.width, key.height, &lines, ink),
6409 };
6410 if (key.dx, key.dy) != (0, 0) {
6411 ov = ov.moved(key.dx, key.dy);
6412 }
6413 ov
6414}
6415
6416impl Burn {
6417 /// What the settings and the timeline ask drawn in, or `None` for a picture
6418 /// left alone. A pick that is not a track of the project is named, not ignored.
6419 fn new(
6420 project: &Project,
6421 settings: &ExportSettings,
6422 fps: f64,
6423 full_range: bool,
6424 ) -> crate::Result<Option<Self>> {
6425 let titles = project.titles().to_vec();
6426 let (cues, style) = match &settings.burn_subtitles {
6427 Some((pick, style)) => {
6428 (burn_cues(project, *pick, fps)?, style.clamped())
6429 }
6430 None => (Vec::new(), TextStyle::default()),
6431 };
6432 if cues.is_empty() && titles.is_empty() && settings.burn_subtitles.is_none() {
6433 return Ok(None);
6434 }
6435 Ok(Some(Self {
6436 cues,
6437 style,
6438 fps,
6439 full_range,
6440 last: None,
6441 title_last: vec![None; titles.len()],
6442 titles,
6443 }))
6444 }
6445
6446 /// The picture at timeline frame `frame` with the titles on screen and the
6447 /// caption drawn in, or `None` where nothing is on screen and the planes go
6448 /// on untouched.
6449 fn paint(
6450 &mut self,
6451 frame: u32,
6452 width: u32,
6453 height: u32,
6454 planes: (&[u8], &[u8], &[u8]),
6455 ) -> Option<Planes> {
6456 let mut out: Option<Planes> = None;
6457 for (i, t) in self.titles.iter().enumerate() {
6458 let Some(motion) = t.motion_at(frame) else {
6459 continue;
6460 };
6461 let alpha = motion.alpha;
6462 if alpha == 0 {
6463 continue;
6464 }
6465 let key = title_key(t, &motion, width, height);
6466 if !matches!(&self.title_last[i], Some((k, _)) if *k == key) {
6467 let ov = title_overlay(t, &key);
6468 self.title_last[i] = Some((key, ov));
6469 }
6470 let Some((_, ov)) = &self.title_last[i] else {
6471 continue;
6472 };
6473 let mut planes = out
6474 .take()
6475 .unwrap_or_else(|| (planes.0.to_vec(), planes.1.to_vec(), planes.2.to_vec()));
6476 if alpha == 255 {
6477 ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range);
6478 } else {
6479 ov.faded(alpha).blend_i420(
6480 &mut planes.0,
6481 &mut planes.1,
6482 &mut planes.2,
6483 self.full_range,
6484 );
6485 }
6486 out = Some(planes);
6487 }
6488 let on = cues_on_screen(&self.cues, frame, self.fps);
6489 if !on.is_empty() {
6490 // A static style is keyed by the cues alone, so a cache hit builds nothing.
6491 // A karaoke cue moves with the clock whatever the style, so it is planned too.
6492 let lit = on.iter().any(|&i| self.cues[i].real_karaoke().is_some());
6493 let planned = (!self.style.caption.is_plain() || lit)
6494 .then(|| crate::captionanim::plan(&self.style, &self.cues, &on, frame, self.fps));
6495 let key = planned.as_deref().map_or(0, crate::captionanim::blocks_key);
6496 let hit = matches!(&self.last, Some((i, w, h, k, _))
6497 if i == &on && (*w, *h) == (width, height) && *k == key);
6498 if !hit {
6499 let blocks = planned.unwrap_or_else(|| {
6500 crate::captionanim::plan(&self.style, &self.cues, &on, frame, self.fps)
6501 });
6502 let ov = overlay_blocks(&self.style, width, height, &blocks);
6503 self.last = Some((on, width, height, key, ov));
6504 }
6505 if let Some((_, _, _, _, ov)) = self.last.as_ref() {
6506 let mut planes = out
6507 .take()
6508 .unwrap_or_else(|| (planes.0.to_vec(), planes.1.to_vec(), planes.2.to_vec()));
6509 ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range);
6510 out = Some(planes);
6511 }
6512 }
6513 out
6514 }
6515}
6516
6517/// [`Burn::paint`] through an optional burn: the picture as it is when there is
6518/// no burn, and as it is with the caption drawn in when there is one.
6519fn burned(
6520 burn: &mut Option<Burn>,
6521 frame: u32,
6522 width: u32,
6523 height: u32,
6524 planes: (&[u8], &[u8], &[u8]),
6525) -> Option<Planes> {
6526 burn.as_mut()?.paint(frame, width, height, planes)
6527}
6528
6529/// A lone clip's effects stack drawn on its placed `w` x `h` picture in place, and
6530/// the result laid over black where the stack keys, masks or blends it -- what the
6531/// layered path draws for the same clip with nothing beneath ([`LayerStack::picture`]).
6532#[allow(clippy::too_many_arguments)]
6533fn effected<T: Sample>(
6534 effects: &[crate::effects::Effect],
6535 planes: &mut Planes<T>,
6536 w: u32,
6537 h: u32,
6538 secs: f64,
6539 src: f64,
6540 matrix: Matrix,
6541 scratch: &mut crate::effects::Scratch<T>,
6542) {
6543 let (w, h) = (w as usize, h as usize);
6544 let out = crate::effects::apply(effects, (&mut planes.0, &mut planes.1, &mut planes.2), w, h, secs, src, matrix, scratch);
6545 crate::effects::over_black((&mut planes.0, &mut planes.1, &mut planes.2), &out, matrix, w, h);
6546}
6547
6548/// One 8-bit code at 10 bits, as the encoder upshifts it (`v << 2 | v >> 6`), so a
6549/// widened black is the black of the 10-bit span.
6550fn widen_code(v: u8) -> u16 {
6551 (u16::from(v) << 2) | (u16::from(v) >> 6)
6552}
6553
6554/// [`widen_code`] over a plane, into `out`.
6555fn widen_into(src: &[u8], out: &mut Vec<u16>) {
6556 out.clear();
6557 out.extend(src.iter().map(|&v| widen_code(v)));
6558}
6559
6560/// [`burned`] at 10 bits. A caption or a title is an 8-bit overlay, so the picture is
6561/// narrowed for it; where the overlay changed a code, that code is written back
6562/// widened, and every other code keeps its 10-bit value.
6563fn burned16(
6564 burn: &mut Option<Burn>,
6565 frame: u32,
6566 width: u32,
6567 height: u32,
6568 planes: (&[u16], &[u16], &[u16]),
6569) -> Option<Planes16> {
6570 let burn = burn.as_mut()?;
6571 let narrow = |s: &[u16]| -> Vec<u8> { s.iter().map(|&c| (c >> 2) as u8).collect() };
6572 let (ny, nu, nv) = (narrow(planes.0), narrow(planes.1), narrow(planes.2));
6573 let painted = burn.paint(frame, width, height, (&ny[..], &nu[..], &nv[..]))?;
6574 let merge = |orig: &[u16], before: &[u8], after: &[u8]| -> Vec<u16> {
6575 orig.iter()
6576 .zip(before.iter().zip(after))
6577 .map(|(&o, (&b, &a))| if a == b { o } else { widen_code(a) })
6578 .collect()
6579 };
6580 Some((
6581 merge(planes.0, &ny, &painted.0[..]),
6582 merge(planes.1, &nu, &painted.1[..]),
6583 merge(planes.2, &nv, &painted.2[..]),
6584 ))
6585}
6586
6587/// The 10-bit placement's scratch: the turn, the pixel-aspect stretch, the grade and the
6588/// transform each want a buffer the planes come back borrowed from.
6589#[derive(Default)]
6590struct Scratch16 {
6591 turned: Planes16,
6592 stretched: Planes16,
6593 graded: Planes16,
6594 transformed: Planes16,
6595}
6596
6597/// [`place_picture`] at 10 bits: the pixel aspect, the display turn, the tone map, the grade,
6598/// the matrix and range remap and the transform, all on 10-bit samples, in the 8-bit order.
6599#[expect(clippy::too_many_arguments, reason = "one span's whole 10-bit picture path")]
6600fn place_picture16<'a>(
6601 y: &'a [u16],
6602 u: &'a [u16],
6603 v: &'a [u16],
6604 width: u32,
6605 height: u32,
6606 rotation: Rotation,
6607 pixel_aspect: crate::demux::PixelAspect,
6608 grade: Option<crate::color::ColorParams>,
6609 transform: TransformParams,
6610 remap: Option<Remap>,
6611 mapper: Option<&ToneMapper>,
6612 scratch: &'a mut Scratch16,
6613 canvas: &'a mut Composer,
6614) -> (&'a [u16], &'a [u16], &'a [u16], u32, u32) {
6615 let Scratch16 { turned, stretched, graded, transformed } = scratch;
6616 let (y, u, v, width, height) = if pixel_aspect.is_square() {
6617 (y, u, v, width, height)
6618 } else {
6619 let display_width = pixel_aspect.width_factor(width);
6620 let (dcw, dch) = (display_width.div_ceil(2) as usize, height.div_ceil(2) as usize);
6621 stretched.0.resize(display_width as usize * height as usize, 0);
6622 stretched.1.resize(dcw * dch, 0);
6623 stretched.2.resize(dcw * dch, 0);
6624 crate::scale::scale_i420(
6625 y,
6626 u,
6627 v,
6628 width as usize,
6629 height as usize,
6630 &mut stretched.0,
6631 &mut stretched.1,
6632 &mut stretched.2,
6633 display_width as usize,
6634 height as usize,
6635 );
6636 (&stretched.0[..], &stretched.1[..], &stretched.2[..], display_width, height)
6637 };
6638 let (y, u, v, width, height) = match rotation.is_none() {
6639 true => (y, u, v, width, height),
6640 false => {
6641 let (w, h) = crate::scale::rotate_i420_90s_into(y, u, v, width, height, rotation.steps(), turned);
6642 (&turned.0[..], &turned.1[..], &turned.2[..], w, h)
6643 }
6644 };
6645 let params = grade.filter(|p| !p.is_identity());
6646 let (y, u, v) = match (params, remap, mapper) {
6647 (None, None, None) => (y, u, v),
6648 (params, remap, mapper) => {
6649 let (gy, gu, gv) = graded;
6650 gy.clear();
6651 gy.extend_from_slice(y);
6652 gu.clear();
6653 gu.extend_from_slice(u);
6654 gv.clear();
6655 gv.extend_from_slice(v);
6656 if let Some(mapper) = mapper {
6657 mapper.map16(gy, gu, gv, width as usize, height as usize);
6658 }
6659 if let Some(params) = params {
6660 crate::color::apply_yuv_wide(&params, gy, gu, gv, width as usize, remap.is_some_and(|r| r.limit));
6661 }
6662 if let Some(remap) = remap {
6663 if remap.limit {
6664 crate::colorspace::limit_range::<u16>(gy, gu, gv);
6665 }
6666 crate::colorspace::remap::<u16>(remap.from, remap.to, gy, gu, gv, width as usize);
6667 }
6668 (&gy[..], &gu[..], &gv[..])
6669 }
6670 };
6671 if transform.is_identity() {
6672 canvas.place_wide(y, u, v, width, height)
6673 } else {
6674 let (py, pu, pv, w, h) = canvas.place_transformed_wide(y, u, v, width, height, &transform);
6675 *transformed = (py, pu, pv);
6676 (&transformed.0[..], &transformed.1[..], &transformed.2[..], w, h)
6677 }
6678}
6679
6680/// One decoded picture turned, graded, tone-mapped, remapped and placed on the
6681/// canvas -- everything between a source's own samples and the ones an encoder
6682/// is fed, which is exactly the work a zero-copy span has none of.
6683///
6684/// `rotation` first, before the grade: it is the file's own display matrix, the
6685/// turn a player would make before showing the picture at all, and everything
6686/// after this -- the grade, the letterbox, the encoder -- is about the picture
6687/// as it is *meant* to be seen. `turned`, `graded` and `canvas` are the span's
6688/// scratch: the planes come back borrowed from one of them, or from the picture
6689/// itself where not a byte was touched.
6690#[expect(clippy::too_many_arguments, reason = "one span's whole picture path")]
6691fn place_picture<'a>(
6692 y: &'a [u8],
6693 u: &'a [u8],
6694 v: &'a [u8],
6695 width: u32,
6696 height: u32,
6697 rotation: Rotation,
6698 pixel_aspect: crate::demux::PixelAspect,
6699 grade: Option<crate::color::ColorParams>,
6700 transform: TransformParams,
6701 remap: Option<Remap>,
6702 mapper: Option<&ToneMapper>,
6703 turned: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
6704 stretched: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
6705 graded: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
6706 transformed: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
6707 canvas: &'a mut Composer,
6708) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) {
6709 // The pixel aspect, applied exactly once -- the same single conversion to
6710 // the square-pixel raster the decode funnel makes, in the same order
6711 // (stretch the coded width, *then* turn, [`crate::decode::Render::frame`]'s
6712 // comment carries the 1440x1440 failure the other order produces). A
6713 // square-pixel file -- every file whose samples are one to one -- borrows
6714 // the planes through.
6715 let (y, u, v, width, height) = if pixel_aspect.is_square() {
6716 (y, u, v, width, height)
6717 } else {
6718 let display_width = pixel_aspect.width_factor(width);
6719 let (dcw, dch) = (
6720 display_width.div_ceil(2) as usize,
6721 height.div_ceil(2) as usize,
6722 );
6723 stretched
6724 .0
6725 .resize(display_width as usize * height as usize, 0);
6726 stretched.1.resize(dcw * dch, 0);
6727 stretched.2.resize(dcw * dch, 0);
6728 crate::scale::scale_i420(
6729 y,
6730 u,
6731 v,
6732 width as usize,
6733 height as usize,
6734 &mut stretched.0,
6735 &mut stretched.1,
6736 &mut stretched.2,
6737 display_width as usize,
6738 height as usize,
6739 );
6740 (
6741 &stretched.0[..],
6742 &stretched.1[..],
6743 &stretched.2[..],
6744 display_width,
6745 height,
6746 )
6747 };
6748 // The file's own turn, taken exactly as playback's decode funnel takes it
6749 // ([`crate::decode`]): a phone's portrait video is landscape in the file,
6750 // and the encoder must be fed what the preview showed. A file that states
6751 // no turn skips this entirely -- the planes go on borrowed.
6752 let (y, u, v, width, height) = match rotation.is_none() {
6753 true => (y, u, v, width, height),
6754 false => {
6755 let (w, h) = crate::scale::rotate_i420_90s_into(
6756 y,
6757 u,
6758 v,
6759 width,
6760 height,
6761 rotation.steps(),
6762 turned,
6763 );
6764 (&turned.0[..], &turned.1[..], &turned.2[..], w, h)
6765 }
6766 };
6767 // The planes are borrowed from the decoder (and `Black::picture` hands the
6768 // same slice as both u and v), so a grade cannot be applied in place: it
6769 // goes onto a copy, which the encoder then reads instead.
6770 let params = grade.filter(|p| !p.is_identity());
6771 let (y, u, v) = match (params, remap, mapper) {
6772 (None, None, None) => (y, u, v),
6773 (params, remap, mapper) => {
6774 let (gy, gu, gv) = graded;
6775 gy.clear();
6776 gy.extend_from_slice(y);
6777 gu.clear();
6778 gu.extend_from_slice(u);
6779 gv.clear();
6780 gv.extend_from_slice(v);
6781 // Tone-map first, so the grade is applied to the SDR picture the
6782 // canvas showed and not to HDR codes; then remap the graded result.
6783 // The order playback renders in, and the only order in which
6784 // preview and export agree.
6785 if let Some(mapper) = mapper {
6786 mapper.map(gy, gu, gv, width as usize, height as usize);
6787 }
6788 if let Some(params) = params {
6789 crate::color::apply_yuv(&params, gy, gu, gv, width as usize, remap.is_some_and(|r| r.limit));
6790 }
6791 if let Some(remap) = remap {
6792 // Range before matrix: the matrix arithmetic is written for limited
6793 // codes, so a full-range picture is brought into that span first.
6794 if remap.limit {
6795 crate::colorspace::limit_range(gy, gu, gv);
6796 }
6797 crate::colorspace::remap(remap.from, remap.to, gy, gu, gv, width as usize);
6798 }
6799 (&gy[..], &gu[..], &gv[..])
6800 }
6801 };
6802 // Grade first, place second: the grade is the clip's own pixels and the
6803 // bars around them are not the clip (see `scale::Composer`).
6804 if transform.is_identity() {
6805 canvas.place(y, u, v, width, height)
6806 } else {
6807 let (py, pu, pv, w, h) = canvas.place_transformed(y, u, v, width, height, &transform);
6808 *transformed = (py, pu, pv);
6809 (
6810 &transformed.0[..],
6811 &transformed.1[..],
6812 &transformed.2[..],
6813 w,
6814 h,
6815 )
6816 }
6817}
6818
6819/// How a span's samples are rewritten on the way into a file whose own matrix is
6820/// `to` and whose range is limited ([`ColorDescription::output`]): the matrix they
6821/// are coded against, and whether they span the full byte and so need scaling
6822/// into the limited span first ([`crate::colorspace::limit_range`]).
6823#[derive(Debug, Clone, Copy, PartialEq, Eq)]
6824struct Remap {
6825 from: Matrix,
6826 to: Matrix,
6827 limit: bool,
6828}
6829
6830/// What [`place_picture`] rewrites a span's samples by -- `None` when they are
6831/// already coded against the output's matrix and span its range, and for a gap,
6832/// whose 16/128/128 black is black in every matrix here.
6833///
6834/// `toned` says the tone map ran on this span: it hands back BT.709 SDR whatever
6835/// the source was coded as, so an HDR clip is never *also* given the matrix
6836/// treatment its BT.2020 tag would ask for -- one conversion or the other, never
6837/// both on one frame -- while a tone-mapped clip on a canvas below 720 lines
6838/// still takes its 709 -> 601 step. It is also limited range already, so only an
6839/// untouched full-range source is scaled here.
6840fn remap_into(color: Option<ColorDescription>, toned: bool, out: Matrix) -> Option<Remap> {
6841 let from = match toned {
6842 true => Matrix::Bt709,
6843 false => color?.matrix,
6844 };
6845 let limit = !toned && color?.full_range;
6846 (from != out || limit).then_some(Remap {
6847 from,
6848 to: out,
6849 limit,
6850 })
6851}
6852
6853/// The picture at timeline `frame`, composed the way [`run`] composes it: the
6854/// same span and source frame, placed by [`place_picture`] (turn, pixel aspect,
6855/// grade, transform, tone map, fit), dissolved into its successor over the
6856/// tail window, and written as the BGRA picture the encoder would have been
6857/// given. A gap is black. Visualizer and still clips take the same decoders
6858/// export does.
6859///
6860/// The output is the project's resolution scaled to fit a `width` x `height`
6861/// box at the project's aspect (so a 16:9 project asked for 640x480 comes back
6862/// 640x360). Each call opens its own decoder for the one source frame it needs,
6863/// so it costs a decoder start; it is for the frame an agent asks for, not a
6864/// sequence.
6865pub fn compose_at(
6866 project: &Project,
6867 meta: &VideoMeta,
6868 frame: u32,
6869 width: u32,
6870 height: u32,
6871) -> crate::Result<crate::decode::Frame> {
6872 compose_at_with(project, meta, frame, width, height, None)
6873}
6874
6875/// [`compose_at`] with every clip's grade taken off (its colour, its keys and
6876/// its LUT): the picture as shot, which is the preview's "before" side and the
6877/// frame Auto reads. A copy of the timeline is graded-off, so `project` is left
6878/// as it is; nothing here is exported. Sequences a compound clip plays keep
6879/// their own grades.
6880pub fn compose_ungraded_at(project: &Project, meta: &VideoMeta, frame: u32, width: u32, height: u32) -> crate::Result<crate::decode::Frame> {
6881 let mut plain = project.clone();
6882 for lane in plain.lanes() {
6883 for idx in 0..plain.lane(lane).len() {
6884 if !plain.color_keys_of(lane, idx).is_empty() {
6885 plain.set_color_keys(lane, idx, Vec::new());
6886 }
6887 plain.set_color(lane, idx, None);
6888 }
6889 }
6890 compose_at(&plain, meta, frame, width, height)
6891}
6892
6893/// [`compose_at`] with captions drawn in: `burn` is the subtitle track's index
6894/// in [`Project::subtitles`] and the style, as [`ExportSettings::burn_subtitles`]
6895/// takes them, and the cue on screen at `frame` is drawn over the output at its
6896/// own size. `None` is exactly [`compose_at`].
6897pub fn compose_at_with(
6898 project: &Project,
6899 meta: &VideoMeta,
6900 frame: u32,
6901 width: u32,
6902 height: u32,
6903 burn: Option<(usize, TextStyle)>,
6904) -> crate::Result<crate::decode::Frame> {
6905 let end = project.media_frames();
6906 if frame >= end {
6907 return Err(format!("frame {frame} is past the end of the timeline ({end} frames)").into());
6908 }
6909 if width == 0 || height == 0 {
6910 return Err("compose_at: the output size must be non-zero".into());
6911 }
6912 let out = ColorDescription::output_sized(meta.width, meta.height);
6913 let span = export_spans(project, None)
6914 .into_iter()
6915 .find(|s| s.start <= frame && frame - s.start < s.len);
6916 let layered = layered_at(project, frame);
6917 let (y, u, v) = match span {
6918 // Two or more clips cover the frame: each is decoded at this frame and
6919 // composed bottom to top, exactly as the export composes it.
6920 _ if layered => {
6921 let stack = stack_at(project, frame);
6922 let mut layers = LayerStack::open(project, meta, &stack, out.matrix, None, None)?;
6923 layers
6924 .picture(frame)?
6925 .ok_or_else(|| -> crate::Error {
6926 format!("compose_at: a clip ends before frame {frame}").into()
6927 })?
6928 }
6929 Some(s) if s.from.is_some() => {
6930 let (source, in_frame) = s.from.expect("checked above");
6931 let offset = frame - s.start;
6932 let mut a = placed_info(project, meta, source)?;
6933 let deint = span_deint(project, s.start, &a.path);
6934 a.rate = crate::deinterlace::counted_rate(deint, a.rate);
6935 let source_frame = a.rate.source_at(s.source_at(in_frame, offset));
6936 let (ay, au, av) = picture_at(project, meta, &a, source_frame, s.start, out.matrix, deint)?;
6937 match dissolve_window(project, &s) {
6938 Some((b_source, b_in, window, b_start))
6939 if offset >= s.len.saturating_sub(window) =>
6940 {
6941 let k = offset - (s.len - window);
6942 let mut b = placed_info(project, meta, b_source)?;
6943 let b_deint = frame_counting(span_deint(project, b_start, &b.path));
6944 b.rate = crate::deinterlace::counted_rate(b_deint, b.rate);
6945 let b_frame = b.rate.source_at(b_in) + k;
6946 let (by, bu, bv) = picture_at(project, meta, &b, b_frame, b_start, out.matrix, b_deint)?;
6947 crate::transitions::blend_planes(
6948 crate::transitions::kind_at(project, s.start),
6949 (&ay, &au, &av),
6950 (&by, &bu, &bv),
6951 dissolve_weight(k, window),
6952 meta.width as usize,
6953 meta.height as usize,
6954 )
6955 }
6956 _ => (ay, au, av),
6957 }
6958 }
6959 _ => {
6960 let (w, h) = (meta.width as usize, meta.height as usize);
6961 (
6962 vec![16; w * h],
6963 vec![128; w.div_ceil(2) * h.div_ceil(2)],
6964 vec![128; w.div_ceil(2) * h.div_ceil(2)],
6965 )
6966 }
6967 };
6968 // A layered picture's fades were applied per clip inside its stack.
6969 let (y, u, v) = match picture_fade_at(project, frame).filter(|_| !layered) {
6970 Some(k) => fade_planes((&y, &u, &v), k),
6971 None => (y, u, v),
6972 };
6973 let bgra =
6974 crate::convert::i420_to_bgra(&out, &y, &u, &v, meta.width as usize, meta.height as usize);
6975 let (tw, th) = fit_box(meta.width, meta.height, width, height);
6976 let mut bgra = if (tw, th) == (meta.width, meta.height) {
6977 bgra
6978 } else {
6979 resize_bgra(&bgra, meta.width, meta.height, tw, th)
6980 };
6981 // The titles, then the caption, drawn at the size the caller gets, so their
6982 // size reads the same whatever the output box was asked for.
6983 for title in project.titles() {
6984 let Some(motion) = title.motion_at(frame) else {
6985 continue;
6986 };
6987 let alpha = motion.alpha;
6988 if alpha == 0 {
6989 continue;
6990 }
6991 let ov = title_overlay(title, &title_key(title, &motion, tw, th));
6992 if alpha == 255 {
6993 ov.blend_bgra(&mut bgra);
6994 } else {
6995 ov.faded(alpha).blend_bgra(&mut bgra);
6996 }
6997 }
6998 if let Some((pick, style)) = burn {
6999 let cues = burn_cues(project, pick, meta.frame_rate)?;
7000 let on = cues_on_screen(&cues, frame, meta.frame_rate);
7001 if !on.is_empty() {
7002 let style = style.clamped();
7003 let blocks = crate::captionanim::plan(&style, &cues, &on, frame, meta.frame_rate);
7004 overlay_blocks(&style, tw, th, &blocks).blend_bgra(&mut bgra);
7005 }
7006 }
7007 Ok(crate::decode::Frame {
7008 index: frame,
7009 width: tw,
7010 height: th,
7011 bgra,
7012 })
7013}
7014
7015/// A source as [`run`] reads it for placement: its path and audio stream, its
7016/// rate against the timeline, its colour, the tone map its curve asks for, and
7017/// its display-matrix turn and pixel aspect.
7018struct Placed {
7019 path: PathBuf,
7020 stream: usize,
7021 rate: Rate,
7022 color: ColorDescription,
7023 mapper: Option<ToneMapper>,
7024 rotation: Rotation,
7025 pixel_aspect: crate::demux::PixelAspect,
7026}
7027
7028/// The deinterlace setting of the clip the composite shows at `frame`, as it
7029/// applies to `path` (`Frame` for anything but interlaced H.264).
7030fn span_deint(project: &Project, frame: u32, path: &Path) -> Deinterlace {
7031 let mode = project
7032 .composite_clip_at(frame)
7033 .map_or(Deinterlace::Frame, |(lane, idx)| project.deinterlace_of(lane, idx));
7034 crate::deinterlace::effective(mode, path)
7035}
7036
7037/// `Field` counts two pictures a frame, which a picture-per-timeline-frame reader
7038/// cannot follow: it takes `Frame` (the same first field at the file's own rate).
7039fn frame_counting(mode: Deinterlace) -> Deinterlace {
7040 if mode == Deinterlace::Field { Deinterlace::Frame } else { mode }
7041}
7042
7043fn placed_info(project: &Project, meta: &VideoMeta, source: usize) -> crate::Result<Placed> {
7044 let sources = project.sources();
7045 let entry = sources
7046 .get(source)
7047 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
7048 let (rate, color, peak, rotation, pixel_aspect) = source_rate(&entry.path, meta.frame_rate);
7049 let mapper = match color.transfer {
7050 Transfer::Sdr => None,
7051 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, project.tone(), peak)),
7052 Transfer::Hlg => Some(ToneMapper::new(
7053 tonemap::Transfer::Hlg,
7054 project.tone(),
7055 peak,
7056 )),
7057 };
7058 Ok(Placed {
7059 path: entry.path.clone(),
7060 stream: entry.audio_stream,
7061 rate,
7062 color,
7063 mapper,
7064 rotation,
7065 pixel_aspect,
7066 })
7067}
7068
7069/// One source picture at `source_frame`, placed as [`run`] places it, as owned
7070/// planes at the project's size. `key` is the timeline frame whose grade,
7071/// transform, fit and visualizer state apply.
7072fn picture_at(
7073 project: &Project,
7074 meta: &VideoMeta,
7075 info: &Placed,
7076 source_frame: u32,
7077 key: u32,
7078 out: Matrix,
7079 deint: Deinterlace,
7080) -> crate::Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
7081 let flags = project.composite_visualizer_at(key);
7082 let mut decoder = if crate::is_audio(&info.path) || flags & 1 != 0 {
7083 ClipDecoder::visualizer(
7084 &info.path,
7085 info.stream,
7086 source_frame,
7087 (meta.width, meta.height),
7088 meta.frame_rate,
7089 flags,
7090 project.composite_viz_paint_at(key),
7091 )?
7092 } else {
7093 ClipDecoder::open_with(&info.path, source_frame, None, None, false, deint)?
7094 };
7095 let Some(picture) = decoder.next()? else {
7096 return Err(format!("{} ends before frame {source_frame}", info.path.display()).into());
7097 };
7098 let Frame::Pixels(y, u, v, width, height) = picture else {
7099 return Err("a single-frame decode produced no pixels".into());
7100 };
7101 let remap = remap_into(Some(info.color), info.mapper.is_some(), out);
7102 let grade = project.composite_color_at(key).copied();
7103 let transform = project
7104 .composite_transform_at(key)
7105 .copied()
7106 .unwrap_or_default();
7107 let mut canvas = Composer::new(meta.width, meta.height, project.composite_fit_at(key));
7108 let (mut rotated, mut stretched, mut graded, mut transformed) = Default::default();
7109 let (py, pu, pv, _, _) = place_picture(
7110 y,
7111 u,
7112 v,
7113 width,
7114 height,
7115 info.rotation,
7116 info.pixel_aspect,
7117 grade,
7118 transform,
7119 remap,
7120 info.mapper.as_ref(),
7121 &mut rotated,
7122 &mut stretched,
7123 &mut graded,
7124 &mut transformed,
7125 &mut canvas,
7126 );
7127 Ok((py.to_vec(), pu.to_vec(), pv.to_vec()))
7128}
7129
7130/// The largest size with the project's `w:h` aspect that fits in `bw` x `bh`.
7131fn fit_box(w: u32, h: u32, bw: u32, bh: u32) -> (u32, u32) {
7132 let (w, h, bw, bh) = (w as u64, h as u64, bw as u64, bh as u64);
7133 let th = (bw * h / w).max(1);
7134 if th <= bh {
7135 (bw as u32, th as u32)
7136 } else {
7137 let tw = (bh * w / h).max(1);
7138 (tw as u32, bh as u32)
7139 }
7140}
7141
7142/// Box-filter resize of a tightly packed BGRA picture. Each destination pixel
7143/// averages the source pixels it covers, so an upscale is nearest-neighbour
7144/// and a downscale is an area average; no float, so it is byte-stable.
7145fn resize_bgra(src: &[u8], sw: u32, sh: u32, dw: u32, dh: u32) -> Vec<u8> {
7146 fn cover(i: usize, src: usize, dst: usize) -> (usize, usize) {
7147 let a = i * src / dst;
7148 let b = ((i + 1) * src / dst).max(a + 1).min(src);
7149 (a, b)
7150 }
7151 let (sw, sh, dw, dh) = (sw as usize, sh as usize, dw as usize, dh as usize);
7152 let mut out = vec![0u8; dw * dh * 4];
7153 for dy in 0..dh {
7154 let (y0, y1) = cover(dy, sh, dh);
7155 for dx in 0..dw {
7156 let (x0, x1) = cover(dx, sw, dw);
7157 let mut acc = [0u32; 4];
7158 for y in y0..y1 {
7159 for x in x0..x1 {
7160 let p = (y * sw + x) * 4;
7161 for (c, a) in acc.iter_mut().enumerate() {
7162 *a += src[p + c] as u32;
7163 }
7164 }
7165 }
7166 let n = ((y1 - y0) * (x1 - x0)) as u32;
7167 let q = (dy * dw + dx) * 4;
7168 for (c, a) in acc.iter().enumerate() {
7169 out[q + c] = ((a + n / 2) / n) as u8;
7170 }
7171 }
7172 }
7173 out
7174}
7175
7176/// What rate `path` was shot at against a timeline at `timeline_fps`
7177/// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own
7178/// -- a still, a song -- and for one that will not open here: the decoder is
7179/// opened a few lines later and fails the export by name, which is a better
7180/// error than this one could raise.
7181fn source_rate(
7182 path: &Path,
7183 timeline_fps: f64,
7184) -> (
7185 Rate,
7186 ColorDescription,
7187 Option<f32>,
7188 Rotation,
7189 crate::demux::PixelAspect,
7190) {
7191 if crate::is_image(path) || crate::is_audio(path) {
7192 // A still is BT.601 by construction whatever it was authored as:
7193 // `decode::rgb_to_i420` is the one matrix that turns its pixels into
7194 // planes. A song has no picture and the answer is never read. Neither
7195 // has a display matrix to be turned by, nor an aspect to be widened
7196 // by: both are authored square. A still's *EXIF* turn is not in this
7197 // arm either, and for a better reason -- `decode::Still::open` already
7198 // made it before the planes were written, so `place_picture` is handed
7199 // the picture the preview showed and must not be told to turn it again.
7200 return (
7201 Rate::REAL_TIME,
7202 ColorDescription::default(),
7203 None,
7204 Rotation::None,
7205 crate::demux::PixelAspect::SQUARE,
7206 );
7207 }
7208 match Demuxer::open(path) {
7209 // ...and one whose rate cannot be named against the timeline's, which
7210 // `matches_timeline` refuses at import, so nothing on a timeline is on
7211 // this arm either.
7212 //
7213 // The declared peak comes off the same open the space does, which is
7214 // what keeps export on the number playback's decode funnel read: one
7215 // header parse, both answers.
7216 Ok((meta, demuxer)) => (
7217 Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME),
7218 meta.color,
7219 demuxer.light().peak(),
7220 // The file's own turn, so the encoder is fed the picture the
7221 // preview shows: the same header read, one more answer.
7222 meta.rotation,
7223 // ...and its own sample aspect, for the same reason on the same
7224 // read: the encoder is fed the shape the preview showed.
7225 meta.pixel_aspect,
7226 ),
7227 // Unreadable here means unreadable below too, where the span dies with a
7228 // real message; the file's own space is the least of that.
7229 Err(_) => (
7230 Rate::REAL_TIME,
7231 ColorDescription::default(),
7232 None,
7233 Rotation::None,
7234 crate::demux::PixelAspect::SQUARE,
7235 ),
7236 }
7237}
7238
7239/// The audio lanes alone, summed, as a WAV or a FLAC.
7240///
7241/// Nothing here re-derives the edit: the play lists are
7242/// [`Project::audio_segments_from`] and they are handed to the very
7243/// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written
7244/// is what was heard -- every lane, mixed the same way, gaps included, which
7245/// arrive as real silence from that choke point rather than as a hole this would
7246/// have to invent.
7247///
7248/// The length is the *timeline's*: each segment resolves its window to whole
7249/// samples on its own, so the sum can miss the timeline by a sample or two, and
7250/// a source that runs out early would leave the file short. Both are settled by
7251/// one `resize` at the end -- padding with silence, trimming what overshot --
7252/// so an exported file is exactly as long as what was edited.
7253/// The timeline frames a picture export covers: its range, clipped to the media, or the whole media.
7254fn picture_span(project: &Project, settings: &ExportSettings) -> (u32, u32) {
7255 let media = project.media_frames();
7256 match settings.range {
7257 Some((from, to)) => {
7258 let from = from.min(media);
7259 (from, to.min(media).max(from))
7260 }
7261 None => (0, media),
7262 }
7263}
7264
7265/// The picture at timeline frame `frame` as a PNG file's bytes, at the project's own size. What
7266/// the still formats write: [`compose_at_with`] draws it as the export would, titles and burnt
7267/// captions included.
7268fn still_png(project: &Project, meta: &VideoMeta, frame: u32, settings: &ExportSettings) -> crate::Result<Vec<u8>> {
7269 let picture = compose_at_with(project, meta, frame, meta.width, meta.height, settings.burn_subtitles.clone())?;
7270 crate::decode::to_png_bytes(&picture)
7271}
7272
7273/// A numbered PNG run ([`Format::PngSequence`]) into the folder `out`, one file per frame,
7274/// named after the folder: `name_00001.png`. A run that fails part way leaves no files behind.
7275fn run_png_sequence(
7276 project: &Project,
7277 meta: &VideoMeta,
7278 out: &Path,
7279 shared: &Arc<Shared>,
7280 settings: &ExportSettings,
7281) -> crate::Result<()> {
7282 let (from, to) = picture_span(project, settings);
7283 let total = to - from;
7284 std::fs::create_dir_all(out)?;
7285 let name = out.file_name().and_then(|n| n.to_str()).unwrap_or("frame").to_string();
7286 let mut written: Vec<PathBuf> = Vec::new();
7287 let result = (|| -> crate::Result<()> {
7288 for k in 0..total {
7289 cancelled(shared)?;
7290 let path = out.join(format!("{name}_{:05}.png", k + 1));
7291 std::fs::write(&path, still_png(project, meta, from + k, settings)?)?;
7292 written.push(path);
7293 shared.progress.fetch_max(picture_progress(k + 1, total), Ordering::Relaxed);
7294 }
7295 Ok(())
7296 })();
7297 if result.is_err() {
7298 for path in &written {
7299 let _ = std::fs::remove_file(path);
7300 }
7301 }
7302 result
7303}
7304
7305/// The poster frame ([`Format::Still`]): the picture at the start of the range, written to `part`
7306/// for the caller to publish.
7307fn run_still(project: &Project, meta: &VideoMeta, part: &Path, settings: &ExportSettings) -> crate::Result<()> {
7308 let frame = settings.range.map_or(0, |(from, _)| from);
7309 std::fs::write(part, still_png(project, meta, frame, settings)?)?;
7310 Ok(())
7311}
7312
7313/// The animated GIF ([`Format::Gif`]): the range sampled at [`GifSettings::fps`], each picture
7314/// composed at [`GifSettings::width`], handed to the GIF writer one frame at a time.
7315fn run_gif(
7316 project: &Project,
7317 meta: &VideoMeta,
7318 part: &Path,
7319 shared: &Arc<Shared>,
7320 settings: &ExportSettings,
7321) -> crate::Result<()> {
7322 let gif = settings.gif;
7323 // The encoder holds every frame until `finish`, so a GIF is bounded in what it can hold.
7324 if gif.width == 0 || gif.width > GIF_MAX_WIDTH || gif.fps == 0 || gif.fps > 60 {
7325 return Err(format!("a GIF is 1 to {GIF_MAX_WIDTH} pixels wide and 1 to 60 frames a second").into());
7326 }
7327 let (from, to) = picture_span(project, settings);
7328 if f64::from(to - from) / meta.frame_rate > GIF_MAX_SECS {
7329 return Err(format!("a GIF is at most {GIF_MAX_SECS} s long: export a shorter range").into());
7330 }
7331 let (width, height) = fit_box(meta.width, meta.height, gif.width, GIF_MAX_WIDTH);
7332 let mut writer = GifWriter::open(width, height, gif.loop_forever)?;
7333 let fps = f64::from(gif.fps);
7334 let frames = ((f64::from(to - from) * fps) / meta.frame_rate).ceil() as u32;
7335 if frames == 0 {
7336 return Err("the range holds no frames".into());
7337 }
7338 for i in 0..frames {
7339 cancelled(shared)?;
7340 // The timeline frame this GIF frame shows, and how long it holds: the hundredths of a
7341 // second between this frame's start and the next, so the rounding never drifts.
7342 let at = ((f64::from(i) * meta.frame_rate) / fps) as u32;
7343 let shown = from + at.min(to - from - 1);
7344 let next = (f64::from(i + 1) * 100.0 / fps).round() as u32;
7345 let delay = (next - (f64::from(i) * 100.0 / fps).round() as u32).max(1) as u16;
7346 let picture = compose_at_with(project, meta, shown, width, height, settings.burn_subtitles.clone())?;
7347 let rgba: Vec<u8> = picture
7348 .bgra
7349 .as_chunks::<4>()
7350 .0
7351 .iter()
7352 .flat_map(|px| [px[2], px[1], px[0], 255])
7353 .collect();
7354 writer.push(&rgba, delay)?;
7355 shared.progress.fetch_max(picture_progress(i + 1, frames), Ordering::Relaxed);
7356 }
7357 std::fs::write(part, writer.finish()?)?;
7358 Ok(())
7359}
7360
7361/// The widest GIF, and the longest: the encoder keeps every frame until it is finished.
7362const GIF_MAX_WIDTH: u32 = 720;
7363const GIF_MAX_SECS: f64 = 30.0;
7364
7365/// The GIF writer, over `ec_image::gif_encode`: 256 colours with dithering (video gradients band
7366/// badly without it), looping forever or playing once.
7367struct GifWriter(ec_image::gif_encode::Encoder);
7368
7369impl GifWriter {
7370 fn open(width: u32, height: u32, loop_forever: bool) -> crate::Result<Self> {
7371 let opts = ec_image::gif_encode::GifOptions {
7372 loop_count: if loop_forever { Some(0) } else { None },
7373 max_colors: 256,
7374 dither: true,
7375 };
7376 let encoder = ec_image::gif_encode::Encoder::new(width as u16, height as u16, opts)
7377 .map_err(|e| format!("GIF: {e}"))?;
7378 Ok(Self(encoder))
7379 }
7380
7381 fn push(&mut self, rgba: &[u8], delay_cs: u16) -> crate::Result<()> {
7382 self.0.push_rgba8(rgba, delay_cs).map_err(|e| format!("GIF: {e}").into())
7383 }
7384
7385 fn finish(self) -> crate::Result<Vec<u8>> {
7386 self.0.finish().map_err(|e| format!("GIF: {e}").into())
7387 }
7388}
7389
7390fn run_audio(
7391 project: &Project,
7392 meta: &VideoMeta,
7393 out: &Path,
7394 shared: &Shared,
7395 settings: &ExportSettings,
7396 sample_rate: Option<u32>,
7397) -> crate::Result<()> {
7398 let format = settings.format;
7399 let (samples, audio) = mix_pcm(project, meta, shared, settings, sample_rate, 16)?
7400 .ok_or("this timeline has no audio to export")?;
7401 // Written in one go and still cancellable up to here, exactly as the mp4
7402 // path is up to its `finish`: the `.part` is what either gets renamed or
7403 // deleted.
7404 cancelled(shared)?;
7405 match format {
7406 Format::Wav => write_wav(out, &samples, &audio)?,
7407 Format::Flac => write_flac(out, &samples, &audio)?,
7408 Format::Mp3 => write_mp3(out, &samples, &audio, audio_kbps_of(settings))?,
7409 Format::Ogg => write_ogg(out, &samples, &audio)?,
7410 Format::Opus => write_opus(out, &samples, &audio, project, settings, shared)?,
7411 _ => unreachable!("the picture formats are `run`"),
7412 }
7413 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
7414 Ok(())
7415}
7416
7417/// The sample width of a ProRes file's PCM sound: 24 unless
7418/// [`ExportSettings::audio_bit_depth`] says 16.
7419fn prores_audio_bits(settings: &ExportSettings) -> u8 {
7420 match settings.audio_bit_depth {
7421 Some(16) => 16,
7422 _ => 24,
7423 }
7424}
7425
7426/// The ProRes file's sound pass: the mix as `bits`-wide samples, `(samples, rate,
7427/// channels)`, or `None` for a timeline with no sound. Runs beside the picture.
7428fn mix_pcm16(
7429 project: &Project,
7430 meta: &VideoMeta,
7431 shared: &Shared,
7432 settings: &ExportSettings,
7433 sample_rate: Option<u32>,
7434 bits: u8,
7435) -> crate::Result<Option<(Vec<i32>, u32, u16)>> {
7436 Ok(mix_pcm(project, meta, shared, settings, sample_rate, bits)?
7437 .map(|(samples, audio)| (samples, audio.sample_rate, audio.channels)))
7438}
7439
7440/// A running ProRes sound pass, joined when dropped for the reason [`AudioPass`] is.
7441struct PcmPass(Option<PcmJob>);
7442
7443/// The ProRes sound pass's thread: `(samples, rate, channels)` or `None` for no sound.
7444type PcmJob = thread::JoinHandle<crate::Result<Option<(Vec<i32>, u32, u16)>>>;
7445
7446impl PcmPass {
7447 fn take(&mut self) -> Option<PcmJob> {
7448 self.0.take()
7449 }
7450}
7451
7452impl Drop for PcmPass {
7453 fn drop(&mut self) {
7454 if let Some(job) = self.0.take() {
7455 let _ = job.join();
7456 }
7457 }
7458}
7459
7460fn join_pcm(job: PcmJob) -> crate::Result<Option<(Vec<i32>, u32, u16)>> {
7461 job.join()
7462 .map_err(|_| crate::Error::from("the sound pass stopped without a picture or a reason"))?
7463}
7464
7465/// The audio lanes mixed to 16-bit samples (in an `i32`), the length of the
7466/// range: [`run_audio`]'s body up to the write, so a WAV and a ProRes file's PCM
7467/// track are the same mix. `None` where the timeline has no sound.
7468fn mix_pcm(
7469 project: &Project,
7470 meta: &VideoMeta,
7471 shared: &Shared,
7472 settings: &ExportSettings,
7473 sample_rate: Option<u32>,
7474 bits: u8,
7475) -> crate::Result<Option<(Vec<i32>, AudioMeta)>> {
7476 let format = settings.format;
7477 // Full scale of the sample width asked for: 32767 or 8388607. The f32 mix is
7478 // scaled straight to it, so a 24-bit file is not a widened 16-bit one.
7479 let full = ((1i64 << (bits - 1)) - 1) as f32;
7480 let sources = project.audio_sources();
7481 let range_start = settings.range.map_or(0, |(s, _)| s);
7482 let pre = warm_up(project, range_start, meta.frame_rate);
7483 let offset = range_start - pre;
7484 let segs = project.audio_segments_from(offset, meta.frame_rate);
7485 // The equalizers with them, so what is written is what is heard down to the
7486 // filter: the worker applies them per segment before the lanes are summed
7487 // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point
7488 // playback's feeder reads from -- there is no second place here that could
7489 // apply them differently.
7490 let eqs = project.audio_eqs_from(offset, meta.frame_rate);
7491 // ...and the rates with them, for exactly the same reason: a speeded clip is
7492 // resampled inside the worker playback feeds from, so a WAV of a timeline at
7493 // 2x is half as long and holds the samples that were heard -- not a
7494 // second pass here that could disagree with what the ear got.
7495 let speeds = project.audio_speeds_from(offset, meta.frame_rate);
7496 // ...and the fades with them, the same choke-point reason again: a clip's
7497 // envelope runs inside the worker playback feeds from too.
7498 let fades = project.audio_fades_from(offset, meta.frame_rate);
7499 // ...and the mix over both: each lane's volume into the sum, the master
7500 // limiter out of it. The same opener playback's feeder reads from, so a
7501 // file is written at the levels it was heard at -- there is no second
7502 // place here that could mix it differently.
7503 let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade(
7504 &sources,
7505 &segs,
7506 &eqs,
7507 &speeds,
7508 &fades,
7509 meta.frame_rate,
7510 &project.audio_gains(),
7511 &project.audio_ducks(),
7512 &project.audio_voices(),
7513 project.limiter(),
7514 sample_rate,
7515 )?
7516 else {
7517 return Ok(None);
7518 };
7519 // The picture path's line, for a file that is sound alone: there is sound
7520 // by the line above, so this names the encoder writing it. A picture file
7521 // publishes its own.
7522 if !format.has_video() {
7523 *shared.encoders.lock().unwrap() =
7524 Some(audio_label(project, format, true, None, settings.range.is_some(), settings.reencode_audio).to_string());
7525 }
7526 let channels = usize::from(audio.channels);
7527 let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| {
7528 e.min(project.media_frames()).saturating_sub(s)
7529 });
7530 let frames =
7531 (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as u64;
7532 let total = frames as usize * channels;
7533 // corner-cut: the whole export sits in memory (4 bytes a sample, so ~23 MB
7534 // per minute of 48 kHz stereo). `ec-flac` takes it that way and
7535 // the mp4 path already collects its copied AAC track the same. Upgrade path
7536 // is ec-riff's incremental writer, fed one block at a time.
7537 let skip = warm_up_samples(range_start, pre, meta.frame_rate, audio.sample_rate, channels);
7538 let mut samples: Vec<i32> = Vec::with_capacity(total + skip);
7539 // Only for a loudness target: the mix at f32, measured and levelled once whole.
7540 let mut wide: Vec<f32> = Vec::new();
7541 for chunk in chunks {
7542 cancelled(shared)?;
7543 if shared.loudness.is_some() {
7544 wide.extend_from_slice(&chunk.samples);
7545 // The same range-only progress as the plain path below.
7546 let done = wide.len().saturating_sub(skip).min(total) * PROGRESS_SCALE as usize / total.max(1);
7547 if !format.has_video() { shared.progress.store(done as u32, Ordering::Relaxed); }
7548 if wide.len() >= skip + total {
7549 break;
7550 }
7551 continue;
7552 }
7553 // Already equalized: the chunks come out of the per-lane workers, which
7554 // filter each segment before the mix (`open_mixed_streams_eq` above).
7555 samples.extend(
7556 chunk
7557 .samples
7558 .iter()
7559 .map(|s| (s.clamp(-1.0, 1.0) * full).round() as i32),
7560 );
7561 // Only the range counts towards the bar: not the pre-roll, not the mix past the end.
7562 let done = samples.len().saturating_sub(skip).min(total) * PROGRESS_SCALE as usize / total.max(1);
7563 if !format.has_video() { shared.progress.store(done as u32, Ordering::Relaxed); }
7564 if samples.len() >= skip + total {
7565 break;
7566 }
7567 }
7568 if let Some(target) = shared.loudness {
7569 // The voice warm-up is dropped first, so the gain is measured over the range alone.
7570 wide.drain(..skip.min(wide.len()));
7571 wide.resize(total, 0.0);
7572 level_to_target(&mut wide, audio.sample_rate, audio.channels.max(1), target);
7573 samples.extend(
7574 wide.iter().map(|s| (s.clamp(-1.0, 1.0) * full).round() as i32),
7575 );
7576 if !format.has_video() { shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); }
7577 } else {
7578 // The pre-roll is in the samples in 16-bit form too, so it goes before the length is set.
7579 samples.drain(..skip.min(samples.len()));
7580 }
7581 samples.resize(total, 0);
7582 Ok(Some((samples, audio)))
7583}
7584
7585/// The sound alone as AAC in an mp4 box: the `.m4a` file, and the `.mp4` of a
7586/// timeline with no picture. The track is the one a picture export carries --
7587/// copied packet for packet where a copy says what the timeline says
7588/// ([`copy_audio`]), encoded where it cannot -- so the two files hold the same
7589/// samples and differ in the brand alone ([`Mp4Muxer::create_audio_only`]).
7590fn run_aac(
7591 project: &Project,
7592 meta: &VideoMeta,
7593 out: &Path,
7594 shared: &Shared,
7595 settings: &ExportSettings,
7596 sample_rate: Option<u32>,
7597) -> crate::Result<()> {
7598 let track = copy_audio(
7599 project,
7600 meta,
7601 audio_kbps_of(settings),
7602 false,
7603 false,
7604 settings.reencode_audio,
7605 shared,
7606 sample_rate,
7607 settings.range,
7608 )?
7609 .ok_or("this timeline has no audio to export")?;
7610 let track = ExportAudio {
7611 language: audio_language(project),
7612 ..track
7613 };
7614 *shared.encoders.lock().unwrap() = Some(
7615 audio_label(
7616 project,
7617 settings.format,
7618 true,
7619 Some(track.copied),
7620 settings.range.is_some(),
7621 settings.reencode_audio,
7622 )
7623 .to_string(),
7624 );
7625 let mut mp4 = Mp4Muxer::create_audio_only(
7626 out,
7627 &params_of(&track),
7628 settings.format == Format::M4a,
7629 )?;
7630 if let Some(frames) = track.pcm_frames {
7631 mp4.set_audio_frames(frames)?;
7632 }
7633 let count = track.packets.len().max(1);
7634 for (i, packet) in track.packets.iter().enumerate() {
7635 cancelled(shared)?;
7636 mp4.write_audio_packet(&packet.bytes)?;
7637 shared
7638 .progress
7639 .fetch_max((i * PROGRESS_SCALE as usize / count) as u32, Ordering::Relaxed);
7640 }
7641 cancelled(shared)?;
7642 mp4.set_faststart(settings.faststart);
7643 mp4.set_chapters(&settings.chapters)?;
7644 mp4.finish()?;
7645 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
7646 Ok(())
7647}
7648
7649/// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in
7650/// this engine, so what the decoder handed over is what the header says.
7651fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
7652 // Every sample is in hand, so the frame count is known before the header
7653 // is written: a long enough export gets RF64 instead of a RIFF that would
7654 // overflow its 32-bit sizes.
7655 let channels = u64::from(audio.channels.max(1));
7656 let options = ec_riff::WavOptions {
7657 expected_frames: samples.len() as u64 / channels,
7658 ..Default::default()
7659 };
7660 let mut writer = ec_riff::WavWriter::create_with_options(
7661 out,
7662 ec_riff::WavSpec {
7663 channels: audio.channels,
7664 sample_rate: audio.sample_rate,
7665 bits_per_sample: 16,
7666 sample_format: ec_riff::SampleType::Int,
7667 },
7668 options,
7669 )?;
7670 for &sample in samples {
7671 writer.write_sample(sample as i16)?;
7672 }
7673 // Not `drop`: this is what rewrites the RIFF sizes in the header, and its
7674 // failure is the difference between a finished file and a truncated one.
7675 writer.finalize()?;
7676 Ok(())
7677}
7678
7679/// The same samples as MPEG-1 Layer III, `ec-mp3` doing the encoding -- the
7680/// family's own, taking the seat at the same contract (CBR in, frames out,
7681/// `Mp3EncoderConfig`'s fields are the old seat's names), so the swap cost the
7682/// call sites nothing.
7683///
7684/// CBR at the caller's rate, [`DEFAULT_AUDIO_KBPS`] where there was none. Every
7685/// offered rate is already a legal Layer III value, so the encoder's snap is a
7686/// backstop and not a silent substitution; a sample rate MPEG has no frame for
7687/// (anything but the nine MPEG rates 8-48 kHz) is refused there by name rather
7688/// than written as something else.
7689///
7690/// corner-cut: CBR only -- the card offers rates and not a quality index. Upgrade
7691/// path is `Mp3EncoderConfig::vbr_quality` behind a setting of its own.
7692fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta, kbps: u32) -> crate::Result<()> {
7693 let mut encoder = ec_mp3::encode::Mp3Encoder::new(ec_mp3::encode::Mp3EncoderConfig {
7694 bitrate_kbps: kbps,
7695 vbr_quality: None,
7696 });
7697 // The samples are the 16-bit ones a WAV of this timeline holds, so the two
7698 // files are one mix -- and `push_pcm_s16` divides by 32768 exactly as this
7699 // engine's own decoders do.
7700 let pcm: Vec<i16> = samples.iter().map(|&s| s as i16).collect();
7701 encoder
7702 .push_pcm_s16(&pcm, audio.channels, audio.sample_rate)
7703 .map_err(|e| format!("mp3 encode: {e}"))?;
7704 encoder.finish();
7705 let mut file = BufWriter::new(File::create(out)?);
7706 // `next_packet` after `finish` yields frames until `Eof`, the Xing/Info
7707 // header first: the loop ends on the only error it can see.
7708 while let Ok(frame) = encoder.next_packet() {
7709 file.write_all(&frame)?;
7710 }
7711 file.flush()?;
7712 Ok(())
7713}
7714
7715/// Where the Vorbis rate loop starts, on `ec-vorbis`'s normalised `[0, 1]`
7716/// scale, beside [`VORBIS_TARGET_BPS`] -- the two numbers every `.ogg` this
7717/// program writes is coded at.
7718///
7719/// A measured operating point, not a taste (2026-09-13 bench, every output
7720/// decoded back with **symphonia** -- an independent decoder, and the very one
7721/// [`crate::audio`] reopens an export with). The incumbent seat's own 0.85 --
7722/// its top quality that still decoded every fixture to exactly its own length
7723/// -- measured 124-176 kbps across this suite's fixtures with correlation
7724/// 0.9947-0.9957 against the source. The quality knob alone on the new seat
7725/// saturates well under that band (0.98 lands ~87 kbps on a 30-second music
7726/// clip), so the seat is driven the way its own rate gates are measured: the
7727/// loop starts at 0.85 and is held to a 128 kbps target, which landed
7728/// 124-134 kbps actual on the same inputs and beat the incumbent at its own
7729/// operating point on every one of them -- correlation 0.9968 against 0.9947
7730/// on the music clip, +3.1 dB PSNR -- at the same size of file. Against
7731/// ffmpeg's own libvorbis at `-q 5` (125.8 kbps actual on the same clip) it
7732/// reads 0.9968 against 0.9973: par at the same rate.
7733const VORBIS_QUALITY: f32 = 0.85;
7734
7735/// The rate [`VORBIS_QUALITY`]'s loop is held to, in bits per second. Measured
7736/// landing within +1..+5% of target across the bench's inputs; the Sound row
7737/// stays refused for this format because this target is the encoder's measured
7738/// operating point, not a number a card may offer.
7739const VORBIS_TARGET_BPS: i32 = 128_000;
7740
7741/// The same samples as Vorbis I in an Ogg container: `ec-vorbis` encodes,
7742/// `ec-ogg` pages. Pure Rust on both halves, like every other encoder here.
7743///
7744/// The old seat's two corrections are gone with it, and the going is measured
7745/// rather than assumed (2026-09-13, every output decoded back with symphonia).
7746/// This encoder numbers its packets the spec's way -- the first audio packet
7747/// at granule 0, every packet after at the absolute sample position its block
7748/// ends on -- and clamps its final granule to the sample count it was fed, so
7749/// a decoder trims the block grid's tail on its own. Written straight through,
7750/// every file decodes to exactly the timeline's frame count with the
7751/// correlation peak at lag zero, which is what the one-hop pre-roll and the
7752/// two granule corrections this function used to carry around the old encoder
7753/// were for.
7754///
7755/// **Stereo, always.** The format row promises stereo, so a mono mix is
7756/// written as dual mono, both channels bit-identical (measured: `max|L-R|` is
7757/// exactly 0; the encoder's own channel coupling codes the empty side channel
7758/// for almost nothing). The encoder would serve a mono stream, but the row
7759/// says stereo and folding the file back down must give exactly what was
7760/// mixed. Wider than stereo cannot reach here -- [`crate::audio`] folds 5.1
7761/// to stereo when the source is opened -- but it is refused by name rather
7762/// than left to the library's own message.
7763///
7764/// corner-cut: one operating point, [`VORBIS_QUALITY`] +
7765/// [`VORBIS_TARGET_BPS`], with no user control -- the Sound row is refused for
7766/// this format. Upgrade path is a quality picker of its own, worth building
7767/// the day the card has a control that speaks in quality rather than kbps.
7768fn write_ogg(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
7769 if audio.channels > 2 {
7770 return Err(format!(
7771 "Ogg Vorbis is written in stereo here and this mix has {} channels",
7772 audio.channels
7773 )
7774 .into());
7775 }
7776 // The mp3 path's conversion, so the two files are one mix -- the same
7777 // /32768 scaling this engine's own decoders do -- plus (for a mono mix)
7778 // the dual-mono widening: the same sample in both channels is the same
7779 // signal, not a widening of it, so what a player folds back down is what
7780 // was mixed.
7781 let pcm: Vec<f32> = match audio.channels < 2 {
7782 true => samples
7783 .iter()
7784 .flat_map(|&s| [f32::from(s as i16) / 32768.0; 2])
7785 .collect(),
7786 false => samples
7787 .iter()
7788 .map(|&s| f32::from(s as i16) / 32768.0)
7789 .collect(),
7790 };
7791 let frames = samples.len() / usize::from(audio.channels).max(1);
7792
7793 let mut encoder = ec_vorbis::VorbisEncoder::new(ec_vorbis::EncoderConfig {
7794 sample_rate: audio.sample_rate,
7795 channels: 2,
7796 bitrate_bps: VORBIS_TARGET_BPS,
7797 quality: VORBIS_QUALITY,
7798 })
7799 .map_err(|e| format!("vorbis encode: {e}"))?;
7800 encoder
7801 .push_interleaved(&pcm)
7802 .map_err(|e| format!("vorbis encode: {e}"))?;
7803 encoder.finish();
7804 let mut packets = Vec::new();
7805 loop {
7806 match encoder.next_packet() {
7807 Ok(packet) => packets.push(packet),
7808 Err(ec_core::Error::Eof) => break,
7809 Err(ec_core::Error::NeedMore) => continue,
7810 Err(e) => return Err(format!("vorbis encode: {e}").into()),
7811 }
7812 }
7813 // The three setup headers travel with the encoder, not in the packet
7814 // stream; with no audio packets there is no stream to page.
7815 if packets.is_empty() {
7816 return Err("vorbis encode: no audio packets is not a stream".into());
7817 }
7818 let headers = encoder.headers();
7819 let extradata =
7820 ec_ogg::xiph_lace(&headers).ok_or("vorbis encode: the three headers would not lace")?;
7821
7822 let time_base =
7823 TimeBase::try_new(1, i64::from(audio.sample_rate)).map_err(|e| format!("ogg mux: {e}"))?;
7824 let mut params = CodecParameters::new(CodecId::Vorbis);
7825 params.extradata = Some(Buf::from(extradata));
7826 params.media = MediaParameters::Audio(AudioParameters {
7827 sample_rate: audio.sample_rate,
7828 layout: ChannelLayout::Stereo,
7829 ..AudioParameters::default()
7830 });
7831 let mut stream = StreamInfo::new(0, time_base, params);
7832 stream.duration = Some(frames as i64);
7833 stream.start_time = Some(0);
7834 let mut muxer = ec_ogg::OggMuxer::new(File::create(out)?);
7835 // Without this every audio packet of a short export lands on one page, and
7836 // the muxer's own note records what that costs: a first-audio-page-is-also-
7837 // EOS stream decodes short by half a small block in a reference decoder.
7838 muxer.set_page_target_bytes(Some(OGG_PAGE_BYTES));
7839 muxer
7840 .add_stream(stream)
7841 .map_err(|e| format!("ogg mux: {e}"))?;
7842 for packet in &packets {
7843 // The granule is the encoder's own: the absolute sample position this
7844 // packet ends at, clamped to the mix's length on the last one. It goes
7845 // in as side data, which is where `ec-ogg` reads it, because a packet's
7846 // `pts + duration` would state the position one block late.
7847 let mut out_packet =
7848 Packet::new(0, time_base, packet.data.clone()).with_duration(packet.samples);
7849 out_packet
7850 .side_data
7851 .push(ec_ogg::granule_side_data(packet.granule));
7852 muxer
7853 .write_packet(&out_packet)
7854 .map_err(|e| format!("ogg mux: {e}"))?;
7855 }
7856 muxer.finish().map_err(|e| format!("ogg mux: {e}"))?;
7857 Ok(())
7858}
7859
7860/// The same samples as Opus in Ogg ([`crate::opus_write`]), at the Sound row's
7861/// rate clamped into Opus's own range (6-510 kbps, [`crate::opus_write::DEFAULT_KBPS`]
7862/// where none was asked for), with the language and chapters in `OpusTags`.
7863/// Cancellable per packet, like the mix before it.
7864fn write_opus(
7865 out: &Path,
7866 samples: &[i32],
7867 audio: &AudioMeta,
7868 project: &Project,
7869 settings: &ExportSettings,
7870 shared: &Shared,
7871) -> crate::Result<()> {
7872 if audio.sample_rate != OPUS_RATE {
7873 return Err(format!("Opus is coded at 48 kHz and this mix came out at {} Hz", audio.sample_rate).into());
7874 }
7875 let pcm: Vec<f32> = samples.iter().map(|&s| f32::from(s as i16) / 32768.0).collect();
7876 let language = audio_language(project);
7877 let tags = crate::opus_write::Tags { language: language.as_deref(), chapters: &settings.chapters };
7878 crate::opus_write::write(
7879 out,
7880 &pcm,
7881 usize::from(audio.channels.max(1)),
7882 audio.sample_rate,
7883 settings.audio_kbps.unwrap_or(crate::opus_write::DEFAULT_KBPS),
7884 &tags,
7885 &mut |_| cancelled(shared),
7886 )
7887}
7888
7889/// The page size [`write_ogg`] asks the Ogg muxer to aim at, in bytes. RFC 3533
7890/// describes pages as "usually 4-8 kB", which is also the muxer's own suggested
7891/// general-purpose value.
7892const OGG_PAGE_BYTES: usize = 4096;
7893
7894/// The same samples, losslessly compressed, through [`crate::flac_write`]. The
7895/// export is always 16-bit: the samples were scaled to `i16` above.
7896fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
7897 crate::flac_write::write(out, samples, usize::from(audio.channels), 16, audio.sample_rate)
7898}
7899
7900/// The I420 planes of one black picture, allocated once for a whole export: a
7901/// gap in the video lane is encoded, not skipped, or every frame after it would
7902/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention
7903/// [`crate::convert`] decodes with.
7904struct Black {
7905 y: Vec<u8>,
7906 uv: Vec<u8>,
7907 width: u32,
7908 height: u32,
7909}
7910
7911impl Black {
7912 fn new(meta: &VideoMeta) -> Self {
7913 let (w, h) = (meta.width as usize, meta.height as usize);
7914 Self {
7915 y: vec![16; w * h],
7916 uv: vec![128; w.div_ceil(2) * h.div_ceil(2)],
7917 width: meta.width,
7918 height: meta.height,
7919 }
7920 }
7921
7922 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
7923 (&self.y, &self.uv, &self.uv, self.width, self.height)
7924 }
7925}
7926
7927/// `Err` once a cancel has been asked for. Called at every point where the work
7928/// left is more than an instant, so an `esc` at 99.9% still stops the export
7929/// instead of quietly completing it.
7930fn cancelled(shared: &Shared) -> crate::Result<()> {
7931 if shared.cancel.load(Ordering::Relaxed) {
7932 return Err("export cancelled".into());
7933 }
7934 Ok(())
7935}
7936
7937/// The two containers an export writes, so the picture loop above is one loop:
7938/// H.264 goes into mp4, AV1 into Matroska, and nothing else is offered.
7939enum Muxer {
7940 Mp4(Mp4Muxer),
7941 Mkv(MkvMuxer),
7942 /// ProRes in QuickTime ([`crate::prores_out::MovWriter`]).
7943 Mov(crate::prores_out::MovWriter),
7944}
7945
7946impl Muxer {
7947 fn finish(self) -> crate::Result<()> {
7948 match self {
7949 Self::Mp4(mp4) => mp4.finish(),
7950 Self::Mkv(mkv) => mkv.finish(),
7951 Self::Mov(mov) => mov.finish(),
7952 }
7953 }
7954}
7955
7956/// Test-only panic point, so the worker's own `catch_unwind` branch in
7957/// [`start`] is reachable without a codec parser that actually panics: the
7958/// variable names the one `.part` whose export dies, and no export but that
7959/// one ever matches it, so a concurrent export in the same process is safe.
7960fn inject_export_test_panic(out: &Path) {
7961 if crate::envcfg::var_os("VE_EXPORT_TEST_PANIC").is_some_and(|target| target == out.as_os_str()) {
7962 panic!("export test panic: the .part is on disk");
7963 }
7964}
7965
7966/// Writes one access unit, creating the file on the first one -- the parameter
7967/// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once
7968/// the encoder has coded something. Units with no coded slice are skipped: a
7969/// software encoder may hand back an empty buffer while it buffers, and the
7970/// muxer rejects a sample that would carry no picture.
7971#[allow(
7972 clippy::too_many_arguments,
7973 reason = "the export's per-access-unit sink: its inputs are passed positionally at its two call sites, and a struct would only rename them"
7974)]
7975fn write_video(
7976 muxer: &mut Option<Muxer>,
7977 out: &Path,
7978 meta: &VideoMeta,
7979 settings: &ExportSettings,
7980 source_colour: Tags,
7981 source_language: Option<&str>,
7982 audio: Option<&AudioParams>,
7983 packets: &mut Option<Vec<crate::AacPacket>>,
7984 subs: &mut Vec<SubParams>,
7985 au: &[u8],
7986 key: bool,
7987 ten_bit: bool,
7988) -> crate::Result<()> {
7989 if settings.format.is_prores() {
7990 // The encoder's own frame, one sample per picture; the track is declared
7991 // by the first one, the sound is written after the last.
7992 let Some(Muxer::Mov(mov)) = muxer else {
7993 unreachable!("the ProRes seat opens its own muxer")
7994 };
7995 return mov.write_frame(au);
7996 }
7997 if settings.format.is_hevc() {
7998 // The parameter sets are in the access unit -- every intra AU carries
7999 // VPS, SPS and PPS -- and the record built from them is what *both*
8000 // containers declare the track with: an mp4's `hvcC` box and a
8001 // Matroska `CodecPrivate` are the same bytes, so the two files are one
8002 // stream written twice rather than two.
8003 let sample =
8004 crate::mux::annex_b_to_hvcc(au).ok_or("a coded HEVC unit with no slice in it")?;
8005 if settings.format == Format::Hevc {
8006 let muxer = match muxer {
8007 Some(Muxer::Mkv(mkv)) => mkv,
8008 Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
8009 none => {
8010 let hvcc = hevc_params(au, ten_bit)?;
8011 let sound = audio.zip(packets.take());
8012 let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create_hevc(
8013 out,
8014 &HevcParams {
8015 width: meta.width,
8016 height: meta.height,
8017 frame_rate: meta.frame_rate,
8018 hvcc: &hvcc,
8019 language: source_language.map(str::to_owned),
8020 colour: (settings.hdr.transfer != HdrTransfer::Sdr).then_some(source_colour),
8021 light: (settings.hdr.transfer != HdrTransfer::Sdr)
8022 .then(|| crate::mux::hdr_light(&settings.hdr)),
8023 },
8024 sound,
8025 std::mem::take(subs),
8026 )?)) else {
8027 unreachable!("just inserted a Matroska muxer")
8028 };
8029 mkv.set_chapters(&settings.chapters)?;
8030 mkv
8031 }
8032 };
8033 return muxer.write_frame(&sample, key);
8034 }
8035 let muxer = match muxer {
8036 Some(Muxer::Mp4(mp4)) => mp4,
8037 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
8038 none => {
8039 let hvcc = hevc_params(au, ten_bit)?;
8040 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_hevc(
8041 out,
8042 &HevcParams {
8043 width: meta.width,
8044 height: meta.height,
8045 frame_rate: meta.frame_rate,
8046 hvcc: &hvcc,
8047 // mp4 does not state a picture's language yet.
8048 language: None,
8049 colour: None,
8050 light: None,
8051 },
8052 audio,
8053 )?)) else {
8054 unreachable!("just inserted an mp4 muxer")
8055 };
8056 // The same `colr` rule as AV1's: the colour a 10-bit SDR export
8057 // declares, which the bitstream's VUI states as well.
8058 if source_colour != Tags::default() {
8059 mp4.set_colour(source_colour);
8060 }
8061 if settings.hdr.transfer != HdrTransfer::Sdr {
8062 mp4.set_hdr(&settings.hdr);
8063 }
8064 mp4
8065 }
8066 };
8067 return muxer.write_coded_sample(&sample, key);
8068 }
8069 if settings.format.is_av1() {
8070 // Every AV1 stream opens on a keyframe, and a keyframe carries the
8071 // sequence header the track has to declare: an encoder that handed back
8072 // neither has produced nothing a decoder can start. The same header goes
8073 // into a `CodecPrivate` and into an `av1C` -- one record, two containers.
8074 fn params<'a>(
8075 meta: &VideoMeta,
8076 au: &'a [u8],
8077 language: Option<&str>,
8078 ten_bit: bool,
8079 colour: Tags,
8080 ) -> crate::Result<Av1Params<'a>> {
8081 Ok(Av1Params {
8082 width: meta.width,
8083 height: meta.height,
8084 frame_rate: meta.frame_rate,
8085 config: crate::mux::av1_sequence_header(au)
8086 .ok_or("the first coded picture carries no AV1 sequence header")?,
8087 language: language.map(str::to_owned),
8088 ten_bit,
8089 colour: (colour != Tags::default()).then_some(colour),
8090 })
8091 }
8092 if matches!(settings.format, Format::Av1 | Format::Webm) {
8093 let muxer = match muxer {
8094 Some(Muxer::Mkv(mkv)) => mkv,
8095 Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
8096 none => {
8097 // The sound with it, all of it: the Matroska muxer writes the
8098 // packets into the clusters of the pictures they play under.
8099 let sound = audio.zip(packets.take());
8100 let created = match settings.format {
8101 // WebM has no subtitle track to take ([`export_subtitles`]).
8102 Format::Webm => MkvMuxer::create_webm(out, &params(meta, au, source_language, ten_bit, source_colour)?, sound)?,
8103 _ => {
8104 MkvMuxer::create(
8105 out,
8106 &params(meta, au, source_language, ten_bit, source_colour)?,
8107 sound,
8108 std::mem::take(subs),
8109 )?
8110 }
8111 };
8112 let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(created)) else {
8113 unreachable!("just inserted a Matroska muxer")
8114 };
8115 mkv.set_chapters(&settings.chapters)?;
8116 mkv
8117 }
8118 };
8119 return muxer.write_frame(au, key);
8120 }
8121 let muxer = match muxer {
8122 Some(Muxer::Mp4(mp4)) => mp4,
8123 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
8124 none => {
8125 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1(
8126 out,
8127 &params(meta, au, None, ten_bit, source_colour)?,
8128 audio,
8129 )?)) else {
8130 unreachable!("just inserted an mp4 muxer")
8131 };
8132 // The `colr` box states the colour a 10-bit SDR export declares; an
8133 // export with no colour of its own keeps the output rule's box.
8134 if source_colour != Tags::default() {
8135 mp4.set_colour(source_colour);
8136 }
8137 mp4
8138 }
8139 };
8140 return muxer.write_coded_sample(au, key);
8141 }
8142 if !crate::mux::has_coded_slice(au) {
8143 return Ok(());
8144 }
8145 let muxer = match muxer {
8146 Some(Muxer::Mp4(mp4)) => mp4,
8147 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
8148 none => {
8149 let (sps, pps) = crate::mux::parameter_sets(au)
8150 .ok_or("the first coded picture carries no SPS/PPS")?;
8151 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create(
8152 out,
8153 &VideoParams {
8154 width: meta.width,
8155 height: meta.height,
8156 frame_rate: meta.frame_rate,
8157 sps,
8158 pps,
8159 },
8160 audio,
8161 )?)) else {
8162 unreachable!("just inserted an mp4 muxer")
8163 };
8164 // A file written in its source's own space says so, rather than
8165 // claiming the space its height would imply
8166 // ([`ExportSettings::keep_source_colour`]).
8167 if settings.keep_source_colour || source_colour != Tags::default() {
8168 mp4.set_colour(source_colour);
8169 }
8170 mp4
8171 }
8172 };
8173 muxer.write_video_au(au)
8174}
8175
8176/// The `hvcC` record of the first coded unit, or the refusal by name. Split out
8177/// because both HEVC containers ask it in the same words.
8178fn hevc_params(au: &[u8], ten_bit: bool) -> crate::Result<Vec<u8>> {
8179 crate::mux::hvcc_record_at(au, ten_bit)
8180 .ok_or_else(|| crate::Error::from("the first coded picture carries no HEVC VPS/SPS/PPS"))
8181}
8182
8183fn bitrate_for(meta: &VideoMeta) -> u64 {
8184 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;
8185 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)
8186}
8187
8188fn forced(var: &str) -> bool {
8189 crate::envcfg::var_os(var).is_some_and(|v| v == "1")
8190}
8191
8192/// Hardware where it is available, software everywhere else -- chosen once for
8193/// the whole export, so the stream never changes encoder mid-file. Both codecs
8194/// have both seats: an AV1 export runs on the plugin's VA-API encoder where the
8195/// GPU has one and on `rav1e` where it has not, which is the same pair H.264 has
8196/// had and the same silent fallback.
8197enum Enc {
8198 Hw(HwEncoder),
8199 Sw {
8200 encoder: Encoder,
8201 /// The access unit currently lent out: the encoder hands back an owned
8202 /// `Vec` where the seat's contract lends a slice, so one lives here
8203 /// between the two.
8204 au: Vec<u8>,
8205 },
8206 /// AV1 on the GPU, through the same plugin the H.264 seat uses.
8207 Av1Hw(HwEncoder),
8208 /// HEVC on the GPU, through that same plugin -- and intra-only there too,
8209 /// so this and [`Enc::Hevc`] write the same kind of file.
8210 HevcHw(HwEncoder, bool),
8211 /// AV1 software at 10 bits: `rav1e`'s 16-bit context. A picture that passes
8212 /// through the span untouched arrives as 16-bit planes off the 10-bit decode
8213 /// ([`Enc::encode_wide`]); an 8-bit picture (one composed on the way) is shifted
8214 /// up to the same scale in [`Enc::encode`].
8215 Av1Sw16 {
8216 context: rav1e::Context<u16>,
8217 ready: std::collections::VecDeque<(Vec<u8>, bool)>,
8218 au: Vec<u8>,
8219 flushed: bool,
8220 scratch: [Vec<u16>; 3],
8221 },
8222 Av1Sw {
8223 context: rav1e::Context<u8>,
8224 /// Temporal units the encoder has finished but the caller has not
8225 /// collected: `rav1e` reorders and may hand back several at once, while
8226 /// this interface is one picture in, one unit out (the plugin's own
8227 /// `ready` queue exists for the same reason).
8228 ready: std::collections::VecDeque<(Vec<u8>, bool)>,
8229 /// The unit currently lent out, for the same reason `Sw` owns one.
8230 au: Vec<u8>,
8231 flushed: bool,
8232 },
8233 /// HEVC, intra-only and software: `ec-h265` codes every picture an IDR
8234 /// carrying its own VPS/SPS/PPS. A batch of frames codes on as many lane
8235 /// encoders as there are pictures, and each encoder's wavefront splits
8236 /// whatever cores the lanes leave over -- the same shape as the seat it
8237 /// replaced, the cores spent on frames and inside one picture at the same
8238 /// time. Asked for by [`ExportSettings::intra_only`].
8239 Hevc(HevcEnc),
8240 /// HEVC, I+P GOPs, software: `ec-h265`'s sequence coder on a worker thread.
8241 /// The default HEVC seat ([`Enc::open_hevc_gop`]).
8242 HevcGop(HevcGop),
8243 /// ProRes, software: `ec-prores` codes one whole frame per call (its own
8244 /// worker threads inside), so one picture in is one sample out. The 4:2:0
8245 /// pictures of the walk are widened to 10 bits and chroma-upsampled to the
8246 /// profile's layout ([`crate::prores_out`]).
8247 ProRes {
8248 encoder: ec_prores::ProResEncoder,
8249 /// The sample currently lent out.
8250 au: Vec<u8>,
8251 /// 4:4:4 profiles (4444, 4444 XQ) code full chroma.
8252 full_chroma: bool,
8253 },
8254}
8255
8256/// The intra HEVC seat. Frames arrive one at a time (the export walk is one
8257/// picture per timeline frame) and are held until there is a lane for each,
8258/// then coded in parallel and queued in **display order**. `ec-h265`'s
8259/// wavefront spreads one picture across the workers it is given and the lanes
8260/// spread the frames across the machine, so decode and render keep filling
8261/// the next batch while this one codes -- a seat that coded one picture at a
8262/// time would serialize the whole walk behind its encoder (measured: 7.4 fps
8263/// against 11.8 at 1080p on the same box, which is the regression this
8264/// batching exists to prevent).
8265///
8266/// corner-cut: a batch of display-size planes sits in memory (~3 MB a frame
8267/// at 1080p, so ~37 MB at 12 lanes) and the tail of a timeline is coded on
8268/// fewer lanes than the middle. Upgrade path is a pipeline that keeps every
8269/// lane fed from a decoder running ahead of the encoder rather than a batch
8270/// barrier.
8271struct HevcEnc {
8272 /// Display-size I420 pictures waiting for a lane, in display order. The
8273 /// encoder pads to its own coded grid, so nothing is pre-padded here.
8274 pending: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)>,
8275 /// Coded access units not yet collected, in the same order.
8276 ready: std::collections::VecDeque<Vec<u8>>,
8277 /// The unit currently lent out, for the reason `Sw` owns one: the encoder
8278 /// hands back an owned `Vec`, the seat's contract lends a slice.
8279 au: Vec<u8>,
8280 /// One encoder per lane. `ec-h265` is stateless from picture to picture
8281 /// (every picture is an IDR), so a lane coding frame *n* needs nothing
8282 /// the other lanes know.
8283 lanes: Vec<HevcEncoder>,
8284 /// The display width the planes arrive at; the height lives in each
8285 /// encoder's config, where the coded grid is derived from it.
8286 width: usize,
8287 /// Whether the lanes code at 10 bits: `pending` then holds little-endian
8288 /// 16-bit samples, which [`HevcEnc::code_batch`] reads back.
8289 ten_bit: bool,
8290}
8291
8292impl Enc {
8293 /// Which seat this *is*, said the way [`video_label`] says it -- so the
8294 /// name a running export shows is the name the card showed, or the honest
8295 /// difference where the probe and the open disagreed.
8296 fn label(&self) -> &'static str {
8297 match self {
8298 Self::Hw(_) => video_label(Format::Mp4, true, false),
8299 Self::Sw { .. } => video_label(Format::Mp4, false, false),
8300 Self::Av1Hw(_) => video_label(Format::Av1, true, false),
8301 Self::Av1Sw { .. } | Self::Av1Sw16 { .. } => video_label(Format::Av1, false, false),
8302 Self::HevcHw(_, intra) => video_label(Format::Hevc, true, *intra),
8303 Self::Hevc(_) => video_label(Format::Hevc, false, true),
8304 Self::HevcGop(_) => video_label(Format::Hevc, false, false),
8305 Self::ProRes { .. } => video_label(Format::ProRes, false, true),
8306 }
8307 }
8308
8309 /// The ProRes seat's codec parameters (the sample entry's fourcc rides in
8310 /// the extradata); `None` for every other seat.
8311 fn prores_params(&self) -> Option<&ec_core::registry::CodecParameters> {
8312 match self {
8313 Self::ProRes { encoder, .. } => Some(ec_core::registry::Encoder::codec_parameters(encoder)),
8314 _ => None,
8315 }
8316 }
8317
8318 /// `ten_bit` is [`wide_ten_bit`]'s answer; it means something to AV1 and HEVC only.
8319 /// `colour` is what the file declares, in the bitstream as well as the container.
8320 fn open(
8321 meta: &VideoMeta,
8322 settings: &ExportSettings,
8323 ten_bit: bool,
8324 colour: ColorDescription,
8325 ) -> crate::Result<Self> {
8326 // Which *codec* the picture is, not which container it goes in: both AV1
8327 // formats run the same encoder, and so do both HEVC ones.
8328 if settings.format.is_av1() {
8329 return Self::open_av1(meta, settings, ten_bit, colour);
8330 }
8331 if settings.format.is_hevc() {
8332 return Self::open_hevc(meta, settings, ten_bit, colour);
8333 }
8334 if settings.format.is_prores() {
8335 return Self::open_prores(meta, settings, colour);
8336 }
8337 // A caller's number goes through the same clamp as the computed one: a
8338 // zero bitrate switches the software encoder's lookahead on, which would
8339 // break the one-picture-per-call contract `encode` documents below.
8340 let bitrate = bitrate_of(meta, settings);
8341 // The plugin wants an exact rational, and the muxer already picks one
8342 // that is exact at every rate we can read -- `fps * 1000 / 1000` would
8343 // hand 24000/1001 over as a rounded 23.976, which is the same
8344 // truncation the container timing had.
8345 crate::mux::frame_timing(meta.frame_rate)?;
8346 if let Some(hw) = hw_seat(meta, settings)? {
8347 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware (VA-API plugin)"); }
8348 return Ok(Self::Hw(hw));
8349 }
8350 if settings.qp.is_some() {
8351 return Err(QP_SOFTWARE_REFUSAL.into());
8352 }
8353 // H.264 codes 16x16 macroblocks, and ec-h264's floor is the
8354 // macroblock itself -- the old encoder took any positive even size.
8355 // Named here, where a card can show it, rather than let the encoder's
8356 // error surface from inside an export already under way.
8357 if meta.width < 16 || meta.height < 16 {
8358 return Err(format!(
8359 "{}x{} cannot be written as H.264: the picture is smaller \
8360 than one 16x16 macroblock",
8361 meta.width, meta.height
8362 )
8363 .into());
8364 }
8365 // 4:2:0 addresses its conformance window in *chroma* samples, so an odd
8366 // picture cannot be cropped back to itself -- and an odd dimension has
8367 // no chroma plane of its own to begin with. Named rather than padded to
8368 // something a decoder would then show a column of: the same refusal the
8369 // HEVC seat makes, and x264's and ffmpeg's own for 4:2:0 H.264.
8370 if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) {
8371 return Err(format!(
8372 "{}x{} cannot be written as H.264: 4:2:0 needs even dimensions",
8373 meta.width, meta.height
8374 )
8375 .into());
8376 }
8377 let mut cfg = EncoderConfig::new(meta.width, meta.height);
8378 cfg.framerate = meta.frame_rate as f32;
8379 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;
8380 // Two seconds between key frames, and no B-frames on either path: the
8381 // muxer times everything by duration alone, which reordering would
8382 // break. A proxy asks for one frame a GOP, which is every frame its own
8383 // starting point ([`ExportSettings::intra_only`]).
8384 cfg.gop_size = match settings.intra_only {
8385 true => 1,
8386 false => gop_frames(meta, settings).unwrap_or((meta.frame_rate * 2.0).round().max(1.0) as u32),
8387 };
8388 // Fast, the rung a fallback is allowed to cost -- the cheaper arm of
8389 // the preset ladder, the one the old seat's own S1 also picked when its
8390 // Balanced rung halved the rate for the same bitrate.
8391 cfg.preset = Preset::Fast;
8392 // 8x8 transform off. At this rung it is half the pure-encode cost
8393 // (17.2 ms/frame against 35.1 at 720p across all cores, measured at
8394 // the swap) for at most 0.7 dB BD-PSNR -- against an old seat that ran
8395 // Constrained Baseline and never had the transform in the first
8396 // place. The export stays Main-profile CABAC, which is where the
8397 // quality over the old seat lives; a constant-QP mode would be the
8398 // place to revisit the rung whole.
8399 cfg.transform_8x8 = false;
8400 let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?;
8401 Ok(Self::Sw {
8402 encoder,
8403 au: Vec::new(),
8404 })
8405 }
8406
8407 /// The AV1 pair. The hardware seat is the plugin's, opened by a symbol of
8408 /// its own (`vh_enc_av1_open`) so a plugin built before AV1 encode existed
8409 /// simply has none and this falls through -- the same "no" a GPU without an
8410 /// AV1 encode entrypoint gives, and the same silent fallback either way.
8411 ///
8412 /// It is **asked for by name**, which is the one place this pair does not
8413 /// mirror the H.264 one: the vendored cros-codecs AV1 encoder hung the GPU
8414 /// on this project's own radeonsi box -- `engine_hw: operation failed`,
8415 /// then an amdgpu hard recovery and a lost context, measured 2026-08-10
8416 /// exporting the 720p fixture. A software encoder that takes half a minute
8417 /// is a worse export than a hardware one; a driver reset is not an export
8418 /// at all. So [`EncoderSeat::Auto`] takes `rav1e` here and only
8419 /// [`EncoderSeat::Hardware`] -- a person picking the GPU for AV1 on the
8420 /// card, under a row that names the risk -- enters the plugin's seat. It
8421 /// was an env pin (`VE_HW_AV1=1`) until the card could ask, which is a
8422 /// switch nobody exporting a film would ever find.
8423 ///
8424 /// corner-cut: the upgrade path is a driver this was reproduced against (or a
8425 /// cros-codecs release that fixes it) plus a probe encode of one frame at
8426 /// open, after which `Auto` can prefer hardware the way H.264 does.
8427 fn open_av1(
8428 meta: &VideoMeta,
8429 settings: &ExportSettings,
8430 ten_bit: bool,
8431 colour: ColorDescription,
8432 ) -> crate::Result<Self> {
8433 let bitrate = bitrate_of(meta, settings);
8434 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
8435 // Two seconds between keyframes, as the H.264 seat does: a seek may only
8436 // land on one, and this is what a cluster of the Matroska file is.
8437 let gop = gop_frames(meta, settings).map_or_else(|| (meta.frame_rate * 2.0).round().max(1.0) as u64, u64::from);
8438 // The 10-bit seat is software: the GPU encode is 8-bit only.
8439 let hw = match ten_bit {
8440 true => None,
8441 false => hw_seat(meta, settings)?,
8442 };
8443 if let Some(hw) = hw {
8444 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); }
8445 return Ok(Self::Av1Hw(hw));
8446 }
8447 if settings.qp.is_some() {
8448 return Err(QP_SOFTWARE_REFUSAL.into());
8449 }
8450 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software AV1 (rav1e)"); }
8451 // Seconds per frame, which is what `frame_timing` already has as an
8452 // exact rational -- 1001/24000 rather than a rounded 23.976.
8453 let mut cfg = rav1e::EncoderConfig {
8454 width: meta.width as usize,
8455 height: meta.height as usize,
8456 bit_depth: if ten_bit { 10 } else { 8 },
8457 chroma_sampling: rav1e::prelude::ChromaSampling::Cs420,
8458 time_base: rav1e::prelude::Rational::new(u64::from(fps_den), u64::from(fps_num)),
8459 ..Default::default()
8460 };
8461 cfg.min_key_frame_interval = gop;
8462 cfg.max_key_frame_interval = gop;
8463 cfg.bitrate = bitrate.min(i32::MAX as u64) as i32;
8464 // The fastest preset, with the settings that matter for speed at that
8465 // preset. Tiles spread one frame over the cores (one tile ran on a single
8466 // core); low latency drops the lookahead; CDEF and loop restoration are
8467 // off for speed (a 10 s 1080p export measured the same PSNR against the
8468 // source either way). Measured: 170 s before, about 17 s after, on a box
8469 // with load ~15. The `asm` feature in Cargo.toml is the other half.
8470 cfg.speed_settings = rav1e::prelude::SpeedSettings::from_preset(AV1_SPEED);
8471 cfg.tiles = AV1_TILES;
8472 cfg.low_latency = true;
8473 cfg.speed_settings.cdef = false;
8474 cfg.speed_settings.lrf = false;
8475 cfg.speed_settings.multiref = false;
8476 // What the sequence header says the samples mean, for the reason
8477 // [`video_signal_type`] gives: a container tag is the second answer a
8478 // decoder looks at, not the first. Written as rav1e's own enums rather
8479 // than the H.273 numbers -- the crate has no `from` for the code points,
8480 // and the output rule only ever picks one of these two spaces.
8481 let out = colour;
8482 cfg.pixel_range = rav1e::prelude::PixelRange::Limited;
8483 cfg.color_description = Some(match out.matrix {
8484 Matrix::Bt709 => rav1e::prelude::ColorDescription {
8485 color_primaries: rav1e::prelude::ColorPrimaries::BT709,
8486 transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT709,
8487 matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT709,
8488 },
8489 // A 10-bit SDR export of a BT.2020 source: the source's own space.
8490 Matrix::Bt2020Ncl => rav1e::prelude::ColorDescription {
8491 color_primaries: rav1e::prelude::ColorPrimaries::BT2020,
8492 transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT2020_10Bit,
8493 matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT2020NCL,
8494 },
8495 _ => rav1e::prelude::ColorDescription {
8496 color_primaries: rav1e::prelude::ColorPrimaries::BT601,
8497 transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT601,
8498 matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT601,
8499 },
8500 });
8501 let config = rav1e::Config::new()
8502 .with_encoder_config(cfg)
8503 .with_threads(std::thread::available_parallelism().map_or(1, |n| n.get()));
8504 if ten_bit {
8505 let context = config
8506 .new_context::<u16>()
8507 .map_err(|e| format!("software AV1 encoder: {e}"))?;
8508 return Ok(Self::Av1Sw16 {
8509 context,
8510 ready: std::collections::VecDeque::new(),
8511 au: Vec::new(),
8512 flushed: false,
8513 scratch: Default::default(),
8514 });
8515 }
8516 let context = config
8517 .new_context::<u8>()
8518 .map_err(|e| format!("software AV1 encoder: {e}"))?;
8519 Ok(Self::Av1Sw {
8520 context,
8521 ready: std::collections::VecDeque::new(),
8522 au: Vec::new(),
8523 flushed: false,
8524 })
8525 }
8526
8527 /// The HEVC pair: the plugin's VA-API seat where the GPU has one, and the
8528 /// software intra encoder everywhere else -- below the driver's 384x384
8529 /// floor, on a plugin too old to carry the symbol, on a GPU with no HEVC
8530 /// encode entrypoint. Silent either way, because both write the same kind
8531 /// of file.
8532 ///
8533 /// The default is I+P GOPs, on the hardware seat where there is one and on
8534 /// the software seat ([`Enc::open_hevc_gop`]) where there is not. With
8535 /// [`ExportSettings::intra_only`] it is intra: every picture an IDR, on the
8536 /// hardware seat where there is one and on the lanes below where there is
8537 /// not -- an intraframe master in the shape of ProRes or DNxHD, large
8538 /// files, every frame a cut point.
8539 ///
8540 /// The picture is coded at its own size and padded to whole minimum coding
8541 /// blocks *by the encoder*, which crops the padding back off with the SPS
8542 /// conformance window, so 1920x1080 is a legal export rather than a
8543 /// refusal.
8544 fn open_hevc(
8545 meta: &VideoMeta,
8546 settings: &ExportSettings,
8547 ten_bit: bool,
8548 colour: ColorDescription,
8549 ) -> crate::Result<Self> {
8550 // The muxers time by it and the mp4 one wants an exact rational: asked
8551 // here so an impossible rate fails before a frame is coded. The same
8552 // rational goes into the SPS's VUI, whose timing is also where the
8553 // encoder picks the level from.
8554 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
8555 // 4:2:0 addresses its conformance window in *chroma* samples, so an odd
8556 // picture cannot be cropped back to itself -- and an odd dimension has
8557 // no chroma plane of its own to begin with. Named rather than padded to
8558 // something a decoder would then show a column of.
8559 if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) {
8560 return Err(format!(
8561 "{}x{} cannot be written as HEVC: 4:2:0 needs even dimensions",
8562 meta.width, meta.height
8563 )
8564 .into());
8565 }
8566 // The GPU seat is 8-bit only, so a 10-bit export is software.
8567 let hw = match ten_bit {
8568 true => None,
8569 false => hw_seat(meta, settings)?,
8570 };
8571 if let Some(hw) = hw {
8572 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware HEVC (VA-API plugin)"); }
8573 return Ok(Self::HevcHw(hw, settings.intra_only));
8574 }
8575 if !settings.intra_only {
8576 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC I+P (ec-h265)"); }
8577 return Self::open_hevc_gop(meta, settings, (fps_num, fps_den), ten_bit, colour);
8578 }
8579 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC intra (ec-h265)"); }
8580 // The cores are split between the lanes and the wavefront inside one:
8581 // twelve lanes of one worker each on this box's twelve threads,
8582 // fewer lanes on a smaller machine with a wider wavefront each.
8583 let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
8584 let lane_count = cores.clamp(1, HEVC_LANES);
8585 let per_lane = cores.div_ceil(lane_count);
8586 let mut lanes = Vec::with_capacity(lane_count);
8587 for _ in 0..lane_count {
8588 let mut cfg = HevcEncoderConfig::new(meta.width, meta.height);
8589 cfg.bit_depth = if ten_bit { 10 } else { 8 };
8590 // The bitrate row a user picked, mapped through the same measured
8591 // anchor as before ([`hevc_qp`]) and held: a *quality* dial, not a
8592 // rate controller. The encoder's own per-picture target-bits mode
8593 // would chase the number with a correction pass -- named headroom,
8594 // not behaviour this seat takes silently.
8595 cfg.rate_control = RateControl::ConstantQp(settings.qp.map_or_else(|| hevc_qp(meta, settings), |qp| qp as i32));
8596 cfg.timing = Some((fps_den, fps_num));
8597 cfg.video_signal_type = Some(video_signal_type(colour));
8598 apply_hdr(&mut cfg, settings);
8599 cfg.speed = settings.hevc_speed.unwrap_or_default().preset();
8600 cfg.threads = per_lane;
8601 lanes.push(HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?);
8602 }
8603 Ok(Self::Hevc(HevcEnc {
8604 pending: Vec::new(),
8605 ready: std::collections::VecDeque::new(),
8606 au: Vec::new(),
8607 lanes,
8608 width: meta.width as usize,
8609 ten_bit,
8610 }))
8611 }
8612
8613 /// The ProRes seat: the profile's encoder at the picture's size, tagged with
8614 /// the colour the file declares. Progressive, no alpha.
8615 fn open_prores(meta: &VideoMeta, settings: &ExportSettings, colour: ColorDescription) -> crate::Result<Self> {
8616 if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) {
8617 return Err(format!(
8618 "{}x{} cannot be written as ProRes from a 4:2:0 picture: it needs even dimensions",
8619 meta.width, meta.height
8620 )
8621 .into());
8622 }
8623 let profile = settings.prores_profile;
8624 let mut cfg = ec_prores::EncoderConfig::new(profile.codec(), meta.width, meta.height);
8625 let (primaries, transfer, matrix) = colour.codes();
8626 cfg.color = ec_core::frame::ColorInfo {
8627 primaries: primaries as u8,
8628 transfer: transfer as u8,
8629 matrix: matrix as u8,
8630 full_range: false,
8631 };
8632 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software ProRes (ec-prores)"); }
8633 let encoder = ec_prores::ProResEncoder::new(cfg).map_err(|e| format!("ProRes encoder: {e}"))?;
8634 Ok(Self::ProRes { encoder, au: Vec::new(), full_chroma: profile.is_444() })
8635 }
8636
8637 /// One 10-bit picture of 16-bit planes, at 10-bit scale, in and at most one
8638 /// access unit out. Asked only of the 10-bit seat, which [`wide_ten_bit`] opens
8639 /// with the same answer the export loop checks.
8640 fn encode_wide(
8641 &mut self,
8642 y: &[u16],
8643 u: &[u16],
8644 v: &[u16],
8645 width: u32,
8646 height: u32,
8647 ) -> crate::Result<Option<(&[u8], bool)>> {
8648 match self {
8649 Self::Av1Sw16 { context, ready, au, .. } => {
8650 submit_av1_16(context, ready, au, [y, u, v], width, height)
8651 }
8652 Self::HevcGop(gop) if gop.ten_bit => {
8653 gop.push_wide(y, u, v, width, height)?;
8654 Ok(pop_gop(gop))
8655 }
8656 Self::ProRes { encoder, au, full_chroma } => {
8657 let frame =
8658 crate::prores_out::upsampled_frame(y, u, v, width as usize, height as usize, *full_chroma)?;
8659 *au = encoder.encode(&frame).map_err(|e| format!("ProRes encode: {e}"))?;
8660 Ok(Some((&au[..], true)))
8661 }
8662 Self::Hevc(hevc) if hevc.ten_bit => {
8663 hevc.pending.push((le_bytes(y), le_bytes(u), le_bytes(v)));
8664 if hevc.pending.len() >= hevc.lanes.len() {
8665 hevc.code_batch()?;
8666 }
8667 Ok(pop_hevc(hevc))
8668 }
8669 _ => Err("a 10-bit picture needs a 10-bit seat".into()),
8670 }
8671 }
8672
8673 /// Whether this is a software HEVC seat coding at 10 bits.
8674 fn hevc_ten_bit(&self) -> bool {
8675 match self {
8676 Self::HevcGop(gop) => gop.ten_bit,
8677 Self::Hevc(hevc) => hevc.ten_bit,
8678 _ => false,
8679 }
8680 }
8681
8682 /// One picture in, at most one access unit out, and whether that unit is one
8683 /// a decoder may be started from -- which only the Matroska muxer asks, the
8684 /// mp4 one reading its own sync flag off the IDR slice.
8685 ///
8686 /// The H.264 seat keeps the contract structurally: `ec-h264` buffers
8687 /// nothing -- no lookahead, and B pictures coded as none -- so one call is
8688 /// one access unit by construction. The HEVC seat's lanes hold a small
8689 /// batch of pictures until there is a lane for each, so it says "at most
8690 /// one" and means it; the old H.264 seat only kept the contract because
8691 /// its GOP-buffering lookahead needed a zero bitrate and this path was
8692 /// always CBR.
8693 fn encode(
8694 &mut self,
8695 y: &[u8],
8696 u: &[u8],
8697 v: &[u8],
8698 width: u32,
8699 height: u32,
8700 intra: bool,
8701 ) -> crate::Result<Option<(&[u8], bool)>> {
8702 // A composed 8-bit picture on the 10-bit HEVC seat: shifted up to the
8703 // seat's scale, the same shift the AV1 10-bit seat makes.
8704 if self.hevc_ten_bit() {
8705 let up = |p: &[u8]| p.iter().map(|&v| u16::from(v) << 2 | u16::from(v) >> 6).collect::<Vec<u16>>();
8706 let (y, u, v) = (up(y), up(u), up(v));
8707 return self.encode_wide(&y, &u, &v, width, height);
8708 }
8709 if let Self::ProRes { encoder, au, full_chroma } = self {
8710 // A composed 8-bit picture: widened to 10 bits and upsampled in one pass.
8711 let frame =
8712 crate::prores_out::upsampled_frame_8(y, u, v, width as usize, height as usize, *full_chroma)?;
8713 *au = encoder.encode(&frame).map_err(|e| format!("ProRes encode: {e}"))?;
8714 return Ok(Some((&au[..], true)));
8715 }
8716 match self {
8717 Self::Av1Hw(hw) => {
8718 let au = hw.encode(y, u, v, width, height, false)?;
8719 // What the *bitstream* says, not what was asked for: an AV1
8720 // keyframe carries the sequence header, which is the same mark
8721 // `demux` reads a sync point off. A driver that emitted one
8722 // unasked is then still a seek target, and one that skipped a
8723 // requested keyframe cannot be mistaken for a decoder's start.
8724 Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
8725 }
8726 Self::Av1Sw16 {
8727 context,
8728 ready,
8729 au,
8730 scratch,
8731 ..
8732 } => {
8733 // An 8-bit picture on the 10-bit seat: each sample scaled up to
8734 // the same range (255 maps to 1023, not 1020).
8735 let (w, h) = (width as usize, height as usize);
8736 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
8737 for (dst, (src, n)) in scratch.iter_mut().zip([(y, w * h), (u, cw * ch), (v, cw * ch)]) {
8738 dst.clear();
8739 dst.extend(src[..n].iter().map(|&s| {
8740 let s = u16::from(s);
8741 (s << 2) | (s >> 6)
8742 }));
8743 }
8744 let [sy, su, sv] = &*scratch;
8745 submit_av1_16(context, ready, au, [&sy[..], &su[..], &sv[..]], width, height)
8746 }
8747 Self::Av1Sw {
8748 context, ready, au, ..
8749 } => {
8750 let mut frame = context.new_frame();
8751 let (w, h) = (width as usize, height as usize);
8752 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
8753 frame.planes[0].copy_from_raw_u8(&y[..w * h], w, 1);
8754 frame.planes[1].copy_from_raw_u8(&u[..cw * ch], cw, 1);
8755 frame.planes[2].copy_from_raw_u8(&v[..cw * ch], cw, 1);
8756 if let Err(e) = context.send_frame(frame) {
8757 return Err(format!("software AV1 encode: {e}").into());
8758 }
8759 collect_av1(context, ready)?;
8760 Ok(pop_av1(ready, au))
8761 }
8762 Self::HevcHw(hw, intra) => Ok(hw
8763 .encode(y, u, v, width, height, *intra)?
8764 .map(|au| (au, hevc_irap(au)))),
8765 Self::Hevc(hevc) => {
8766 // The display-size planes are kept as they came: `ec-h265`
8767 // pads to its own coded grid and crops back through the SPS
8768 // conformance window.
8769 hevc.pending.push((y.to_vec(), u.to_vec(), v.to_vec()));
8770 if hevc.pending.len() >= hevc.lanes.len() {
8771 hevc.code_batch()?;
8772 }
8773 // Every intra AU is an IDR, so every one of them is a key
8774 // frame -- which is what an intraframe master means.
8775 Ok(pop_hevc(hevc))
8776 }
8777 Self::HevcGop(gop) => {
8778 gop.push(y, u, v, width, height)?;
8779 Ok(pop_gop(gop))
8780 }
8781 // A key frame is asked for on every picture where the file is an
8782 // intraframe one, and the flag says what was asked: the mp4 muxer
8783 // reads its own sync marks off the IDR slices either way, so this
8784 // is what a Matroska one would be told.
8785 Self::Hw(hw) => Ok(hw
8786 .encode(y, u, v, width, height, intra)?
8787 .map(|au| (au, intra))),
8788 Self::ProRes { .. } => unreachable!("the ProRes seat is handled before this match"),
8789 Self::Sw { encoder, au } => {
8790 // The key flag is what the bitstream says -- an IDR where the
8791 // GOP asked for one, every picture on an intraframe export --
8792 // which is what the hardware seat's `intra` carries too. The
8793 // planes go in as borrows; the old seat was handed a copy.
8794 let view = PictureView::i420(width, height, y, u, v);
8795 let coded = encoder
8796 .encode(&view)
8797 .map_err(|e| format!("software encode: {e}"))?;
8798 *au = coded.au;
8799 Ok(Some((&au[..], coded.key_frame)).filter(|(au, _)| !au.is_empty()))
8800 }
8801 }
8802 }
8803
8804 /// What a decoded buffer must look like to reach this seat without ever
8805 /// being read back -- `None` for every seat that reads bytes, which is both
8806 /// software encoders and the intra HEVC one.
8807 ///
8808 /// The AV1 hardware seat is left out on purpose: it is entered only when a
8809 /// person picks it by name because the vendored encoder reset this project's GPU
8810 /// ([`Enc::open_av1`]), and a path that cannot be measured is not one to
8811 /// widen.
8812 /// `&mut` because an isolated seat has to *ask* the process it lives in
8813 /// ([`crate::hwproc`]), which is a round trip on its socket.
8814 fn dma_want(&mut self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> {
8815 match self {
8816 Self::Hw(hw) | Self::HevcHw(hw, _) => hw.dma_want(meta.width, meta.height),
8817 _ => None,
8818 }
8819 }
8820
8821 /// One picture the decoder left on the GPU in, at most one access unit out.
8822 /// Same answer as [`Enc::encode`], including which units a decoder may be
8823 /// started from, because it is the same encoder -- only the picture took
8824 /// another way in.
8825 ///
8826 /// `intra` therefore carries here too, and not for symmetry's sake: a proxy
8827 /// of a file already small enough is coded at that file's own size
8828 /// ([`crate::proxy::size_for`]), which is the one case where an intraframe
8829 /// export's decoder and encoder agree on a surface and the buffer goes
8830 /// straight across. An access unit marked as no sync point there would give
8831 /// a stand-in whose whole reason to exist is that every frame is one.
8832 fn encode_dma(&mut self, dma: &DmaFrame, intra: bool) -> crate::Result<Option<(&[u8], bool)>> {
8833 match self {
8834 Self::Hw(hw) => Ok(hw.encode_dma(dma, intra)?.map(|au| (au, intra))),
8835 Self::HevcHw(hw, intra) => Ok(hw.encode_dma(dma, *intra)?.map(|au| (au, hevc_irap(au)))),
8836 // Unreachable through [`Enc::dma_want`], which is the only thing
8837 // that puts a span's decoder on this path.
8838 _ => Err("this encoder takes pictures as bytes, not as buffers".into()),
8839 }
8840 }
8841
8842 /// End of stream; call until it returns `None`.
8843 fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> {
8844 match self {
8845 Self::Av1Hw(hw) => {
8846 let au = hw.drain()?;
8847 Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
8848 }
8849 Self::Av1Sw16 {
8850 context,
8851 ready,
8852 au,
8853 flushed,
8854 ..
8855 } => {
8856 if !*flushed {
8857 *flushed = true;
8858 context.flush();
8859 collect_av1(context, ready)?;
8860 }
8861 Ok(pop_av1(ready, au))
8862 }
8863 Self::Av1Sw {
8864 context,
8865 ready,
8866 au,
8867 flushed,
8868 } => {
8869 if !*flushed {
8870 *flushed = true;
8871 context.flush();
8872 collect_av1(context, ready)?;
8873 }
8874 Ok(pop_av1(ready, au))
8875 }
8876 Self::HevcHw(hw, _) => Ok(hw.drain()?.map(|au| (au, hevc_irap(au)))),
8877 // The tail batch: fewer frames than lanes, coded on as many
8878 // encoders as there are frames left.
8879 Self::Hevc(hevc) => {
8880 if !hevc.pending.is_empty() {
8881 hevc.code_batch()?;
8882 }
8883 Ok(pop_hevc(hevc))
8884 }
8885 Self::HevcGop(gop) => {
8886 gop.finish()?;
8887 Ok(pop_gop(gop))
8888 }
8889 Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))),
8890 // Nothing is held back: every picture `encode` took already came
8891 // back with its access unit, so end of stream is the empty answer.
8892 Self::Sw { .. } | Self::ProRes { .. } => Ok(None),
8893 }
8894 }
8895}
8896
8897impl HevcEnc {
8898 /// The whole pending batch, one frame per lane, collected back in the
8899 /// order it went out -- `std::thread::scope`, because the encode borrows
8900 /// the planes and the lanes rather than copying them again. A panic inside
8901 /// a lane comes back as an error rather than unwinding the export thread.
8902 fn code_batch(&mut self) -> crate::Result<()> {
8903 let width = self.width;
8904 let chroma = width / 2;
8905 let pending = std::mem::take(&mut self.pending);
8906 let ten_bit = self.ten_bit;
8907 let coded: Vec<crate::Result<Vec<u8>>> = std::thread::scope(|scope| {
8908 let lanes: Vec<_> = self
8909 .lanes
8910 .iter()
8911 .zip(pending.iter())
8912 .map(|(encoder, (y, cb, cr))| {
8913 scope.spawn(move || {
8914 let coded = if ten_bit {
8915 let samples = |p: &[u8]| -> Vec<u16> {
8916 p.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect()
8917 };
8918 let (y, cb, cr) = (samples(y), samples(cb), samples(cr));
8919 encoder.encode_idr_samples(&y, width, &cb, chroma, &cr, chroma)
8920 } else {
8921 encoder.encode_idr_planes(y, width, cb, chroma, cr, chroma)
8922 };
8923 coded
8924 .map(|coded| coded.au)
8925 .map_err(|e| crate::Error::from(format!("software HEVC encode: {e}")))
8926 })
8927 })
8928 .collect();
8929 lanes
8930 .into_iter()
8931 .map(|lane| {
8932 lane.join()
8933 .unwrap_or_else(|_| Err("an HEVC encode lane panicked".into()))
8934 })
8935 .collect()
8936 });
8937 for au in coded {
8938 self.ready.push_back(au?);
8939 }
8940 Ok(())
8941 }
8942}
8943
8944/// The oldest coded intra AU, lent out under the same "valid until the next
8945/// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key
8946/// flag is not a guess.
8947fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> {
8948 hevc.au = hevc.ready.pop_front()?;
8949 Some((&hevc.au[..], true))
8950}
8951
8952/// The longest GOP the HEVC seat asks for, in pictures. `ec-h265` codes GOPs
8953/// concurrently only up to this length, and the sequence coder's own limit is
8954/// 256; a 60 fps export is 60 pictures and a faster one takes the serial path.
8955const HEVC_GOP_MAX_KEYINT: usize = 64;
8956
8957/// The longest key interval `ec-h265` codes, in pictures; a `keyframe_s` past it is capped here.
8958const HEVC_KEYINT_MAX: usize = 256;
8959
8960impl Enc {
8961 /// The HEVC I+P seat: `ec-h265`'s sequence coder, an IDR once a second at
8962 /// the picture's own rate with P pictures between, on a worker thread.
8963 ///
8964 /// The export walk pushes one picture at a time and the encoder pulls its
8965 /// frames from an iterator, so the two meet on a bounded channel: the walk
8966 /// is never more than one GOP ahead of the worker. The encoder codes whole
8967 /// GOPs concurrently on [`default_threads`](ec_h265::encoder::default_threads)
8968 /// workers, which is at most six, and hands the pictures back in order.
8969 ///
8970 /// Rate: an explicit bitrate row goes to bitrate control at that rate, the
8971 /// same number the H.264 seat codes at. No bitrate is the automatic quality
8972 /// row, constant QP at [`HEVC_GOP_QP`]: a quality default of its own, not
8973 /// the intra seat's [`hevc_qp`], whose anchor is measured on intra pictures.
8974 fn open_hevc_gop(
8975 meta: &VideoMeta,
8976 settings: &ExportSettings,
8977 (fps_num, fps_den): (u32, u32),
8978 ten_bit: bool,
8979 colour: ColorDescription,
8980 ) -> crate::Result<Self> {
8981 let keyint = gop_frames(meta, settings).map_or_else(|| hevc_gop_keyint(meta.frame_rate), |g| (g as usize).clamp(2, HEVC_KEYINT_MAX));
8982 let mut cfg = HevcEncoderConfig::new(meta.width, meta.height);
8983 cfg.bit_depth = if ten_bit { 10 } else { 8 };
8984 cfg.rate_control = match (settings.qp, settings.bitrate) {
8985 (Some(qp), _) => RateControl::ConstantQp(qp as i32),
8986 (None, Some(_)) => RateControl::Bitrate {
8987 kbps: (bitrate_of(meta, settings) / 1000).max(1) as u32,
8988 fps: meta.frame_rate,
8989 },
8990 (None, None) => RateControl::ConstantQp(HEVC_GOP_QP),
8991 };
8992 cfg.keyint = keyint;
8993 cfg.threads = ec_h265::encoder::default_threads();
8994 cfg.timing = Some((fps_den, fps_num));
8995 cfg.video_signal_type = Some(video_signal_type(colour));
8996 apply_hdr(&mut cfg, settings);
8997 cfg.speed = settings.hevc_speed.unwrap_or_default().preset();
8998 let encoder = HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?;
8999 let (frames_tx, frames_rx) = sync_channel::<VideoFrame>(keyint);
9000 let (au_tx, coded) = std::sync::mpsc::channel::<(Vec<u8>, bool)>();
9001 // The P pictures refer to a second picture parameter set, which the
9002 // samples do not keep: the first unit carries it, so the record the
9003 // container builds from that unit holds it.
9004 let p_pps = encoder.p_picture_parameter_set();
9005 let worker = thread::Builder::new()
9006 .name("ec-h265-gop".into())
9007 .spawn(move || {
9008 let mut picture = 0usize;
9009 encoder
9010 .encode_sequence_with(frames_rx, |pic| {
9011 // Every GOP opens on an IDR, so a picture's key flag is
9012 // its place in the sequence.
9013 let key = picture.is_multiple_of(keyint);
9014 let au = if picture == 0 {
9015 with_parameter_set(pic.au, &p_pps)
9016 } else {
9017 pic.au
9018 };
9019 picture += 1;
9020 // A closed receiver is an export dropped part way: the
9021 // rest is unwanted, and draining it is not an error.
9022 let _ = au_tx.send((au, key));
9023 Ok(())
9024 })
9025 .map_err(|e| e.to_string())
9026 })
9027 .map_err(|e| format!("HEVC software encoder: {e}"))?;
9028 Ok(Self::HevcGop(HevcGop {
9029 frames: Some(frames_tx),
9030 worker: Some(worker),
9031 coded,
9032 ready: std::collections::VecDeque::new(),
9033 au: Vec::new(),
9034 ten_bit,
9035 }))
9036 }
9037}
9038
9039/// The GOP the I+P seat codes at this frame rate: an IDR about a second apart.
9040fn hevc_gop_keyint(frame_rate: f64) -> usize {
9041 (frame_rate.round() as usize).clamp(2, HEVC_GOP_MAX_KEYINT)
9042}
9043
9044/// What an HEVC export codes as, in the words an export start names: the I+P
9045/// GOP and its key interval and rate, or `intra-only`. `None` for any other
9046/// format. The rate is the bitrate the file aims at, or, with no bitrate given,
9047/// the quality mode the automatic row codes at: constant QP ([`HEVC_GOP_QP`]), named
9048/// with its number and with how to ask for a fixed rate instead.
9049pub fn hevc_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<String> {
9050 if !settings.format.is_hevc() {
9051 return None;
9052 }
9053 if settings.intra_only {
9054 return Some(match (settings.qp, settings.bitrate) {
9055 (Some(qp), _) => format!("intra-only, constant QP {qp}"),
9056 (None, Some(_)) => "intra-only".to_string(),
9057 (None, None) => format!(
9058 "intra-only, constant quality QP {} on the software seat (the GPU seat codes at the automatic rate); pass bitrate_kbps for a fixed rate",
9059 hevc_qp(meta, settings)
9060 ),
9061 });
9062 }
9063 let seconds = gop_frames(meta, settings).map_or_else(|| hevc_gop_keyint(meta.frame_rate), |g| g as usize) as f64 / meta.frame_rate;
9064 let every = if (seconds - seconds.round()).abs() < 1e-6 {
9065 format!("{} s", seconds.round() as u64)
9066 } else {
9067 format!("{seconds:.2} s")
9068 };
9069 let rate = match (settings.qp, settings.bitrate) {
9070 (Some(qp), _) => format!("constant QP {qp}"),
9071 (None, Some(_)) => rate_words(bitrate_of(meta, settings) / 1000),
9072 (None, None) => format!("constant quality QP {HEVC_GOP_QP}; pass bitrate_kbps for a fixed rate"),
9073 };
9074 Some(format!("I+P GOP ({every} keyframes), {rate}"))
9075}
9076
9077/// What an AV1 export codes as, in the words an export start names. AV1 is always
9078/// coded at a bitrate, so with none given the automatic target is named as one
9079/// (chosen from the picture size and frame rate). `None` for any other format.
9080pub fn av1_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<String> {
9081 if !settings.format.is_av1() {
9082 return None;
9083 }
9084 if let Some(qp) = settings.qp {
9085 return Some(format!("constant QP {qp}"));
9086 }
9087 let rate = rate_words(bitrate_of(meta, settings) / 1000);
9088 Some(match settings.bitrate {
9089 Some(_) => format!("average bitrate {rate}"),
9090 None => format!("average bitrate {rate} chosen from the picture size and frame rate; pass bitrate_kbps for a fixed rate"),
9091 })
9092}
9093
9094/// A rate in kilobits a second, in the words a reply uses: `4 Mb/s` on a whole megabit, `6.2 Mb/s`
9095/// above one, else `850 kb/s`.
9096fn rate_words(kbps: u64) -> String {
9097 if kbps.is_multiple_of(1000) {
9098 format!("{} Mb/s", kbps / 1000)
9099 } else if kbps >= 1000 {
9100 format!("{:.1} Mb/s", kbps as f64 / 1000.0)
9101 } else {
9102 format!("{kbps} kb/s")
9103 }
9104}
9105
9106/// The words an export start names when the source's chroma is reduced to 4:2:0 on
9107/// the way out, e.g. `VP9 4:4:4 source: chroma reduced to 4:2:0 for export`. `codec`
9108/// and `chroma` are the source's; the chroma is read off the stream
9109/// ([`Demuxer::chroma`]). `None` where nothing is reduced: a 4:2:0 or grey source,
9110/// or a sound-only format, which has no picture to reduce.
9111pub fn chroma_reduction_words(codec: Codec, chroma: Chroma, settings: &ExportSettings) -> Option<String> {
9112 let format = match chroma {
9113 Chroma::C422 => "4:2:2",
9114 Chroma::C444 => "4:4:4",
9115 _ => return None,
9116 };
9117 if !settings.format.has_video() {
9118 return None;
9119 }
9120 Some(format!("{} {format} source: chroma reduced to 4:2:0 for export", codec.name()))
9121}
9122
9123/// The I+P seat's state: the worker running the sequence coder, the channel
9124/// the frames go to it on, and the access units it has handed back.
9125struct HevcGop {
9126 /// The frames for the worker, in display order. `None` once the sequence
9127 /// has ended, which is what lets the worker finish its last GOP.
9128 frames: Option<SyncSender<VideoFrame>>,
9129 worker: Option<thread::JoinHandle<Result<(), String>>>,
9130 /// Access units and their key flags, in coding order, which is display order.
9131 coded: Receiver<(Vec<u8>, bool)>,
9132 /// Units collected from `coded` and not yet handed to the caller.
9133 ready: std::collections::VecDeque<(Vec<u8>, bool)>,
9134 /// The unit currently lent out, for the reason `Sw` owns one.
9135 au: Vec<u8>,
9136 /// Whether the sequence codes at 10 bits: its frames are I010 then.
9137 ten_bit: bool,
9138}
9139
9140impl HevcGop {
9141 fn push(&mut self, y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> crate::Result<()> {
9142 let frame = i420_frame(y, u, v, width, height)?;
9143 self.send(frame)
9144 }
9145
9146 /// One 10-bit picture of 16-bit samples, as the I010 frame the 10-bit sequence takes.
9147 fn push_wide(&mut self, y: &[u16], u: &[u16], v: &[u16], width: u32, height: u32) -> crate::Result<()> {
9148 let frame = i010_frame(y, u, v, width, height)?;
9149 self.send(frame)
9150 }
9151
9152 fn send(&mut self, frame: VideoFrame) -> crate::Result<()> {
9153 if self
9154 .frames
9155 .as_ref()
9156 .is_some_and(|tx| tx.send(frame).is_ok())
9157 {
9158 self.collect();
9159 return Ok(());
9160 }
9161 // The worker has stopped on its own: its error is the answer.
9162 self.finish()?;
9163 Err("the HEVC encoder stopped before the export ended".into())
9164 }
9165
9166 /// Ends the sequence and waits for the worker's last GOP.
9167 fn finish(&mut self) -> crate::Result<()> {
9168 self.frames = None;
9169 if let Some(worker) = self.worker.take() {
9170 match worker.join() {
9171 Ok(Ok(())) => {}
9172 Ok(Err(e)) => return Err(format!("software HEVC encode: {e}").into()),
9173 Err(_) => return Err("the HEVC encoder thread panicked".into()),
9174 }
9175 }
9176 self.collect();
9177 Ok(())
9178 }
9179
9180 fn collect(&mut self) {
9181 while let Ok(unit) = self.coded.try_recv() {
9182 self.ready.push_back(unit);
9183 }
9184 }
9185}
9186
9187/// One I420 picture at the display size, as the sequence coder takes it.
9188fn i420_frame(y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> crate::Result<VideoFrame> {
9189 let (w, h) = (width as usize, height as usize);
9190 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
9191 let planes = vec![
9192 ec_core::frame::Plane::new(y[..w * h].to_vec(), w),
9193 ec_core::frame::Plane::new(u[..cw * ch].to_vec(), cw),
9194 ec_core::frame::Plane::new(v[..cw * ch].to_vec(), cw),
9195 ];
9196 VideoFrame::try_new(ec_core::frame::PixelFormat::I420, width, height, planes)
9197 .map_err(|e| format!("HEVC frame: {e}").into())
9198}
9199
9200/// One 10-bit I010 picture at the display size: 16-bit little-endian samples, the
9201/// stride in bytes, as the sequence coder takes it.
9202fn i010_frame(y: &[u16], u: &[u16], v: &[u16], width: u32, height: u32) -> crate::Result<VideoFrame> {
9203 let (w, h) = (width as usize, height as usize);
9204 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
9205 let planes = vec![
9206 ec_core::frame::Plane::new(le_bytes(&y[..w * h]), w * 2),
9207 ec_core::frame::Plane::new(le_bytes(&u[..cw * ch]), cw * 2),
9208 ec_core::frame::Plane::new(le_bytes(&v[..cw * ch]), cw * 2),
9209 ];
9210 VideoFrame::try_new(ec_core::frame::PixelFormat::I010, width, height, planes)
9211 .map_err(|e| format!("HEVC frame: {e}").into())
9212}
9213
9214/// Little-endian bytes of 16-bit samples.
9215fn le_bytes(samples: &[u16]) -> Vec<u8> {
9216 samples.iter().flat_map(|s| s.to_le_bytes()).collect()
9217}
9218
9219/// `au` with `nal` (one Annex-B unit) placed before its first coded slice, so
9220/// after the parameter sets that open the unit. `au` comes back as it went in
9221/// where it has no slice.
9222fn with_parameter_set(au: Vec<u8>, nal: &[u8]) -> Vec<u8> {
9223 let starts = (0..au.len().saturating_sub(3)).filter(|&i| au[i..i + 3] == [0, 0, 1]);
9224 for start in starts {
9225 // The NAL unit type is the six bits after the forbidden bit.
9226 if (au[start + 3] >> 1) & 0x3F < 32 {
9227 // A four-byte start code keeps its leading zero in front of the new unit.
9228 let at = if start > 0 && au[start - 1] == 0 {
9229 start - 1
9230 } else {
9231 start
9232 };
9233 let mut out = Vec::with_capacity(au.len() + nal.len());
9234 out.extend_from_slice(&au[..at]);
9235 out.extend_from_slice(nal);
9236 out.extend_from_slice(&au[at..]);
9237 return out;
9238 }
9239 }
9240 au
9241}
9242
9243fn pop_gop(gop: &mut HevcGop) -> Option<(&[u8], bool)> {
9244 let (au, key) = gop.ready.pop_front()?;
9245 gop.au = au;
9246 Some((&gop.au[..], key))
9247}
9248/// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a
9249/// user picked -- the card has no QP control and this codec has no rate control,
9250/// so the two are joined by measurement rather than promised to each other.
9251///
9252/// The encoder codes ~0.6 bits per pixel at QP 27 ([`HEVC_BPP_AT_27`], measured
9253/// on the 720p and 1080p benches to within 4% of each other), and a step of 6 QP
9254/// is a factor of two in rate, which is the classic HEVC relation. So the QP
9255/// that would land on a target is `27 + 6 * log2(0.6 / target)` -- and it is
9256/// clamped, because this is a *quality* dial and not a rate controller: below QP
9257/// 22 the file grows without a picture to show for it, and past QP 40 an
9258/// intra-only frame goes blocky in a way no bitrate row asked for. A 1080p30
9259/// timeline at the automatic 6.2 Mbps therefore codes at QP 40 and comes out
9260/// bigger than that, which is what "intra-only, large files" on the format row
9261/// means: the row buys quality, not a size.
9262fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 {
9263 let pixels = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate;
9264 let target = bitrate_of(meta, settings) as f64 / pixels.max(1.0);
9265 let qp = 27.0 + 6.0 * (HEVC_BPP_AT_27 / target.max(f64::MIN_POSITIVE)).log2();
9266 (qp.round() as i32).clamp(HEVC_QP_MIN, HEVC_QP_MAX)
9267}
9268
9269/// What the *bitstream* says the samples mean, in the words a sequence header
9270/// spells them -- the same H.273 code points [`crate::mux`] writes into the
9271/// container, from the same colour the export declares there ([`source_sdr_colour`] or the
9272/// [`ColorDescription::output`] rule), so the two halves of a file cannot drift apart.
9273///
9274/// This exists because a container tag is not enough: libavcodec takes the
9275/// bitstream's answer first, and a stream that says nothing is "unspecified",
9276/// which renders BT.601 -- a visible shift on a 709 export that a player reads
9277/// from the wrong matrix. Every export is limited range, which is what
9278/// `video_full_range_flag = false` says here.
9279fn video_signal_type(colour: ColorDescription) -> HevcVideoSignalType {
9280 let (primaries, transfer, matrix) = colour.codes();
9281 HevcVideoSignalType {
9282 // "Unspecified", which is what every encoder here writes: the field is
9283 // the analogue system a picture came off, and none of these did.
9284 video_format: 5,
9285 video_full_range_flag: false,
9286 colour_description: Some(HevcColourDescription {
9287 colour_primaries: primaries as u8,
9288 transfer_characteristics: transfer as u8,
9289 matrix_coeffs: matrix as u8,
9290 }),
9291 }
9292}
9293
9294/// The HDR extras of an HEVC export, in the bitstream: BT.2020's chroma sample
9295/// location (type 2, top-left) in the VUI, and the mastering display and content
9296/// light SEIs where [`ExportSettings::hdr`] gives them. Nothing for an SDR export,
9297/// whose stream stays byte-identical to what it was.
9298fn apply_hdr(cfg: &mut HevcEncoderConfig, settings: &ExportSettings) {
9299 let hdr = &settings.hdr;
9300 if hdr.transfer == HdrTransfer::Sdr {
9301 return;
9302 }
9303 cfg.chroma_sample_loc = Some((2, 2));
9304 cfg.mastering_display = hdr.mastering_display.map(|m| ec_h265_syntax::sei::MasteringDisplay {
9305 display_primaries: m.primaries,
9306 white_point: m.white_point,
9307 max_luminance: m.max_luminance,
9308 min_luminance: m.min_luminance,
9309 });
9310 cfg.content_light.max_cll = hdr.max_cll.map(f32::from);
9311 cfg.content_light.max_fall = hdr.max_fall.map(f32::from);
9312}
9313
9314/// The colour a 10-bit export declares when every clip is SDR in one matrix: that
9315/// matrix, limited range, the source's own rather than the output rule's. `None`
9316/// for a mixed timeline, an HDR one or an empty one, which keep the rule.
9317fn source_sdr_colour(colours: &[ColorDescription]) -> Option<ColorDescription> {
9318 let first = *colours.first()?;
9319 let same = colours
9320 .iter()
9321 .all(|c| c.transfer == Transfer::Sdr && c.matrix == first.matrix);
9322 (same && first.transfer == Transfer::Sdr).then_some(ColorDescription {
9323 matrix: first.matrix,
9324 transfer: Transfer::Sdr,
9325 full_range: false,
9326 })
9327}
9328
9329/// Whether a software export is written at 10 bits: the setting where it names a
9330/// depth, the source's own where it does not. AV1 and HEVC have the choice --
9331/// H.264 is 8-bit here -- and a depth the file cannot be is refused. The HEVC
9332/// hardware seat is 8-bit, so a 10-bit HEVC export falls back to software
9333/// ([`open_hevc`]).
9334fn wide_ten_bit(
9335 settings: &ExportSettings,
9336 source_ten_bit: impl FnOnce() -> bool,
9337) -> crate::Result<bool> {
9338 // ProRes is coded at 10 bits whatever the setting says (it has no 8-bit
9339 // sample), so the walk keeps 10-bit sources at 10 bits.
9340 if settings.format.is_prores() {
9341 return Ok(true);
9342 }
9343 if !settings.format.is_av1() && !settings.format.is_hevc() {
9344 return Ok(false);
9345 }
9346 // An HDR transfer is a 10-bit claim: 8 bits of PQ bands visibly.
9347 if settings.hdr.transfer != HdrTransfer::Sdr {
9348 return match settings.video_bit_depth {
9349 Some(8) => Err("an HDR export is 10-bit: PQ and HLG are not carried in 8 bits".into()),
9350 Some(10) | None => Ok(true),
9351 Some(bits) => Err(format!("an AV1 or HEVC export is 8 or 10 bits, not {bits}").into()),
9352 };
9353 }
9354 match settings.video_bit_depth {
9355 None => Ok(source_ten_bit()),
9356 Some(8) => Ok(false),
9357 Some(10) => Ok(true),
9358 Some(bits) => Err(format!("an AV1 or HEVC export is 8 or 10 bits, not {bits}").into()),
9359 }
9360}
9361
9362/// The colour an HDR HEVC export declares, or `None` for an SDR export; `Err`
9363/// where the settings ask for HDR of something that cannot carry it.
9364fn hdr_colour_of(settings: &ExportSettings) -> crate::Result<Option<ColorDescription>> {
9365 let hdr = &settings.hdr;
9366 let Some(colour) = hdr.transfer.colour() else {
9367 if hdr.mastering_display.is_some() || hdr.max_cll.is_some() || hdr.max_fall.is_some() {
9368 return Err("mastering display and MaxCLL/MaxFALL need an HDR transfer (PQ or HLG)".into());
9369 }
9370 return Ok(None);
9371 };
9372 if !settings.format.is_hevc() {
9373 return Err(format!("{} cannot be written as HDR: only HEVC is", settings.format.name()).into());
9374 }
9375 if settings.keep_source_colour {
9376 return Err("an HDR export cannot also keep its source's colour".into());
9377 }
9378 Ok(Some(colour))
9379}
9380
9381fn transfer_name(t: Transfer) -> &'static str {
9382 match t {
9383 Transfer::Sdr => "SDR",
9384 Transfer::Pq => "PQ",
9385 Transfer::Hlg => "HLG",
9386 }
9387}
9388
9389/// Every temporal unit `rav1e` has finished, moved into the queue in display
9390/// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is
9391/// through) are the two ways it says there is nothing more; `Encoded` means a
9392/// picture was coded but not yet packetised, which is a *keep asking* -- taking
9393/// it for an end leaves the tail of the export inside the encoder.
9394fn collect_av1<T: rav1e::prelude::Pixel>(
9395 context: &mut rav1e::Context<T>,
9396 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
9397) -> crate::Result<()> {
9398 use rav1e::prelude::{EncoderStatus, FrameType};
9399 loop {
9400 match context.receive_packet() {
9401 Ok(packet) => ready.push_back((packet.data, packet.frame_type == FrameType::KEY)),
9402 Err(EncoderStatus::Encoded) => {}
9403 Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()),
9404 Err(e) => return Err(format!("software AV1 encode: {e}").into()),
9405 }
9406 }
9407}
9408
9409/// The oldest finished unit, moved into the buffer that is lent out -- the same
9410/// "valid until the next call" contract the plugin's slice has.
9411fn pop_av1<'a>(
9412 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
9413 au: &'a mut Vec<u8>,
9414) -> Option<(&'a [u8], bool)> {
9415 let (unit, key) = ready.pop_front()?;
9416 *au = unit;
9417 Some((&au[..], key))
9418}
9419
9420/// One picture of 16-bit planes into the 10-bit `rav1e` context, and whatever
9421/// unit it finished. The planes are the picture's own size, 4:2:0.
9422fn submit_av1_16<'a>(
9423 context: &mut rav1e::Context<u16>,
9424 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
9425 au: &'a mut Vec<u8>,
9426 planes: [&[u16]; 3],
9427 width: u32,
9428 height: u32,
9429) -> crate::Result<Option<(&'a [u8], bool)>> {
9430 let (w, h) = (width as usize, height as usize);
9431 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
9432 let mut frame = context.new_frame();
9433 // A plane's rows sit `stride` apart from its origin, past any padding.
9434 let fill = |plane: &mut rav1e::prelude::Plane<u16>, src: &[u16], w: usize, h: usize| {
9435 let stride = plane.cfg.stride;
9436 let dst = plane.data_origin_mut();
9437 for (row, line) in src.chunks_exact(w).take(h).enumerate() {
9438 dst[row * stride..row * stride + w].copy_from_slice(line);
9439 }
9440 };
9441 fill(&mut frame.planes[0], &planes[0][..w * h], w, h);
9442 fill(&mut frame.planes[1], &planes[1][..cw * ch], cw, ch);
9443 fill(&mut frame.planes[2], &planes[2][..cw * ch], cw, ch);
9444 if let Err(e) = context.send_frame(frame) {
9445 return Err(format!("software AV1 encode: {e}").into());
9446 }
9447 collect_av1(context, ready)?;
9448 Ok(pop_av1(ready, au))
9449}
9450
9451/// A 10-bit plane narrowed to 8 bits for the composition that runs at 8 bits: the
9452/// same truncation [`crate::decode::narrow_av1`] makes on playback.
9453fn narrow_10(src: &[u16], dst: &mut Vec<u8>) {
9454 dst.clear();
9455 dst.extend(src.iter().map(|&s| (s >> 2) as u8));
9456}
9457
9458/// The frame as an 8-bit composition takes it: a 10-bit picture narrowed into
9459/// `scratch`, anything else as it came.
9460fn narrowed<'a>(frame: Frame<'a>, scratch: &'a mut [Vec<u8>; 3]) -> Frame<'a> {
9461 match frame {
9462 Frame::Wide(y, u, v, width, height) => {
9463 let [sy, su, sv] = scratch;
9464 narrow_10(y, sy);
9465 narrow_10(u, su);
9466 narrow_10(v, sv);
9467 Frame::Pixels(&sy[..], &su[..], &sv[..], width, height)
9468 }
9469 other => other,
9470 }
9471}
9472
9473/// I420 straight out of the decoder: the export never converts to BGRA and back,
9474/// which would cost two conversions and a generation of colour precision.
9475///
9476/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`,
9477/// which only speaks BGRA. A hardware decode that fails *before* the first
9478/// picture falls back to software, exactly as playback's does -- nothing has
9479/// been encoded yet, so the span can be taken over cleanly. One that fails
9480/// after the first picture fails the export, which then deletes the
9481/// half-written file: a restart there would re-encode what the muxer holds.
9482enum ClipDecoder {
9483 /// A stream, decoded on a thread of its own: the encode of picture *n* and
9484 /// the decode of picture *n + 1* are the two halves an export used to do in
9485 /// turns, each idle while the other worked. The channel is two pictures
9486 /// deep, so the decoder runs no further ahead than that (a 1080p I420
9487 /// picture is 3.1 MB) and a slow encoder still stops it.
9488 ///
9489 /// The thread is also where the plugin is *opened*: a VA-API session is not
9490 /// ours to hand between threads ([`crate::decode::open_worker_deferred`]
9491 /// keeps the same rule), which is why the open's error comes back down the
9492 /// channel rather than out of [`ClipDecoder::open`].
9493 Streamed(Streamed),
9494 /// A still image: one picture, handed out for as long as the span runs.
9495 /// It is decoded here rather than in `run`'s loop for the same reason the
9496 /// other two are opened there -- the span's pictures come from one place,
9497 /// and no thread can make one picture arrive sooner.
9498 Still(crate::decode::Still),
9499 /// A clip played backwards ([`Reversed`]): its pictures, last to first.
9500 Reversed(Box<Reversed>),
9501 /// An audio file playing as a picture: each `next` paints one visualizer
9502 /// frame from peaks already decoded ([`crate::decode::visualizer_i420`]).
9503 Visualizer {
9504 peaks: Vec<(f32, f32)>,
9505 width: u32,
9506 height: u32,
9507 fps: f64,
9508 next: u32,
9509 flags: u8,
9510 paint: u64,
9511 /// This seat's own painting scratch, kept for the whole export: the
9512 /// same reuse the playback worker's thread does.
9513 scratch: crate::decode::VizScratch,
9514 y: Vec<u8>,
9515 u: Vec<u8>,
9516 v: Vec<u8>,
9517 },
9518}
9519
9520/// One 8-bit picture owned: its three planes and the size.
9521type Owned = (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32);
9522
9523/// A clip's pictures in reverse ([`ClipDecoder::reversed`]).
9524struct Reversed {
9525 path: PathBuf,
9526 walk: crate::reverse::Walk,
9527 /// The block being served, oldest first: the next picture is the last one.
9528 block: Vec<Owned>,
9529 /// The picture last handed out, which `next` lends.
9530 current: Option<Owned>,
9531 /// The clip's deinterlace setting; `Field` makes the numbers above fields.
9532 deint: Deinterlace,
9533}
9534
9535impl Reversed {
9536 fn next(&mut self) -> crate::Result<Option<Frame<'_>>> {
9537 if self.block.is_empty() && !self.fill()? {
9538 return Ok(None);
9539 }
9540 self.current = self.block.pop();
9541 Ok(self
9542 .current
9543 .as_ref()
9544 .map(|(y, u, v, w, h)| Frame::Pixels(y, u, v, *w, *h)))
9545 }
9546
9547 /// Decodes the next block down, forwards, into `block`. `false` when the window
9548 /// has no frames left, or the file gave none.
9549 fn fill(&mut self) -> crate::Result<bool> {
9550 let Some((start, end)) = self.walk.next() else {
9551 return Ok(false);
9552 };
9553 let mut decoder = ClipDecoder::open_with(&self.path, start, None, None, false, self.deint)?;
9554 for _ in start..end {
9555 match decoder.next()? {
9556 Some(Frame::Pixels(y, u, v, w, h)) => {
9557 if self.block.is_empty() {
9558 // The pictures' real size is known now: hold as many as the
9559 // budget allows from the next block on.
9560 let bytes = y.len() + u.len() + v.len();
9561 self.walk.set_cap(crate::reverse::block_cap(bytes));
9562 }
9563 self.block.push((y.to_vec(), u.to_vec(), v.to_vec(), w, h));
9564 }
9565 Some(_) => return Err("a reversed clip's decoder produced no pixels".into()),
9566 None => break,
9567 }
9568 }
9569 Ok(!self.block.is_empty())
9570 }
9571}
9572
9573/// The planes of one 10-bit picture, borrowed from its seat: luma, the two
9574/// chroma planes, and the size.
9575type Wide16View<'a> = (&'a [u16], &'a [u16], &'a [u16], u32, u32);
9576
9577/// The receiving half of a decode thread, plus the picture it last handed out
9578/// -- which is what lets `next` keep lending planes rather than moving them.
9579///
9580/// The first two fields are in this order on purpose, and it is the order
9581/// [`crate::decode::FrameStream`] states for the same pair: Rust drops fields as
9582/// they are declared, so the receiver disconnects *first* -- the only thing that
9583/// wakes a decoder parked in a full `send` -- and the join inside
9584/// [`DecodeThread::drop`] runs second. The other way round is a hang and not a
9585/// slow path.
9586struct Streamed {
9587 frames: Receiver<crate::Result<Option<Yuv>>>,
9588 /// Held only to be dropped: joining is all it does, and it must happen
9589 /// after the receiver above (`_lib` in `crate::hw` is kept the same way).
9590 /// Its result is the software decoder a stopped span leaves behind, if any.
9591 _thread: DecodeThread<Option<Kept>>,
9592 current: Option<Yuv>,
9593 /// Whether the thread has said "no more pictures" in as many words. What
9594 /// separates a stream that ended from a thread that vanished: after this,
9595 /// the channel is disconnected because the decoder is *done*, and a further
9596 /// ask is end of stream rather than a failure.
9597 ended: bool,
9598 /// Where the decoder goes when this span is done with it, if it may be kept.
9599 park: Option<Park>,
9600}
9601
9602/// What a software decode thread leaves behind when it is stopped: the
9603/// decoder, and the pictures it had decoded past the last one its span took,
9604/// in order -- the ones the channel still held, then the ones it had not sent.
9605type Kept = (Box<SwDecoder>, VecDeque<Yuv>);
9606
9607/// The way back from a span's [`Streamed`] to the [`Parked`] lot: the lot, the
9608/// file, and the flag that asks the decode thread to stop at its next picture.
9609struct Park {
9610 lot: Arc<Parked>,
9611 path: PathBuf,
9612 stop: Arc<AtomicBool>,
9613}
9614
9615/// Software H.264 decoders from spans that have ended, kept so that the next
9616/// span of the same file can carry on from where they stopped instead of
9617/// seeking back to a sync sample and decoding the whole GOP in front of its in
9618/// point again (a long-GOP source pays up to a GOP per clip that way).
9619///
9620/// Only a decoder that is *resumable* is ever taken: see [`resumable`]. Hardware
9621/// sessions are never kept, since whether a span gets one is the hardware's
9622/// answer and not this lot's.
9623#[derive(Default)]
9624struct Parked(Mutex<VecDeque<ParkedDecoder>>);
9625
9626/// Most decoders kept at once. Each holds a demuxer and its reference pictures,
9627/// so the lot stays small: a dissolve needs two, and a multi-source edit a few.
9628const PARKED_MAX: usize = 4;
9629
9630/// One decoder in the lot: the file it reads, the decoder itself, and the
9631/// pictures it decoded that no span took (see [`Kept`]).
9632struct ParkedDecoder {
9633 path: PathBuf,
9634 decoder: Box<SwDecoder>,
9635 backlog: VecDeque<Yuv>,
9636}
9637
9638impl Parked {
9639 fn keep(&self, entry: ParkedDecoder) {
9640 let Ok(mut lot) = self.0.lock() else { return };
9641 lot.push_back(entry);
9642 while lot.len() > PARKED_MAX {
9643 lot.pop_front();
9644 }
9645 }
9646
9647 /// The decoder that can serve a span of `path` starting at `start`, taken
9648 /// out of the lot and wound forward to that picture: whatever it holds
9649 /// before `start` is dropped, and the rest is what the span decodes from.
9650 fn take(&self, path: &Path, start: u32) -> Option<ParkedDecoder> {
9651 let mut lot = self.0.lock().ok()?;
9652 let at = lot
9653 .iter()
9654 .position(|entry| entry.path == path && entry.serves(start))?;
9655 let mut entry = lot.remove(at)?;
9656 let start = i64::from(start);
9657 while entry.backlog.front().is_some()
9658 && entry.decoder.index() - (entry.backlog.len() as i64) < start
9659 {
9660 entry.backlog.pop_front();
9661 }
9662 entry.decoder.start = start as u32;
9663 Some(entry)
9664 }
9665}
9666
9667impl ParkedDecoder {
9668 /// Whether this decoder can serve a span starting at `start`: asked of the
9669 /// file itself, where a fresh decoder would seek to.
9670 fn serves(&self, start: u32) -> bool {
9671 let Ok((_, mut demuxer)) = Demuxer::open(&self.path) else {
9672 return false;
9673 };
9674 let restart = demuxer.seek_to_sync_at_or_before(start);
9675 resumable(
9676 self.decoder.index(),
9677 self.backlog.len(),
9678 self.decoder.origin(),
9679 restart,
9680 i64::from(start),
9681 )
9682 }
9683}
9684
9685/// Whether a decoder can carry on for a span starting at display frame `start`
9686/// instead of a fresh one opened there. `next` is the display index of the
9687/// picture it produces next, `backlog` how many decoded pictures sit before
9688/// that, unclaimed; `origin` is the sync sample it was started at, and
9689/// `restart` the sync sample a fresh decoder for `start` would start at.
9690///
9691/// Two things must hold. The span's first picture must still be held or not
9692/// yet decoded, since a decoder cannot go back. And the decoder must have been
9693/// started at the sample a fresh one would start at, so that it has read the
9694/// same access units from the same point and produces the same pictures -- a
9695/// later sync sample is a restart the decoder did not make, and one that is not
9696/// an IDR would be decoded from references the fresh one does not have.
9697fn resumable(next: i64, backlog: usize, origin: i64, restart: i64, start: i64) -> bool {
9698 next - (backlog as i64) <= start && restart == origin
9699}
9700
9701/// A decode thread, joined when its span's decoder is dropped -- the rule
9702/// [`crate::decode::Worker`] is written for: a thread abandoned mid
9703/// `vaInitialize` outlives the process, and Mesa's `atexit` handlers then free
9704/// the state it is still reading, which is a SIGSEGV at exit long after the
9705/// export succeeded.
9706struct DecodeThread<T = ()>(Option<thread::JoinHandle<T>>);
9707
9708impl<T> DecodeThread<T> {
9709 /// The thread's result, once it has finished. Joins it if it has not.
9710 fn finish(&mut self) -> Option<T> {
9711 self.0.take().and_then(|handle| handle.join().ok())
9712 }
9713}
9714
9715impl<T> Drop for DecodeThread<T> {
9716 fn drop(&mut self) {
9717 if let Some(handle) = self.0.take() {
9718 // The receiver is already gone (see `Streamed`'s field order), so a
9719 // decoder blocked on `send` has been woken and this waits only for
9720 // the thread to unwind its VA-API session.
9721 let _ = handle.join();
9722 }
9723 }
9724}
9725
9726impl Drop for Streamed {
9727 fn drop(&mut self) {
9728 let Some(park) = self.park.take() else {
9729 return;
9730 };
9731 // Ask the decoder to stop, then take what it sends until it does: its
9732 // next send is answered by this drain and its next look at the flag
9733 // ends it, dropping the sender, which is what the drain waits for.
9734 park.stop.store(true, Ordering::Relaxed);
9735 let mut backlog = VecDeque::new();
9736 // A GPU buffer is not kept: a hardware decoder is waiting on the
9737 // surfaces it has lent, and nothing here would hand them back.
9738 while let Ok(item) = self.frames.recv() {
9739 if let Ok(Some(frame @ (Yuv::Pixels { .. } | Yuv::Wide { .. }))) = item {
9740 backlog.push_back(frame);
9741 }
9742 }
9743 if let Some((decoder, rest)) = self._thread.finish().flatten() {
9744 backlog.extend(rest);
9745 park.lot.keep(ParkedDecoder {
9746 path: park.path,
9747 decoder,
9748 backlog,
9749 });
9750 }
9751 }
9752}
9753
9754/// One picture on its way from a decode thread to the encoder: its bytes, or
9755/// the GPU buffer they are still in.
9756enum Yuv {
9757 Pixels {
9758 y: Vec<u8>,
9759 u: Vec<u8>,
9760 v: Vec<u8>,
9761 width: u32,
9762 height: u32,
9763 },
9764 /// The same picture at 16 bits a sample, at 10-bit scale: what a 10-bit export
9765 /// encodes whole ([`Enc::encode_wide`]).
9766 Wide {
9767 y: Vec<u16>,
9768 u: Vec<u16>,
9769 v: Vec<u16>,
9770 width: u32,
9771 height: u32,
9772 },
9773 /// Never read back and never copied: a DRM-PRIME handle the encoder imports
9774 /// on the other side of the channel. Sending it is sending an integer, and
9775 /// what keeps the buffer from being decoded over is the channel's own depth
9776 /// (see [`crate::hw::HwSession::next_frame_dma`]).
9777 Dma(DmaFrame),
9778}
9779
9780impl Yuv {
9781 /// The decoder's own buffer copied out, which is what it costs to hand a
9782 /// picture to another thread when the pixels have to travel.
9783 fn pixels(y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> Self {
9784 Self::Pixels {
9785 y: y.to_vec(),
9786 u: u.to_vec(),
9787 v: v.to_vec(),
9788 width,
9789 height,
9790 }
9791 }
9792}
9793
9794/// What [`ExportHandle::stage`] calls a stabilised clip's shake being measured.
9795pub const MEASURING_SHAKE: &str = "Measuring shake";
9796
9797/// How a layer opened for an export measures a stabilised clip with no finished
9798/// analysis ([`LayerFeed::open`]): under this cancel flag, reporting to this
9799/// stage ([`Shared::measuring`]).
9800type Measure<'a> = (&'a AtomicBool, &'a AtomicU32);
9801
9802/// The luma of file frames `lo..hi` of `path` as a layer's decoder hands them to
9803/// [`LayerFeed::advance`] -- before the file's display turn and pixel stretch --
9804/// for the stabilise analysis, whose maps move those same planes. `each` takes
9805/// the frame number, the luma plane and its size, and stops the walk with `false`.
9806pub(crate) fn each_layer_luma(
9807 path: &Path,
9808 lo: u32,
9809 hi: u32,
9810 mut each: impl FnMut(u32, &[u8], u32, u32) -> bool,
9811) -> crate::Result<()> {
9812 let mut decoder = ClipDecoder::open(path, lo, None, None, false)?;
9813 for index in lo..hi {
9814 match decoder.next()? {
9815 Some(Frame::Pixels(y, _, _, w, h)) => {
9816 if !each(index, y, w, h) {
9817 break;
9818 }
9819 }
9820 Some(_) => return Err("stabilise: the decoder gave no 8-bit pixels".into()),
9821 None => break,
9822 }
9823 }
9824 Ok(())
9825}
9826
9827/// One picture as the export loop sees it: planes to grade and place, or a
9828/// buffer that goes straight into the encoder.
9829enum Frame<'a> {
9830 Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32),
9831 /// A 10-bit picture at 10-bit scale, which only a 10-bit export asks for.
9832 Wide(&'a [u16], &'a [u16], &'a [u16], u32, u32),
9833 Dma(&'a DmaFrame),
9834}
9835
9836impl ClipDecoder {
9837 /// A decoder for `path` from `start_frame`. `parked` is the lot a span's
9838 /// software decoder may be taken from and returned to; `None` never keeps one.
9839 fn open(
9840 path: &Path,
9841 start_frame: u32,
9842 want: Option<DmaWant>,
9843 parked: Option<&Arc<Parked>>,
9844 wide: bool,
9845 ) -> crate::Result<Self> {
9846 Self::open_with(path, start_frame, want, parked, wide, Deinterlace::Frame)
9847 }
9848
9849 /// [`open`](Self::open) for a clip with a deinterlace setting. `Field` over an
9850 /// interlaced file makes `start_frame` a field number and every picture a field.
9851 fn open_with(
9852 path: &Path,
9853 start_frame: u32,
9854 want: Option<DmaWant>,
9855 parked: Option<&Arc<Parked>>,
9856 wide: bool,
9857 deint: Deinterlace,
9858 ) -> crate::Result<Self> {
9859 // Before either decoder: an image is not a stream, so `start_frame`
9860 // means nothing to it -- every frame of a still span is the same
9861 // picture, which is what playback shows for it too.
9862 if crate::is_image(path) {
9863 return Ok(Self::Still(crate::decode::Still::open_at(path, start_frame)?));
9864 }
9865 let path = path.to_path_buf();
9866 let (tx, frames) = sync_channel(2);
9867 let stop = Arc::new(AtomicBool::new(false));
9868 let park = parked.map(|lot| Park {
9869 lot: Arc::clone(lot),
9870 path: path.clone(),
9871 stop: Arc::clone(&stop),
9872 });
9873 let thread_park = parked.map(|lot| (Arc::clone(lot), Arc::clone(&stop)));
9874 let handle = thread::Builder::new()
9875 .name("export-decode".into())
9876 .spawn(move || decode_stream(&path, start_frame, want, &tx, thread_park, wide, deint))?;
9877 Ok(Self::Streamed(Streamed {
9878 frames,
9879 _thread: DecodeThread(Some(handle)),
9880 current: None,
9881 ended: false,
9882 park,
9883 }))
9884 }
9885
9886 fn visualizer(
9887 path: &Path,
9888 stream: usize,
9889 start_frame: u32,
9890 (width, height): (u32, u32),
9891 fps: f64,
9892 flags: u8,
9893 paint: u64,
9894 ) -> crate::Result<Self> {
9895 let peaks = crate::waveform::peaks(path, stream, crate::decode::VIZ_BUCKETS_PER_SEC)
9896 .ok()
9897 .flatten()
9898 .unwrap_or_default();
9899 let fps = if fps.is_finite() && fps > 0.0 {
9900 fps
9901 } else {
9902 30.0
9903 };
9904 Ok(Self::Visualizer {
9905 peaks,
9906 width,
9907 height,
9908 fps,
9909 next: start_frame,
9910 flags,
9911 paint,
9912 scratch: crate::decode::VizScratch::default(),
9913 y: Vec::new(),
9914 u: Vec::new(),
9915 v: Vec::new(),
9916 })
9917 }
9918
9919 /// The pictures of `path` from file frame `top` down to `lo`, last to first:
9920 /// a clip played backwards. Decoded forwards a block at a time and served from
9921 /// the back, so the memory held is one block ([`crate::reverse`]), and always
9922 /// 8-bit software pictures -- the block is copied out of the decoder, which a GPU
9923 /// buffer or a 10-bit plane does not allow.
9924 fn reversed(path: &Path, top: u32, lo: u32, deint: Deinterlace) -> Self {
9925 let mut sync = crate::reverse::sync_frames(path);
9926 if deint == Deinterlace::Field {
9927 sync.iter_mut().for_each(|f| *f *= 2);
9928 }
9929 Self::Reversed(Box::new(Reversed {
9930 deint,
9931 path: path.to_path_buf(),
9932 walk: crate::reverse::Walk::new(
9933 sync,
9934 lo,
9935 top + 1,
9936 // Until a picture says how big they are: the biggest the engine takes.
9937 crate::reverse::block_cap(3840 * 2160 * 3 / 2),
9938 ),
9939 block: Vec::new(),
9940 current: None,
9941 }))
9942 }
9943
9944 /// The next picture, borrowed until the call after -- as tightly packed
9945 /// I420, or as the GPU buffer the decoder wrote it into.
9946 fn next(&mut self) -> crate::Result<Option<Frame<'_>>> {
9947 match self {
9948 Self::Still(still) => {
9949 let (y, u, v, width, height) = still.picture();
9950 Ok(Some(Frame::Pixels(y, u, v, width, height)))
9951 }
9952 Self::Reversed(reversed) => reversed.next(),
9953 Self::Visualizer {
9954 peaks,
9955 width,
9956 height,
9957 fps,
9958 next,
9959 flags,
9960 paint,
9961 scratch,
9962 y,
9963 u,
9964 v,
9965 } => {
9966 let (yy, uu, vv) = crate::decode::visualizer_i420(
9967 scratch,
9968 peaks,
9969 f64::from(*next) / *fps,
9970 *width,
9971 *height,
9972 *flags,
9973 *paint,
9974 );
9975 *y = yy;
9976 *u = uu;
9977 *v = vv;
9978 *next += 1;
9979 Ok(Some(Frame::Pixels(y, u, v, *width & !1, *height & !1)))
9980 }
9981 Self::Streamed(stream) if stream.ended => Ok(None),
9982 Self::Streamed(stream) => match stream.frames.recv() {
9983 Ok(Ok(Some(frame))) => Ok(Some(match stream.current.insert(frame) {
9984 Yuv::Pixels {
9985 y,
9986 u,
9987 v,
9988 width,
9989 height,
9990 } => Frame::Pixels(y, u, v, *width, *height),
9991 Yuv::Wide {
9992 y,
9993 u,
9994 v,
9995 width,
9996 height,
9997 } => Frame::Wide(y, u, v, *width, *height),
9998 Yuv::Dma(dma) => Frame::Dma(dma),
9999 })),
10000 Ok(Ok(None)) => {
10001 stream.ended = true;
10002 Ok(None)
10003 }
10004 Ok(Err(e)) => Err(e),
10005 Err(_) => Err("the decoder stopped without a picture or a reason".into()),
10006 },
10007 }
10008 }
10009}
10010
10011/// One span's decode, on its own thread: open the file (hardware if the plugin
10012/// will have it, software otherwise) and send every picture until the encoder
10013/// stops taking them.
10014///
10015/// Hardware that fails, before the first picture or after some, hands the rest
10016/// of the span to the software seat at the first picture not yet sent.
10017///
10018/// Every way this returns says which way it was, down the channel: a picture, an
10019/// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not
10020/// one of them -- a silent close is a panicked thread, and the receiver treats
10021/// it as the failure it is rather than as a source that ran out.
10022///
10023/// With `parked`, a software decode takes a parked decoder for this file when
10024/// one can serve `start_frame`, and a decoder that is asked to stop (its span
10025/// was dropped) is handed back: see [`Streamed`]'s drop.
10026fn decode_stream(
10027 path: &Path,
10028 start_frame: u32,
10029 want: Option<DmaWant>,
10030 tx: &SyncSender<crate::Result<Option<Yuv>>>,
10031 parked: Option<(Arc<Parked>, Arc<AtomicBool>)>,
10032 wide: bool,
10033 deint: Deinterlace,
10034) -> Option<Kept> {
10035 // A 10-bit export decodes in software: the hardware seat hands 8-bit planes.
10036 let opened = match forced("VE_SW") || wide {
10037 // The decode door's own gate ([`crate::decode::open_hw`]): a VP9 4:2:2 or 4:4:4
10038 // stream is never offered to the GPU, which would refuse it on stderr.
10039 false => crate::decode::open_hw(path, start_frame).map(|hw| Pictures::Hw(Box::new(hw))),
10040 true => None,
10041 };
10042 // Pictures decoded ahead of the span that a parked decoder still holds.
10043 let (mut decoder, mut backlog) = match opened {
10044 Some(hw) => (hw, VecDeque::new()),
10045 None => match parked
10046 .as_ref()
10047 .and_then(|(lot, _)| lot.take(path, start_frame))
10048 {
10049 Some(kept) => (Pictures::Sw(kept.decoder), kept.backlog),
10050 None => match Pictures::software(path, start_frame, wide, deint) {
10051 Ok(sw) => (sw, VecDeque::new()),
10052 Err(e) => {
10053 let _ = tx.send(Err(e));
10054 return None;
10055 }
10056 },
10057 },
10058 };
10059 // Pictures handed down the channel. Hardware that dies hands the rest of the
10060 // span to the software seat at `start_frame + decoded`: the first picture
10061 // not yet sent, so nothing already encoded is repeated.
10062 let mut decoded = 0u32;
10063 loop {
10064 // Asked to stop: the span is over, and a software decoder that has not
10065 // reached its end is what the next span may take up.
10066 if parked
10067 .as_ref()
10068 .is_some_and(|(_, stop)| stop.load(Ordering::Relaxed))
10069 {
10070 return match decoder {
10071 Pictures::Sw(sw) if sw.parkable() && !sw.flushed() => Some((sw, backlog)),
10072 _ => None,
10073 };
10074 }
10075 // Hardware that ends before its first picture has failed the same way
10076 // one that errors there has: the mid-GOP AV1 seek ends the stream with
10077 // nothing (see `decode::run_hw`), and it falls back here too.
10078 let next = match backlog.pop_front() {
10079 Some(frame) => Ok(Some(frame)),
10080 None => decoder.next(want),
10081 };
10082 let next = match next {
10083 Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(_)) => {
10084 Err("hardware gave no picture from the start frame".into())
10085 }
10086 other => other,
10087 };
10088 let frame = match next {
10089 Ok(Some(frame)) => frame,
10090 Ok(None) => {
10091 let _ = tx.send(Ok(None));
10092 return None;
10093 }
10094 Err(e) => {
10095 if matches!(decoder, Pictures::Hw(_)) {
10096 // Before the first picture, or after some: either way the
10097 // software seat takes the span from the first picture not yet
10098 // sent (`decoded` is 0 in the first case), so nothing is
10099 // encoded twice and nothing is skipped.
10100 if std::env::var_os("EDITH_DEBUG").is_some() || decoded > 0 { eprintln!(
10101 "export decode: hardware failed at frame {} ({e}); falling back to software",
10102 start_frame + decoded
10103 ); }
10104 match Pictures::software(path, start_frame + decoded, wide, deint) {
10105 Ok(sw) => {
10106 decoder = sw;
10107 continue;
10108 }
10109 Err(sw_refusal) => {
10110 let _ = tx.send(Err(sw_refusal));
10111 return None;
10112 }
10113 }
10114 }
10115 let _ = tx.send(Err(e));
10116 return None;
10117 }
10118 };
10119 // The consumer went away: the span ended early, or the export was
10120 // cancelled. Either way there is nothing left to decode for. A parked
10121 // span drains the channel before it drops it, so this is not reached.
10122 if tx.send(Ok(Some(frame))).is_err() {
10123 return None;
10124 }
10125 decoded += 1;
10126 }
10127}
10128
10129/// The stream decoders, on the thread that opened them.
10130enum Pictures {
10131 Hw(Box<HwSession>),
10132 /// `ec-h264`, on this thread.
10133 Sw(Box<SwDecoder>),
10134 /// `ec-av1`, on a thread of its own -- see [`Av1Stream`].
10135 Av1(Box<Av1Stream>),
10136}
10137
10138impl Pictures {
10139 /// The software seat for `path`: `ec-h264` for H.264, `ec-av1` on its own
10140 /// thread for AV1, and the pulled seats (`ec-h265`, `ec-vp9`, `ec-vp8`) for the
10141 /// rest. The codec is read once here, so it decides which seat takes the file.
10142 fn software(path: &Path, start_frame: u32, wide: bool, deint: Deinterlace) -> crate::Result<Self> {
10143 let (meta, demuxer) = Demuxer::open(path)?;
10144 match meta.codec {
10145 Codec::H264 => Ok(Self::Sw(Box::new(SwDecoder::new(demuxer, start_frame, wide, deint)))),
10146 Codec::Av1 => Ok(Self::Av1(Box::new(Av1Stream::spawn(demuxer, start_frame, wide)?))),
10147 _ => Ok(Self::Sw(Box::new(SwDecoder::open(path, start_frame, wide, deint)?))),
10148 }
10149 }
10150
10151 /// The next picture, owned, ready to cross the channel. `want` is what the
10152 /// export's encoder can read straight off the GPU: where the hardware
10153 /// decoder can hand such a buffer over there is no copy here at all, and
10154 /// everything else is the 3 MB memcpy out of the decoder's own buffer that
10155 /// buys the decode and the encode their overlap.
10156 fn next(&mut self, want: Option<DmaWant>) -> crate::Result<Option<Yuv>> {
10157 match (self, want) {
10158 (Self::Hw(hw), Some(want)) => Ok(match hw.next_frame_dma(want)? {
10159 Some(HwPicture::Dma(dma)) => Some(Yuv::Dma(dma)),
10160 Some(HwPicture::Pixels(y, u, v, width, height)) => {
10161 Some(Yuv::pixels(y, u, v, width, height))
10162 }
10163 None => None,
10164 }),
10165 (Self::Hw(hw), None) => Ok(hw
10166 .next_frame()?
10167 .map(|(y, u, v, width, height)| Yuv::pixels(y, u, v, width, height))),
10168 (Self::Av1(av1), _) => av1.next(),
10169 (Self::Sw(sw), _) => {
10170 if !sw.advance()? {
10171 return Ok(None);
10172 }
10173 if let Some((y, u, v, width, height)) = sw.picture16() {
10174 return Ok(Some(Yuv::Wide {
10175 y: y.to_vec(),
10176 u: u.to_vec(),
10177 v: v.to_vec(),
10178 width,
10179 height,
10180 }));
10181 }
10182 let (y, u, v, width, height) = sw.picture();
10183 Ok(Some(Yuv::pixels(y, u, v, width, height)))
10184 }
10185 }
10186 }
10187}
10188
10189/// The software decoder one export span reads from: H.264 with its own reorder
10190/// and flush, or one of the pulled seats playback's spans read too.
10191struct SwDecoder {
10192 demuxer: Demuxer,
10193 /// The first display index the export takes. Pictures before it are decoded
10194 /// (the target references them) and then dropped.
10195 start: u32,
10196 seat: SwSeat,
10197}
10198
10199enum SwSeat {
10200 H264(Box<H264Seat>),
10201 /// `wide` is the 10-bit plane buffer when this seat decodes at 10 bits.
10202 Pulled {
10203 stream: Box<Pulled>,
10204 out: I420,
10205 wide: Option<Wide>,
10206 },
10207}
10208
10209struct H264Seat {
10210 decoder: H264Decoder,
10211 /// Display index of the next picture the decoder will produce. Signed: a
10212 /// sync sample inside what the edit list trims is before frame 0.
10213 index: i64,
10214 /// The display index the decoder started at (its sync sample), what
10215 /// [`resumable`] compares a later span's restart against.
10216 origin: i64,
10217 /// Set once the demuxer runs dry: `flush` has then released what the
10218 /// decoder's reorder still held, and only those pictures are left.
10219 flushed: bool,
10220 frame: Option<VideoFrame>,
10221 /// Whether the export is 10-bit, and the High 10 picture taken for it.
10222 wide: bool,
10223 deep: crate::decode::Deep,
10224 /// Deinterlaces an interlaced stream (a pass-through for every other).
10225 deint: crate::deinterlace::Deinterlacer,
10226 /// Pictures the deinterlacer released that `advance` has not handed over yet:
10227 /// the second field of a frame in field mode.
10228 pending: VecDeque<(i64, VideoFrame)>,
10229}
10230
10231impl SwDecoder {
10232 fn open(path: &Path, start_frame: u32, wide: bool, deint: Deinterlace) -> crate::Result<Self> {
10233 let (meta, mut demuxer) = Demuxer::open(path)?;
10234 // Decoding restarts at a sync sample, so pictures between it and the in
10235 // point are decoded (the target references them) and then dropped.
10236 let seat = match Pulled::open(meta.codec, &mut demuxer, start_frame, deint) {
10237 Some(stream) => SwSeat::Pulled {
10238 stream: Box::new(stream),
10239 out: I420::default(),
10240 // Only HEVC and the intra-only professional codecs have a 10-bit seat; the others narrow as they always did.
10241 wide: (wide && (matches!(meta.codec, Codec::Hevc | Codec::ProRes | Codec::Dnxhd) || (meta.codec == Codec::Raw && demuxer.bit_depth() >= 10))).then(Wide::default),
10242 },
10243 None if meta.codec == Codec::H264 => {
10244 SwSeat::H264(H264Seat::open(&mut demuxer, start_frame, wide, deint))
10245 }
10246 // AV1 never gets here: `Pictures::software` gives it `Av1Stream`.
10247 None => return Err(format!("{} has no export seat", meta.codec.name()).into()),
10248 };
10249 Ok(Self {
10250 demuxer,
10251 start: start_frame,
10252 seat,
10253 })
10254 }
10255
10256 /// Decodes up to and including the next picture at or after the in point.
10257 /// `false` at end of stream.
10258 fn advance(&mut self) -> crate::Result<bool> {
10259 match &mut self.seat {
10260 SwSeat::H264(seat) => seat.advance(&mut self.demuxer, self.start),
10261 SwSeat::Pulled { stream, out, wide } => loop {
10262 let next = match wide {
10263 Some(wide) => stream.next_wide(&mut self.demuxer, wide)?,
10264 None => stream.next(&mut self.demuxer, out)?,
10265 };
10266 let Some(due) = next else {
10267 return Ok(false);
10268 };
10269 if due >= i64::from(self.start) {
10270 return Ok(true);
10271 }
10272 },
10273 }
10274 }
10275
10276 /// The 10-bit planes of the picture `advance` stopped on, when this seat
10277 /// decodes at 10 bits; `None` otherwise.
10278 fn picture16(&self) -> Option<Wide16View<'_>> {
10279 match &self.seat {
10280 SwSeat::Pulled { wide: Some(w), .. } => Some((&w.y, &w.u, &w.v, w.width, w.height)),
10281 SwSeat::H264(s) if s.deep.in_wide => {
10282 let w = &s.deep.wide;
10283 Some((&w.y, &w.u, &w.v, w.width, w.height))
10284 }
10285 _ => None,
10286 }
10287 }
10288
10289 /// The picture `advance` stopped on, as planes and size.
10290 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
10291 match &self.seat {
10292 SwSeat::H264(seat) if seat.deep.on => {
10293 let n = &seat.deep.narrow;
10294 (&n.y, &n.u, &n.v, n.width, n.height)
10295 }
10296 SwSeat::H264(seat) => {
10297 let frame = seat.frame.as_ref().expect("advance stored a picture");
10298 let [y, u, v] = [&frame.planes[0], &frame.planes[1], &frame.planes[2]];
10299 debug_assert_eq!(y.stride, frame.width as usize, "padded luma plane");
10300 (&y.data, &u.data, &v.data, frame.width, frame.height)
10301 }
10302 SwSeat::Pulled { out, .. } => (&out.y, &out.u, &out.v, out.width, out.height),
10303 }
10304 }
10305}
10306
10307/// An AV1 software span: [`decode_av1`] runs on a thread of its own and sends
10308/// every picture down a channel two deep, the same shape [`Streamed`] gives a
10309/// stream decoded elsewhere. The thread is needed because `ec-av1` pushes its
10310/// pictures through a callback rather than handing them out one at a time.
10311struct Av1Stream {
10312 frames: Receiver<crate::Result<Option<Yuv>>>,
10313 /// Held only to be joined: field order matters, as it does for
10314 /// [`Streamed`] -- `frames` drops first and wakes a decoder parked in a
10315 /// full `send`, and the join runs after.
10316 _thread: DecodeThread,
10317 /// Whether the thread has said "no more pictures" in as many words.
10318 ended: bool,
10319}
10320
10321impl Av1Stream {
10322 fn spawn(demuxer: Demuxer, start_frame: u32, wide: bool) -> crate::Result<Self> {
10323 let (tx, frames) = sync_channel(2);
10324 let handle = thread::Builder::new()
10325 .name("export-decode-av1".into())
10326 .spawn(move || decode_av1(demuxer, start_frame, wide, &tx))?;
10327 Ok(Self {
10328 frames,
10329 _thread: DecodeThread(Some(handle)),
10330 ended: false,
10331 })
10332 }
10333
10334 fn next(&mut self) -> crate::Result<Option<Yuv>> {
10335 if self.ended {
10336 return Ok(None);
10337 }
10338 match self.frames.recv() {
10339 Ok(Ok(Some(frame))) => Ok(Some(frame)),
10340 Ok(Ok(None)) => {
10341 self.ended = true;
10342 Ok(None)
10343 }
10344 Ok(Err(e)) => Err(e),
10345 Err(_) => Err("the decoder stopped without a picture or a reason".into()),
10346 }
10347 }
10348}
10349
10350/// The chroma plane size `len` samples can be, for a `width` x `height` luma
10351/// picture: full (4:4:4), half the width (4:2:2) or a quarter (4:2:0, odd sizes
10352/// rounding up). `None` for any other count, which no decoder here produces.
10353pub(crate) fn chroma_shape(len: usize, width: usize, height: usize) -> Option<(usize, usize)> {
10354 let (half_w, half_h) = (width.div_ceil(2), height.div_ceil(2));
10355 [(width, height), (half_w, height), (half_w, half_h)]
10356 .into_iter()
10357 .find(|&(cw, ch)| cw * ch == len)
10358}
10359
10360/// A chroma plane of `cw` x `ch` samples averaged down to `ow` x `oh`, the
10361/// 4:2:0 size of the luma. A dimension that already matches is kept one sample
10362/// to one; one that is larger takes the mean of the (at most two) source
10363/// samples under each output sample, rounded to nearest. Samples keep the
10364/// depth they came in at, so a 10-bit picture averages in 10 bits and
10365/// [`crate::decode::narrow_av1`] shifts it as it would any other.
10366pub(crate) fn chroma_420<T: Copy + Into<u32>>(src: &[T], cw: usize, ch: usize, ow: usize, oh: usize) -> Vec<u32> {
10367 // The source run under output index `i` along one axis.
10368 let run = |src_len: usize, out_len: usize, i: usize| match src_len == out_len {
10369 true => (i, i + 1),
10370 false => (2 * i, (2 * i + 2).min(src_len)),
10371 };
10372 let mut out = Vec::with_capacity(ow * oh);
10373 for oy in 0..oh {
10374 let (y0, y1) = run(ch, oh, oy);
10375 for ox in 0..ow {
10376 let (x0, x1) = run(cw, ow, ox);
10377 let (mut sum, mut n) = (0u32, 0u32);
10378 for sy in y0..y1 {
10379 for sx in x0..x1 {
10380 sum += src[sy * cw + sx].into();
10381 n += 1;
10382 }
10383 }
10384 out.push((sum + n / 2) / n);
10385 }
10386 }
10387 out
10388}
10389
10390/// The AV1 software seat for the export: the same walk `decode::run_av1` makes
10391/// for playback, one chunk at a time. `ec-av1` takes a whole OBU stream, so the
10392/// demuxer's access units are gathered from one sync sample (a sequence header
10393/// leads it) up to the next, and each chunk decodes to its end -- its hidden
10394/// frames are references, and the frames they hold back in output order are
10395/// the tail. Shown pictures before `start_frame` are decoded and dropped.
10396///
10397/// Pictures are narrowed to 8-bit I420 by the same [`narrow_av1`] playback
10398/// uses, so an export and a playback of one file hand the encoder the same
10399/// planes. A 4:2:2 or 4:4:4 picture has its chroma averaged down to 4:2:0 first
10400/// ([`chroma_420`]), since the composer and every software encoder take I420 and
10401/// nothing else. A decode refusal ends the span with the error, after the
10402/// pictures already sent.
10403fn decode_av1(
10404 mut demuxer: Demuxer,
10405 start_frame: u32,
10406 wide: bool,
10407 tx: &SyncSender<crate::Result<Option<Yuv>>>,
10408) {
10409 let depth = demuxer.bit_depth();
10410 // A monochrome stream states it in its sequence header; see the chroma below.
10411 let gray = demuxer.chroma() == Some(Chroma::Gray);
10412 // Decoding restarts at a sync sample; see [`SwDecoder::new`].
10413 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
10414 let mut pending: Option<Vec<u8>> = None;
10415 let mut demux_dry = false;
10416 loop {
10417 // One chunk: the access units from a sync sample up to the next one.
10418 let mut stream = pending.take().unwrap_or_default();
10419 while !demux_dry && pending.is_none() {
10420 match demuxer.next_access_unit() {
10421 Ok(Some(au)) => {
10422 if !stream.is_empty() && crate::decode::leads_with_sequence_header(&au) {
10423 pending = Some(au);
10424 } else {
10425 stream.extend_from_slice(&au);
10426 }
10427 }
10428 Ok(None) => demux_dry = true,
10429 Err(e) => {
10430 let _ = tx.send(Err(e));
10431 return;
10432 }
10433 }
10434 }
10435 if stream.is_empty() {
10436 let _ = tx.send(Ok(None));
10437 return;
10438 }
10439 // Set by the sink when the consumer is gone, or when a picture is
10440 // refused; `Eof` is the sentinel that stops the chunk's decode there.
10441 let mut gone = false;
10442 let mut refused = None;
10443 let decode = decode_stream_with(&stream, |picture, _, shown| {
10444 if !shown {
10445 return Ok(());
10446 }
10447 let due = index;
10448 index += 1;
10449 if due < i64::from(start_frame) {
10450 return Ok(());
10451 }
10452 let (w, h) = (picture.width, picture.height);
10453 let (ow, oh) = (w.div_ceil(2), h.div_ceil(2));
10454 // 4:2:2 and 4:4:4 pictures are averaged down to the 4:2:0 the
10455 // composer and every software encoder take ([`chroma_420`]). A
10456 // monochrome stream carries no chroma, and the decoder hands back
10457 // zeros in its place: the neutral grey is written instead, at the
10458 // depth the samples are held in (512 for 10-bit).
10459 let Some((cw, ch)) = chroma_shape(picture.u.len(), w, h) else {
10460 refused = Some(format!(
10461 "software AV1 decode (ec-av1) gave a {w}x{h} picture with {} chroma samples per plane, which is no 4:2:0, 4:2:2 or 4:4:4 layout",
10462 picture.u.len()
10463 ));
10464 return Err(Av1Error::Eof);
10465 };
10466 let half = if gray {
10467 let mid = 1u16 << (depth - 1);
10468 Some(Av1Picture {
10469 width: w,
10470 height: h,
10471 y: picture.y.clone(),
10472 u: vec![mid; ow * oh],
10473 v: vec![mid; ow * oh],
10474 })
10475 } else if (cw, ch) != (ow, oh) {
10476 let down = |plane: &[u16]| -> Vec<u16> {
10477 chroma_420(plane, cw, ch, ow, oh)
10478 .into_iter()
10479 .map(|s| s as u16)
10480 .collect()
10481 };
10482 Some(Av1Picture {
10483 width: w,
10484 height: h,
10485 y: picture.y.clone(),
10486 u: down(&picture.u),
10487 v: down(&picture.v),
10488 })
10489 } else {
10490 None
10491 };
10492 let src = half.as_ref().unwrap_or(picture);
10493 let frame = if wide {
10494 // At 10-bit scale: a 10-bit stream's samples are there already, an
10495 // 8-bit one (in a 10-bit export) is shifted up by two.
10496 // A 12-bit one is rounded down by two.
10497 let plane = |s: &[u16]| -> Vec<u16> {
10498 s.iter()
10499 .map(|&x| match depth {
10500 ..=9 => x << (10 - depth),
10501 10 => x,
10502 _ => ((x + (1 << (depth - 11))) >> (depth - 10)).min(1023),
10503 })
10504 .collect()
10505 };
10506 Yuv::Wide {
10507 y: plane(&src.y),
10508 u: plane(&src.u),
10509 v: plane(&src.v),
10510 width: w as u32,
10511 height: h as u32,
10512 }
10513 } else {
10514 let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new());
10515 crate::decode::narrow_av1(src, depth, &mut y, &mut u, &mut v);
10516 Yuv::Pixels {
10517 y,
10518 u,
10519 v,
10520 width: w as u32,
10521 height: h as u32,
10522 }
10523 };
10524 if tx.send(Ok(Some(frame))).is_err() {
10525 gone = true;
10526 return Err(Av1Error::Eof);
10527 }
10528 Ok(())
10529 });
10530 if gone {
10531 return;
10532 }
10533 if let Some(msg) = refused {
10534 let _ = tx.send(Err(msg.into()));
10535 return;
10536 }
10537 if let Err(e) = decode {
10538 let msg = format!("software AV1 decode failed at picture {index}: {e}");
10539 let _ = tx.send(Err(msg.into()));
10540 return;
10541 }
10542 }
10543}
10544
10545impl SwDecoder {
10546 /// The H.264 seat over an opened demuxer. Decoding restarts at a sync
10547 /// sample, so pictures between it and the in point are decoded (the target
10548 /// references them) and then dropped.
10549 fn new(mut demuxer: Demuxer, start_frame: u32, wide: bool, deint: Deinterlace) -> Self {
10550 let seat = SwSeat::H264(H264Seat::open(&mut demuxer, start_frame, wide, deint));
10551 Self {
10552 demuxer,
10553 start: start_frame,
10554 seat,
10555 }
10556 }
10557
10558 /// Whether this decoder can be parked for a later span: only the H.264 seat
10559 /// has a display index to resume from, so the pulled seats never are.
10560 fn parkable(&self) -> bool {
10561 // An interlaced seat holds a picture back for its successor, so it has
10562 // no display index a later span could resume from.
10563 matches!(&self.seat, SwSeat::H264(s) if !s.deint.is_interlaced())
10564 }
10565
10566 /// The display index the seat's next picture will carry; `0` off the H.264 seat.
10567 fn index(&self) -> i64 {
10568 match &self.seat {
10569 SwSeat::H264(seat) => seat.index,
10570 SwSeat::Pulled { .. } => 0,
10571 }
10572 }
10573
10574 /// The display index the seat started at; `0` off the H.264 seat.
10575 fn origin(&self) -> i64 {
10576 match &self.seat {
10577 SwSeat::H264(seat) => seat.origin,
10578 SwSeat::Pulled { .. } => 0,
10579 }
10580 }
10581
10582 /// Set once the demuxer ran dry. Always `true` off the H.264 seat, which is
10583 /// what keeps a pulled decoder from being parked (see [`SwDecoder::parkable`]).
10584 fn flushed(&self) -> bool {
10585 match &self.seat {
10586 SwSeat::H264(seat) => seat.flushed || seat.deint.is_interlaced(),
10587 SwSeat::Pulled { .. } => true,
10588 }
10589 }
10590}
10591
10592impl H264Seat {
10593 /// A fresh `ec-h264` seat whose first picture is display index `index`.
10594 ///
10595 /// An interlaced stream lands one picture earlier than the in point, so the
10596 /// deinterlacer has the picture before it, as a sequential decode does.
10597 fn open(demuxer: &mut Demuxer, start: u32, wide: bool, mode: Deinterlace) -> Box<Self> {
10598 let deint = crate::deinterlace::Deinterlacer::with_mode(
10599 mode,
10600 demuxer.h264_interlaced(),
10601 i64::from(start),
10602 ec_core::frame::Interlace::Progressive,
10603 )
10604 .cadenced(mode, demuxer);
10605 let index = demuxer.seek_to_sync_at_or_before(deint.landing(start));
10606 Box::new(Self {
10607 deint,
10608 ..*Self::at(index, wide)
10609 })
10610 }
10611
10612 fn at(index: i64, wide: bool) -> Box<Self> {
10613 Box::new(Self {
10614 decoder: H264Decoder::new(CodecParameters::new(CodecId::H264))
10615 .expect("ec-h264 takes its own codec id"),
10616 index,
10617 origin: index,
10618 flushed: false,
10619 frame: None,
10620 wide,
10621 deep: Default::default(),
10622 deint: crate::deinterlace::Deinterlacer::new(false, 0, ec_core::frame::Interlace::Progressive),
10623 pending: VecDeque::new(),
10624 })
10625 }
10626
10627 /// Decodes up to and including the next picture at or after the in point,
10628 /// leaving it in `frame`. `false` at end of stream. Pictures leave the
10629 /// decoder in display order -- clause C.4.5.3, the same contract the
10630 /// playback seat keeps -- so the landing index, itself a display index by
10631 /// the demuxer's contract, counts one to one with them.
10632 fn advance(&mut self, demuxer: &mut Demuxer, start: u32) -> crate::Result<bool> {
10633 loop {
10634 // The second field of the frame the last call took the first of.
10635 if let Some((due, pic)) = self.pending.pop_front() {
10636 if due < i64::from(start) {
10637 continue;
10638 }
10639 self.deep.load(&pic, self.wide);
10640 self.frame = Some(pic);
10641 return Ok(true);
10642 }
10643 if !self.flushed {
10644 match demuxer.next_access_unit()? {
10645 Some(au) => self
10646 .decoder
10647 .send_packet(&Packet::new(0, TimeBase::new(1, 1), au))
10648 .map_err(|e| format!("decode at picture {}: {e}", self.index))?,
10649 None => {
10650 self.flushed = true;
10651 self.decoder
10652 .flush()
10653 .map_err(|e| format!("decode at end of stream: {e}"))?;
10654 }
10655 }
10656 }
10657 match self.decoder.receive_frame() {
10658 Ok(frame) => {
10659 let ec_core::frame::Frame::Video(pic) = frame else {
10660 continue;
10661 };
10662 let tag = self.index;
10663 self.index += 1;
10664 // Held one picture back while the deinterlacer waits for
10665 // the successor; below the in point it only primes. In
10666 // field mode it releases two, queued for the loop's top.
10667 self.pending.extend(self.deint.push_all(tag, pic));
10668 }
10669 // End of stream counts once the flush has happened; before it,
10670 // either answer means go back for the next access unit. The
10671 // last picture an interlaced stream held leaves first.
10672 Err(e) if e.is_eof() && self.flushed => {
10673 self.pending.extend(self.deint.finish_all());
10674 if self.pending.is_empty() {
10675 return Ok(false);
10676 }
10677 }
10678 Err(e) if e.is_need_more() || e.is_eof() => {}
10679 Err(e) => return Err(format!("decode at picture {}: {e}", self.index).into()),
10680 }
10681 }
10682 }
10683}
10684
10685#[cfg(test)]
10686mod tests {
10687 /// A standalone file's soft track is titled with its language's name, or left
10688 /// untitled, and never with its file name; an embedded track keeps the title
10689 /// its container gave it.
10690 #[test]
10691 fn a_soft_track_is_titled_by_its_language_never_its_file_name() {
10692 let file = |language: &str| SubtitleTrack {
10693 path: "/media/talk.fr.srt".into(),
10694 track: None,
10695 language: language.into(),
10696 name: String::new(),
10697 label: "talk.fr.srt".into(),
10698 cues: Vec::new(),
10699 bitmap: false,
10700 refused: None,
10701 };
10702 assert_eq!(subtitle_title(&file("fra")), "French");
10703 assert_eq!(subtitle_title(&file("")), "", "unset: no title, and never the file name");
10704 let embedded = SubtitleTrack {
10705 track: Some(3),
10706 name: "Signs".into(),
10707 ..file("fra")
10708 };
10709 assert_eq!(subtitle_title(&embedded), "Signs");
10710 }
10711
10712 /// Two caption lanes, one per palette track: a pick list names the lanes it
10713 /// keeps, and an empty one keeps them all -- in the plan and in the file.
10714 #[test]
10715 fn a_pick_list_keeps_only_the_lanes_it_names() {
10716 use crate::project::{LaneKind, SubClip};
10717 let track = |label: &str, text: &str| SubtitleTrack {
10718 path: "/nonexistent/film.mkv".into(),
10719 track: Some(1),
10720 language: "eng".into(),
10721 name: label.into(),
10722 label: label.into(),
10723 bitmap: false,
10724 cues: vec![Cue {
10725 start_us: 0,
10726 end_us: 1_000_000,
10727 text: text.into(),
10728 image: None,
10729 words: Vec::new(),
10730 karaoke: Vec::new(),
10731 }],
10732 refused: None,
10733 };
10734 let mut project = Project::single("/nonexistent/a.mp4", 150)
10735 .with_subtitles(vec![track("one", "first words"), track("two", "second words")]);
10736 for track in 0..2 {
10737 let lane = project.add_lane(LaneKind::Subtitle);
10738 project
10739 .place_sub(
10740 lane,
10741 0,
10742 SubClip {
10743 start: 0,
10744 frames: 150,
10745 track,
10746 in_us: 0,
10747 out_us: 1_000_000,
10748 link: None,
10749 },
10750 )
10751 .expect("an empty lane takes the placement");
10752 }
10753 let names = |subs: &[SubParams]| subs.iter().map(|s| s.name.clone()).collect::<Vec<_>>();
10754
10755 let only_zero = lane_subtitles(&project, 30.0, None, &[0]);
10756 assert_eq!(names(&only_zero), ["one"], "pick [0] keeps track 0's lane alone");
10757 assert_eq!(only_zero[0].cues[0].text, "first words");
10758
10759 let all = lane_subtitles(&project, 30.0, None, &[]);
10760 assert_eq!(names(&all), ["one", "two"], "an empty pick list keeps every lane");
10761
10762 let plan = planned_subtitles(&project, Format::Mp4, [0]);
10763 assert!(plan.contains("S1 one") && !plan.contains("two"), "plan: {plan}");
10764 let plan = planned_subtitles(&project, Format::Mp4, Vec::<usize>::new());
10765 assert!(plan.contains("S1 one") && plan.contains("S2 two"), "plan: {plan}");
10766 }
10767
10768 /// Four palette tracks, lanes S1 and S2 holding tracks 0 and 2: the file writes the tracks in
10769 /// the order the caller gave them, placed or not, and the card names them in that order.
10770 #[test]
10771 fn soft_tracks_are_written_in_the_order_the_caller_gave() {
10772 use crate::project::{LaneKind, SubClip};
10773 let track = |label: &str| SubtitleTrack {
10774 path: "/nonexistent/film.srt".into(),
10775 track: None,
10776 language: "eng".into(),
10777 name: label.into(),
10778 label: label.into(),
10779 bitmap: false,
10780 cues: vec![Cue {
10781 start_us: 0,
10782 end_us: 1_000_000,
10783 text: format!("{label} words"),
10784 image: None,
10785 words: Vec::new(),
10786 karaoke: Vec::new(),
10787 }],
10788 refused: None,
10789 };
10790 let mut project = Project::single("/nonexistent/a.mp4", 150)
10791 .with_subtitles(vec![track("one"), track("two"), track("three"), track("four")]);
10792 for track in [0, 2] {
10793 let lane = project.add_lane(LaneKind::Subtitle);
10794 project
10795 .place_sub(
10796 lane,
10797 0,
10798 SubClip {
10799 start: 0,
10800 frames: 150,
10801 track,
10802 in_us: 0,
10803 out_us: 1_000_000,
10804 link: None,
10805 },
10806 )
10807 .expect("an empty lane takes the placement");
10808 }
10809 let lanes = project.subtitle_lanes();
10810 let (s1, s2) = (lanes[0], lanes[1]);
10811
10812 assert_eq!(soft_order(&project, &lanes, &[2, 0]), [SoftEntry::Lane(s2), SoftEntry::Lane(s1)]);
10813 assert_eq!(soft_order(&project, &lanes, &[0, 2]), [SoftEntry::Lane(s1), SoftEntry::Lane(s2)]);
10814 assert_eq!(soft_order(&project, &lanes, &[3, 1]), [SoftEntry::Track(3), SoftEntry::Track(1)]);
10815 assert_eq!(soft_order(&project, &lanes, &[]), [SoftEntry::Lane(s1), SoftEntry::Lane(s2)]);
10816
10817 let plan = planned_subtitles(&project, Format::Mp4, [2, 0]);
10818 assert!(plan.contains("2 lanes → embedded (S2 three, S1 one)"), "plan: {plan}");
10819 let plan = planned_subtitles(&project, Format::Mp4, [3, 1]);
10820 assert!(plan.contains("2 tracks → embedded (four, two)"), "plan: {plan}");
10821 let plan = planned_subtitles(&project, Format::Mp4, [3, 2, 1, 0]);
10822 assert!(plan.contains("4 tracks → embedded (four, S2 three, two, S1 one)"), "plan: {plan}");
10823 }
10824
10825 /// A ranged file names a track with no cue inside the range as dropped, and carries the rest;
10826 /// a standalone ASS script with override blocks is named as styling the file drops.
10827 #[test]
10828 fn a_range_drops_tracks_with_no_cue_in_it_and_ass_styling_is_named() {
10829 use crate::project::{LaneKind, SubClip};
10830 let track = |label: &str, path: &str| SubtitleTrack {
10831 path: path.into(),
10832 track: None,
10833 language: "eng".into(),
10834 name: label.into(),
10835 label: label.into(),
10836 bitmap: false,
10837 cues: vec![Cue {
10838 start_us: 0,
10839 end_us: 1_000_000,
10840 text: format!("{label} words"),
10841 image: None,
10842 words: Vec::new(),
10843 karaoke: Vec::new(),
10844 }],
10845 refused: None,
10846 };
10847 let ass = std::env::temp_dir().join(format!("edith_export_styling_{}.ass", std::process::id()));
10848 std::fs::write(
10849 &ass,
10850 "[Script Info]\nScriptType: v4.00+\n\n[Events]\nFormat: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\nDialogue: 0,0:00:00.00,0:00:01.00,Default,,0,0,0,,{\\i1}Hi{\\i0}\n",
10851 )
10852 .expect("a scratch script");
10853 let mut project = Project::single("/nonexistent/a.mp4", 150)
10854 .with_subtitles(vec![track("one", ass.to_str().unwrap()), track("two", "/nonexistent/film.srt")]);
10855 for t in 0..2 {
10856 let lane = project.add_lane(LaneKind::Subtitle);
10857 project
10858 .place_sub(
10859 lane,
10860 0,
10861 SubClip {
10862 start: 0,
10863 frames: 30,
10864 track: t,
10865 in_us: 0,
10866 out_us: 1_000_000,
10867 link: None,
10868 },
10869 )
10870 .expect("an empty lane takes the placement");
10871 }
10872 // Cues sit in the first second (frames 0 to 30 at 30 fps): a range after it has none.
10873 let late = planned_subtitles_in(&project, Format::Mp4, [0, 1], Some((60, 150)), 30.0);
10874 assert!(late.contains("S1 one — no cues in range") && late.contains("S2 two — no cues in range"), "plan: {late}");
10875 assert!(!late.contains("→ embedded"), "plan: {late}");
10876 let early = planned_subtitles_in(&project, Format::Mp4, [0, 1], Some((0, 30)), 30.0);
10877 assert!(early.contains("2 lanes → embedded (S1 one, S2 two)"), "plan: {early}");
10878
10879 assert_eq!(stripped_styling(&project, &[0, 1]), ["one"], "the ASS script's override tags");
10880 assert!(stripped_styling(&project, &[1]).is_empty(), "a plain SRT has no styling to drop");
10881 let _ = std::fs::remove_file(&ass);
10882 }
10883
10884 #[test]
10885 fn fit_picture_clips_sets_every_picture_clip_on_the_copy() {
10886 let mut p = Project::single("/nonexistent/a.mp4", 90);
10887 let before = p.lane(Lane::V1)[0].fit;
10888 assert_eq!(before, FitPolicy::Fit, "a clip starts on its own default");
10889 assert_eq!(
10890 fit_picture_clips(&mut p, FitPolicy::Fill),
10891 FitOutcome { lanes: vec![(Lane::V1, 1)], overlays: 0 },
10892 "one picture clip"
10893 );
10894 assert_eq!(p.lane(Lane::V1)[0].fit, FitPolicy::Fill);
10895 assert_eq!(p.fit_of(Lane::V1, 0), FitPolicy::Fill);
10896 }
10897
10898 /// The I+P seat's automatic quality is its own default, not the intra
10899 /// seat's mapping: at 1080p30 the intra mapping clamps to QP 40 and the
10900 /// GOP seat must name QP 28 instead.
10901 #[test]
10902 fn the_gop_default_is_not_the_intra_seats_clamped_qp() {
10903 let m = meta(1920, 1080);
10904 let auto = ExportSettings { format: Format::HevcMp4, ..Default::default() };
10905 assert_eq!(hevc_qp(&m, &auto), 40, "the intra mapping clamps at 1080p30");
10906 assert_eq!(
10907 hevc_mode_words(&m, &auto),
10908 Some("I+P GOP (1 s keyframes), constant quality QP 28; pass bitrate_kbps for a fixed rate".to_string())
10909 );
10910 }
10911
10912 #[test]
10913 fn hevc_and_av1_words_name_the_quality_or_the_rate() {
10914 let m = meta(1920, 1080);
10915 let auto = |format| ExportSettings { format, ..Default::default() };
10916 let fixed = |format| ExportSettings { format, bitrate: Some(4_000_000), ..Default::default() };
10917 // With no bitrate the HEVC row is constant QP: the number is the one the encoder is given.
10918 assert_eq!(
10919 hevc_mode_words(&m, &auto(Format::HevcMp4)),
10920 Some(format!("I+P GOP (1 s keyframes), constant quality QP {HEVC_GOP_QP}; pass bitrate_kbps for a fixed rate"))
10921 );
10922 assert_eq!(
10923 hevc_mode_words(&m, &fixed(Format::HevcMp4)),
10924 Some("I+P GOP (1 s keyframes), 4 Mb/s".to_string())
10925 );
10926 assert_eq!(hevc_mode_words(&m, &auto(Format::Mp4)), None, "not an HEVC format");
10927 // AV1 is coded at a bitrate: the automatic one is named as the target it is.
10928 let target = av1_mode_words(&m, &auto(Format::Av1)).expect("an AV1 format");
10929 assert!(target.starts_with("average bitrate ") && target.contains("pass bitrate_kbps"), "{target}");
10930 assert_eq!(av1_mode_words(&m, &fixed(Format::Av1Mp4)), Some("average bitrate 4 Mb/s".to_string()));
10931 assert_eq!(rate_words(6220), "6.2 Mb/s");
10932 assert_eq!(rate_words(850), "850 kb/s");
10933 assert_eq!(av1_mode_words(&m, &auto(Format::HevcMp4)), None, "not an AV1 format");
10934 }
10935
10936 #[test]
10937 fn fit_picture_clips_leaves_a_transformed_overlay_on_its_own_fit() {
10938 use crate::transform::TransformParams;
10939 let mut p = Project::single("/nonexistent/a.mp4", 90);
10940 let v2 = Lane::new(LaneKind::Video, 1);
10941 assert_eq!(p.add_lane(LaneKind::Video), v2);
10942 let logo = p.lane(Lane::V1)[0].clone();
10943 assert!(p.place(v2, 0, logo), "a logo on V2");
10944 // The logo as the project has it: 0.3 of the canvas width, 80% opaque, moved up and right.
10945 let placed = TransformParams { pos_x: 0.32, pos_y: -0.32, scale: 0.3, opacity: 0.8, ..Default::default() };
10946 assert!(p.set_transform(v2, 0, Some(placed)));
10947 assert_eq!(
10948 fit_picture_clips(&mut p, FitPolicy::Fill),
10949 FitOutcome { lanes: vec![(Lane::V1, 1)], overlays: 1 },
10950 "the base picture refits, the overlay does not"
10951 );
10952 assert_eq!(p.fit_of(Lane::V1, 0), FitPolicy::Fill);
10953 assert_eq!(p.fit_of(v2, 0), FitPolicy::Fit, "the overlay keeps its own fit");
10954 assert_eq!(p.transform_of(v2, 0), Some(&placed), "and its placement");
10955
10956 // An identity transform is not an overlay: it refits like any full-frame clip.
10957 assert!(p.set_transform(v2, 0, Some(TransformParams::default())));
10958 assert_eq!(fit_picture_clips(&mut p, FitPolicy::Fill).overlays, 0);
10959 assert_eq!(p.fit_of(v2, 0), FitPolicy::Fill);
10960 }
10961
10962 #[test]
10963 fn a_caption_and_a_title_clash_only_in_the_same_place_and_on_screen_together() {
10964 use crate::project::Title;
10965 use crate::text::TextStyle;
10966 let cue = |start_s: f64, end_s: f64, text: &str| Cue {
10967 start_us: (start_s * 1e6) as i64,
10968 end_us: (end_s * 1e6) as i64,
10969 text: text.into(),
10970 image: None,
10971 words: Vec::new(),
10972 karaoke: Vec::new(),
10973 };
10974 let title = |start: u32, frames: u32, text: &str, place: Place| Title {
10975 start,
10976 frames,
10977 text: text.into(),
10978 style: TextStyle { place, ..TextStyle::default() },
10979 fade_in: 0,
10980 fade_out: 0,
10981 in_anim: Default::default(),
10982 out_anim: Default::default(),
10983 anim_frames: 0,
10984 keys: Vec::new(),
10985 };
10986 // Captions 86.0 to 88.0 s; a bottom title from frame 2163 (86.52 s at 25 fps) for 3 s.
10987 let cues = [cue(86.0, 88.0, "hello")];
10988 let titles = [title(2163, 75, "EVENING, MIRADOURO", Place::Bottom)];
10989 let clash = caption_title_clash(&cues, &titles, Place::Bottom, 25.0).expect("same place, on screen together");
10990 assert!((clash.0 - 86.52).abs() < 0.01, "the clash starts where both are up: {clash:?}");
10991 assert_eq!(clash.1, 0);
10992 assert_eq!(caption_title_clash(&cues, &titles, Place::Top, 25.0), None, "a top caption clears a bottom title");
10993 // The title is up after the captions end: no clash.
10994 let late = [title(2300, 25, "LATE", Place::Bottom)];
10995 assert_eq!(caption_title_clash(&cues, &late, Place::Bottom, 25.0), None, "not on screen together");
10996 // A blank cue is no words on the picture.
10997 let blank = [cue(86.0, 88.0, " ")];
10998 assert_eq!(caption_title_clash(&blank, &titles, Place::Bottom, 25.0), None);
10999 }
11000
11001 #[test]
11002 fn h264_levels_follow_table_a1() {
11003 use super::h264_level_idc;
11004 assert_eq!(h264_level_idc(1280, 720, 30, 1), 31);
11005 assert_eq!(h264_level_idc(1920, 1080, 30, 1), 40);
11006 assert_eq!(h264_level_idc(1920, 1080, 60, 1), 42);
11007 assert_eq!(h264_level_idc(2560, 1440, 30, 1), 50);
11008 assert_eq!(h264_level_idc(3840, 1608, 24000, 1001), 51);
11009 assert_eq!(h264_level_idc(3840, 2160, 60, 1), 52);
11010 assert_eq!(h264_level_idc(640, 360, 30, 1), 30);
11011 }
11012
11013 use super::*;
11014
11015 /// The bar of a *feature film*: a picture count times a permille is a
11016 /// product that has to be computed in `u64`, or a timeline past ~4.5 M
11017 /// pictures (42 hours at 30 fps) overflowed the `u32` this used to be --
11018 /// a panic in debug inside the export thread, and a bar that thrashed in
11019 /// release. Every value here is a fraction of the whole, so none of them
11020 /// may leave the scale, and the counts straddle the old overflow point.
11021 #[test]
11022 fn a_films_frame_count_does_not_overflow_the_bar() {
11023 // The straddle, in the very product the old shape computed: `boundary`
11024 // is the largest picture count whose `done * band` still fitted a
11025 // `u32`, and one more is where it began to wrap -- a panic in debug,
11026 // inside the export thread.
11027 let band = u64::from(PROGRESS_SCALE - AUDIO_BAND);
11028 let boundary = u64::from(u32::MAX) / band;
11029 assert!(boundary * band <= u64::from(u32::MAX));
11030 assert!((boundary + 1) * band > u64::from(u32::MAX));
11031 for total in [boundary as u32 + 1, 21_600_000, u32::MAX] {
11032 assert_eq!(picture_progress(total, total), PROGRESS_SCALE, "{total}");
11033 assert_eq!(picture_progress(0, total), AUDIO_BAND, "{total}");
11034 let half = picture_progress(total / 2, total);
11035 assert!(
11036 (AUDIO_BAND..PROGRESS_SCALE).contains(&half),
11037 "half of {total} is {half}"
11038 );
11039 assert!(
11040 picture_progress(total - 1, total) <= PROGRESS_SCALE,
11041 "{total}"
11042 );
11043 }
11044 }
11045
11046 /// How a decode thread ended is never guessed from the channel being shut.
11047 /// A source that genuinely ran out says so, and the span ends on it; a
11048 /// thread that died without a word is a failure, because reading it as end
11049 /// of stream would truncate the picture and *report the export finished*.
11050 #[test]
11051 fn a_decoder_that_dies_without_a_word_is_not_end_of_stream() {
11052 let streamed = |handle, frames| {
11053 ClipDecoder::Streamed(Streamed {
11054 frames,
11055 _thread: DecodeThread(Some(handle)),
11056 current: None,
11057 ended: false,
11058 park: None,
11059 })
11060 };
11061
11062 let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2);
11063 // Said its piece, then finished: the span walks on to its next clip.
11064 let handle = thread::spawn(move || {
11065 tx.send(Ok(None)).expect("the receiver is alive");
11066 None
11067 });
11068 let mut ended = streamed(handle, frames);
11069 assert!(ended.next().expect("a clean end is not an error").is_none());
11070 // ...and asking again is the same answer and not a disconnect error.
11071 assert!(ended.next().expect("still not an error").is_none());
11072
11073 let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2);
11074 // Died holding the sender: the channel shuts with nothing said.
11075 let handle = thread::spawn(move || {
11076 let _tx = tx;
11077 panic!("decoder died");
11078 });
11079 let mut died = streamed(handle, frames);
11080 let Err(e) = died.next() else {
11081 panic!("a silent death must fail the export, not end the clip")
11082 };
11083 assert!(
11084 e.to_string().contains("without a picture or a reason"),
11085 "{e}"
11086 );
11087 }
11088
11089 /// When a parked decoder may carry on for a later span. A decoder cannot go
11090 /// back, so the span must start at or after the first picture it still
11091 /// holds; and it must have been started at the sync sample a fresh decoder
11092 /// would seek to, or the pictures after it would not be the fresh ones.
11093 #[test]
11094 fn a_parked_decoder_resumes_only_where_a_fresh_one_would_match() {
11095 // Stopped at display 330 with two decoded pictures unclaimed (328 and
11096 // 329), started at the sync sample 250.
11097 let stopped = |start| resumable(330, 2, 250, 250, start);
11098 assert!(stopped(328), "the first held picture is the span's first");
11099 assert!(stopped(329), "the second held picture is the span's first");
11100 assert!(stopped(330), "the span starts where the decoder stopped");
11101 assert!(stopped(400), "a span further on decodes on to its picture");
11102 assert!(!stopped(327), "a span before what is held needs a restart");
11103 // Nothing unclaimed: the decoder's own position is the first picture.
11104 assert!(resumable(330, 0, 250, 250, 330));
11105 assert!(!resumable(330, 0, 250, 250, 329));
11106 // A fresh decoder for the span would seek to a later sync sample than
11107 // the one this decoder started at, so this one is not the same decode.
11108 assert!(!resumable(330, 2, 250, 300, 400));
11109 // And one that started at a later sync sample than a fresh one would
11110 // is not the same decode either.
11111 assert!(!resumable(330, 2, 300, 250, 330));
11112 }
11113
11114 /// Three seconds of two tones, one per channel, interleaved: enough shape
11115 /// that a correlation says something and enough length that the encoder
11116 /// settles into a mode.
11117 fn two_tones(secs: usize) -> Vec<f32> {
11118 (0..OPUS_RATE as usize * secs)
11119 .flat_map(|i| {
11120 let t = i as f32 / OPUS_RATE as f32;
11121 let tau = std::f32::consts::TAU;
11122 [
11123 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin(),
11124 0.25 * (tau * 880.0 * t).sin(),
11125 ]
11126 })
11127 .collect()
11128 }
11129
11130 /// Three seconds of the same two tones summed onto one channel: the mono
11131 /// mix `opus-rs 0.1.26` mis-encoded at every rate, which is why a mono
11132 /// export kept the AAC path until `ec-opus` took the seat.
11133 fn mono_tones(secs: usize) -> Vec<f32> {
11134 (0..OPUS_RATE as usize * secs)
11135 .map(|i| {
11136 let t = i as f32 / OPUS_RATE as f32;
11137 let tau = std::f32::consts::TAU;
11138 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin()
11139 })
11140 .collect()
11141 }
11142
11143 /// The best correlation of one channel of `got` against `want`, and the
11144 /// offset it sat at. `stride` is the interleave width: 2 for the stereo
11145 /// fixtures, 1 for mono.
11146 fn align(want: &[f32], got: &[f32], stride: usize) -> (f64, usize) {
11147 let (mut best, mut at) = (-2.0, 0);
11148 let window = OPUS_RATE as usize;
11149 for lag in 0..1400 {
11150 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
11151 for (x, y) in want[..window]
11152 .iter()
11153 .step_by(stride)
11154 .zip(got[lag * stride..].iter().step_by(stride))
11155 {
11156 num += f64::from(*x) * f64::from(*y);
11157 da += f64::from(*x) * f64::from(*x);
11158 db += f64::from(*y) * f64::from(*y);
11159 }
11160 let c = num / (da.sqrt() * db.sqrt()).max(1e-12);
11161 if c > best {
11162 (best, at) = (c, lag);
11163 }
11164 }
11165 (best, at)
11166 }
11167
11168 fn ec_decode(packets: &[crate::AacPacket]) -> Vec<f32> {
11169 let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);
11170 let mut pcm = Vec::new();
11171 for packet in packets {
11172 pcm.extend(
11173 decoder
11174 .decode_packet(&packet.bytes)
11175 .expect("a valid packet"),
11176 );
11177 }
11178 pcm
11179 }
11180
11181 /// [`ec_decode`] for a mono packet stream: one stream, no coupling.
11182 fn ec_decode_mono(packets: &[crate::AacPacket]) -> Vec<f32> {
11183 let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 0, &[0]);
11184 let mut pcm = Vec::new();
11185 for packet in packets {
11186 pcm.extend(
11187 decoder
11188 .decode_packet(&packet.bytes)
11189 .expect("a valid packet"),
11190 );
11191 }
11192 pcm
11193 }
11194
11195 /// Why [`OPUS_MAX_KBPS`] is a cap, why [`OPUS_PRE_SKIP`] is a constant and
11196 /// why [`opus_fidelity`] exists at all -- all three measured here through
11197 /// the same decoder door the product reads every Opus file back with, the
11198 /// decoder being the witness and the *encoder* the one under test.
11199 ///
11200 /// The second half pins the two failures the seat's move here fixed: under
11201 /// `opus-rs 0.1.26` the encoder wrote stereo packets that only its own
11202 /// decoder read back above roughly 165 kbps (fidelity 0.06 at 256), and it
11203 /// mis-encoded mono at every rate -- which is what the old 128 cap and the
11204 /// mono-mix-keeps-AAC rule stood on. Both asserts are survival now, and a
11205 /// regression fails here, loudly: that is the signal to lower
11206 /// [`OPUS_MAX_KBPS`] again, not a reason to widen it quietly.
11207 #[test]
11208 fn the_opus_encoder_is_pinned_to_the_band_it_was_measured_in() {
11209 let pcm = two_tones(3);
11210 for kbps in [96, OPUS_MAX_KBPS] {
11211 let (packets, pre_skip) = encode_opus(&pcm, kbps, 2)
11212 .expect("the encoder opens")
11213 .expect("and inside the band it passes its own round trip");
11214 assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16);
11215 assert_eq!(
11216 packets.len(),
11217 pcm.len().div_ceil(OPUS_FRAME * 2) + 2,
11218 "one packet per 20 ms frame, plus the warm-up and the flush"
11219 );
11220 let decoded = ec_decode(&packets);
11221 let (c, lag) = align(&pcm, &decoded, 2);
11222 // From the first audible sample, head included -- and the head is
11223 // why this is 0.98 and not the 0.999 below: the encoder's first
11224 // audible 20 ms comes out a few dB down (one frame of cold start;
11225 // a second warm-up frame changes the numbers in no decimal place),
11226 // so that ramp is stated rather than hidden behind a loose
11227 // threshold.
11228 assert!(c >= 0.98, "{kbps} kbps came back at correlation {c:.4}");
11229 let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..], 2);
11230 assert!(
11231 settled >= 0.999,
11232 "{kbps} kbps past the first frame: correlation {settled:.4}"
11233 );
11234 // The whole point of the number in the header: drop exactly that
11235 // many samples and the sound starts where the timeline says. A lag
11236 // that is not it is a file that plays late or eats its own head.
11237 assert_eq!(
11238 lag,
11239 usize::from(pre_skip),
11240 "{kbps} kbps: the declared pre-skip is not where the sound starts"
11241 );
11242 // ...and the tail is all there: the flush frame pushed the last
11243 // samples out, so what is left after the pre-skip covers the input.
11244 assert!(
11245 decoded.len() - usize::from(pre_skip) * 2 >= pcm.len(),
11246 "{kbps} kbps: the track ends {} samples short of the timeline",
11247 (pcm.len() + usize::from(pre_skip) * 2 - decoded.len()) / 2
11248 );
11249 // The gate the export runs before it writes anything, on a track
11250 // that deserves to pass it.
11251 let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip), 2);
11252 assert!(
11253 fidelity >= OPUS_MIN_FIDELITY,
11254 "{kbps} kbps scored {fidelity:.4} on its own round trip"
11255 );
11256 }
11257
11258 // Mono, the shape `opus-rs 0.1.26` mis-encoded at every rate and the
11259 // reason a mono mix kept the AAC path: straight through the same seat,
11260 // including at the rate where the old encoder was already writing
11261 // stereo noise, let alone mono.
11262 let mono = mono_tones(3);
11263 for kbps in [96, 256] {
11264 let (packets, pre_skip) = encode_opus(&mono, kbps, 1)
11265 .expect("the encoder opens")
11266 .expect("and mono passes its own round trip");
11267 assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16);
11268 let decoded = ec_decode_mono(&packets);
11269 let (c, lag) = align(&mono, &decoded, 1);
11270 assert!(
11271 c >= 0.98,
11272 "mono at {kbps} kbps came back at correlation {c:.4}"
11273 );
11274 let (settled, _) = align(&mono[OPUS_FRAME..], &decoded[OPUS_FRAME..], 1);
11275 assert!(
11276 settled >= 0.999,
11277 "mono at {kbps} kbps past the first frame: correlation {settled:.4}"
11278 );
11279 assert_eq!(
11280 lag,
11281 usize::from(pre_skip),
11282 "mono at {kbps} kbps: the declared pre-skip is not where the sound starts"
11283 );
11284 assert!(
11285 decoded.len() - usize::from(pre_skip) >= mono.len(),
11286 "mono at {kbps} kbps: the track ends {} samples short of the timeline",
11287 mono.len() + usize::from(pre_skip) - decoded.len()
11288 );
11289 let fidelity = opus_fidelity(&packets, &mono, usize::from(pre_skip), 1);
11290 assert!(
11291 fidelity >= OPUS_MIN_FIDELITY,
11292 "mono at {kbps} kbps scored {fidelity:.4} on its own round trip"
11293 );
11294 }
11295 }
11296
11297 /// The gate on a track too long to listen to whole: it samples, and the
11298 /// middle of what it hears is the answer. A track whose sound is *not* what
11299 /// was encoded fails it; one bad five-second window does not, which is
11300 /// deliberate and measured ([`opus_fidelity`] carries the distribution:
11301 /// five windows of a good film's mix score under 0.95, the lowest 0.803).
11302 /// A silent track is not a failure either, which is what it used to be
11303 /// scored as -- 0.0 against a denominator of nothing, and an all-quiet
11304 /// timeline fell back to AAC for it.
11305 ///
11306 /// 61 s of sound: one second past the minute the gate stops listening whole,
11307 /// which is what puts this on the sampled path at all.
11308 #[test]
11309 fn a_long_track_is_judged_by_the_middle_of_what_it_samples() {
11310 let pcm = two_tones(61);
11311 let (packets, pre_skip) = encode_opus(&pcm, 96, 2)
11312 .expect("the encoder opens")
11313 .expect("and passes its own round trip");
11314 assert!(
11315 packets.len() > FIDELITY_WINDOW * FIDELITY_WINDOWS,
11316 "{} packets is not the sampled path",
11317 packets.len()
11318 );
11319 let pre_skip = usize::from(pre_skip);
11320 let whole = opus_fidelity(&packets, &pcm, pre_skip, 2);
11321 assert!(whole >= OPUS_MIN_FIDELITY, "a good track scored {whole:.4}");
11322
11323 // One window's worth of the *mix* replaced by its own phase inverse:
11324 // the packets still decode, they are simply no longer this sound. Placed
11325 // on a window the gate samples -- window 6 of the twelve, by the same
11326 // arithmetic the gate spreads them with. The track still passes, and
11327 // that is the measured decision, not an oversight: this codec really
11328 // does score 0.80 on five seconds of film it otherwise handles at 0.998.
11329 let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);
11330 let from = (6 * step * OPUS_FRAME).saturating_sub(pre_skip) * 2;
11331 let mut one_bad = pcm.clone();
11332 for sample in &mut one_bad[from..(from + FIDELITY_WINDOW * OPUS_FRAME * 2).min(pcm.len())] {
11333 *sample = -*sample;
11334 }
11335 let dip = opus_fidelity(&packets, &one_bad, pre_skip, 2);
11336 assert!(
11337 dip >= OPUS_MIN_FIDELITY,
11338 "one ruined window sank the whole track ({dip:.4})"
11339 );
11340
11341 // ...and the shape the gate is actually for, which is what a rate the
11342 // encoder cannot hold does: the track is not the mix any more, not one
11343 // window of it. The middle of the list moves with it.
11344 let mut ruined = pcm.clone();
11345 for sample in &mut ruined[pcm.len() / 4..] {
11346 *sample = -*sample;
11347 }
11348 let ruined = opus_fidelity(&packets, &ruined, pre_skip, 2);
11349 assert!(
11350 ruined < OPUS_MIN_FIDELITY,
11351 "a track that is no longer the mix scored {ruined:.4}"
11352 );
11353
11354 // ...and silence is silence: nothing to correlate is not a round trip
11355 // that failed. Short, because the floor is the same on either path.
11356 let quiet = vec![0f32; OPUS_RATE as usize * 2 * 2];
11357 let (packets, pre_skip) = encode_opus(&quiet, 96, 2)
11358 .expect("the encoder opens")
11359 .expect("silence is written as Opus, not sent to AAC");
11360 let fidelity = opus_fidelity(&packets, &quiet, usize::from(pre_skip), 2);
11361 assert!(
11362 fidelity >= OPUS_MIN_FIDELITY,
11363 "a silent track scored {fidelity:.4} and would fall back to AAC"
11364 );
11365 }
11366
11367 /// The one rule that keeps a picture from being converted twice: a frame the
11368 /// tone map has already brought to BT.709 is never handed the 2020 matrix as
11369 /// well, on either canvas -- and everything else about the remap is
11370 /// unchanged by the tone map existing.
11371 #[test]
11372 fn a_tone_mapped_span_is_never_matrix_remapped_too() {
11373 let hdr = ColorDescription {
11374 matrix: Matrix::Bt2020Ncl,
11375 transfer: Transfer::Pq,
11376 full_range: false,
11377 };
11378 let sdr = ColorDescription::default(); // BT.601
11379 // The (from, to) pair of a remap, which is all these cases are about.
11380 let pair = |remap: Option<Remap>| remap.map(|r| (r.from, r.to));
11381 for out in [Matrix::Bt709, Matrix::Bt601] {
11382 let toned = pair(remap_into(Some(hdr), true, out));
11383 assert!(
11384 toned.is_none_or(|(from, _)| from == Matrix::Bt709),
11385 "tone-mapped onto a {out:?} canvas asked for {toned:?}"
11386 );
11387 // Untouched by any of this: the 2020 clip that was *not* tone-mapped
11388 // (an unreachable state today, and still the matrix answer), the
11389 // ordinary 601-on-709 reconcile, and a gap.
11390 assert_eq!(
11391 pair(remap_into(Some(hdr), false, out)),
11392 (out != Matrix::Bt2020Ncl).then_some((Matrix::Bt2020Ncl, out))
11393 );
11394 assert_eq!(
11395 pair(remap_into(Some(sdr), false, out)),
11396 (out != Matrix::Bt601).then_some((Matrix::Bt601, out))
11397 );
11398 assert_eq!(remap_into(None, false, out), None);
11399 }
11400 assert_eq!(
11401 pair(remap_into(Some(hdr), true, Matrix::Bt601)),
11402 Some((Matrix::Bt709, Matrix::Bt601)),
11403 "a tone-mapped clip below 720 lines still takes its 709 -> 601 step"
11404 );
11405 }
11406
11407 /// A full-range source is scaled into the limited span before it is matrix
11408 /// converted, and only an untouched one: a tone-mapped picture is already
11409 /// limited, and a limited source has nothing to scale.
11410 #[test]
11411 fn a_full_range_source_is_limited_before_it_is_remapped() {
11412 let full = ColorDescription {
11413 matrix: Matrix::Bt709,
11414 transfer: Transfer::Sdr,
11415 full_range: true,
11416 };
11417 let limited = ColorDescription {
11418 full_range: false,
11419 ..full
11420 };
11421 assert_eq!(
11422 remap_into(Some(full), false, Matrix::Bt709),
11423 Some(Remap {
11424 from: Matrix::Bt709,
11425 to: Matrix::Bt709,
11426 limit: true,
11427 }),
11428 "same matrix, but the range still has to come down"
11429 );
11430 assert_eq!(remap_into(Some(limited), false, Matrix::Bt709), None);
11431 assert_eq!(remap_into(Some(full), true, Matrix::Bt709), None);
11432 }
11433
11434 /// The picture as [`place_picture`] hands it to the encoder: a full-range
11435 /// source on a canvas of its own size, so the placement is the identity and
11436 /// what comes out is exactly the range change.
11437 #[test]
11438 fn a_full_range_picture_is_placed_as_limited_codes() {
11439 let (w, h) = (4u32, 2u32);
11440 let y = [0u8, 255, 130, 130, 0, 255, 130, 130];
11441 let (u, v) = ([0u8, 255], [255u8, 0]);
11442 let mut canvas = Composer::new(w, h, crate::scale::FitPolicy::default());
11443 let (mut turned, mut stretched, mut graded, mut transformed) = (
11444 (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()),
11445 (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()),
11446 (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()),
11447 (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()),
11448 );
11449 let remap = Some(Remap {
11450 from: Matrix::Bt709,
11451 to: Matrix::Bt709,
11452 limit: true,
11453 });
11454 let (py, pu, pv, _, _) = place_picture(
11455 &y,
11456 &u,
11457 &v,
11458 w,
11459 h,
11460 Rotation::default(),
11461 crate::demux::PixelAspect::SQUARE,
11462 None,
11463 TransformParams::default(),
11464 remap,
11465 None,
11466 &mut turned,
11467 &mut stretched,
11468 &mut graded,
11469 &mut transformed,
11470 &mut canvas,
11471 );
11472 assert_eq!(py, [16, 235, 128, 128, 16, 235, 128, 128]);
11473 assert_eq!(pu, [16, 240]);
11474 assert_eq!(pv, [240, 16]);
11475 }
11476
11477 /// A track of three cues, in whichever clock `track` says: `Some(n)` is a
11478 /// track of the media file, `None` a `.srt` beside it.
11479 fn subtitles(path: &str, track: Option<u64>) -> SubtitleTrack {
11480 SubtitleTrack {
11481 path: path.into(),
11482 track,
11483 language: "eng".into(),
11484 name: String::new(),
11485 label: "eng".into(),
11486 bitmap: false,
11487 cues: vec![
11488 Cue {
11489 start_us: 500_000,
11490 end_us: 1_500_000,
11491 text: "first".into(),
11492 image: None,
11493 words: Vec::new(),
11494 karaoke: Vec::new(),
11495 },
11496 Cue {
11497 start_us: 2_000_000,
11498 end_us: 3_250_000,
11499 text: "second".into(),
11500 image: None,
11501 words: Vec::new(),
11502 karaoke: Vec::new(),
11503 },
11504 Cue {
11505 start_us: 4_000_000,
11506 end_us: 4_750_000,
11507 text: "third".into(),
11508 image: None,
11509 words: Vec::new(),
11510 karaoke: Vec::new(),
11511 },
11512 ],
11513 refused: None,
11514 }
11515 }
11516
11517 /// A standalone subtitle file is timed against the timeline itself -- there
11518 /// is no clip to hang it on -- so a cut moves the pictures and not it. What
11519 /// it does get is the exported length: a cue past the end of the file would
11520 /// otherwise be a block after the last picture.
11521 ///
11522 /// The pair of this, the embedded clock, is measured against a real exported
11523 /// file in `tests/export_subs.rs`; both live in one function and this is the
11524 /// half that needs no encoder.
11525 #[test]
11526 fn a_subtitle_file_beside_the_media_keeps_the_timelines_own_clock() {
11527 // 5 seconds at 30, with `[0.5s, 2.5s)` cut out of it: 3 seconds left.
11528 let mut project = Project::single("/nonexistent/film.mp4", 150);
11529 let track = subtitles("/nonexistent/film.srt", None);
11530 assert!(project.ripple_delete(15, 60));
11531 assert_eq!(project.timeline_frames(), 90);
11532 let cues = timeline_cues(&project, &track, 30.0);
11533 assert_eq!(
11534 cues,
11535 vec![
11536 Cue {
11537 start_us: 500_000,
11538 end_us: 1_500_000,
11539 text: "first".into(),
11540 image: None,
11541 words: Vec::new(),
11542 karaoke: Vec::new(),
11543 },
11544 // Clipped to the three seconds the export writes...
11545 Cue {
11546 start_us: 2_000_000,
11547 end_us: 3_000_000,
11548 text: "second".into(),
11549 image: None,
11550 words: Vec::new(),
11551 karaoke: Vec::new(),
11552 },
11553 // ...and the one wholly past the end is not written at all.
11554 ]
11555 );
11556 // A track *of a file* the project no longer plays has no span to be
11557 // carried through either, so it falls back to the same clock rather
11558 // than exporting nothing.
11559 let orphan = subtitles("/nonexistent/other.mkv", Some(2));
11560 assert_eq!(timeline_cues(&project, &orphan, 30.0).len(), 2);
11561 }
11562
11563 /// The embedded clock, without an encoder in it: the cut moves the cues with
11564 /// the pictures, and a cue nothing clipped keeps its own microseconds.
11565 #[test]
11566 fn a_track_of_the_media_is_carried_through_the_cut() {
11567 let mut project = Project::single("/nonexistent/film.mkv", 150);
11568 let track = subtitles("/nonexistent/film.mkv", Some(2));
11569 assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out");
11570 let cues = timeline_cues(&project, &track, 30.0);
11571 assert_eq!(
11572 cues,
11573 vec![
11574 // The first cue was wholly inside the cut. The second straddled
11575 // its far edge and kept the 0.75s that is still there...
11576 Cue {
11577 start_us: 500_000,
11578 end_us: 1_250_000,
11579 text: "second".into(),
11580 image: None,
11581 words: Vec::new(),
11582 karaoke: Vec::new(),
11583 },
11584 // ...and the third simply moves back the two seconds that went.
11585 Cue {
11586 start_us: 2_000_000,
11587 end_us: 2_750_000,
11588 text: "third".into(),
11589 image: None,
11590 words: Vec::new(),
11591 karaoke: Vec::new(),
11592 },
11593 ]
11594 );
11595 }
11596
11597 #[test]
11598 fn export_spans_clips_to_the_marked_range_keeping_absolute_start() {
11599 let project = Project::single("/nonexistent/film.mkv", 150);
11600 // The whole timeline, unmarked: one span, the source's own length.
11601 let whole = export_spans(&project, None);
11602 assert_eq!(whole.len(), 1);
11603 assert_eq!((whole[0].start, whole[0].len), (0, 150));
11604 // A range wholly inside the span: `start` stays the timeline's own
11605 // coordinate ([`composite_color_at`] needs that), and the length is
11606 // exactly what the mark asked for.
11607 let clipped = export_spans(&project, Some((30, 100)));
11608 assert_eq!(clipped.len(), 1);
11609 assert_eq!((clipped[0].start, clipped[0].len), (30, 70));
11610 // A range past the end of the media clamps to it rather than reading
11611 // short on the wrong side.
11612 let past_end = export_spans(&project, Some((100, 500)));
11613 assert_eq!((past_end[0].start, past_end[0].len), (100, 50));
11614 }
11615
11616 #[test]
11617 fn bitrate_clamps_at_both_ends() {
11618 let meta = |width, height, frame_rate| VideoMeta {
11619 width,
11620 height,
11621 frame_rate,
11622 frame_count: 1,
11623 codec: crate::demux::Codec::H264,
11624 color: Default::default(),
11625 matrix_assumed: false,
11626 rotation: Rotation::None,
11627 // Square pixels, coded where they are declared: a meta no container
11628 // wrote, so nothing was read to disagree with it.
11629 coded_width: width,
11630 coded_height: height,
11631 pixel_aspect: crate::demux::PixelAspect::SQUARE,
11632 };
11633 // 1280 * 720 * 30 * 0.1
11634 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
11635 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), 230_400, "tiny");
11636 assert_eq!(
11637 bitrate_for(&meta(160, 120, 15.0)),
11638 MIN_BITRATE,
11639 "tinier floors"
11640 );
11641 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
11642 // A rate somebody typed goes through untouched to its own ceiling, which
11643 // is above where the derived one stops: the card offers 50 Mbps, and a
11644 // second clamp here would write a file at a bitrate nobody picked.
11645 let asked = |bps| {
11646 bitrate_of(
11647 &meta(1920, 1080, 30.0),
11648 &ExportSettings {
11649 bitrate: Some(bps),
11650 ..Default::default()
11651 },
11652 )
11653 };
11654 assert_eq!(asked(50_000_000), 50_000_000, "the card's ceiling travels");
11655 assert_eq!(asked(21_000_000), 21_000_000, "past the derived range");
11656 assert_eq!(asked(600_000), 600_000, "a sub-Mbps ask travels");
11657 assert_eq!(asked(999_000_000), MAX_EXPLICIT_BITRATE, "still bounded");
11658 assert_eq!(asked(1), MIN_BITRATE, "and floored");
11659 }
11660
11661 /// A clip's fade takes the copy path away, exactly as an equalizer does:
11662 /// a copied AAC packet cannot carry gain math nobody put in the file. The
11663 /// bug this guards is [`forces_encode`] gating on `equalized`/`mastered`
11664 /// but never checking a clip's own `fade_in`/`fade_out` at all -- the
11665 /// default Web MP4 export then labelled and took the "AAC copy" path for
11666 /// a project whose picture showed a fade, and the fade never reached the
11667 /// file.
11668 #[test]
11669 fn a_fade_forces_the_audio_to_be_re_encoded() {
11670 let mut project = Project::single("/nonexistent/film.mp4", 90);
11671 assert!(!forces_encode(&project, false), "flat, so a copy is fine");
11672 assert!(project.set_fade_in(
11673 crate::project::Lane::new(crate::project::LaneKind::Audio, 0),
11674 0,
11675 15
11676 ));
11677 assert!(
11678 forces_encode(&project, false),
11679 "a fade-in on the only clip must force a re-encode"
11680 );
11681 }
11682
11683 fn meta(width: u32, height: u32) -> VideoMeta {
11684 VideoMeta {
11685 width,
11686 height,
11687 frame_rate: 30.0,
11688 frame_count: 1,
11689 codec: crate::demux::Codec::H264,
11690 color: Default::default(),
11691 matrix_assumed: false,
11692 rotation: Rotation::None,
11693 // Square pixels, coded where they are declared: a meta no
11694 // container wrote, so nothing was read to disagree with it.
11695 coded_width: width,
11696 coded_height: height,
11697 pixel_aspect: crate::demux::PixelAspect::SQUARE,
11698 }
11699 }
11700
11701 /// The bitrate row a user picked, read as the quality tier it is: a higher
11702 /// row is a lower QP, the band is honoured at both ends, and the same
11703 /// picture at the same rate gets the same number whatever its size (the
11704 /// mapping is bits per *pixel*, which is what makes 720p and 1080p one
11705 /// table).
11706 #[test]
11707 fn the_quality_rows_map_onto_quantisers_that_only_go_one_way() {
11708 let at = |width, height, mbps: Option<u64>| {
11709 hevc_qp(
11710 &meta(width, height),
11711 &ExportSettings {
11712 bitrate: mbps.map(|m| m * 1_000_000),
11713 ..Default::default()
11714 },
11715 )
11716 };
11717 // 20 Mbps at 1080p30 is 0.32 bits a pixel against the 0.6 measured at
11718 // QP 27, which is just over half: five QP up, and QP is not an
11719 // arithmetic scale, so this is the number the formula gives.
11720 assert_eq!(at(1920, 1080, Some(20)), 32);
11721 // Every step down the card is a step up in QP, never sideways.
11722 let rows: Vec<i32> = [20, 12, 8, 4, 2, 1]
11723 .into_iter()
11724 .map(|mbps| at(1920, 1080, Some(mbps)))
11725 .collect();
11726 assert!(
11727 rows.windows(2).all(|w| w[0] <= w[1]),
11728 "a lower bitrate row must never code at a lower QP: {rows:?}"
11729 );
11730 assert_eq!(*rows.last().unwrap(), HEVC_QP_MAX, "the floor is clamped");
11731 // ...and the top of the range is the clamp, not an unbounded number: 20
11732 // Mbps at 320x240 is 8.7 bits a pixel, which no picture needs.
11733 assert_eq!(at(320, 240, Some(20)), HEVC_QP_MIN);
11734 // The same bits per pixel is the same quantiser at any size: 1080p at
11735 // 20 Mbps and 720p at 8.9 Mbps are one picture quality.
11736 assert_eq!(at(1920, 1080, Some(20)), at(1280, 720, Some(9)));
11737 // The automatic bitrate is 0.1 bpp at every size, so it is one QP
11738 // everywhere -- the honest end of "intra-only, large files": the file
11739 // will be bigger than the row says, and the row buys quality.
11740 assert_eq!(at(1920, 1080, None), at(1280, 720, None));
11741 }
11742
11743 /// An odd picture cannot be cropped back to itself in 4:2:0 -- the
11744 /// conformance window is stated in chroma samples -- so it is refused by
11745 /// name rather than written a column wider than the timeline.
11746 #[test]
11747 fn an_odd_picture_is_refused_an_hevc_export_by_name() {
11748 let settings = ExportSettings {
11749 format: Format::Hevc,
11750 ..Default::default()
11751 };
11752 let refused = Enc::open(&meta(1919, 1080), &settings, false, ColorDescription::default())
11753 .err()
11754 .expect("an odd width has no chroma plane")
11755 .to_string();
11756 assert!(refused.contains("1919x1080"), "{refused}");
11757 assert!(refused.contains("even"), "{refused}");
11758 // ...and the even one it neighbours opens.
11759 assert!(Enc::open(&meta(1920, 1080), &settings, false, ColorDescription::default()).is_ok());
11760 }
11761
11762 /// H.264 codes 16x16 macroblocks and ec-h264's floor is the macroblock
11763 /// itself -- the old encoder took any positive even size -- so a
11764 /// sub-macroblock picture is refused by name, like every other seat
11765 /// refusal, rather than surfaced from inside a running export.
11766 #[test]
11767 fn a_sub_macroblock_picture_is_refused_an_h264_export_by_name() {
11768 let settings = ExportSettings {
11769 format: Format::Mp4,
11770 seat: EncoderSeat::Software,
11771 ..Default::default()
11772 };
11773 let refused = Enc::open(&meta(8, 8), &settings, false, ColorDescription::default())
11774 .err()
11775 .expect("8x8 is smaller than one macroblock")
11776 .to_string();
11777 assert!(refused.contains("8x8"), "{refused}");
11778 assert!(refused.contains("16x16"), "{refused}");
11779 }
11780
11781 /// Weights ramp from just above 0 to just below 1 and never touch either
11782 /// end -- the frame *after* the window is where a viewer would see plain
11783 /// B, and the window itself never quite repeats a hard cut's own instant.
11784 #[test]
11785 fn dissolve_weight_ramps_strictly_between_zero_and_one() {
11786 assert_eq!(
11787 dissolve_weight(0, 1),
11788 0.5,
11789 "a one-frame window is the midpoint"
11790 );
11791 assert_eq!(dissolve_weight(0, 4), 0.2);
11792 assert_eq!(dissolve_weight(1, 4), 0.4);
11793 assert_eq!(dissolve_weight(2, 4), 0.6);
11794 assert_eq!(dissolve_weight(3, 4), 0.8);
11795 }
11796
11797 /// [`dissolve_window`] reads [`crate::project::Clip::transition_out`] back
11798 /// only once adjacency is re-checked at render time: two clips a split
11799 /// just made, still touching, still name B by its own source and its own
11800 /// timeline start.
11801 #[test]
11802 fn dissolve_window_names_bs_source_in_frame_window_and_start() {
11803 use crate::project::{Lane, Project};
11804 let mut p = Project::single("/nonexistent/film.mkv", 20);
11805 assert!(p.split(15));
11806 assert!(p.set_transition_out(Lane::V1, 0, 5));
11807 let spans = export_spans(&p, None);
11808 let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span");
11809 assert_eq!(
11810 dissolve_window(&p, a_span),
11811 Some((0, 15, 5, 15)),
11812 "b's source, b's in_frame, the window, b's timeline start"
11813 );
11814 }
11815
11816 /// A `transition_out` set while two clips touched, then made stale by a
11817 /// trim that opens a gap between them: the number is still in storage,
11818 /// [`dissolve_window`] reads `None` from it, and the span renders as the
11819 /// hard cut two clips that no longer touch actually are.
11820 #[test]
11821 fn a_stale_transition_out_after_a_trim_renders_as_a_hard_cut() {
11822 use crate::project::{Edge, Lane, Project};
11823 let mut p = Project::single("/nonexistent/film.mkv", 20);
11824 assert!(p.split(15));
11825 assert!(p.set_transition_out(Lane::V1, 0, 5));
11826 assert!(p.trim(Lane::V1, 1, Edge::Start, 18, &[100]), "opens a gap");
11827 let spans = export_spans(&p, None);
11828 let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span");
11829 assert!(
11830 dissolve_window(&p, a_span).is_none(),
11831 "b no longer abuts a; hard cut"
11832 );
11833 }
11834}
11835
11836#[cfg(test)]
11837mod audio_language_tests {
11838 use super::*;
11839
11840 fn asset(name: &str) -> PathBuf {
11841 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
11842 }
11843
11844 /// `test_multilang.mp4` has an `und` track 0 and a `fra` track 1.
11845 #[test]
11846 fn a_stream_states_its_language_or_none() {
11847 let path = asset("test_multilang.mp4");
11848 assert_eq!(stream_language(&path, 0), None, "und is no language");
11849 assert_eq!(stream_language(&path, 1).as_deref(), Some("fra"));
11850 assert_eq!(stream_language(&path, 9), None, "a track the file does not have");
11851 }
11852
11853 /// The tag is the one language every clip shares; any disagreement or any `und` leaves it out.
11854 #[test]
11855 fn the_mix_takes_a_language_only_when_every_clip_shares_it() {
11856 let s = |l: &str| Some(l.to_string());
11857 assert_eq!(shared_language([s("fra"), s("fra")]), s("fra"));
11858 assert_eq!(shared_language([s("fra"), s("eng")]), None, "two languages");
11859 assert_eq!(shared_language([s("fra"), None]), None, "one clip states none");
11860 assert_eq!(shared_language(Vec::<Option<String>>::new()), None, "no sound at all");
11861 }
11862
11863 /// The clips on the audio lanes name the streams the sound comes from: a `und` clip beside
11864 /// a `fra` one leaves the tag out.
11865 #[test]
11866 fn a_mix_of_und_and_french_clips_has_no_tag() {
11867 let path = asset("test_multilang.mp4");
11868 let mut p = Project::single(&path, 30);
11869 assert_eq!(audio_language(&p), None, "the first track is und");
11870 let fra = p.import(&path, 1);
11871 assert!(p.append_clip(fra, 30));
11872 assert_eq!(audio_language(&p), None, "the und clip is still on A1");
11873 }
11874}
11875
11876#[cfg(test)]
11877mod burn_stack_tests {
11878 #[test]
11879 fn two_overlapping_cues_are_both_drawn_stacked() {
11880 use super::{Burn, Cue, cues_on_screen};
11881 use crate::text::TextStyle;
11882 let cue = |text: &str| Cue {
11883 start_us: 0,
11884 end_us: 5_000_000,
11885 text: text.to_string(),
11886 image: None,
11887 words: Vec::new(),
11888 karaoke: Vec::new(),
11889 };
11890 let (w, h) = (640u32, 360u32);
11891 let paint = |cues: Vec<Cue>| {
11892 let mut burn = Burn {
11893 cues,
11894 style: TextStyle {
11895 boxed: false,
11896 ..TextStyle::default()
11897 },
11898 fps: 30.0,
11899 full_range: false,
11900 last: None,
11901 titles: Vec::new(),
11902 title_last: Vec::new(),
11903 };
11904 let y = vec![40u8; (w * h) as usize];
11905 let u = vec![128u8; (w / 2 * (h / 2)) as usize];
11906 let v = u.clone();
11907 burn.paint(30, w, h, (&y, &u, &v))
11908 .expect("a caption is drawn")
11909 };
11910 // The rows that carry a lit (white) pixel in the luma plane.
11911 let lit_rows = |planes: &(Vec<u8>, Vec<u8>, Vec<u8>)| -> Vec<u32> {
11912 (0..h)
11913 .filter(|&r| {
11914 let row = &planes.0[(r * w) as usize..((r + 1) * w) as usize];
11915 row.iter().any(|&l| l > 40)
11916 })
11917 .collect()
11918 };
11919 let cues = vec![cue("First cue"), cue("Second cue")];
11920 assert_eq!(cues_on_screen(&cues, 30, 30.0), vec![0, 1], "both are on screen");
11921 let one = lit_rows(&paint(vec![cue("First cue")]));
11922 let both = lit_rows(&paint(cues));
11923 assert!(
11924 both.len() >= 2 * one.len() - 1,
11925 "second cue not drawn: {} lit rows against {} for the first alone",
11926 both.len(),
11927 one.len()
11928 );
11929 // The first cue keeps its place on the bottom edge; the second stacks above.
11930 assert_eq!(both.last(), one.last(), "the first cue moved");
11931 }
11932}
11933
11934#[cfg(test)]
11935mod chroma_420_tests {
11936 use super::*;
11937
11938 fn asset(name: &str) -> PathBuf {
11939 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
11940 }
11941
11942 /// The layout a chroma plane's sample count names, for each subsampling.
11943 #[test]
11944 fn a_chroma_count_names_its_layout() {
11945 assert_eq!(chroma_shape(64 * 64, 64, 64), Some((64, 64)), "4:4:4");
11946 assert_eq!(chroma_shape(32 * 64, 64, 64), Some((32, 64)), "4:2:2");
11947 assert_eq!(chroma_shape(32 * 32, 64, 64), Some((32, 32)), "4:2:0");
11948 assert_eq!(chroma_shape(3 * 3, 5, 3), Some((3, 3)), "odd 4:4:4 keeps its width");
11949 assert_eq!(chroma_shape(3 * 2, 5, 3), Some((3, 2)), "odd 4:2:2");
11950 assert_eq!(chroma_shape(7, 5, 3), None, "no layout has seven samples");
11951 }
11952
11953 /// A 2x2 block of 4:4:4 chroma becomes its rounded mean.
11954 #[test]
11955 fn a_444_block_averages_to_its_rounded_mean() {
11956 let src: Vec<u16> = vec![1, 2, 3, 4];
11957 assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![3], "(10 + 2) / 4");
11958 let src: Vec<u16> = vec![0, 0, 0, 1];
11959 assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![0], "a quarter rounds down");
11960 let src: Vec<u16> = vec![0, 0, 1, 1];
11961 assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![1], "a half rounds up");
11962 }
11963
11964 /// 4:2:2 has full height, so only the rows pair up.
11965 #[test]
11966 fn a_422_plane_pairs_rows_only() {
11967 // Two columns, four rows: rows (0,1) and (2,3) average, columns stay apart.
11968 let src: Vec<u8> = vec![10, 100, 20, 200, 30, 0, 40, 0];
11969 assert_eq!(chroma_420(&src, 2, 4, 2, 2), vec![15, 150, 35, 0]);
11970 }
11971
11972 /// An odd edge averages the samples there are, and 10-bit samples stay in 10 bits.
11973 #[test]
11974 fn an_odd_edge_and_ten_bit_samples_are_handled() {
11975 // 3x3 chroma down to 2x2: the last column and row are a single sample each,
11976 // so the corner is the 8 alone and the edge pairs are (2, 5) and (6, 7).
11977 let src: Vec<u16> = (0..9).collect();
11978 assert_eq!(chroma_420(&src, 3, 3, 2, 2), vec![2, 4, 7, 8]);
11979 // A 10-bit mean is still a 10-bit value, not a truncated 8-bit one.
11980 let src: Vec<u16> = vec![1023, 1023, 1022, 1023];
11981 assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![1023]);
11982 }
11983
11984 /// The AV1 seat hands the composer 4:2:0 planes for every layout edith decodes
11985 /// (4:2:0, 4:2:2, 4:4:4 and gray), at the size a 4:2:0 picture would have.
11986 #[test]
11987 fn every_av1_fixture_arrives_as_420() {
11988 for name in ["test_av1_444.mp4", "test_av1_422.mp4", "test_av1_12bit.mp4"] {
11989 let mut pictures = Pictures::software(&asset(name), 0, false, Deinterlace::Frame).expect(name);
11990 let Ok(Some(Yuv::Pixels { u, v, width, height, .. })) = pictures.next(None) else {
11991 panic!("{name}: no picture");
11992 };
11993 let (cw, ch) = (width.div_ceil(2) as usize, height.div_ceil(2) as usize);
11994 assert_eq!((u.len(), v.len()), (cw * ch, cw * ch), "{name}: chroma is 4:2:0");
11995 }
11996 for name in ["test_av1_gray.mp4", "test_av1_420.mp4"] {
11997 let mut pictures = Pictures::software(&asset(name), 0, false, Deinterlace::Frame).expect(name);
11998 let Ok(Some(Yuv::Pixels { y, u, v, width, height })) = pictures.next(None) else {
11999 panic!("{name}: no picture");
12000 };
12001 let (cw, ch) = (width.div_ceil(2) as usize, height.div_ceil(2) as usize);
12002 assert_eq!(y.len(), (width * height) as usize, "{name}: luma");
12003 assert_eq!((u.len(), v.len()), (cw * ch, cw * ch), "{name}: chroma is 4:2:0");
12004 if name.contains("gray") {
12005 assert!(u.iter().chain(&v).all(|&s| s == 128), "{name}: grey chroma is 128");
12006 }
12007 }
12008 }
12009}
12010
12011#[cfg(test)]
12012mod planned_sound_tests {
12013 use super::*;
12014
12015 fn asset(name: &str) -> PathBuf {
12016 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
12017 }
12018
12019 /// The sound [`planned_seats`] predicts for `timeline` in an mp4, with the
12020 /// picture's meta taken from `picture`.
12021 fn predicted_sound(timeline: &str, picture: &str) -> &'static str {
12022 let project = Project::single(asset(timeline), 30);
12023 let (meta, _) = Demuxer::open(&asset(picture)).expect("the picture's file opens");
12024 let settings = ExportSettings { format: Format::Mp4, ..Default::default() };
12025 planned_seats(&project, &meta, &settings).1
12026 }
12027
12028 /// A DTS track is decoded by `ec-dts`, so the export predicts an encode of its
12029 /// sound (as it does for an mp3), not the "can't be decoded" card.
12030 #[test]
12031 fn a_dts_source_is_predicted_as_an_encode() {
12032 assert_eq!(
12033 predicted_sound("test_dts.mkv", "test_dts.mkv"),
12034 "AAC · SW encode (ec-aac)"
12035 );
12036 }
12037
12038 /// An mp3 on the timeline has no sample table to copy from: the sound is
12039 /// decoded and encoded as AAC, not copied.
12040 #[test]
12041 fn a_standalone_mp3_source_is_predicted_as_an_encode() {
12042 assert_eq!(
12043 predicted_sound("test_tone.mp3", "test_av.mp4"),
12044 "AAC · SW encode (ec-aac)"
12045 );
12046 }
12047
12048 /// The untouched AAC of an mp4 is still the copy it was.
12049 #[test]
12050 fn an_untouched_aac_mp4_is_still_predicted_as_a_copy() {
12051 assert_eq!(predicted_sound("test_av.mp4", "test_av.mp4"), "AAC copy");
12052 }
12053
12054 /// The HDR meta and picture size of a fixture, as the export reads them.
12055 fn meta_of(name: &str) -> VideoMeta {
12056 Demuxer::open(&asset(name)).expect("the fixture opens").0
12057 }
12058
12059 /// A PQ source is tone-mapped to SDR in every picture export, and the plan says so.
12060 #[test]
12061 fn a_pq_source_is_predicted_as_tone_mapped() {
12062 let project = Project::single(asset("test_pq.mp4"), 30);
12063 let meta = meta_of("test_pq.mp4");
12064 let settings = ExportSettings { format: Format::Mp4, ..Default::default() };
12065 let expected = match ColorDescription::output_sized(meta.width, meta.height).matrix {
12066 Matrix::Bt601 => "HDR (PQ) source tone-mapped to SDR BT.601",
12067 _ => "HDR (PQ) source tone-mapped to SDR BT.709",
12068 };
12069 assert_eq!(planned_tone(&project, &meta, &settings).as_deref(), Some(expected));
12070 }
12071
12072 /// The matrix the words name is the one the file is tagged with: a standard-definition
12073 /// canvas is BT.601 and an HD one BT.709, whatever the source's own size, and a
12074 /// `size` setting moves the canvas the rule is applied to.
12075 #[test]
12076 fn the_tone_map_names_the_matrix_of_the_size_it_is_written_at() {
12077 let project = Project::single(asset("test_pq.mp4"), 30);
12078 let mut hd = meta_of("test_pq.mp4");
12079 hd.width = 1920;
12080 hd.height = 1080;
12081 let mut sd = hd;
12082 sd.width = 720;
12083 sd.height = 576;
12084 let mp4 = ExportSettings { format: Format::Mp4, ..Default::default() };
12085 assert_eq!(
12086 planned_tone(&project, &hd, &mp4).as_deref(),
12087 Some("HDR (PQ) source tone-mapped to SDR BT.709")
12088 );
12089 assert_eq!(
12090 planned_tone(&project, &sd, &mp4).as_deref(),
12091 Some("HDR (PQ) source tone-mapped to SDR BT.601"),
12092 "720x576 is SD, and is tagged BT.601"
12093 );
12094 let small = ExportSettings { size: Some((640, 360)), ..mp4.clone() };
12095 assert_eq!(
12096 planned_tone(&project, &hd, &small).as_deref(),
12097 Some("HDR (PQ) source tone-mapped to SDR BT.601"),
12098 "a 640x360 export is SD though the project is HD"
12099 );
12100 let hd_again = ExportSettings { size: Some((1280, 720)), ..mp4.clone() };
12101 assert_eq!(
12102 planned_tone(&project, &sd, &hd_again).as_deref(),
12103 Some("HDR (PQ) source tone-mapped to SDR BT.709"),
12104 "a 1280x720 export of an SD canvas is HD"
12105 );
12106 }
12107
12108 /// A preview that keeps its source's curve is not tone-mapped, and an SDR timeline or a
12109 /// sound-only format has nothing to say.
12110 #[test]
12111 fn only_a_tone_mapped_picture_is_predicted_as_one() {
12112 let pq = Project::single(asset("test_hdr_sei.mkv"), 30);
12113 let meta = meta_of("test_hdr_sei.mkv");
12114 let keep = ExportSettings {
12115 format: Format::Mp4,
12116 keep_source_colour: true,
12117 ..Default::default()
12118 };
12119 assert_eq!(planned_tone(&pq, &meta, &keep), None, "a preview keeps the curve");
12120 let mp4 = ExportSettings { format: Format::Mp4, ..Default::default() };
12121 assert!(planned_tone(&pq, &meta, &mp4).is_some(), "the mkv's PQ too");
12122 let sdr = Project::single(asset("test_av.mp4"), 30);
12123 assert_eq!(planned_tone(&sdr, &meta, &mp4), None, "an SDR timeline");
12124 let wav = ExportSettings { format: Format::Wav, ..Default::default() };
12125 assert_eq!(planned_tone(&pq, &meta, &wav), None, "no picture to tone-map");
12126 }
12127
12128 /// A size setting draws the export at that size, coded size included, and leaves every
12129 /// other fact of the project's canvas as it is; no size is the project's canvas.
12130 #[test]
12131 fn a_size_setting_moves_the_canvas_and_only_the_canvas() {
12132 let meta = meta_of("test_av.mp4");
12133 let none = ExportSettings::default();
12134 assert_eq!(output_meta(&meta, &none), meta);
12135 let small = ExportSettings { size: Some((640, 360)), ..Default::default() };
12136 let out = output_meta(&meta, &small);
12137 assert_eq!((out.width, out.height), (640, 360));
12138 assert_eq!((out.coded_width, out.coded_height), (640, 360));
12139 assert_eq!(out.frame_rate, meta.frame_rate);
12140 assert_eq!(out.frame_count, meta.frame_count);
12141 assert_eq!(out.pixel_aspect, meta.pixel_aspect);
12142 }
12143
12144 /// An mkv export that is encoded names the codec its mix will get: Opus when the sources
12145 /// put it at 48 kHz mono or stereo, AAC otherwise. `test_av1.mkv` is 44.1 kHz stereo AAC,
12146 /// so its export is AAC, as its done line says; `test_seek_chirp.mkv` is 48 kHz mono Opus.
12147 #[test]
12148 fn a_matroska_export_names_the_codec_its_mix_will_get() {
12149 let settings = ExportSettings { format: Format::Av1, ..Default::default() };
12150 let aac = Project::single(asset("test_av1.mkv"), 30);
12151 let meta = meta_of("test_av1.mkv");
12152 let (_, sound) = planned_seats(&aac, &meta, &settings);
12153 assert_eq!(sound, "AAC · SW encode (ec-aac)");
12154 let opus = Project::single(asset("test_seek_chirp.mkv"), 30);
12155 let meta = meta_of("test_seek_chirp.mkv");
12156 let (_, sound) = planned_seats(&opus, &meta, &settings);
12157 assert_eq!(sound, "Opus · SW encode (ec-opus)");
12158 }
12159}
12160
12161#[cfg(test)]
12162mod vp9_444_tests {
12163 use super::*;
12164
12165 #[test]
12166 fn a_422_or_444_source_names_its_reduction_on_a_video_export() {
12167 let mut settings = ExportSettings { format: Format::Mp4, ..Default::default() };
12168 assert_eq!(
12169 chroma_reduction_words(Codec::Vp9, Chroma::C444, &settings).as_deref(),
12170 Some("VP9 4:4:4 source: chroma reduced to 4:2:0 for export"),
12171 );
12172 assert_eq!(
12173 chroma_reduction_words(Codec::Vp9, Chroma::C422, &settings).as_deref(),
12174 Some("VP9 4:2:2 source: chroma reduced to 4:2:0 for export"),
12175 );
12176 assert_eq!(
12177 chroma_reduction_words(Codec::H264, Chroma::C444, &settings).as_deref(),
12178 Some("H.264 4:4:4 source: chroma reduced to 4:2:0 for export"),
12179 );
12180 assert!(chroma_reduction_words(Codec::Vp9, Chroma::C420, &settings).is_none());
12181 assert!(chroma_reduction_words(Codec::Vp9, Chroma::Gray, &settings).is_none());
12182 for format in [Format::Wav, Format::Flac, Format::Mp3, Format::Ogg, Format::M4a, Format::Opus] {
12183 settings.format = format;
12184 assert!(
12185 chroma_reduction_words(Codec::Vp9, Chroma::C444, &settings).is_none(),
12186 "{format:?} has no picture to reduce",
12187 );
12188 }
12189 }
12190
12191 /// A VP9 profile 1 4:4:4 file is never offered to the GPU on an export: the decode
12192 /// door's gate refuses it before the plugin is asked, so the plugin's refusal never
12193 /// reaches stderr. Stderr is not read in-process; the seam is the plugin's attempt count.
12194 #[test]
12195 fn a_vp9_444_export_never_offers_the_file_to_the_gpu() {
12196 let path = std::env::temp_dir().join(format!("edith-vp9-444-{}.webm", std::process::id()));
12197 let generated = std::process::Command::new("ffmpeg")
12198 .args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=64x64:rate=5:duration=1"])
12199 .args(["-c:v", "libvpx-vp9", "-pix_fmt", "yuv444p", "-f", "webm"])
12200 .arg(&path)
12201 .status()
12202 .map(|status| status.success() && path.exists())
12203 .unwrap_or(false);
12204 if !generated {
12205 eprintln!("no ffmpeg with libvpx-vp9: the 4:4:4 fixture cannot be generated, skipping");
12206 return;
12207 }
12208 let chroma = Demuxer::open(&path).ok().and_then(|(_, demuxer)| demuxer.chroma());
12209 assert_eq!(chroma, Some(Chroma::C444), "the fixture is a 4:4:4 stream");
12210 let (tx, rx) = sync_channel(64);
12211 let before = crate::hw::OPEN_ATTEMPTS.with(|n| n.get());
12212 let _ = decode_stream(&path, 0, None, &tx, None, false, Deinterlace::Frame);
12213 let after = crate::hw::OPEN_ATTEMPTS.with(|n| n.get());
12214 drop(rx);
12215 let _ = std::fs::remove_file(&path);
12216 assert_eq!(after, before, "the GPU was asked for a decoder for a 4:4:4 VP9 file");
12217 }
12218}