forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa888db9Tahinli14 days ago1052 commits

export.rs12559 lines, 564.9 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 it shows a picture at all: a video format, or the PNG and GIF ones.
319 pub fn shows_picture(self) -> bool {
320 self.has_video() || matches!(self, Self::PngSequence | Self::Still | Self::Gif)
321 }
322
323 /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs
324 /// and which of the two AV1 containers is being written are separate
325 /// questions, and this is the first.
326 pub fn is_av1(self) -> bool {
327 matches!(self, Self::Av1 | Self::Av1Mp4 | Self::Webm)
328 }
329
330 /// The same question for HEVC, and the same answer for both its containers:
331 /// one encoder, two boxes to put its stream in.
332 pub fn is_hevc(self) -> bool {
333 matches!(self, Self::Hevc | Self::HevcMp4)
334 }
335
336 /// Whether the file is an mp4 box file (mp4, hevc-mp4, av1-mp4 or m4a), which is what faststart lays out.
337 pub fn is_mp4_family(self) -> bool {
338 matches!(self, Self::Mp4 | Self::HevcMp4 | Self::Av1Mp4 | Self::M4a)
339 }
340
341 /// Whether the picture is ProRes in a QuickTime file ([`Format::ProRes`]).
342 pub fn is_prores(self) -> bool {
343 self == Self::ProRes
344 }
345
346 /// Whether the file is a Matroska one. Only that container carries this
347 /// project's Opus track ([`encode_opus`]): an mp4 may hold Opus by spec, but
348 /// the crate that writes the mp4s here has no sample entry for it, so the
349 /// mp4 formats stay on AAC and say so.
350 fn is_mkv(self) -> bool {
351 matches!(self, Self::Av1 | Self::Hevc | Self::Webm)
352 }
353
354 /// What the format is called where a refusal names it.
355 pub fn name(self) -> &'static str {
356 match self {
357 Self::Mp4 => "an mp4",
358 Self::Webm => "a WebM",
359 Self::Av1 => "an AV1 Matroska",
360 Self::Av1Mp4 => "an AV1 mp4",
361 Self::Hevc => "an HEVC Matroska",
362 Self::HevcMp4 => "an HEVC mp4",
363 Self::Wav => "a WAV",
364 Self::Flac => "a FLAC",
365 Self::Mp3 => "an MP3",
366 Self::Ogg => "an Ogg Vorbis",
367 Self::M4a => "an M4A",
368 Self::Opus => "an Ogg Opus",
369 Self::ProRes => "a ProRes QuickTime",
370 Self::PngSequence => "a PNG sequence",
371 Self::Still => "a PNG still",
372 Self::Gif => "an animated GIF",
373 }
374 }
375}
376
377/// Which encoder writes the picture, as a person picks it on a card. Three
378/// discrete choices and not a switch, because "whatever is best" and "the GPU,
379/// and say so if there is none" are different answers: a driver that encodes
380/// badly wants [`Software`](Self::Software), and a person who *needs* the GPU
381/// (a long delivery, a machine whose CPU is doing something else) wants to be
382/// told when it is not there rather than to wait out a silent fallback.
383#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
384pub enum EncoderSeat {
385 /// Hardware where this machine has a seat for the picked codec, software
386 /// everywhere else -- what every export did before there was a choice, and
387 /// still what an unpicked project does.
388 #[default]
389 Auto,
390 /// The GPU or nothing: no silent fallback, and [`Enc::open`] refuses in
391 /// words before a byte is written. The only way to the plugin's AV1 seat,
392 /// which [`Auto`](Self::Auto) will not enter (see [`Enc::open_av1`]).
393 Hardware,
394 /// The software encoder even where a seat exists -- for a driver that
395 /// encodes badly, and for the AV1 pair, where it is what `Auto` picks too.
396 Software,
397}
398
399impl EncoderSeat {
400 pub const ALL: [EncoderSeat; 3] = [Self::Auto, Self::Hardware, Self::Software];
401
402 /// What a card row and a project file call it. The file's keyword too, so
403 /// the two can never drift ([`crate::edith`]).
404 pub fn name(self) -> &'static str {
405 match self {
406 Self::Auto => "auto",
407 Self::Hardware => "hardware",
408 Self::Software => "software",
409 }
410 }
411
412 /// Reads one back. `None` for anything else, which a project file refuses
413 /// by name rather than silently exporting on another seat.
414 pub fn from_name(name: &[u8]) -> Option<Self> {
415 Self::ALL.into_iter().find(|s| s.name().as_bytes() == name)
416 }
417}
418
419/// The six ProRes profiles ([`Format::ProRes`]). The first four code 4:2:2, the
420/// last two 4:4:4; the encoder's rate is Apple's nominal one for the profile and
421/// the picture size, so a profile *is* the quality row ([`ExportSettings::bitrate`]
422/// means nothing to ProRes).
423#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
424pub enum ProResProfile {
425 Proxy,
426 Lt,
427 Standard,
428 #[default]
429 Hq,
430 P4444,
431 P4444Xq,
432}
433
434impl ProResProfile {
435 pub const ALL: [ProResProfile; 6] =
436 [Self::Proxy, Self::Lt, Self::Standard, Self::Hq, Self::P4444, Self::P4444Xq];
437
438 /// What a card row calls it.
439 pub fn name(self) -> &'static str {
440 match self {
441 Self::Proxy => "ProRes 422 Proxy",
442 Self::Lt => "ProRes 422 LT",
443 Self::Standard => "ProRes 422",
444 Self::Hq => "ProRes 422 HQ",
445 Self::P4444 => "ProRes 4444",
446 Self::P4444Xq => "ProRes 4444 XQ",
447 }
448 }
449
450 /// Whether the profile codes full-resolution chroma (4:4:4).
451 pub fn is_444(self) -> bool {
452 matches!(self, Self::P4444 | Self::P4444Xq)
453 }
454
455 fn codec(self) -> ec_prores::Profile {
456 match self {
457 Self::Proxy => ec_prores::Profile::Proxy,
458 Self::Lt => ec_prores::Profile::Lt,
459 Self::Standard => ec_prores::Profile::Standard,
460 Self::Hq => ec_prores::Profile::Hq,
461 Self::P4444 => ec_prores::Profile::P4444,
462 Self::P4444Xq => ec_prores::Profile::P4444Xq,
463 }
464 }
465}
466
467/// The HDR transfer an HEVC export is written on ([`HdrOutput::transfer`]).
468#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
469pub enum HdrTransfer {
470 /// No HDR: the export is SDR as it always was (tone-mapped from HDR sources).
471 #[default]
472 Sdr,
473 /// SMPTE ST 2084 (HDR10): BT.2020 primaries and matrix, limited range, 10-bit.
474 Pq,
475 /// ARIB STD-B67 (HLG): BT.2020 primaries and matrix, limited range, 10-bit.
476 Hlg,
477}
478
479impl HdrTransfer {
480 pub const ALL: [HdrTransfer; 3] = [Self::Sdr, Self::Pq, Self::Hlg];
481
482 pub fn name(self) -> &'static str {
483 match self {
484 Self::Sdr => "SDR",
485 Self::Pq => "PQ (HDR10)",
486 Self::Hlg => "HLG",
487 }
488 }
489
490 fn colour(self) -> Option<ColorDescription> {
491 let transfer = match self {
492 Self::Sdr => return None,
493 Self::Pq => Transfer::Pq,
494 Self::Hlg => Transfer::Hlg,
495 };
496 Some(ColorDescription { matrix: Matrix::Bt2020Ncl, transfer, full_range: false })
497 }
498}
499
500/// A SMPTE ST 2086 mastering display, in the units the SEI states: chromaticities
501/// in 0.00002 steps, luminance in 0.0001 cd/m2.
502#[derive(Debug, Clone, Copy, PartialEq, Eq)]
503pub struct MasteringDisplay {
504 /// Green, blue, red `(x, y)`, in that order (the SEI's).
505 pub primaries: [(u16, u16); 3],
506 pub white_point: (u16, u16),
507 /// Peak luminance, 0.0001 cd/m2 (1000 nits = 10_000_000).
508 pub max_luminance: u32,
509 /// Black level, 0.0001 cd/m2 (0.005 nits = 50).
510 pub min_luminance: u32,
511}
512
513impl MasteringDisplay {
514 /// A BT.2020-primaries, D65 display with the given peak and black, in nits.
515 pub fn bt2020(max_nits: f32, min_nits: f32) -> Self {
516 Self {
517 primaries: [(8500, 39850), (6550, 2300), (35400, 14600)],
518 white_point: (15635, 16450),
519 max_luminance: (max_nits * 10_000.0).round() as u32,
520 min_luminance: (min_nits * 10_000.0).round() as u32,
521 }
522 }
523
524 /// A DCI-P3 (D65) display, the usual HDR10 grading monitor, with the given
525 /// peak and black in nits.
526 pub fn p3_d65(max_nits: f32, min_nits: f32) -> Self {
527 Self {
528 primaries: [(13250, 34500), (7500, 3000), (34000, 16000)],
529 white_point: (15635, 16450),
530 max_luminance: (max_nits * 10_000.0).round() as u32,
531 min_luminance: (min_nits * 10_000.0).round() as u32,
532 }
533 }
534}
535
536/// HDR output of an HEVC export ([`ExportSettings::hdr`]). The default is none:
537/// every export that does not set it is the SDR file it always was.
538///
539/// With a transfer set the file is 10-bit (an explicit
540/// [`ExportSettings::video_bit_depth`] of 8 is refused), tagged BT.2020 primaries
541/// and matrix with that transfer in the bitstream VUI, the mp4 `colr` box or the
542/// Matroska `Colour` element, and the HDR sources are *not* tone-mapped.
543#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
544pub struct HdrOutput {
545 pub transfer: HdrTransfer,
546 /// Written as a mastering display colour volume SEI (in the bitstream).
547 pub mastering_display: Option<MasteringDisplay>,
548 /// MaxCLL in cd/m2, with `max_fall`, written as a content light level SEI.
549 pub max_cll: Option<u16>,
550 /// MaxFALL in cd/m2.
551 pub max_fall: Option<u16>,
552}
553
554/// What the caller gets to decide about the output. The codec is not among it:
555/// [`Format`] names a container *and* what goes in it, because every pair we
556/// can write is a pair we can also read back.
557#[derive(Debug, Clone, Default, PartialEq)]
558pub struct ExportSettings {
559 /// Bits per second, clamped to the same sane range the automatic value uses.
560 /// `None` picks it from the picture size and frame rate. Video only.
561 pub bitrate: Option<u64>,
562 /// A constant quantiser (0..51 for H.264 and HEVC) instead of a bitrate.
563 pub qp: Option<u32>,
564 /// Which encoder writes the picture ([`EncoderSeat`]). Was a `force_sw`
565 /// flag, which could say "not the GPU" and never "the GPU or say so".
566 /// [`EncoderSeat::Software`] is what the `VE_SW_ENC` env pin still forces
567 /// on every export of a run.
568 pub seat: EncoderSeat,
569 /// The file to write. Defaults to [`Format::Mp4`], which is what every
570 /// caller wrote before there was a choice.
571 pub format: Format,
572 /// The sample depth an AV1 software export is written at: `Some(8)` or
573 /// `Some(10)`, and `None` follows the source -- 10 where any video source of
574 /// the timeline is 10-bit. AV1 and software HEVC (H.264 stays 8-bit, and so do
575 /// the hardware AV1 and HEVC seats, which the 10-bit seats do not take). An HDR
576 /// transfer ([`ExportSettings::hdr`]) and ProRes are always 10-bit.
577 ///
578 /// A 10-bit export is decoded at 10 bits and encoded from its 16-bit planes
579 /// ([`Enc::encode_wide`]) wherever the span passes its picture through
580 /// untouched. A picture composed on the way (a grade, a transform, a fade, a
581 /// dissolve, a caption, a tone map, a layer) is composed at 8 bits as it always
582 /// was and shifted up to the file's depth, so the file is 10-bit either way.
583 pub video_bit_depth: Option<u8>,
584 /// What the *sound* is coded at, in kbps, wherever an encoder writes it --
585 /// the AAC of a video export as much as an MP3. `None` is
586 /// [`DEFAULT_AUDIO_KBPS`], which is what every caller wrote before there
587 /// was a choice, so a settings value nobody touched writes the same bytes
588 /// it used to. Means nothing to WAV and FLAC, which code no rate, and
589 /// nothing to a *copied* AAC track, which carries its source's.
590 pub audio_kbps: Option<u32>,
591 /// Code the sound at [`ExportSettings::audio_kbps`] even where its packets could be copied.
592 pub reencode_audio: bool,
593 /// Bits per sample of the PCM sound in a ProRes `.mov`: 16 or 24. `None` (and
594 /// anything else) is 24. No other format reads it.
595 pub audio_bit_depth: Option<u8>,
596 /// Which of the project's subtitle tracks travel with the file: indices into
597 /// [`Project::subtitles`], which is the same list a front-end picks rows of.
598 /// As many as the timeline holds, in the order given -- the file declares
599 /// them in that order and a player's subtitle menu lists them in it. Empty
600 /// writes none -- what every caller wrote before there was a choice, so an
601 /// export of a timeline without subtitles is the file it always was, byte
602 /// for byte.
603 ///
604 /// Every container that carries picture carries them: Matroska as
605 /// `S_TEXT/UTF8` blocks, an mp4 as a `tx3g` timed-text track
606 /// ([`crate::mux::Mp4Muxer::write_subtitles`]). A Matroska block names its
607 /// track in one byte, so a Matroska file carries at most
608 /// [`crate::mux::MAX_SUB_TRACKS`] of them and asking for more is refused by
609 /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has
610 /// no such ceiling.
611 pub subtitles: Vec<usize>,
612 /// Writes no soft subtitle track at all -- not the lanes, not the picks. The
613 /// captions a file carries are then only the ones [`burn_subtitles`] drew
614 /// into its picture. `false` is what every caller wrote before there was a
615 /// choice, so the lanes and the picks decide as they always did.
616 ///
617 /// [`burn_subtitles`]: ExportSettings::burn_subtitles
618 pub no_soft_subtitles: bool,
619 /// Code every picture as a key frame a decoder may be started from: no
620 /// frame references another, the file is an intraframe master in the shape
621 /// of ProRes, and a seek to any frame at all is one decode.
622 ///
623 /// Bigger files for that, so it is off for delivery and on for the
624 /// stand-ins [`crate::proxy`] makes, which exist precisely to be seeked
625 /// through. This is the switch of the H.264 and HEVC pairs; on HEVC the
626 /// software seat then codes every picture an IDR ([`Enc::open_hevc`]) and
627 /// the hardware seat is already intra. AV1 has no such switch.
628 pub intra_only: bool,
629 /// Captions drawn into the picture: the track at this index in
630 /// [`Project::subtitles`] (the index [`ExportSettings::subtitles`] and
631 /// [`crate::PlaybackSession::timeline_cues`] take), its cue on screen at
632 /// each timeline frame, drawn in this style ([`crate::text`]). `None` writes
633 /// the picture as it is -- what every caller wrote before there was a
634 /// choice.
635 ///
636 /// A burned-in picture is never copied out of its source: it is decoded,
637 /// drawn and encoded, so [`exact_refusal`] names the copy it gives up. The
638 /// cues are the ones the timeline plays, so a rippled edit captions what it
639 /// shows, the way the soft track does.
640 pub burn_subtitles: Option<(usize, TextStyle)>,
641 /// Write the picture in the space its **source** declares -- no tone map to
642 /// SDR, no matrix conversion -- and tag the file with it, instead of
643 /// converting everything into the space the output height implies.
644 ///
645 /// For a preview file and nothing else ([`crate::proxy`]): it makes the
646 /// stand-in a smaller copy of the film rather than a rendition of it, so
647 /// the screen tone-maps it live with whatever preset the project is set to
648 /// -- and it takes the per-frame conversion off the *source's* full
649 /// resolution, which on a 4K HDR film was 48 ms a frame and the whole of a
650 /// proxy's cost (measured 2026-08-13).
651 ///
652 /// A delivery export must leave it off: an mp4 in BT.2020 PQ is a file for
653 /// this editor to read back, not one to hand anybody.
654 pub keep_source_colour: bool,
655 /// Half-open `[start, end)` in timeline frames, or `None` for the whole
656 /// timeline -- what every caller wrote before there was a choice, so an
657 /// export nobody has marked in or out on writes the same bytes it always
658 /// did. Session state, like the mark itself: never saved to a `.edith`.
659 pub range: Option<(u32, u32)>,
660 /// The Exact quality row: this file must be the source's own coded
661 /// picture, copied wherever [`CopyPlan`] already says a copy is exactly
662 /// what the timeline says. `bitrate` and `seat` mean nothing to a copied
663 /// track, but a fallback re-encode (a cut off a sync point, a grade, a
664 /// speed, a transform) still honours them, so a copy-minded caller sends
665 /// `bitrate: None` beside this and gets the automatic figure rather than
666 /// a preset's.
667 ///
668 /// [`exact_refusal`] is the gate a front-end asks before the button is
669 /// pressed; [`run`] asks it again, which is what makes this a setting a
670 /// worker can trust rather than one only the card checked.
671 pub exact: bool,
672 /// The picture's size in pixels for this export alone, `(width, height)`:
673 /// the canvas the file is drawn and encoded at, in place of the project's
674 /// resolution. The project itself is not touched -- [`start`] applies it to
675 /// the export's own copy of the settings, and every clip refits on that
676 /// canvas by its fit mode, as it does when the project's resolution changes.
677 /// `None` is the project's own size, as every caller wrote before there was
678 /// a choice. Each side must be a picture size ([`crate::is_resolution`]) and
679 /// even, which the caller checks: a size here is trusted as given.
680 pub size: Option<(u32, u32)>,
681 /// Chapter marks the file carries, `(start in ns, title)` each, sorted by start. An mp4 gets
682 /// them as a Nero `chpl` and a QuickTime chapter track, a Matroska file as a `Chapters`
683 /// element. Empty writes none, which is what every caller wrote before there was a choice.
684 pub chapters: Vec<(u64, String)>,
685 /// Level the mixed sound to this integrated loudness under this true-peak ceiling before it
686 /// is coded ([`LoudnessTarget`]). `None` writes the mix at the level it was heard at, which
687 /// is what every caller wrote before there was a choice. A track is never *copied* when this
688 /// is set: a packet copy carries no gain.
689 pub loudness: Option<LoudnessTarget>,
690 /// The ProRes profile of a [`Format::ProRes`] export; means nothing to any
691 /// other format. Defaults to [`ProResProfile::Hq`].
692 pub prores_profile: ProResProfile,
693 /// HDR output of an HEVC export ([`Format::Hevc`], [`Format::HevcMp4`]); see
694 /// [`HdrOutput`]. Refused for every other format. The default is none.
695 pub hdr: HdrOutput,
696 /// Speed preset of the software HEVC encoder ([`Format::Hevc`], [`Format::HevcMp4`]); means
697 /// nothing to any other format. `None` is [`HevcSpeed::Default`], the encoder's own search,
698 /// bit-identical to every export written before there was a choice.
699 pub hevc_speed: Option<HevcSpeed>,
700 /// What a GIF asks for beyond the picture ([`Format::Gif`]); means nothing to any other format.
701 pub gif: GifSettings,
702 /// Seconds between key frames of a video export's H.264, HEVC or AV1 picture, `None` for the
703 /// encoder's own. Refused with [`ExportSettings::intra_only`], which codes every picture a key frame.
704 pub keyframe_s: Option<f64>,
705 /// Lays an mp4 out `ftyp`, `moov`, `mdat` so it can start playing before its end. Means
706 /// something only to [`Format::Mp4`], [`Format::HevcMp4`], [`Format::Av1Mp4`] and [`Format::M4a`].
707 pub faststart: bool,
708}
709
710/// The settings of an animated GIF ([`Format::Gif`]): its width in pixels (the height follows
711/// the project's aspect), its frame rate, and whether it loops. The default is the size and rate
712/// a GIF is usually shared at: 480 pixels wide, 15 frames a second, looping forever.
713#[derive(Debug, Clone, Copy, PartialEq, Eq)]
714pub struct GifSettings {
715 pub width: u32,
716 pub fps: u32,
717 pub loop_forever: bool,
718}
719
720impl Default for GifSettings {
721 fn default() -> Self {
722 Self { width: 480, fps: 15, loop_forever: true }
723 }
724}
725
726/// Speed preset of the software HEVC encoder (`ec-h265`'s `Preset`). `Fast` costs about 0-3%
727/// BD-rate for 1.2-1.6x speed, `Faster` up to 27% for about 1.5-2x.
728#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
729pub enum HevcSpeed {
730 #[default]
731 Default,
732 Fast,
733 Faster,
734}
735
736impl HevcSpeed {
737 fn preset(self) -> ec_h265::encoder::Preset {
738 match self {
739 Self::Default => ec_h265::encoder::Preset::Default,
740 Self::Fast => ec_h265::encoder::Preset::Fast,
741 Self::Faster => ec_h265::encoder::Preset::Faster,
742 }
743 }
744}
745
746/// An export-time loudness normalisation: one gain over the whole mix, from
747/// [`crate::loudness::gain_to_target`], so the integrated loudness lands on `lufs` and the true
748/// peak is held at or under `true_peak_dbtp` (the gain is cut back, never a limiter).
749#[derive(Debug, Clone, Copy, PartialEq)]
750pub struct LoudnessTarget {
751 pub lufs: f64,
752 pub true_peak_dbtp: f64,
753}
754
755// Plain finite figures, never NaN: the settings that hold one are `Eq`.
756impl Eq for LoudnessTarget {}
757
758/// Measures `samples` (interleaved) and scales them by the gain that reaches `target`.
759fn level_to_target(samples: &mut [f32], rate: u32, channels: u16, target: LoudnessTarget) {
760 let mut meter = crate::loudness::Meter::new(rate, channels);
761 meter.push(samples);
762 let gain = crate::loudness::gain_to_target(&meter.finish(), target.lufs, target.true_peak_dbtp);
763 if gain != 0.0 {
764 let g = 10f32.powf(gain as f32 / 20.0);
765 for s in samples.iter_mut() {
766 *s *= g;
767 }
768 }
769}
770
771/// The export's picture size: the project's canvas, or the [`ExportSettings::size`]
772/// this export is asked to draw at. Everything that decides what the file's picture
773/// is (the encoder's seat, the copy's gate, the colour matrix) asks it through here,
774/// so the answer each gives is the one the file has.
775pub fn output_meta(meta: &VideoMeta, settings: &ExportSettings) -> VideoMeta {
776 match settings.size {
777 // The coded size goes with the drawn one: a copy's gate compares the coded pair with its
778 // source's, and a picture drawn at another size is not a copy of anything.
779 Some((width, height)) => VideoMeta {
780 width,
781 height,
782 coded_width: width,
783 coded_height: height,
784 ..*meta
785 },
786 None => *meta,
787 }
788}
789
790/// What [`fit_picture_clips`] did: the full-frame clips it put on the policy, per lane (a lane
791/// with none is left out), and how many transformed overlays it left on their own fit.
792#[derive(Debug, Clone, PartialEq, Eq, Default)]
793pub struct FitOutcome {
794 pub lanes: Vec<(Lane, usize)>,
795 pub overlays: usize,
796}
797
798/// Puts every full-frame picture clip of `project` on `fit`, in place. Meant for the export's own
799/// copy of the timeline ([`start`] takes it by value), so the project a user edits keeps its
800/// clips' fit modes. A clip refits on the export's canvas by its fit mode, so this is how an
801/// export asks for `fit` on the pictures that fill the frame.
802///
803/// A clip placed by a transform (moved, scaled, cropped, faded or animated) is an overlay and
804/// keeps its own fit: `fill` would crop it to the canvas's shape, so a logo would lose its
805/// aspect on a vertical canvas. Its size stays relative to the canvas width, as in the project.
806/// The whole change is one undo step on the copy, which nothing reads.
807pub fn fit_picture_clips(project: &mut Project, fit: FitPolicy) -> FitOutcome {
808 let videos: Vec<Lane> = project.lanes().into_iter().filter(|l| l.kind == LaneKind::Video).collect();
809 project.begin_batch();
810 let mut outcome = FitOutcome::default();
811 for lane in videos {
812 let mut count = 0;
813 for idx in 0..project.lane(lane).len() {
814 if is_placed(project, lane, idx) {
815 outcome.overlays += 1;
816 } else {
817 project.set_fit(lane, idx, fit);
818 count += 1;
819 }
820 }
821 if count > 0 {
822 outcome.lanes.push((lane, count));
823 }
824 }
825 project.end_batch();
826 outcome
827}
828
829/// Whether the clip at `idx` of `lane` is placed by a transform that is not the identity, or has
830/// a placement animation: the overlays [`fit_picture_clips`] leaves alone.
831fn is_placed(project: &Project, lane: Lane, idx: usize) -> bool {
832 project.transform_of(lane, idx).is_some_and(|t| !t.is_identity())
833 || !project.transform_keys_of(lane, idx).is_empty()
834}
835
836/// The first moment a burned caption and a title show together in the same place. `cues` are the
837/// burn's cues ([`burn_cues`]) and `place` the burn's own place; a title sits where its
838/// `style.place` says, so a clash is a caption and a title with the same place on screen at once.
839/// Returns the moment in seconds and the index into `titles` of the title, the earliest such
840/// moment; `None` when no caption and title clash.
841pub fn caption_title_clash(cues: &[Cue], titles: &[Title], place: Place, fps: f64) -> Option<(f64, usize)> {
842 let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64;
843 let mut first: Option<(i64, usize)> = None;
844 for (i, t) in titles.iter().enumerate().filter(|(_, t)| t.style.place == place) {
845 let (start, end) = (us(t.start), us(t.end()));
846 for c in cues.iter().filter(|c| c.image.is_none() && !c.text.trim().is_empty()) {
847 let lo = c.start_us.max(start);
848 if lo < c.end_us.min(end) && first.is_none_or(|(f, _)| lo < f) {
849 first = Some((lo, i));
850 }
851 }
852 }
853 first.map(|(lo, i)| (lo as f64 / 1e6, i))
854}
855
856/// The lowest H.264 level (Table A-1) whose frame size and macroblock rate
857/// hold `width`x`height` at `fps_num/fps_den`, as the `level_idc` byte; 62
858/// past the table. One table for both seats: the software encoder writes it
859/// into its SPS (its default is 3.0, which is out of spec above 720p30) and
860/// the plugin hands it to the driver.
861pub fn h264_level_idc(width: u32, height: u32, fps_num: u32, fps_den: u32) -> u8 {
862 const LEVELS: [(u8, u64, u64); 17] = [
863 (10, 1485, 99),
864 (11, 3000, 396),
865 (12, 6000, 396),
866 (13, 11880, 396),
867 (20, 11880, 396),
868 (21, 19800, 792),
869 (22, 20250, 1620),
870 (30, 40500, 1620),
871 (31, 108000, 3600),
872 (32, 216000, 5120),
873 (40, 245760, 8192),
874 (41, 245760, 8192),
875 (42, 522240, 8704),
876 (50, 589824, 22080),
877 (51, 983040, 36864),
878 (52, 2073600, 36864),
879 (60, 4177920, 139264),
880 ];
881 let frame_mbs = u64::from(width.div_ceil(16)) * u64::from(height.div_ceil(16));
882 let fps = f64::from(fps_num.max(1)) / f64::from(fps_den.max(1));
883 let mbps = (frame_mbs as f64 * fps).ceil() as u64;
884 LEVELS
885 .iter()
886 .find(|&&(_, max_mbps, max_fs)| mbps <= max_mbps && frame_mbs <= max_fs)
887 .map_or(62, |&(idc, ..)| idc)
888}
889
890struct Shared {
891 /// Fraction of the job done, in [`PROGRESS_SCALE`]ths.
892 ///
893 /// **Every stage that can run beside another writes this with `fetch_max`,
894 /// never `store`.** The sound and the picture are two threads publishing
895 /// two bands of one bar ([`AUDIO_BAND`]): a `store` from the lower band
896 /// pulls the bar backwards every time the other thread has already moved
897 /// it on, which is what a person sees as a progress bar that stutters
898 /// backwards -- 5,458 backward steps over one film export before this rule
899 /// was written down. A `store` is only correct where nothing else can be
900 /// publishing at all, which now means the terminal [`PROGRESS_SCALE`] and
901 /// the audio-only export ([`run_audio`]) that has no second thread. The
902 /// rule outlives one attempt at the file: an export rerun in software
903 /// because the hardware seat died writes this same atomic, and the bar
904 /// holds where the dead seat left it rather than starting again.
905 progress: AtomicU32,
906 cancel: AtomicBool,
907 finished: AtomicBool,
908 outcome: Mutex<Option<crate::Result<()>>>,
909 /// The encoders this job really opened, published the moment they are
910 /// chosen and never changed after -- one seat for the whole file, which is
911 /// what [`Enc`] states. `None` until then. The one thing that joins it
912 /// afterwards is how much of the edit never got a picture
913 /// ([`Shared::truncated`]), and [`ExportHandle::encoders`] does that
914 /// joining, so a notice cannot land on the line twice.
915 encoders: Mutex<Option<String>>,
916 /// Timeline frames of the edit the walk could not write because a file ran
917 /// out before its clip did ([`run`]'s break). The bar reaches its end
918 /// whatever happens, so without this a truncated file reads as a whole one.
919 /// Published the moment the walk gives up and read by
920 /// [`ExportHandle::encoders`] beside the seat line.
921 truncated: AtomicU32,
922 /// A stage that runs before a span can encode -- a stabilised clip's shake
923 /// being measured ([`crate::stabilise::ensure`]) -- as `1 +` its thousandths
924 /// done, `0` while none runs. Its own fraction, beside [`Shared::progress`]
925 /// rather than in it, which holds still meanwhile ([`ExportHandle::stage`]).
926 measuring: AtomicU32,
927 /// [`ExportSettings::loudness`], for the audio stages that only see `Shared`.
928 loudness: Option<LoudnessTarget>,
929}
930
931/// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per
932/// rendered frame and take the [`result`](ExportHandle::result) when it flips;
933/// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel)
934/// does.
935pub struct ExportHandle {
936 shared: Arc<Shared>,
937 /// The length of the file this export writes, in seconds: the range's, or the
938 /// picture and sound's end for a whole-timeline export. Known before the first frame.
939 length_secs: f64,
940}
941
942impl ExportHandle {
943 /// Fraction of the timeline written, `0.0..=1.0`.
944 pub fn progress(&self) -> f32 {
945 self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32
946 }
947
948 /// The length of the file this export writes, in seconds: the frames it holds at the
949 /// canvas's frame rate, which is the file's duration as a player shows it (a range is
950 /// cut to the picture's end the same way the encoder cuts it).
951 pub fn length_secs(&self) -> f64 {
952 self.length_secs
953 }
954
955 /// Asks the worker to stop at its next checkpoint and delete the partial
956 /// file. The outcome then reports the cancellation as an error. Checkpoints
957 /// run to the last instant before the rename, so even a cancel at full
958 /// progress leaves no output.
959 pub fn cancel(&self) {
960 self.shared.cancel.store(true, Ordering::Relaxed);
961 }
962
963 /// Whether [`cancel`](Self::cancel) was asked: the worker has not yet reached its
964 /// next checkpoint, so the export is still running though it is going to stop.
965 pub fn is_cancelling(&self) -> bool {
966 self.shared.cancel.load(Ordering::Relaxed)
967 }
968
969 pub fn is_finished(&self) -> bool {
970 self.shared.finished.load(Ordering::Acquire)
971 }
972
973 /// What this export is encoding with -- the video seat and what the sound
974 /// is doing -- as the worker chose them, hardware fallback included.
975 /// `None` for the first instants of a job, before the encoder is open.
976 ///
977 /// ...and, where a file ran out under its clip, how much of the edit never
978 /// got a picture. Composed here rather than written into the stored line,
979 /// because that line is published more than once on a rerun (a hardware
980 /// seat that died) and a notice appended at the write site lands twice.
981 pub fn encoders(&self) -> Option<String> {
982 let line = self.shared.encoders.lock().unwrap().clone()?;
983 Some(match self.shared.truncated.load(Ordering::Relaxed) {
984 0 => line,
985 past => format!("{line} · {past} frames of the edit past the last picture"),
986 })
987 }
988
989 /// The stage the export is in when it is not encoding: its name and its own
990 /// fraction done, `0.0..=1.0` -- `("Measuring shake", 0.4)` while a stabilised
991 /// clip with no finished analysis is measured. `None` while it encodes, when
992 /// [`progress`](Self::progress) is the one to show.
993 pub fn stage(&self) -> Option<(&'static str, f32)> {
994 match self.shared.measuring.load(Ordering::Relaxed) {
995 0 => None,
996 n => Some((MEASURING_SHAKE, ((n - 1) as f32 / 1000.0).clamp(0.0, 1.0))),
997 }
998 }
999
1000 /// The outcome, once — taken out of the handle, so a caller that already
1001 /// reported it sees `None` afterwards. `None` while the export is running.
1002 pub fn result(&self) -> Option<crate::Result<()>> {
1003 self.shared.outcome.lock().unwrap().take()
1004 }
1005}
1006
1007/// Starts the worker. Failures are reported through the handle rather than
1008/// returned, so a caller has exactly one place to look. The files to read are
1009/// the project's own [`sources`](Project::sources) -- every clip names one --
1010/// so nothing but the edit list decides what is decoded.
1011pub fn start(
1012 project: Project,
1013 meta: VideoMeta,
1014 out: &Path,
1015 settings: &ExportSettings,
1016 sample_rate: Option<u32>,
1017) -> ExportHandle {
1018 let settings = settings.clone();
1019 // The canvas this export draws at: the project's, unless the settings name another.
1020 let meta = output_meta(&meta, &settings);
1021 let media = project.media_frames();
1022 let frames = match settings.range {
1023 Some((from, to)) => to.min(media).saturating_sub(from),
1024 None => media,
1025 };
1026 let length_secs = f64::from(frames) / meta.frame_rate;
1027 let shared = Arc::new(Shared {
1028 progress: AtomicU32::new(0),
1029 cancel: AtomicBool::new(false),
1030 finished: AtomicBool::new(false),
1031 outcome: Mutex::new(None),
1032 encoders: Mutex::new(None),
1033 truncated: AtomicU32::new(0),
1034 measuring: AtomicU32::new(0),
1035 loudness: settings.loudness,
1036 });
1037 let worker = Arc::clone(&shared);
1038 // A second handle to the same slot, held outside the caught body below --
1039 // what settles it if that body never gets to its own [`settle`] call at
1040 // all, because a codec parser deep inside `run` panicked instead of
1041 // returning the parse error it should have. Without this a panic there
1042 // strands the slot: [`ExportHandle::is_finished`] never flips, and a
1043 // proxy or export that hit a malformed frame sits in "Making" forever.
1044 let panic_worker = Arc::clone(&worker);
1045 let out = out.to_path_buf();
1046 // `<out>.part`, appended rather than substituted: the temporary of
1047 // `a.export.mp4` is `a.export.mp4.part`, which no other export claims.
1048 let mut part = out.clone().into_os_string();
1049 part.push(".part");
1050 let part = PathBuf::from(part);
1051 let spawned = thread::Builder::new().name("export".into()).spawn(move || {
1052 let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1053 // Every file this export will read, named before a byte of one is.
1054 // These are the project's own sources and can be nothing else: a
1055 // stand-in ([`crate::proxy`]) is a substitution playback makes when it
1056 // opens a span, and nothing here knows such a thing exists. Printed so
1057 // that "the delivery came off the film itself" is a grep rather than a
1058 // belief.
1059 for source in project.sources() {
1060 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export source: {}", source.path.display()); }
1061 }
1062 // The rename is the last step and the only one that publishes a file
1063 // under the name the caller asked for; it stays on the same directory,
1064 // so it is atomic.
1065 //
1066 // An emptied timeline is a legal project and an illegal file: no
1067 // picture, no sound, and a muxer that is never created because no coded
1068 // frame arrives. Refused by name here -- before the format is even
1069 // looked at, so an mp4 and a WAV refuse in the same words -- rather than
1070 // left to write a file of no frames that nothing opens. Every caller of
1071 // `start` comes through this, the app's own door
1072 // (`PlaybackSession::is_empty`) being only the first fence.
1073 //
1074 // An audio-only timeline has no picture to give a file, and an mp4 of
1075 // it would be black picture over the sound -- minutes of encoding for a
1076 // video of nothing. So an mp4 of it is written as the sound alone, the
1077 // same AAC track in an mp4 with no picture entry ([`run_aac`]); the
1078 // Matroska and WebM containers, which have no such form, are refused by
1079 // name. The app says the same on the format row before a destination
1080 // is even picked (`mp4_refusal`).
1081 let written = match settings.format {
1082 _ if project.timeline_frames() == 0 => {
1083 Err("the timeline is empty: there is nothing to export".into())
1084 }
1085 Format::PngSequence | Format::Still | Format::Gif if !has_picture(&project) => Err(format!(
1086 "the timeline has no picture: {} would be black. Export an mp4, an \
1087 M4A, WAV, FLAC, MP3, Ogg or Opus, which are the sound itself",
1088 settings.format.name()
1089 )
1090 .into()),
1091 // The pictures are composed one timeline frame at a time, with no sound.
1092 Format::PngSequence => run_png_sequence(&project, &meta, &out, &worker, &settings),
1093 Format::Still => run_still(&project, &meta, &part, &settings),
1094 Format::Gif => run_gif(&project, &meta, &part, &worker, &settings),
1095 format if format.ext() == "mp4" && !has_picture(&project) => {
1096 run_aac(&project, &meta, &part, &worker, &settings, sample_rate)
1097 }
1098 format if format.has_video() && !has_picture(&project) => Err(format!(
1099 "the timeline has no picture: {} would be black. Export an mp4, an \
1100 M4A, WAV, FLAC, MP3, Ogg or Opus, which are the sound itself",
1101 format.name()
1102 )
1103 .into()),
1104 format if format.has_video() => {
1105 let first = run(&project, &meta, &part, &worker, &settings, sample_rate);
1106 match first {
1107 // The hardware encoder's *process* died under the driver
1108 // ([`crate::hwproc`]) -- the editor is still here, and the
1109 // file is still owed. Written again by the software encoder
1110 // for this codec, from the first frame: the pictures the
1111 // dead seat coded are not ones this one may continue from.
1112 //
1113 // Not where a person picked the GPU by name: that export
1114 // refuses in words, the same answer [`hw_seat`] already
1115 // gives a machine with no seat at all, rather than quietly
1116 // spending an hour in an encoder nobody chose.
1117 Err(e)
1118 if crate::hwproc::is_lost(&e)
1119 && settings.seat != EncoderSeat::Hardware =>
1120 {
1121 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export video: {e}; writing it again in software"); }
1122 let _ = std::fs::remove_file(&part);
1123 // The bar is *not* put back to zero: the rerun writes
1124 // it with `fetch_max` like everything else
1125 // ([`Shared::progress`]), so it holds where the dead
1126 // seat left it and moves again once the software
1127 // encoder passes that mark. A person whose GPU has just
1128 // died is the last one who should also watch the bar
1129 // run backwards.
1130 let mut software = settings.clone();
1131 software.seat = EncoderSeat::Software;
1132 run(&project, &meta, &part, &worker, &software, sample_rate)
1133 }
1134 other => other,
1135 }
1136 }
1137 Format::M4a => run_aac(&project, &meta, &part, &worker, &settings, sample_rate),
1138 // Opus codes at 48 kHz and nothing else, so the mix is made there.
1139 Format::Opus => run_audio(&project, &meta, &part, &worker, &settings, Some(OPUS_RATE)),
1140 _ => run_audio(&project, &meta, &part, &worker, &settings, sample_rate),
1141 };
1142 let result = match settings.format {
1143 // A run of pictures is written into the folder it was asked for, which has no
1144 // temporary of its own to publish.
1145 Format::PngSequence => written,
1146 _ => written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)),
1147 };
1148 if result.is_err() {
1149 // The muxer -- and with it the file handle -- died with `run`.
1150 let _ = std::fs::remove_file(&part);
1151 }
1152 settle(&worker, result);
1153 }));
1154 if let Err(payload) = caught {
1155 // The body above panicked before it could settle its own slot --
1156 // the panic message becomes the outcome, so a caller sees a
1157 // failure and a notice rather than a bar that never moves again.
1158 let message = payload
1159 .downcast_ref::<&str>()
1160 .map(ToString::to_string)
1161 .or_else(|| payload.downcast_ref::<String>().cloned())
1162 .unwrap_or_else(|| "unknown panic".to_string());
1163 if !panic_worker.finished.load(Ordering::Acquire) {
1164 // ...and the `.part` the body left behind is deleted here: the
1165 // module promises every failure path removes it, and the only
1166 // path that did was the body's own `result.is_err()` arm, which
1167 // a panic never reaches. Done inside this branch only -- a body
1168 // that *did* settle has already renamed or deleted the file.
1169 let _ = std::fs::remove_file(&part);
1170 settle(
1171 &panic_worker,
1172 Err(format!("export worker panicked: {message}").into()),
1173 );
1174 }
1175 }
1176 });
1177 if let Err(e) = spawned {
1178 settle(&shared, Err(e.into()));
1179 }
1180 ExportHandle { shared, length_secs }
1181}
1182
1183/// Whether any video lane holds anything at all -- what tells an audio-only
1184/// timeline from one that merely opens on a gap. Asked of the *lanes* rather
1185/// than of the sources, because a project may name a video file no clip plays
1186/// from any more.
1187fn has_picture(project: &Project) -> bool {
1188 // A title is a picture of its own: a timeline of nothing but a title card
1189 // over black is a picture, not a black one.
1190 !project.titles().is_empty()
1191 || project
1192 .lanes()
1193 .into_iter()
1194 .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty())
1195}
1196
1197/// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a
1198/// timeline whose export will carry sound from one whose file has none.
1199fn has_sound(project: &Project) -> bool {
1200 project
1201 .lanes()
1202 .into_iter()
1203 .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty())
1204}
1205
1206/// Whether any equalizer on the sound is doing something -- the one edit a
1207/// packet copy cannot carry, so an mp4 whose lane has one is decoded and
1208/// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane:
1209/// the copy path has exactly one by the time it asks, and [`planned_audio`] is
1210/// asked before that is settled.
1211fn equalized(project: &Project) -> bool {
1212 project.audio_lanes().into_iter().any(|lane| {
1213 (0..project.lane(lane).len())
1214 .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity()))
1215 })
1216}
1217
1218/// How many timeline frames before a ranged export's start the mix is opened, so the voice
1219/// chain's envelopes and the noise reduction's overlap are warm when the range begins
1220/// instead of starting from silence ([`voice`](crate::voice)). Half a second, as far back as
1221/// the timeline goes; none when no lane has a processor on. [`warm_up_samples`] is how much
1222/// of the mix's front that is, taken off again.
1223fn warm_up(project: &Project, offset: u32, fps: f64) -> u32 {
1224 if offset == 0 || !project.audio_voices().iter().any(crate::voice::VoiceFx::is_active) {
1225 return 0;
1226 }
1227 offset.min((fps * 0.5).ceil() as u32)
1228}
1229
1230/// How many interleaved samples the `pre` frames of [`warm_up`] before `range_start` are:
1231/// the samples the timeline's mix puts between the two frames, counted with the mixer's own
1232/// rounding ([`timeline_sample`](crate::audio::timeline_sample)), so the range starts on the
1233/// same sample a full export has there. Rounding the pre-roll's own length instead can miss
1234/// by one at 29.97 or 23.976 fps.
1235fn warm_up_samples(range_start: u32, pre: u32, fps: f64, rate: u32, channels: usize) -> usize {
1236 let at = |frame: u32| crate::audio::timeline_sample(f64::from(frame) / fps, rate);
1237 (at(range_start) - at(range_start - pre)) as usize * channels
1238}
1239
1240/// Whether the *mix* is doing something -- a lane turned off unity, a lane
1241/// ducked under another, or a limiter in circuit. [`equalized`]'s pair, and a
1242/// copy cannot carry any of them: all live where the lanes are summed
1243/// ([`AudioSession::open_mixed_streams_master`]), and a copied packet was never
1244/// summed at all. An mp4 whose timeline is mixed is decoded and re-encoded.
1245fn mastered(project: &Project) -> bool {
1246 project.limiter().is_active()
1247 || project.audio_gains().iter().any(|&g| g != 1.0)
1248 || project.audio_ducks().iter().any(|lane| !lane.is_empty())
1249 || project.audio_voices().iter().any(crate::voice::VoiceFx::is_active)
1250}
1251
1252/// Whether any audio clip has a fade -- [`equalized`]'s pair again: a fade is
1253/// gain math on decoded samples ([`crate::project::Fade::apply`]), and a
1254/// packet copy carries neither an equalizer nor a fade. An mp4 whose timeline
1255/// has one is decoded and re-encoded so the fade actually reaches the file.
1256fn faded(project: &Project) -> bool {
1257 project.audio_lanes().into_iter().any(|lane| {
1258 project
1259 .lane(lane)
1260 .iter()
1261 .any(|c| c.fade_in > 0 || c.fade_out > 0)
1262 })
1263}
1264
1265/// The bitrate an export codes at: the caller's number clamped into what an
1266/// asked-for rate may be ([`MIN_BITRATE`]..[`MAX_EXPLICIT_BITRATE`]), the
1267/// derived one where there was none. Clamped rather than refused, for the
1268/// reason [`Enc::open`] states.
1269fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 {
1270 settings.bitrate.map_or_else(
1271 || bitrate_for(meta),
1272 |b| b.clamp(MIN_BITRATE, MAX_EXPLICIT_BITRATE),
1273 )
1274}
1275
1276fn rate_of(meta: &VideoMeta, settings: &ExportSettings) -> SeatRate {
1277 match settings.qp {
1278 Some(qp) => SeatRate::ConstantQp(qp),
1279 None => SeatRate::Bitrate(bitrate_of(meta, settings)),
1280 }
1281}
1282
1283/// The pictures between key frames the caller asked for, `None` for the encoder's own.
1284fn gop_frames(meta: &VideoMeta, settings: &ExportSettings) -> Option<u32> {
1285 settings.keyframe_s.map(|s| (meta.frame_rate * s).round().max(1.0) as u32)
1286}
1287
1288/// The rate the sound codes at: the caller's pick clamped into the offered
1289/// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused,
1290/// for [`bitrate_of`]'s reason -- a number out of range is a caller's slip and
1291/// not a file worth failing.
1292fn audio_kbps_of(settings: &ExportSettings) -> u32 {
1293 // 384 is above the offered rows, which a preset asks for (YouTube's AAC); MP3 has no such rate.
1294 let ceiling = if settings.format == Format::Mp3 { AUDIO_KBPS[3] } else { AAC_MAX_KBPS };
1295 settings.audio_kbps.map_or(DEFAULT_AUDIO_KBPS, |k| k.clamp(AUDIO_KBPS[0], ceiling))
1296}
1297
1298/// The hardware seat for these settings, opened exactly as the export opens it
1299/// -- the same pins, the same dimensions a driver may refuse -- or `None` where
1300/// the software encoder takes the file. The single place that choice is made,
1301/// which is what lets [`planned_video`] *measure* it instead of promising it.
1302///
1303/// `Err` is the one answer the software encoder does **not** take over from:
1304/// [`EncoderSeat::Hardware`] asked for the GPU by name and this machine has no
1305/// seat for the codec, so the export refuses in words rather than falling back
1306/// to an encoder nobody picked. Every caller is before a file exists
1307/// ([`Enc::open`] runs ahead of the muxer), which is what makes the refusal
1308/// free.
1309fn hw_seat(
1310 meta: &VideoMeta,
1311 settings: &ExportSettings,
1312 ten_bit: bool,
1313 colour: ColorDescription,
1314) -> crate::Result<Option<HwEncoder>> {
1315 if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") {
1316 return Ok(None);
1317 }
1318 if ten_bit && settings.format.is_hevc() && hdr_metadata(settings) {
1319 if settings.seat == EncoderSeat::Hardware {
1320 return Err("the hardware HEVC seat writes no mastering display or MaxCLL/MaxFALL SEI: \
1321 drop that metadata, or pick Auto or Software"
1322 .into());
1323 }
1324 return Ok(None);
1325 }
1326 let opened = open_hw_seat(meta, settings, ten_bit, colour);
1327 if opened.is_none() && settings.seat == EncoderSeat::Hardware {
1328 return Err(format!(
1329 "hardware encoding was asked for and this machine has no VA-API seat for {}{}: \
1330 pick Auto or Software on the export card",
1331 if ten_bit { "10-bit " } else { "" },
1332 settings.format.name()
1333 )
1334 .into());
1335 }
1336 Ok(opened)
1337}
1338
1339/// The plugin half of [`hw_seat`]: what the driver gives for this codec and
1340/// this picture, with no policy in it but the AV1 one.
1341/// Whether the export carries HDR static metadata, which only the software HEVC seat writes.
1342fn hdr_metadata(settings: &ExportSettings) -> bool {
1343 let hdr = &settings.hdr;
1344 hdr.mastering_display.is_some() || hdr.max_cll.is_some() || hdr.max_fall.is_some()
1345}
1346
1347fn open_hw_seat(
1348 meta: &VideoMeta,
1349 settings: &ExportSettings,
1350 ten_bit: bool,
1351 colour: ColorDescription,
1352) -> Option<HwEncoder> {
1353 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
1354 let rate = rate_of(meta, settings);
1355 match settings.format {
1356 // Both HEVC formats sit on the plugin's HEVC seat, GOP or intra as the
1357 // export asks. `None` here is the plugin's own "no" -- no entrypoint, or
1358 // a picture under the driver's 384x384 floor -- and the software seat
1359 // takes it. The colour goes in at the open, from the same
1360 // [`ColorDescription::output`] rule the software seat's VUI and both
1361 // containers' tags come from, so the file cannot say one thing in its
1362 // bitstream and another in its header.
1363 format if format.is_hevc() && settings.intra_only => HwEncoder::open_hevc_intra(
1364 meta.width,
1365 meta.height,
1366 fps_num,
1367 fps_den,
1368 rate,
1369 colour,
1370 ten_bit,
1371 ),
1372 format if format.is_hevc() => HwEncoder::open_hevc(
1373 meta.width,
1374 meta.height,
1375 fps_num,
1376 fps_den,
1377 rate,
1378 colour,
1379 gop_frames(meta, settings),
1380 ten_bit,
1381 ),
1382 // Asked for by name only, for the reason [`Enc::open_av1`] states in
1383 // full: `Auto` takes the software encoder here and nowhere else. Both
1384 // AV1 formats sit on it: the container is not the encoder's business.
1385 format if format.is_av1() && settings.seat != EncoderSeat::Hardware => None,
1386 format if format.is_av1() => {
1387 HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, rate, gop_frames(meta, settings))
1388 }
1389 // An intra-only H.264 file is a *different seat*, not the same seat with
1390 // a flag on the pictures: asking this one for a key frame every time
1391 // gets I slices that are not IDRs and carry no parameter sets, which is
1392 // a file with one starting point in it however many I pictures it holds
1393 // (measured: a 60-frame hardware proxy, 1 sync point of 60). `None`
1394 // where the plugin is older than that seat, and then the software
1395 // encoder takes the file -- its `gop_size = 1` writes what was asked
1396 // for, slowly, which is the only honest fallback here.
1397 //
1398 // Only H.264 reaches this arm: the arms above take every HEVC and AV1 format.
1399 _ if settings.intra_only => {
1400 HwEncoder::open_intra(meta.width, meta.height, fps_num, fps_den, rate)
1401 }
1402 _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, rate, gop_frames(meta, settings)),
1403 }
1404}
1405
1406/// True when an Annex B HEVC access unit holds an IRAP picture (NAL types 16..=23).
1407fn hevc_irap(au: &[u8]) -> bool {
1408 au.windows(4)
1409 .any(|w| w[0] == 0 && w[1] == 0 && w[2] == 1 && (16..=23).contains(&((w[3] >> 1) & 0x3F)))
1410}
1411
1412/// What a hardware encode is called wherever one is named -- the card's line
1413/// before the export and the progress line during it.
1414const HW_LABEL: &str = "HW encode (VA-API)";
1415
1416/// ...and what a card says instead where [`EncoderSeat::Hardware`] was picked
1417/// and there is no seat: the export's own refusal in the width of a card row,
1418/// shown *before* the button is pressed rather than a minute into a file.
1419pub const NO_HW_SEAT: &str = "no HW seat here — pick Auto or Software";
1420
1421/// How a front-end names a video seat: which of the two encoders has the file,
1422/// and which library that is. Not the codec -- a caller shows this beside the
1423/// format it picked, and `rav1e` names AV1 as `ec-h264` names H.264. One
1424/// place, so what a card says before an export and what its progress line says
1425/// during one cannot drift apart.
1426fn video_label(format: Format, hw: bool, intra: bool) -> &'static str {
1427 match (format, hw) {
1428 (_, true) => HW_LABEL,
1429 (Format::Hevc | Format::HevcMp4, false) if intra => "SW encode (ec-h265 intra)",
1430 (Format::Hevc | Format::HevcMp4, false) => "SW encode (ec-h265 GOP)",
1431 (Format::Av1 | Format::Av1Mp4 | Format::Webm, false) => "SW encode (rav1e)",
1432 (Format::ProRes, false) => "SW encode (ec-prores)",
1433 (_, false) => "SW encode (ec-h264)",
1434 }
1435}
1436
1437/// Whether the *edit* has touched the samples a copy would carry out: the one
1438/// predicate both copy-or-encode decisions ask, with `lanes` the sound's own
1439/// list as the caller has it -- every audio lane for the question a card asks
1440/// before the button ([`forces_encode`]), and the single lane the segments have
1441/// already narrowed a copy to ([`copy_audio`]).
1442///
1443/// One function and not two lists of the same conditions, which is what they
1444/// were: `faded` reached [`forces_encode`] and not [`copy_audio`]'s gate, so an
1445/// mp4 whose lane carried a fade wrote the source's own packets with the fade
1446/// nowhere, while the card had promised a re-encode -- and the WAV, FLAC and
1447/// MP3 exports of the same project applied it. Two gates that cannot be given
1448/// two answers is the fix; the drift was the defect.
1449fn sample_altered(project: &Project, lanes: &[Lane]) -> bool {
1450 // Two lanes are a mix and a mix is not a copy; a speeded lane is resampled;
1451 // an equalizer, a fade and the mix itself are gain math on decoded samples
1452 // ([`equalized`], [`faded`], [`mastered`]). None of them is inside a packet.
1453 lanes.len() > 1
1454 || lanes
1455 .iter()
1456 .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal() || !c.speed_keys.is_empty() || c.reversed))
1457 || equalized(project)
1458 || mastered(project)
1459 || faded(project)
1460}
1461
1462/// The cheap half of "does this timeline's sound have to be re-encoded": what
1463/// the *edit* says, with no file opened ([`sample_altered`], asked of every
1464/// audio lane). The other half -- whether the sources can be copied out of at
1465/// all -- costs a file open each and belongs to [`copy_audio`], which may
1466/// re-encode where this says copy.
1467fn forces_encode(project: &Project, ranged: bool) -> bool {
1468 // A ranged export needs an exact offset and an exact length, which a copy
1469 // of the source's own packets cannot give it ([`copy_audio`]) -- so a
1470 // range marked at all always encodes, whatever the lanes look like.
1471 ranged || sample_altered(project, &project.audio_lanes())
1472}
1473
1474/// What the sound is written by. Every audio encoder here is software -- there
1475/// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and
1476/// whether a container escapes encoding altogether by copying the packets it was
1477/// given. Both AV1 formats are in it like the mp4: an AV1 export carries the
1478/// timeline's sound too, so leaving it unnamed would be the old lie.
1479///
1480/// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a
1481/// card asking before the export has no way to know (a source that cannot be
1482/// copied out of is only found by opening it). `None` predicts from the edit
1483/// alone.
1484fn audio_label(
1485 project: &Project,
1486 format: Format,
1487 sound: bool,
1488 copied: Option<bool>,
1489 ranged: bool,
1490 reencode: bool,
1491) -> &'static str {
1492 if !sound {
1493 return "no sound to write";
1494 }
1495 match format {
1496 Format::Wav => "PCM · SW (ec-riff)",
1497 Format::Flac => "FLAC · SW (ec-flac)",
1498 Format::Mp3 => "MP3 · SW (ec-mp3)",
1499 Format::Ogg => "Vorbis · SW (ec-vorbis)",
1500 Format::Opus => "Opus · SW (ec-opus)",
1501 Format::ProRes => "PCM · SW (16-bit, mov)",
1502 // Never a copy: WebM carries Opus, and the sound is mixed and encoded
1503 // for it at 48 kHz ([`start`], [`encode_audio`]).
1504 Format::Webm => "Opus · SW encode (ec-opus)",
1505 _ => match copied.unwrap_or(!(reencode || forces_encode(project, ranged))) {
1506 true => "AAC copy",
1507 // A Matroska file gets Opus where the mix allows it -- 48 kHz and
1508 // stereo, which is every Opus source and most of everything else --
1509 // and AAC where it does not ([`encode_audio`]). Which of the two it
1510 // will be cannot be known here: both answers need a source opened,
1511 // and this function may be asked per repaint. So the card names the
1512 // codec it will nearly always be, as a prediction like the copy above
1513 // it, and the line the export publishes while it runs is the measured
1514 // one ([`run`]) -- it says AAC when the fallback took it, so the
1515 // fallback is visible rather than silent.
1516 //
1517 // It is one line and 76 characters wide (`summary_head` in the app
1518 // has the test), which is why the condition is in this comment
1519 // instead of in the string.
1520 false if format.is_mkv() => "Opus · SW encode (ec-opus)",
1521 false => "AAC · SW encode (ec-aac)",
1522 },
1523 }
1524}
1525
1526/// What the export *did* to the sound, for the line it publishes while it runs:
1527/// [`audio_label`]'s words with the one thing no prediction can know filled in
1528/// -- whether the Opus seat took the track or handed it back
1529/// ([`encode_opus`]'s gate).
1530///
1531/// `sound` is `Some(copied)` for a track and `None` for a file with no sound.
1532/// Naming Opus for *every* Matroska encode is what made that fallback
1533/// invisible: a track the gate refused was written as AAC and the line still
1534/// said Opus, on the one path where the difference is audible.
1535fn measured_audio_label(
1536 project: &Project,
1537 format: Format,
1538 sound: Option<bool>,
1539 opus: bool,
1540) -> &'static str {
1541 match (sound, opus) {
1542 (_, true) => "Opus · SW encode (ec-opus)",
1543 // Encoded, into a container that would have carried Opus, and it is not
1544 // Opus: the fidelity gate sent it to AAC ([`OPUS_MIN_FIDELITY`]), or
1545 // the mix was not 48 kHz at a width the seat is measured in.
1546 (Some(false), false) if format.is_mkv() => "AAC · SW encode (ec-aac)",
1547 // `sound` is already what happened, not a prediction, so `copied` is
1548 // filled in and `ranged` never reaches the branch that reads it.
1549 _ => audio_label(project, format, sound.is_some(), sound, false, false),
1550 }
1551}
1552
1553/// What [`start`] would write this timeline's sound with, before one is
1554/// started. Pure: no probe and no file opened, so a card may ask it per
1555/// repaint. `ranged` is whether the export a card is describing is bounded to
1556/// a marked range -- a copy needs the source's own packets to *be* the file,
1557/// which a range's exact offset and length rule out ([`copy_audio`]).
1558pub fn planned_audio(project: &Project, format: Format, ranged: bool) -> &'static str {
1559 audio_label(project, format, has_sound(project), None, ranged, false)
1560}
1561
1562/// Why the sound's rate is nothing this timeline can be asked about in this
1563/// format, or `None` where it is a real choice: there is no sound to write, the
1564/// format codes the samples themselves, or the packets are the source's own and
1565/// carry the rate *it* was coded at. Pure, like [`planned_audio`], and a
1566/// prediction in the same way -- a copy that turns out impossible (a source no
1567/// mp4 sample table holds) falls through to [`encode_audio`], which codes at
1568/// [`ExportSettings::audio_kbps`] like every other encode. So the value travels
1569/// even where this refuses; what it cannot do is silently write a rate nobody
1570/// picked.
1571pub fn audio_rate_refusal(project: &Project, format: Format, ranged: bool, reencode: bool) -> Option<&'static str> {
1572 match format {
1573 _ if !has_sound(project) => Some("no sound to write"),
1574 Format::Wav | Format::Flac | Format::ProRes => Some("lossless — the samples themselves, at no rate"),
1575 // Vorbis is written at one measured operating point ([`VORBIS_QUALITY`]
1576 // + [`VORBIS_TARGET_BPS`]), not at a rate a user may pick: its actual
1577 // landing moves with the content around that target (124-134 kbps
1578 // across this suite's bench inputs), so a live rate row would print a
1579 // figure the file does not hold -- the one thing this card is built
1580 // not to do.
1581 Format::Ogg => Some("quality-coded — Vorbis holds no rate to pick"),
1582 // The bitrate is the one choice WebM leaves: Opus at the rate picked.
1583 Format::Mp3 | Format::Webm | Format::Opus => None,
1584 _ if reencode || forces_encode(project, ranged) => None,
1585 _ => Some("the source's own packets are copied — at the rate they hold"),
1586 }
1587}
1588
1589/// The soft subtitle tracks an export carries: the lanes the timeline places, each
1590/// as its placement (the lanes a pick reaches), then every picked track no lane
1591/// places, whole. Empty where it carries none: no pick and no placement, a pick
1592/// nothing answers, a track that could not be read, one with no cue left on the
1593/// exported timeline -- and every format that is the sound alone, which has
1594/// nowhere to put them. Filtered *per track*, so one unusable pick costs its own
1595/// row and not the others.
1596///
1597/// Both containers, since the mp4 muxer gained its `tx3g` track: what the two
1598/// do with the very same [`SubParams`] is theirs to say
1599/// ([`crate::mux::Mp4Muxer::write_subtitles`], [`MkvMuxer`]), and nothing here
1600/// asks which one is being written.
1601fn export_subtitles(
1602 project: &Project,
1603 meta: &VideoMeta,
1604 settings: &ExportSettings,
1605) -> Vec<SubParams> {
1606 // WebM has no subtitle track this writer can state: [`planned_subtitles`]
1607 // says so on the card, and nothing is written.
1608 if !settings.format.has_video() || matches!(settings.format, Format::Webm | Format::ProRes) || !has_picture(project) {
1609 return Vec::new();
1610 }
1611 // Burned captions are the only ones this file carries: a soft track of the
1612 // same words would show them twice.
1613 if settings.no_soft_subtitles {
1614 return Vec::new();
1615 }
1616 // Words placed on a lane are written through the lanes, at their placement
1617 // (`lane_subtitle`; none when nothing is placed). A picked track that no lane
1618 // places is written whole beside them, as it always was: the palette's pick
1619 // is the only say it has in the file, so it must not be dropped for a lane
1620 // elsewhere. A placed track is never written twice. The tracks go in the
1621 // order the caller gave them ([`soft_order`]), placed or not.
1622 let lanes = placed_lanes(project);
1623 let mut subs = Vec::new();
1624 for entry in soft_order(project, &lanes, &settings.subtitles) {
1625 match entry {
1626 SoftEntry::Lane(lane) => subs.extend(lane_subtitle(
1627 project,
1628 lane,
1629 meta.frame_rate,
1630 settings.range,
1631 &settings.subtitles,
1632 )),
1633 SoftEntry::Track(pick) => subs.extend(whole_track(project, meta, settings, pick)),
1634 }
1635 }
1636 subs
1637}
1638
1639/// Whether a track has a cue the file would carry: any cue at all on the whole timeline, or one
1640/// left inside `range` (on the clock the range is cut to, as [`written_cues`] cuts it).
1641fn track_has_cues(project: &Project, track: &SubtitleTrack, range: Option<(u32, u32)>, fps: f64) -> bool {
1642 match range {
1643 None => !track.cues.is_empty(),
1644 Some(_) => !written_cues(timeline_cues(project, track, fps), range, fps, project.media_frames()).is_empty(),
1645 }
1646}
1647
1648/// The reason a track with nothing to carry is dropped, in the card's words.
1649fn no_cues_word(range: Option<(u32, u32)>) -> &'static str {
1650 if range.is_some() { "no cues in range" } else { "no cues" }
1651}
1652
1653/// The labels of the written soft tracks whose styling the file drops: a standalone ASS or SSA
1654/// script whose lines carry override blocks (`{\i1}`, `{\an8}`), which a cue's plain text does not
1655/// keep. An embedded ASS track is not read here, so it is not named. Empty when none is.
1656pub fn stripped_styling(project: &Project, picks: &[usize]) -> Vec<String> {
1657 let lanes = placed_lanes(project);
1658 let placed = placed_tracks(project);
1659 let mut used: std::collections::BTreeSet<usize> = picks.iter().copied().filter(|p| !placed.contains(p)).collect();
1660 for &lane in &lanes {
1661 let on_lane = project.sub_lane(lane);
1662 if picked(on_lane, picks) {
1663 used.extend(on_lane.iter().map(|s| s.track));
1664 }
1665 }
1666 used.into_iter()
1667 .filter_map(|i| project.subtitles().get(i))
1668 .filter(|t| t.refused.is_none() && !t.is_bitmap() && t.track.is_none() && has_override_blocks(&t.path))
1669 .map(|t| t.label.clone())
1670 .collect()
1671}
1672
1673/// Whether `path` is an ASS or SSA script with an override block in it.
1674fn has_override_blocks(path: &Path) -> bool {
1675 let ass = path
1676 .extension()
1677 .and_then(|e| e.to_str())
1678 .is_some_and(|e| e.eq_ignore_ascii_case("ass") || e.eq_ignore_ascii_case("ssa"));
1679 ass && std::fs::read_to_string(path).is_ok_and(|text| text.contains("{\\"))
1680}
1681
1682/// One soft track of the file: a subtitle lane (written through its placements) or a picked
1683/// track no lane places (written whole).
1684#[derive(Clone, Copy, Debug, PartialEq)]
1685enum SoftEntry {
1686 Lane(Lane),
1687 Track(usize),
1688}
1689
1690/// The soft tracks the file writes, in the order the file declares them. With picks, that is
1691/// the order the caller gave them: a lane goes where the first pick that reaches it sits, and a
1692/// pick no lane places goes whole in its own place. Without picks, every placed lane in lane
1693/// order and no whole track.
1694fn soft_order(project: &Project, lanes: &[Lane], picks: &[usize]) -> Vec<SoftEntry> {
1695 if picks.is_empty() {
1696 return lanes.iter().map(|&l| SoftEntry::Lane(l)).collect();
1697 }
1698 let placed = placed_tracks(project);
1699 let mut out: Vec<SoftEntry> = Vec::new();
1700 for &pick in picks {
1701 let entry = if placed.contains(&pick) {
1702 match lanes.iter().find(|&&l| project.sub_lane(l).iter().any(|s| s.track == pick)) {
1703 Some(&lane) => SoftEntry::Lane(lane),
1704 None => continue,
1705 }
1706 } else {
1707 SoftEntry::Track(pick)
1708 };
1709 if !out.contains(&entry) {
1710 out.push(entry);
1711 }
1712 }
1713 out
1714}
1715
1716/// One picked track written whole, on the timeline's clock and clipped to the range
1717/// and the picture. `None` for a track that writes nothing: no row for the pick, a
1718/// track that could not be read, a picture track (the muxer writes words), or no cue
1719/// left in the file.
1720fn whole_track(
1721 project: &Project,
1722 meta: &VideoMeta,
1723 settings: &ExportSettings,
1724 pick: usize,
1725) -> Option<SubParams> {
1726 let track = project.subtitles().get(pick)?;
1727 // A picture is not a line: the muxer writes an `S_TEXT/UTF8` track and a PGS cue
1728 // has no words to put in one. `planned_subtitles` says so before the button is
1729 // pressed rather than the file coming out short.
1730 if track.refused.is_some() || track.is_bitmap() {
1731 return None;
1732 }
1733 let cues = written_cues(
1734 timeline_cues(project, track, meta.frame_rate),
1735 settings.range,
1736 meta.frame_rate,
1737 project.media_frames(),
1738 );
1739 // The container's own two fields, carried as two
1740 // ([`SubtitleTrack::language`]): a `TrackEntry` with no `Language` means `eng`
1741 // by spec, so a French track that arrives here as one flattened string leaves
1742 // as an English one.
1743 (!cues.is_empty()).then(|| SubParams {
1744 language: track.language.clone(),
1745 name: subtitle_title(track),
1746 cues,
1747 })
1748}
1749
1750/// The title a soft subtitle track is written under. An embedded track keeps the
1751/// title its container gave it; a standalone file has none of its own, so it is
1752/// titled with its language's name (`French`) or left untitled -- never with its
1753/// file name.
1754fn subtitle_title(track: &SubtitleTrack) -> String {
1755 match track.track {
1756 Some(_) => track.name.clone(),
1757 None => crate::subtitle::language_name(&track.language).unwrap_or_default().to_string(),
1758 }
1759}
1760
1761/// The indices of the tracks some placement on a subtitle lane names. Those tracks
1762/// are written through their lanes, so a pick of one of them is not written whole.
1763fn placed_tracks(project: &Project) -> std::collections::BTreeSet<usize> {
1764 project
1765 .subtitle_lanes()
1766 .into_iter()
1767 .flat_map(|lane| project.sub_lane(lane).iter().map(|s| s.track))
1768 .collect()
1769}
1770
1771/// The labels of the soft subtitle tracks this export writes whose cues overlap. An mp4
1772/// writes an overlap as one stretch with both lines in it (`mux`'s `timed_text`), so the
1773/// cue times the timeline holds are not the file's; an mkv keeps every cue. Empty when
1774/// nothing is written or no two cues of a written track overlap.
1775pub fn overlapping_subtitles(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Vec<String> {
1776 export_subtitles(project, meta, settings)
1777 .into_iter()
1778 .filter(|t| {
1779 let mut spans: Vec<(i64, i64)> = t.cues.iter().map(|c| (c.start_us, c.end_us)).collect();
1780 spans.sort_unstable();
1781 let mut reach = i64::MIN;
1782 spans.iter().any(|&(start, end)| {
1783 let overlap = start < reach;
1784 reach = reach.max(end);
1785 overlap
1786 })
1787 })
1788 .map(|t| match (t.name.is_empty(), t.language.is_empty()) {
1789 (false, _) => t.name,
1790 (true, false) => t.language,
1791 (true, true) => "an unnamed track".to_string(),
1792 })
1793 .collect()
1794}
1795
1796/// Whether a lane with these placements is in the file: an empty pick list is
1797/// every lane, otherwise the lane must hold at least one placement of a picked
1798/// track ([`Project::subtitles`] index, as [`ExportSettings::subtitles`] gives).
1799fn picked(placed: &[crate::project::SubClip], picks: &[usize]) -> bool {
1800 picks.is_empty() || placed.iter().any(|s| picks.contains(&s.track))
1801}
1802
1803/// The project's subtitle lanes in display order, and empty where **nothing is
1804/// placed on any of them** -- an empty list is what the export and the card both
1805/// read as "this project does not use lanes yet", so a project holding a bare
1806/// `S1` nobody dropped a caption on still exports by the pick list.
1807fn placed_lanes(project: &Project) -> Vec<Lane> {
1808 let lanes = project.subtitle_lanes();
1809 match lanes.iter().any(|&l| !project.sub_lane(l).is_empty()) {
1810 true => lanes,
1811 false => Vec::new(),
1812 }
1813}
1814
1815/// One track per subtitle *lane*, in lane order -- so the file declares them
1816/// top-down as the timeline shows them and a player's subtitle menu lists them
1817/// in that order.
1818///
1819/// The cues are [`Project::sub_lane_cues`]: each placement's window of its
1820/// palette track, on the timeline's own clock. Clipped again here to what the
1821/// export *writes*, which ends with the last picture or sound
1822/// ([`Project::media_frames`]) -- a caption hanging past both holds the
1823/// timeline open ([`Project::timeline_frames`]) but there is no picture under
1824/// it to write, so a cue out there is dropped and one straddling the end keeps
1825/// the half that is inside. [`planned_subtitles`] says so before the button is
1826/// pressed.
1827///
1828/// A lane is dropped whole -- no track at all in the file -- where any
1829/// placement on it is a picture ([`SubtitleTrack::is_bitmap`]), a track that
1830/// could not be read, or a palette row that has since gone: the muxers write
1831/// words, and half a lane's cues under the other half's name would be worse
1832/// than none. Its language and title are the lane's *first* placement's track,
1833/// which is the one thing the whole lane is named by.
1834///
1835/// `picks` narrows the lanes the same way [`ExportSettings::subtitles`] does: a
1836/// lane is kept when it holds a placement of a picked track ([`picked`]), and an
1837/// empty list keeps every lane.
1838#[cfg(test)]
1839fn lane_subtitles(
1840 project: &Project,
1841 fps: f64,
1842 range: Option<(u32, u32)>,
1843 picks: &[usize],
1844) -> Vec<SubParams> {
1845 placed_lanes(project)
1846 .into_iter()
1847 .filter_map(|lane| lane_subtitle(project, lane, fps, range, picks))
1848 .collect()
1849}
1850
1851/// One lane written as its track ([`lane_subtitles`] for a single lane); `None` where the
1852/// lane is not in the file (see there for the reasons).
1853fn lane_subtitle(
1854 project: &Project,
1855 lane: Lane,
1856 fps: f64,
1857 range: Option<(u32, u32)>,
1858 picks: &[usize],
1859) -> Option<SubParams> {
1860 let end = (f64::from(project.media_frames()) / fps * 1e6).round() as i64;
1861 let placed = project.sub_lane(lane);
1862 if !picked(placed, picks) {
1863 return None;
1864 }
1865 let first = placed.first()?;
1866 let writable = |track: usize| {
1867 project
1868 .subtitles()
1869 .get(track)
1870 .filter(|t| t.refused.is_none() && !t.is_bitmap())
1871 };
1872 let named = writable(first.track)?;
1873 if placed.iter().any(|s| writable(s.track).is_none()) {
1874 return None;
1875 }
1876 let cues: Vec<Cue> = written_cues(
1877 project
1878 .sub_lane_cues(lane, fps)
1879 .into_iter()
1880 .filter_map(|cue| {
1881 let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end));
1882 (end_us > start_us).then_some(Cue {
1883 start_us,
1884 end_us,
1885 text: cue.text,
1886 image: cue.image,
1887 words: Vec::new(),
1888 karaoke: Vec::new(),
1889 })
1890 })
1891 .collect(),
1892 range,
1893 fps,
1894 project.media_frames(),
1895 );
1896 (!cues.is_empty()).then(|| SubParams {
1897 language: named.language.clone(),
1898 name: subtitle_title(named),
1899 cues,
1900 })
1901}
1902
1903/// `cues` on the clock the export *writes*, for a range-relative file.
1904///
1905/// A cue is timed on the timeline; a ranged export's file starts its own clock
1906/// at zero where the range starts, so every cue moves back by the range's start.
1907/// What falls before the range is dropped, what falls after it is dropped, and a
1908/// cue straddling either edge keeps the half inside. The window is the range
1909/// clamped to the media, the same clamp [`export_spans`] makes, so the cues stop
1910/// where the pictures do. Both ends are whole microseconds of the same
1911/// frame-to-time mapping the cues were timed with, so the only rounding left is
1912/// the container's own tick.
1913///
1914/// Unranged, the cues come back as they were.
1915fn written_cues(
1916 cues: Vec<Cue>,
1917 range: Option<(u32, u32)>,
1918 fps: f64,
1919 media_frames: u32,
1920) -> Vec<Cue> {
1921 let Some((r_start, r_end)) = range else {
1922 return cues;
1923 };
1924 let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64;
1925 let from = us(r_start);
1926 let to = us(r_end.min(media_frames).max(r_start));
1927 cues.into_iter()
1928 .filter_map(|cue| {
1929 let start_us = cue.start_us.max(from);
1930 let end_us = cue.end_us.min(to);
1931 (end_us > start_us).then_some(Cue {
1932 start_us: start_us - from,
1933 end_us: end_us - from,
1934 text: cue.text,
1935 image: cue.image,
1936 words: Vec::new(),
1937 karaoke: Vec::new(),
1938 })
1939 })
1940 .collect()
1941}
1942
1943/// The composite spans an export *writes*: [`Project::composite_spans_from`]
1944/// cut to where the media runs out ([`Project::media_frames`]), and, with
1945/// `range` set, to that window too.
1946///
1947/// The walk itself is the timeline's ([`Project::timeline_frames`]), because a
1948/// caption placed past the last picture holds the timeline open under it and
1949/// playback parks on that tail -- but there is nothing to *write* out there, so
1950/// an unbounded walk encoded and muxed black frames past the end of the media
1951/// and padded the sound to match. This is the one place that end is decided:
1952/// the frame count [`run`] publishes, the cues [`lane_subtitles`] clips and the
1953/// blocks [`CopyPlan`] copies are then the same number by construction, which
1954/// is what makes [`planned_lanes`]' "cut off there" true of the file.
1955///
1956/// `span.start` stays the *project's* own timeline coordinate throughout --
1957/// what [`Project::composite_color_at`] and its fit sibling are keyed on -- so
1958/// a caller writing a range-relative output shifts it at the one place that
1959/// actually emits a position (`CopyPlan`'s own region, since the encode loop
1960/// counts pictures rather than reading `span.start` for its output clock).
1961/// Trimming the left edge mid-span moves `from`'s source frame by
1962/// [`Speed::source_at`], the same mapping a legal cut is placed by.
1963fn export_spans(project: &Project, range: Option<(u32, u32)>) -> Vec<crate::project::Span> {
1964 let end = project.media_frames();
1965 let mut spans = stack_spans_from(project, 0);
1966 spans.retain(|span| span.start < end);
1967 for span in &mut spans {
1968 span.len = span.len.min(end - span.start);
1969 }
1970 // A title past the last clip is picture: the frames up to its end are black
1971 // under it, a gap like any other. Only titles extend the picture here; a
1972 // sound that runs on still does not, as it never did.
1973 let title_end = project
1974 .titles()
1975 .iter()
1976 .map(Title::end)
1977 .max()
1978 .unwrap_or(0)
1979 .min(end);
1980 let covered = spans.last().map_or(0, crate::project::Span::end);
1981 if covered < title_end {
1982 spans.push(crate::project::Span {
1983 ramp: None,
1984 start: covered,
1985 len: title_end - covered,
1986 from: None,
1987 speed: Speed::NORMAL,
1988 reverse: false,
1989 pitch: 0.0,
1990 });
1991 }
1992 let Some((r_start, r_end)) = range else {
1993 return spans;
1994 };
1995 let r_end = r_end.min(end).max(r_start);
1996 spans.retain(|span| span.start < r_end && span.start + span.len > r_start);
1997 for span in &mut spans {
1998 if span.start < r_start {
1999 let cut = r_start - span.start;
2000 if let Some((source, in_frame)) = span.from {
2001 span.from = Some((source, span.source_at(in_frame, cut)));
2002 }
2003 // A ramp's offsets are counted from the span's start, which has moved.
2004 span.ramp = span.ramp.map(|r| r.advanced(cut));
2005 span.len -= cut;
2006 span.start = r_start;
2007 }
2008 span.len = span.len.min(r_end - span.start);
2009 }
2010 spans
2011}
2012
2013/// The visible video lanes, bottom first: the last one is the topmost, the order
2014/// [`Project::composite_clip_at`] counts in.
2015fn split_spans(spans: Vec<crate::project::Span>, quiet: impl Fn(u32) -> bool) -> Vec<crate::project::Span> {
2016 let mut out = Vec::with_capacity(spans.len());
2017 for mut cur in spans {
2018 let mut off = 1;
2019 while off < cur.len {
2020 if quiet(cur.start + off) != quiet(cur.start + off - 1)
2021 && let Some(tail) = span_tail(&cur, off)
2022 {
2023 out.push(crate::project::Span { len: off, ..cur });
2024 cur = tail;
2025 off = 1;
2026 continue;
2027 }
2028 off += 1;
2029 }
2030 out.push(cur);
2031 }
2032 out
2033}
2034
2035fn span_tail(span: &crate::project::Span, cut: u32) -> Option<crate::project::Span> {
2036 let mut tail = *span;
2037 tail.start += cut;
2038 tail.len -= cut;
2039 tail.ramp = span.ramp.map(|r| r.advanced(cut));
2040 if let Some((source, first)) = span.from {
2041 let next = span.source_at(first, cut);
2042 tail.from = Some((source, next));
2043 if (0..tail.len).any(|o| tail.source_at(next, o) != span.source_at(first, cut + o)) {
2044 return None;
2045 }
2046 }
2047 Some(tail)
2048}
2049
2050fn wide_yuv(bytes: &[u8], width: u32, height: u32) -> Yuv {
2051 let (w, h) = (width as usize, height as usize);
2052 let (luma, chroma) = (w * h, w.div_ceil(2) * h.div_ceil(2));
2053 let unpack = crate::hwproc::unpack16;
2054 Yuv::Wide {
2055 y: unpack(&bytes[..2 * luma]),
2056 u: unpack(&bytes[2 * luma..2 * (luma + chroma)]),
2057 v: unpack(&bytes[2 * (luma + chroma)..2 * (luma + 2 * chroma)]),
2058 width,
2059 height,
2060 }
2061}
2062
2063fn visible_video_lanes(project: &Project) -> Vec<Lane> {
2064 project
2065 .lanes()
2066 .into_iter()
2067 .filter(|lane| lane.kind == LaneKind::Video && !project.lane_hidden(*lane))
2068 .collect()
2069}
2070
2071/// Every visible video clip covering `frame`, bottom first: the stack the
2072/// picture is composed from. One entry is the single-clip picture every path
2073/// has always drawn; two or more are a layered picture ([`layered_at`]), where
2074/// each clip is drawn over the ones beneath it.
2075pub(crate) fn stack_at(project: &Project, frame: u32) -> Vec<(Lane, usize)> {
2076 visible_video_lanes(project)
2077 .into_iter()
2078 .filter_map(|lane| Some((lane, project.lane_clip_at(lane, frame)?)))
2079 .collect()
2080}
2081
2082/// Whether `frame` is a layered picture: more than one visible clip covers it.
2083pub(crate) fn layered_at(project: &Project, frame: u32) -> bool {
2084 let stack = stack_at(project, frame);
2085 stack.len() >= 2 || animated_at(project, frame) || generated_at(project, &stack)
2086}
2087
2088/// Whether a clip covering `frame` is an adjustment layer or an animated generator
2089/// ([`crate::generate`]): neither is a picture the single-clip path draws.
2090fn generated_at(project: &Project, stack: &[(Lane, usize)]) -> bool {
2091 stack.iter().any(|&(lane, idx)| {
2092 let src = project.sources().get(project.lane(lane)[idx].source);
2093 src.and_then(|s| crate::generate::Gen::parse(&s.path)).is_some_and(|g| g.animated() || g.is_adjust() || g.has_alpha())
2094 })
2095}
2096
2097/// The one clip covering `frame` when its only animation is colour keys or an
2098/// effects stack and nothing dissolves out of it: a 10-bit export keeps such a
2099/// clip on the single-clip path, grading each picture by [`clip_color_at`] and
2100/// drawing its effects at 10 bits ([`crate::effects`]), rather than composing it
2101/// layered at 8 bits.
2102fn color_keyed_alone_at(project: &Project, frame: u32) -> Option<&crate::project::Clip> {
2103 let [(lane, idx)] = stack_at(project, frame)[..] else {
2104 return None;
2105 };
2106 let clip = &project.lane(lane)[idx];
2107 ((!clip.color_keys.is_empty() || crate::effects::active(&clip.effects))
2108 && clip.transform_keys.is_empty()
2109 && clip.opacity_keys.is_empty()
2110 && cross_window(project, lane, idx).is_none())
2111 .then_some(clip)
2112}
2113
2114/// Whether the picture at `frame` is one a single clip cannot show: the clip on
2115/// top has placement keys, or its dissolve partner does. A keyed picture is
2116/// composed as a layered one, which places each frame's own placement
2117/// ([`LayerFeed::advance`]), so a single clip's span-long transform never has
2118/// to stand in for a moving one.
2119fn animated_at(project: &Project, frame: u32) -> bool {
2120 visible_video_lanes(project).into_iter().any(|lane| {
2121 let Some(idx) = project.lane_clip_at(lane, frame) else {
2122 return false;
2123 };
2124 if crate::project::clip_animated(&project.lane(lane)[idx]) {
2125 return true;
2126 }
2127 matches!(
2128 cross_window(project, lane, idx),
2129 Some((window, start)) if frame >= start && frame - start < window
2130 ) && project.lane(lane).get(idx + 1).is_some_and(crate::project::clip_animated)
2131 })
2132}
2133
2134/// [`Project::composite_span_at`] over the stack. The topmost covering clip
2135/// supplies `from` and `speed`, and the span runs until any visible video lane
2136/// changes what covers the frame -- a clip there starts or ends. With one
2137/// covering clip that is exactly the composite's own span; across a stack it
2138/// also cuts where a lower lane changes beneath the picture on top, since the
2139/// picture under it is then a different one.
2140pub(crate) fn stack_span_at(project: &Project, frame: u32) -> Option<crate::project::Span> {
2141 let total = project.timeline_frames();
2142 if frame >= total {
2143 return None;
2144 }
2145 let mut until = total;
2146 for lane in visible_video_lanes(project) {
2147 let clips = project.lane(lane);
2148 match project.lane_clip_at(lane, frame) {
2149 Some(idx) => until = until.min(clips[idx].end()),
2150 None => {
2151 if let Some(next) = clips.iter().find(|c| c.start > frame) {
2152 until = until.min(next.start);
2153 }
2154 }
2155 }
2156 }
2157 let (from, speed, ramp, reverse) = match stack_at(project, frame).pop() {
2158 Some((lane, idx)) => {
2159 let clip = &project.lane(lane)[idx];
2160 let (speed, ramp) = crate::project::span_speed_of(clip, frame);
2161 (
2162 Some((clip.source, clip_source_frame(clip, frame))),
2163 speed,
2164 ramp,
2165 clip.reversed,
2166 )
2167 }
2168 None => (None, Speed::NORMAL, None, false),
2169 };
2170 Some(crate::project::Span {
2171 start: frame,
2172 len: until - frame,
2173 from,
2174 speed,
2175 ramp,
2176 reverse,
2177 pitch: 0.0,
2178 })
2179}
2180
2181/// [`Project::composite_spans_from`] over the stack: every span from `frame` on.
2182pub(crate) fn stack_spans_from(project: &Project, frame: u32) -> Vec<crate::project::Span> {
2183 let mut out = Vec::new();
2184 let mut t = frame;
2185 while let Some(span) = stack_span_at(project, t) {
2186 t = span.end();
2187 out.push(span);
2188 }
2189 out
2190}
2191
2192/// Which source frame a clip plays at timeline `frame` -- the project's own
2193/// rule, clamped inside the clip's range.
2194fn clip_source_frame(clip: &crate::project::Clip, frame: u32) -> u32 {
2195 (crate::project::source_pos(clip, frame - clip.start).floor() as u32).min(clip.out_frame - 1)
2196}
2197
2198/// One clip of a layered picture, open for the span: its decoder, read forward
2199/// as the picture advances, and the canvas its picture lands on -- the same
2200/// placement a single clip gets ([`place_picture`]).
2201struct LayerFeed {
2202 clip: crate::project::Clip,
2203 info: Placed,
2204 meta: VideoMeta,
2205 grade: Option<crate::color::ColorParams>,
2206 /// The grade the current picture was graded with, so a colour-keyed clip is
2207 /// graded again the frame its grade moves, even on the same source frame.
2208 graded_with: Option<crate::color::ColorParams>,
2209 /// The clip's base placement ([`Clip::transform`] resolved); its keys, when
2210 /// it has any, are read from `clip` at each frame ([`clip_transform_at`]).
2211 transform: TransformParams,
2212 /// The placement the current picture was placed with, so a keyed clip is
2213 /// placed again the frame its placement moves, even on the same source frame.
2214 placed_with: TransformParams,
2215 /// The clip's own opacity ([`TransformParams::opacity`]), applied as its
2216 /// coverage over the layers beneath rather than in its placement.
2217 opacity: f32,
2218 fit_canvas: Composer,
2219 rotated: Planes,
2220 stretched: Planes,
2221 graded: Planes,
2222 transformed: Planes,
2223 /// The decoder, and the file frame its next picture is.
2224 decoder: Option<(ClipDecoder, u32)>,
2225 parked: Option<Arc<Parked>>,
2226 /// The placed picture, and the file frame it is of.
2227 current: Option<(u32, Planes)>,
2228 /// The same picture composed at 10 bits ([`LayerStack::picture16`]), and the
2229 /// scratch only that path uses.
2230 current16: Option<(u32, Planes16)>,
2231 scratch16: Scratch16,
2232 widened: Planes16,
2233 steadied16: Planes16,
2234 adjusted16: Planes16,
2235 fx16: crate::effects::Scratch<u16>,
2236 /// Luma-sized coverage of the placed picture on the canvas: 255 where the
2237 /// clip's own pixels are, 0 in the letterbox bars and off the canvas. A
2238 /// layer above lets the one beneath show wherever this is 0.
2239 cover: Option<Vec<u8>>,
2240 matrix: Matrix,
2241 /// The dissolve this clip's tail owes the clip after it on its lane, when
2242 /// one is set and adjacent ([`cross_window`]).
2243 cross: Option<Box<LayerCross>>,
2244 /// The effects stack's scratch, and what it made of the current picture: its
2245 /// coverage (the placed footprint times the keys and masks) where it has any,
2246 /// and the mode it is laid down in ([`crate::effects`]).
2247 fx: crate::effects::Scratch<u8>,
2248 fx_cover: Option<Vec<u8>>,
2249 fx_mode: crate::effects::BlendMode,
2250 /// The clip's stabilisation, once its analysis is cached
2251 /// ([`crate::stabilise::correction`]): applied to the decoded picture, by its
2252 /// file frame, before anything else is.
2253 steady: Option<std::sync::Arc<crate::stabilise::Correction>>,
2254 steadied: Planes,
2255 /// The clip's deinterlace setting as it applies to its file. `Field` makes
2256 /// `info.rate` count fields; stabilisation is measured per file frame, so a
2257 /// field takes its frame's correction.
2258 deint: Deinterlace,
2259 /// An adjustment layer ([`crate::generate`]): no picture, its grade and effects act on the
2260 /// layers beneath ([`LayerFeed::adjust_over`]).
2261 adjust: bool,
2262 /// An adjustment layer's scratch, kept between frames like `steadied`: the placed and
2263 /// effected copy of the layers beneath, and its coverage.
2264 adjusted: Planes,
2265 adjust_cover: Vec<u8>,
2266 /// A generator with a transparent background ([`crate::generate::Gen::has_alpha`]) and its
2267 /// alpha at the size last asked for, kept so the mask is drawn once, not per coverage.
2268 alpha_gen: Option<crate::generate::Gen>,
2269 alpha_mask: Option<(u32, u32, Vec<u8>)>,
2270}
2271
2272/// The clip a layer's tail dissolves into: its own feed, and the window of
2273/// timeline frames the blend runs over, from `start` for `window` frames.
2274struct LayerCross {
2275 next: LayerFeed,
2276 window: u32,
2277 start: u32,
2278}
2279
2280/// The dissolve window a clip's tail owes its successor, as [`dissolve_window`]
2281/// reads it -- without the span rules, which a layered picture does not have:
2282/// it blends wherever its lane is on the clip, whatever is above it. `None` for
2283/// a hard cut, a stale transition out (the clips are no longer adjacent), or an
2284/// empty window. `(window, start)` in timeline frames.
2285fn cross_window(project: &Project, lane: Lane, idx: usize) -> Option<(u32, u32)> {
2286 let clips = project.lane(lane);
2287 let a = clips.get(idx)?;
2288 if a.transition_out == 0 {
2289 return None;
2290 }
2291 let b = clips.get(idx + 1)?;
2292 if a.end() != b.start {
2293 return None;
2294 }
2295 let window = a.transition_out.min(a.frames()).min(b.frames());
2296 (window > 0).then_some((window, a.end() - window))
2297}
2298
2299impl LayerFeed {
2300 /// The feed for clip `idx` of `lane`, with the dissolve it owes its
2301 /// successor opened beside it. `paths`, when given, is the file each source
2302 /// is decoded from in place of its own (a proxy stand-in), by source index.
2303 /// `measure`, when given, is the cancel flag a stabilised clip's missing
2304 /// analysis is run under before this returns ([`crate::stabilise::ensure`])
2305 /// and the stage it reports to ([`Shared::measuring`]); `None` takes only a
2306 /// finished one (the viewer, which shows the analysis's progress and redraws
2307 /// when it lands).
2308 fn open(
2309 project: &Project,
2310 meta: &VideoMeta,
2311 lane: Lane,
2312 idx: usize,
2313 matrix: Matrix,
2314 paths: Option<&[PathBuf]>,
2315 measure: Option<Measure<'_>>,
2316 ) -> crate::Result<Self> {
2317 let mut feed = Self::plain(project, meta, lane, idx, matrix, paths, measure)?;
2318 if let Some((window, start)) = cross_window(project, lane, idx) {
2319 let next = Self::plain(project, meta, lane, idx + 1, matrix, paths, measure)?;
2320 feed.cross = Some(Box::new(LayerCross {
2321 next,
2322 window,
2323 start,
2324 }));
2325 }
2326 Ok(feed)
2327 }
2328
2329 fn plain(
2330 project: &Project,
2331 meta: &VideoMeta,
2332 lane: Lane,
2333 idx: usize,
2334 matrix: Matrix,
2335 paths: Option<&[PathBuf]>,
2336 measure: Option<Measure<'_>>,
2337 ) -> crate::Result<Self> {
2338 let Some(clip) = project.lane(lane).get(idx).cloned() else {
2339 return Err("a layer names a clip that is not there".into());
2340 };
2341 let mut info = placed_info(project, meta, clip.source)?;
2342 if let Some(path) = paths.and_then(|paths| paths.get(clip.source)) {
2343 info.path = path.clone();
2344 }
2345 // Smoothed at the timeline's rate, as the viewer smooths it, over every
2346 // file frame the clip plays: an export measures what is missing rather
2347 // than write the clip unstabilised.
2348 let steady = match (clip.stabilise, project.sources().get(clip.source)) {
2349 (Some(st), Some(source)) => {
2350 let (lo, hi) = crate::stabilise::file_range(&clip, info.rate);
2351 match measure {
2352 Some((cancel, stage)) => {
2353 let mut tell = |f: f32| stage.store(1 + (f.clamp(0.0, 1.0) * 1000.0) as u32, Ordering::Relaxed);
2354 let c = crate::stabilise::ensure(&source.path, lo, hi, st, meta.frame_rate, &mut tell, cancel);
2355 stage.store(0, Ordering::Relaxed);
2356 Some(c?)
2357 }
2358 None => crate::stabilise::correction_or_start(&source.path, lo, hi, st, meta.frame_rate),
2359 }
2360 }
2361 _ => None,
2362 };
2363 let deint = crate::deinterlace::effective(clip.deinterlace, &info.path);
2364 info.rate = crate::deinterlace::counted_rate(deint, info.rate);
2365 Ok(Self {
2366 steady,
2367 steadied: Default::default(),
2368 parked: None,
2369 deint,
2370 adjust: crate::generate::is_adjust(&info.path),
2371 adjusted: Default::default(),
2372 adjust_cover: Vec::new(),
2373 alpha_gen: crate::generate::Gen::parse(&info.path).filter(|g| g.has_alpha()),
2374 alpha_mask: None,
2375 info,
2376 meta: *meta,
2377 grade: project.color_of(lane, idx).copied(),
2378 graded_with: None,
2379 // The layer's opacity is its coverage in [`LayerStack::picture`], so
2380 // the placement below runs at opacity 1: a placed mask at opacity
2381 // below 1 would fade the coverage it is read for.
2382 transform: {
2383 let whole = project.transform_of(lane, idx).copied().unwrap_or_default();
2384 TransformParams {
2385 opacity: 1.0,
2386 ..whole
2387 }
2388 },
2389 opacity: project
2390 .transform_of(lane, idx)
2391 .map_or(1.0, |t| t.opacity),
2392 fit_canvas: Composer::new(meta.width, meta.height, project.fit_of(lane, idx)),
2393 clip,
2394 rotated: Default::default(),
2395 stretched: Default::default(),
2396 graded: Default::default(),
2397 transformed: Default::default(),
2398 decoder: None,
2399 current: None,
2400 current16: None,
2401 scratch16: Default::default(),
2402 widened: Default::default(),
2403 steadied16: Default::default(),
2404 adjusted16: Default::default(),
2405 fx16: Default::default(),
2406 cover: None,
2407 placed_with: TransformParams::default(),
2408 matrix,
2409 cross: None,
2410 fx: Default::default(),
2411 fx_cover: None,
2412 fx_mode: Default::default(),
2413 })
2414 }
2415
2416 /// The dissolve picture this clip shows at timeline `frame` while its tail
2417 /// blends into the next clip on its lane: the two placed pictures mixed by
2418 /// [`dissolve_weight`], and the coverage between the two clips' footprints
2419 /// mixed the same way. `None` outside the window, and where the next clip's
2420 /// file ends first -- then this clip's own picture stands, as a single
2421 /// clip's does. The next clip is read forward as this one is.
2422 fn cross_at(&mut self, frame: u32) -> crate::Result<Option<(Planes, Vec<u8>)>> {
2423 let Some(cross) = self.cross.as_mut() else {
2424 return Ok(None);
2425 };
2426 if frame < cross.start || frame - cross.start >= cross.window {
2427 return Ok(None);
2428 }
2429 // The next clip shows its own picture from its first frame on, as the
2430 // single clip's dissolve reads it ([`compose_at_with`]): window frame k
2431 // is its frame k, not the timeline frame, which is before its start.
2432 let k = frame - cross.start;
2433 if !cross.next.advance(cross.next.clip.start + k)? {
2434 return Ok(None);
2435 }
2436 let t = dissolve_weight(k, cross.window);
2437 let a_cover = self.fx_cover.as_deref().or(self.cover.as_deref());
2438 let (Some((_, a)), Some(a_cover)) = (self.current.as_ref(), a_cover) else {
2439 return Ok(None);
2440 };
2441 let b_cover = cross.next.fx_cover.as_deref().or(cross.next.cover.as_deref());
2442 let (Some((_, b)), Some(b_cover)) = (cross.next.current.as_ref(), b_cover)
2443 else {
2444 return Ok(None);
2445 };
2446 let planes = crate::transitions::blend_planes(
2447 self.clip.transition_kind,
2448 (&a.0, &a.1, &a.2),
2449 (&b.0, &b.1, &b.2),
2450 t,
2451 self.meta.width as usize,
2452 self.meta.height as usize,
2453 );
2454 let cover = a_cover
2455 .iter()
2456 .zip(b_cover)
2457 .map(|(&x, &y)| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8)
2458 .collect();
2459 Ok(Some((planes, cover)))
2460 }
2461
2462 /// [`LayerFeed::cross_at`] at 10 bits.
2463 fn cross_at16(&mut self, frame: u32) -> crate::Result<Option<(Planes16, Vec<u8>)>> {
2464 let Some(cross) = self.cross.as_mut() else {
2465 return Ok(None);
2466 };
2467 if frame < cross.start || frame - cross.start >= cross.window {
2468 return Ok(None);
2469 }
2470 let k = frame - cross.start;
2471 if !cross.next.advance16(cross.next.clip.start + k)? {
2472 return Ok(None);
2473 }
2474 let t = dissolve_weight(k, cross.window);
2475 let a_cover = self.fx_cover.as_deref().or(self.cover.as_deref());
2476 let (Some((_, a)), Some(a_cover)) = (self.current16.as_ref(), a_cover) else {
2477 return Ok(None);
2478 };
2479 let b_cover = cross.next.fx_cover.as_deref().or(cross.next.cover.as_deref());
2480 let (Some((_, b)), Some(b_cover)) = (cross.next.current16.as_ref(), b_cover) else {
2481 return Ok(None);
2482 };
2483 let planes = crate::transitions::blend_planes(
2484 self.clip.transition_kind,
2485 (&a.0, &a.1, &a.2),
2486 (&b.0, &b.1, &b.2),
2487 t,
2488 self.meta.width as usize,
2489 self.meta.height as usize,
2490 );
2491 let cover = a_cover
2492 .iter()
2493 .zip(b_cover)
2494 .map(|(&x, &y)| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8)
2495 .collect();
2496 Ok(Some((planes, cover)))
2497 }
2498
2499 /// Makes the placed picture for timeline `frame` the current one, reading
2500 /// the decoder forward to it. `false` when the file ends first.
2501 fn advance(&mut self, frame: u32) -> crate::Result<bool> {
2502 self.advance_as(frame, false)
2503 }
2504
2505 /// [`LayerFeed::advance`] at 10 bits: the placed picture lands in `current16`.
2506 fn advance16(&mut self, frame: u32) -> crate::Result<bool> {
2507 self.advance_as(frame, true)
2508 }
2509
2510 fn advance_as(&mut self, frame: u32, wide: bool) -> crate::Result<bool> {
2511 let want = self.info.rate.source_at(clip_source_frame(&self.clip, frame));
2512 // Coverage is the layer's own (see `LayerFeed::picture`), so the placement
2513 // runs at opacity 1 whatever the keys say.
2514 let tf = TransformParams {
2515 opacity: 1.0,
2516 ..crate::project::clip_transform_at(&self.clip, self.transform, frame)
2517 };
2518 // A colour-keyed clip's grade moves with the frame ([`clip_color_at`]).
2519 let grade = match self.clip.color_keys.is_empty() {
2520 true => self.grade,
2521 false => Some(crate::project::clip_color_at(
2522 &self.clip,
2523 self.grade.unwrap_or_default(),
2524 frame,
2525 )),
2526 };
2527 let have = match wide {
2528 true => self.current16.as_ref().map(|(at, _)| *at),
2529 false => self.current.as_ref().map(|(at, _)| *at),
2530 };
2531 if have == Some(want)
2532 && self.placed_with == tf
2533 && self.graded_with == grade
2534 && !crate::effects::animated(&self.clip.effects)
2535 {
2536 return Ok(true);
2537 }
2538 // A decoder that has read past the picture wanted is reopened at it;
2539 // playback and export only ever move forward through a span -- down it,
2540 // for a reversed clip, whose decoder counts the file frame it is on
2541 // downwards.
2542 let backwards = self.clip.reversed;
2543 let behind = matches!(&self.decoder, Some((_, pos)) if match backwards {
2544 true => *pos < want,
2545 false => *pos > want,
2546 });
2547 if self.decoder.is_none() || behind {
2548 let path = self.info.path.clone();
2549 let flags = self.clip.visualizer;
2550 let decoder = if crate::is_audio(&path) || flags & 1 != 0 {
2551 ClipDecoder::visualizer(
2552 &path,
2553 self.info.stream,
2554 want,
2555 (self.meta.width, self.meta.height),
2556 self.meta.frame_rate,
2557 flags,
2558 self.clip.viz_paint,
2559 )?
2560 } else if backwards && !crate::is_image(&path) {
2561 ClipDecoder::reversed(&path, want, self.info.rate.source_at(self.clip.in_frame), self.deint)
2562 } else {
2563 ClipDecoder::open_with(&path, want, None, self.parked.as_ref(), wide, self.deint)?
2564 };
2565 self.decoder = Some((decoder, want));
2566 }
2567 let (decoder, pos) = self.decoder.as_mut().expect("opened above");
2568 while match backwards {
2569 true => *pos > want,
2570 false => *pos < want,
2571 } {
2572 if decoder.next()?.is_none() {
2573 return Ok(false);
2574 }
2575 *pos = if backwards { *pos - 1 } else { *pos + 1 };
2576 }
2577 let Some(picture) = decoder.next()? else {
2578 return Ok(false);
2579 };
2580 *pos = if backwards { pos.saturating_sub(1) } else { *pos + 1 };
2581 if wide {
2582 let (y, u, v, w, h): (&[u16], &[u16], &[u16], u32, u32) = match picture {
2583 Frame::Wide(y, u, v, w, h) => (y, u, v, w, h),
2584 Frame::Pixels(y, u, v, w, h) => {
2585 widen_into(y, &mut self.widened.0);
2586 widen_into(u, &mut self.widened.1);
2587 widen_into(v, &mut self.widened.2);
2588 (&self.widened.0[..], &self.widened.1[..], &self.widened.2[..], w, h)
2589 }
2590 Frame::Dma(_) => return Err("a layer's decoder produced no pixels".into()),
2591 };
2592 let (y, u, v) = match &self.steady {
2593 Some(c) => {
2594 let m = c.at(crate::deinterlace::file_frame(self.deint, &self.info.path, want), w).ok_or_else(|| -> crate::Error {
2595 format!("stabilise: file frame {want} lies before the measured range").into()
2596 })?;
2597 crate::stabilise::warp_i420(y, u, v, w, h, m, &mut self.steadied16);
2598 (&self.steadied16.0[..], &self.steadied16.1[..], &self.steadied16.2[..])
2599 }
2600 None => (y, u, v),
2601 };
2602 let remap = remap_into(Some(self.info.color), self.info.mapper.is_some(), self.matrix);
2603 let (py, pu, pv, pw, ph) = place_picture16(
2604 y,
2605 u,
2606 v,
2607 w,
2608 h,
2609 self.info.rotation,
2610 self.info.pixel_aspect,
2611 grade,
2612 tf,
2613 remap,
2614 self.info.mapper.as_ref(),
2615 &mut self.scratch16,
2616 &mut self.fit_canvas,
2617 );
2618 let mut planes = (py.to_vec(), pu.to_vec(), pv.to_vec());
2619 if self.cover.is_none() || self.placed_with != tf {
2620 self.cover = Some(self.coverage(w, h, tf));
2621 }
2622 debug_assert_eq!((pw, ph), (self.meta.width, self.meta.height), "a placed layer is canvas-sized");
2623 let secs = f64::from(frame) / self.meta.frame_rate;
2624 let src = crate::project::key_sample_pos(&self.clip, frame);
2625 let (mode, fx_cover) = layer_effects(
2626 &self.clip.effects,
2627 &mut planes,
2628 (pw, ph),
2629 secs,
2630 src,
2631 self.matrix,
2632 &mut self.fx16,
2633 self.cover.as_deref().expect("set above"),
2634 );
2635 self.fx_mode = mode;
2636 self.fx_cover = fx_cover;
2637 self.placed_with = tf;
2638 self.graded_with = grade;
2639 self.current16 = Some((want, planes));
2640 return Ok(true);
2641 }
2642 let Frame::Pixels(y, u, v, w, h) = picture else {
2643 return Err("a layer's decoder produced no pixels".into());
2644 };
2645 let (y, u, v) = match &self.steady {
2646 Some(c) => {
2647 let m = c.at(crate::deinterlace::file_frame(self.deint, &self.info.path, want), w).ok_or_else(|| -> crate::Error {
2648 format!("stabilise: file frame {want} lies before the measured range").into()
2649 })?;
2650 crate::stabilise::warp_i420(y, u, v, w, h, m, &mut self.steadied);
2651 (&self.steadied.0[..], &self.steadied.1[..], &self.steadied.2[..])
2652 }
2653 None => (y, u, v),
2654 };
2655 let remap = remap_into(
2656 Some(self.info.color),
2657 self.info.mapper.is_some(),
2658 self.matrix,
2659 );
2660 let (py, pu, pv, pw, ph) = place_picture(
2661 y,
2662 u,
2663 v,
2664 w,
2665 h,
2666 self.info.rotation,
2667 self.info.pixel_aspect,
2668 grade,
2669 tf,
2670 remap,
2671 self.info.mapper.as_ref(),
2672 &mut self.rotated,
2673 &mut self.stretched,
2674 &mut self.graded,
2675 &mut self.transformed,
2676 &mut self.fit_canvas,
2677 );
2678 let mut planes = (py.to_vec(), pu.to_vec(), pv.to_vec());
2679 if self.cover.is_none() || self.placed_with != tf {
2680 self.cover = Some(self.coverage(w, h, tf));
2681 }
2682 // The effects stack, on the placed picture: its filters rewrite the
2683 // samples, and its keys and masks narrow the footprint it lands with.
2684 debug_assert_eq!((pw, ph), (self.meta.width, self.meta.height), "a placed layer is canvas-sized");
2685 let secs = f64::from(frame) / self.meta.frame_rate;
2686 let src = crate::project::key_sample_pos(&self.clip, frame);
2687 let (mode, fx_cover) = layer_effects(
2688 &self.clip.effects,
2689 &mut planes,
2690 (pw, ph),
2691 secs,
2692 src,
2693 self.matrix,
2694 &mut self.fx,
2695 self.cover.as_deref().expect("set above"),
2696 );
2697 self.fx_mode = mode;
2698 self.fx_cover = fx_cover;
2699 self.placed_with = tf;
2700 self.graded_with = grade;
2701 self.current = Some((want, planes));
2702 Ok(true)
2703 }
2704
2705 /// The layers composed so far, `base`, with this adjustment layer's grade, placement and
2706 /// effects applied to them, at strength `k` (its fade times its opacity).
2707 ///
2708 /// The clip's transform moves the composite below it (as Motion on an adjustment layer does
2709 /// in Premiere), so what the placement uncovers -- a shrunk, shifted or rotated composite --
2710 /// goes black. Crop is different: the layer only reaches where its crop footprint
2711 /// ([`LayerFeed::coverage`], placement left out) is, so a cropped-away region keeps the base.
2712 fn adjust_over(&mut self, base: Planes, k: f32, frame: u32) -> Planes {
2713 let (w, h) = (self.meta.width, self.meta.height);
2714 let grade = match self.clip.color_keys.is_empty() {
2715 true => self.grade,
2716 false => Some(crate::project::clip_color_at(&self.clip, self.grade.unwrap_or_default(), frame)),
2717 };
2718 let tf = TransformParams { opacity: 1.0, ..crate::project::clip_transform_at(&self.clip, self.transform, frame) };
2719 let (py, pu, pv, _, _) = place_picture(
2720 &base.0, &base.1, &base.2, w, h, Rotation::None, crate::demux::PixelAspect::SQUARE, grade, tf, None, None,
2721 &mut self.rotated, &mut self.stretched, &mut self.graded, &mut self.transformed, &mut self.fit_canvas,
2722 );
2723 let mut adjusted = std::mem::take(&mut self.adjusted);
2724 for (dst, src) in [(&mut adjusted.0, py), (&mut adjusted.1, pu), (&mut adjusted.2, pv)] {
2725 dst.clear();
2726 dst.extend_from_slice(src);
2727 }
2728 let mut cover = std::mem::take(&mut self.adjust_cover);
2729 cover.clear();
2730 // Only the crop limits the layer: the placement moved the composite itself, and
2731 // what it uncovers is the black of its own fit bars.
2732 // With crop and a transform together the crop footprint stays at the identity
2733 // position while the picture moves: the crop limits where the layer acts, not what moves.
2734 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() };
2735 match crop == TransformParams::default() {
2736 true => cover.resize(w as usize * h as usize, 255),
2737 false => cover.extend(self.coverage(w, h, crop)),
2738 }
2739 if crate::effects::active(&self.clip.effects) {
2740 let out = crate::effects::apply(
2741 &self.clip.effects,
2742 (&mut adjusted.0, &mut adjusted.1, &mut adjusted.2),
2743 w as usize,
2744 h as usize,
2745 f64::from(frame) / self.meta.frame_rate,
2746 crate::project::key_sample_pos(&self.clip, frame),
2747 self.matrix,
2748 &mut self.fx,
2749 );
2750 if let Some(alpha) = out.alpha {
2751 for (c, a) in cover.iter_mut().zip(alpha) {
2752 *c = ((u32::from(*c) * u32::from(a) + 127) / 255) as u8;
2753 }
2754 }
2755 }
2756 let mut result = base;
2757 layer_over(&mut result, &adjusted, &cover, k, w as usize, h as usize);
2758 self.adjusted = adjusted;
2759 self.adjust_cover = cover;
2760 result
2761 }
2762
2763 /// [`LayerFeed::adjust_over`] at 10 bits.
2764 fn adjust_over16(&mut self, base: Planes16, k: f32, frame: u32) -> Planes16 {
2765 let (w, h) = (self.meta.width, self.meta.height);
2766 let grade = match self.clip.color_keys.is_empty() {
2767 true => self.grade,
2768 false => Some(crate::project::clip_color_at(&self.clip, self.grade.unwrap_or_default(), frame)),
2769 };
2770 let tf = TransformParams { opacity: 1.0, ..crate::project::clip_transform_at(&self.clip, self.transform, frame) };
2771 let (py, pu, pv, _, _) = place_picture16(
2772 &base.0, &base.1, &base.2, w, h, Rotation::None, crate::demux::PixelAspect::SQUARE, grade, tf, None, None,
2773 &mut self.scratch16, &mut self.fit_canvas,
2774 );
2775 let mut adjusted = std::mem::take(&mut self.adjusted16);
2776 for (dst, src) in [(&mut adjusted.0, py), (&mut adjusted.1, pu), (&mut adjusted.2, pv)] {
2777 dst.clear();
2778 dst.extend_from_slice(src);
2779 }
2780 let mut cover = std::mem::take(&mut self.adjust_cover);
2781 cover.clear();
2782 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() };
2783 match crop == TransformParams::default() {
2784 true => cover.resize(w as usize * h as usize, 255),
2785 false => cover.extend(self.coverage(w, h, crop)),
2786 }
2787 if crate::effects::active(&self.clip.effects) {
2788 let out = crate::effects::apply(
2789 &self.clip.effects,
2790 (&mut adjusted.0, &mut adjusted.1, &mut adjusted.2),
2791 w as usize,
2792 h as usize,
2793 f64::from(frame) / self.meta.frame_rate,
2794 crate::project::key_sample_pos(&self.clip, frame),
2795 self.matrix,
2796 &mut self.fx16,
2797 );
2798 if let Some(alpha) = out.alpha {
2799 for (c, a) in cover.iter_mut().zip(alpha) {
2800 *c = ((u32::from(*c) * u32::from(a) + 127) / 255) as u8;
2801 }
2802 }
2803 }
2804 let mut result = base;
2805 layer_over(&mut result, &adjusted, &cover, k, w as usize, h as usize);
2806 self.adjusted16 = adjusted;
2807 self.adjust_cover = cover;
2808 result
2809 }
2810
2811 /// Where a `w` x `h` picture of this clip lands on the canvas, as luma: the
2812 /// same placement, run on a picture that is white everywhere, so the cover
2813 /// is exactly the placed picture's footprint -- transform, crop, fit bars
2814 /// and all -- without a second copy of that geometry to keep in step.
2815 fn coverage(&mut self, w: u32, h: u32, transform: TransformParams) -> Vec<u8> {
2816 // A generator with a transparent background ([`crate::generate::Gen::has_alpha`]) places
2817 // its alpha as the luma (limited range, so the fit bars are 0) and is covered by degree.
2818 // The mask is drawn at the picture's own size, so a canvas that is not the generator's
2819 // still gets a shape, not the full frame. It reaches `place_picture` as plain luma with
2820 // no grade, remap or tonemap (all `None` below): only geometry and resampling touch it.
2821 if let Some(g) = self.alpha_gen
2822 && !matches!(&self.alpha_mask, Some((mw, mh, _)) if (*mw, *mh) == (w, h))
2823 {
2824 let mask = crate::generate::Gen::new(g.kind, w, h).alpha().expect("an alpha generator has a mask");
2825 self.alpha_mask = Some((w, h, mask));
2826 }
2827 let alpha = self.alpha_gen.and(self.alpha_mask.as_ref()).map(|(_, _, m)| m);
2828 let ones: Vec<u8> = match alpha {
2829 Some(a) => a.iter().map(|&v| 16 + (u32::from(v) * 219 / 255) as u8).collect(),
2830 None => vec![255u8; w as usize * h as usize],
2831 };
2832 let chroma = vec![128u8; w.div_ceil(2) as usize * h.div_ceil(2) as usize];
2833 let (cy, _, _, _, _) = place_picture(
2834 &ones,
2835 &chroma,
2836 &chroma,
2837 w,
2838 h,
2839 self.info.rotation,
2840 self.info.pixel_aspect,
2841 None,
2842 transform,
2843 None,
2844 None,
2845 &mut self.rotated,
2846 &mut self.stretched,
2847 &mut self.graded,
2848 &mut self.transformed,
2849 &mut self.fit_canvas,
2850 );
2851 match alpha.is_some() {
2852 true => cy.iter().map(|&p| ((u32::from(p.clamp(16, 235)) - 16) * 255 / 219) as u8).collect(),
2853 false => cy.iter().map(|&p| if p >= 128 { 255 } else { 0 }).collect(),
2854 }
2855 }
2856}
2857
2858/// A layer's effects stack drawn on its placed picture `planes` (a canvas of `size`): the
2859/// blend mode it lands in and the coverage its keys and masks leave of `cover`, `None` where
2860/// it has no effects (or none that cut the footprint). Generic over the sample so the 8-bit
2861/// and the 10-bit layer paths draw one stack the same way.
2862#[allow(clippy::too_many_arguments)]
2863fn layer_effects<T: crate::scale::Sample>(
2864 effects: &[crate::effects::Effect],
2865 planes: &mut Planes<T>,
2866 size: (u32, u32),
2867 secs: f64,
2868 src: f64,
2869 matrix: Matrix,
2870 scratch: &mut crate::effects::Scratch<T>,
2871 cover: &[u8],
2872) -> (crate::effects::BlendMode, Option<Vec<u8>>) {
2873 if !crate::effects::active(effects) {
2874 return (Default::default(), None);
2875 }
2876 let out = crate::effects::apply(
2877 effects,
2878 (&mut planes.0, &mut planes.1, &mut planes.2),
2879 size.0 as usize,
2880 size.1 as usize,
2881 secs,
2882 src,
2883 matrix,
2884 scratch,
2885 );
2886 let fx_cover = out.alpha.map(|alpha| {
2887 debug_assert_eq!(cover.len(), alpha.len(), "the cover and the effects' alpha are one size");
2888 cover
2889 .iter()
2890 .zip(alpha)
2891 .map(|(&c, a)| ((u32::from(c) * u32::from(a) + 127) / 255) as u8)
2892 .collect()
2893 });
2894 (out.mode, fx_cover)
2895}
2896
2897/// A layered picture's clips, open together: read forward by timeline frame and
2898/// composed bottom to top ([`LayerStack::picture`]).
2899pub(crate) struct LayerStack {
2900 feeds: Vec<LayerFeed>,
2901 width: usize,
2902 height: usize,
2903}
2904
2905impl LayerStack {
2906 /// The clips of `stack` ([`stack_at`]) on a `meta`-sized canvas, colour
2907 /// converted with `matrix`, decoded from `paths` where given (see
2908 /// [`LayerFeed::open`]). Nothing is decoded until a frame is asked for.
2909 pub(crate) fn open(
2910 project: &Project,
2911 meta: &VideoMeta,
2912 stack: &[(Lane, usize)],
2913 matrix: Matrix,
2914 paths: Option<&[PathBuf]>,
2915 measure: Option<Measure<'_>>,
2916 ) -> crate::Result<Self> {
2917 let feeds = stack
2918 .iter()
2919 .map(|&(lane, idx)| LayerFeed::open(project, meta, lane, idx, matrix, paths, measure))
2920 .collect::<crate::Result<Vec<_>>>()?;
2921 Ok(Self {
2922 feeds,
2923 width: meta.width as usize,
2924 height: meta.height as usize,
2925 })
2926 }
2927
2928 fn park_in(mut self, lot: &Arc<Parked>) -> Self {
2929 for feed in &mut self.feeds {
2930 feed.parked = Some(Arc::clone(lot));
2931 }
2932 self
2933 }
2934
2935 /// The composed I420 picture at timeline `frame`, or `None` once a clip's
2936 /// file ends before it. The bottom clip is drawn exactly as a single clip
2937 /// is (its bars black); each clip above lands on it where its own picture
2938 /// covers, at its own fade -- so a fade on a picture on top shows the one
2939 /// beneath through it, rather than fading the whole frame. A clip whose
2940 /// tail is dissolving into the next clip on its lane shows the blend of the
2941 /// two over the window ([`LayerFeed::cross_at`]), and the layers above
2942 /// composite over that -- so a dissolve under a picture-in-picture blends
2943 /// the same as one without it.
2944 pub(crate) fn picture(&mut self, frame: u32) -> crate::Result<Option<Planes>> {
2945 let (w, h) = (self.width, self.height);
2946 let mut out: Option<Planes> = None;
2947 for feed in &mut self.feeds {
2948 if !feed.adjust && !feed.advance(frame)? {
2949 return Ok(None);
2950 }
2951 // The fade and the opacity both scale this layer's coverage.
2952 let opacity = crate::project::clip_transform_at(
2953 &feed.clip,
2954 TransformParams {
2955 opacity: feed.opacity,
2956 ..TransformParams::default()
2957 },
2958 frame,
2959 )
2960 .opacity;
2961 let opacity = crate::project::clip_opacity_at(&feed.clip, opacity, frame);
2962 let k = clip_fade(&feed.clip, frame).unwrap_or(1.0) * opacity;
2963 // An adjustment layer with nothing beneath it is a no-op. Adjacent adjustment clips
2964 // hard-cut: `cross_at` is skipped for them, so a dissolve between two does nothing.
2965 if feed.adjust {
2966 out = out.take().map(|base| feed.adjust_over(base, k, frame));
2967 continue;
2968 }
2969 let blended = feed.cross_at(frame)?;
2970 let (planes, cover): (&Planes, &[u8]) = match blended.as_ref() {
2971 Some((planes, cover)) => (planes, cover.as_slice()),
2972 None => {
2973 let Some((_, planes)) = feed.current.as_ref() else {
2974 return Ok(None);
2975 };
2976 let cover = feed.fx_cover.as_deref().or(feed.cover.as_deref());
2977 (planes, cover.expect("set with the picture"))
2978 }
2979 };
2980 // A clip whose effects key, mask or blend it is laid over what is
2981 // beneath -- black, at the bottom -- by [`crate::effects::blend_over`].
2982 let mode = feed.fx_mode;
2983 if feed.fx_cover.is_some() || mode != crate::effects::BlendMode::Normal {
2984 let base = out.get_or_insert_with(|| crate::scale::black_i420(w, h));
2985 crate::effects::blend_over(
2986 (&mut base.0, &mut base.1, &mut base.2),
2987 borrow_planes(planes),
2988 cover,
2989 k,
2990 mode,
2991 feed.matrix,
2992 w,
2993 h,
2994 );
2995 continue;
2996 }
2997 // A picture with a transparent background lands on black, as the bottom layer does.
2998 if out.is_none() && feed.alpha_gen.is_some() {
2999 out = Some(crate::scale::black_i420(w, h));
3000 }
3001 match out.as_mut() {
3002 // The bottom layer sits on black, as a single clip does.
3003 None => {
3004 out = Some(match k < 1.0 {
3005 true => fade_planes(borrow_planes(planes), k),
3006 false => planes.clone(),
3007 });
3008 }
3009 Some(base) => layer_over(base, planes, cover, k, w, h),
3010 }
3011 }
3012 // Nothing drew (a stack of adjustment layers alone) is a gap: black.
3013 Ok(Some(out.unwrap_or_else(|| crate::scale::black_i420(w, h))))
3014 }
3015
3016 /// [`LayerStack::picture`] at 10 bits: 10-bit layers keep every sample, 8-bit ones are
3017 /// widened where they meet, and the grade, the placement, the blends and the effects all
3018 /// run on 10-bit codes.
3019 pub(crate) fn picture16(&mut self, frame: u32) -> crate::Result<Option<Planes16>> {
3020 let (w, h) = (self.width, self.height);
3021 let mut out: Option<Planes16> = None;
3022 for feed in &mut self.feeds {
3023 if !feed.adjust && !feed.advance16(frame)? {
3024 return Ok(None);
3025 }
3026 let opacity = crate::project::clip_transform_at(
3027 &feed.clip,
3028 TransformParams {
3029 opacity: feed.opacity,
3030 ..TransformParams::default()
3031 },
3032 frame,
3033 )
3034 .opacity;
3035 let opacity = crate::project::clip_opacity_at(&feed.clip, opacity, frame);
3036 let k = clip_fade(&feed.clip, frame).unwrap_or(1.0) * opacity;
3037 if feed.adjust {
3038 out = out.take().map(|base| feed.adjust_over16(base, k, frame));
3039 continue;
3040 }
3041 let blended = feed.cross_at16(frame)?;
3042 let (planes, cover): (&Planes16, &[u8]) = match blended.as_ref() {
3043 Some((planes, cover)) => (planes, cover.as_slice()),
3044 None => {
3045 let Some((_, planes)) = feed.current16.as_ref() else {
3046 return Ok(None);
3047 };
3048 let cover = feed.fx_cover.as_deref().or(feed.cover.as_deref());
3049 (planes, cover.expect("set with the picture"))
3050 }
3051 };
3052 let mode = feed.fx_mode;
3053 if feed.fx_cover.is_some() || mode != crate::effects::BlendMode::Normal {
3054 let base = out.get_or_insert_with(|| crate::scale::black_i420_wide(w, h));
3055 crate::effects::blend_over(
3056 (&mut base.0, &mut base.1, &mut base.2),
3057 borrow_planes(planes),
3058 cover,
3059 k,
3060 mode,
3061 feed.matrix,
3062 w,
3063 h,
3064 );
3065 continue;
3066 }
3067 if out.is_none() && feed.alpha_gen.is_some() {
3068 out = Some(crate::scale::black_i420_wide(w, h));
3069 }
3070 match out.as_mut() {
3071 None => {
3072 out = Some(match k < 1.0 {
3073 true => fade_planes(borrow_planes(planes), k),
3074 false => planes.clone(),
3075 });
3076 }
3077 Some(base) => layer_over(base, planes, cover, k, w, h),
3078 }
3079 }
3080 Ok(Some(out.unwrap_or_else(|| crate::scale::black_i420_wide(w, h))))
3081 }
3082}
3083
3084/// `top` laid over `base` where `cover` says the picture is, at strength `k`
3085/// (its fade times 1). Luma takes each sample's own coverage; chroma takes the
3086/// coverage of the luma sample at its block's top left.
3087fn layer_over<T: crate::scale::Sample>(base: &mut Planes<T>, top: &Planes<T>, cover: &[u8], k: f32, w: usize, h: usize) {
3088 let mix = |b: T, t: T, a: f32| {
3089 let (b, t) = (b.code() as f32, t.code() as f32);
3090 T::from_f32(b + (t - b) * a)
3091 };
3092 for (i, (b, &t)) in base.0.iter_mut().zip(&top.0).enumerate() {
3093 let a = f32::from(cover[i]) / 255.0 * k;
3094 if a > 0.0 {
3095 *b = mix(*b, t, a);
3096 }
3097 }
3098 let cw = w.div_ceil(2);
3099 for i in 0..cw * h.div_ceil(2) {
3100 let (cx, cy) = (i % cw, i / cw);
3101 let a = f32::from(cover[2 * cy * w + 2 * cx]) / 255.0 * k;
3102 if a > 0.0 {
3103 base.1[i] = mix(base.1[i], top.1[i], a);
3104 base.2[i] = mix(base.2[i], top.2[i], a);
3105 }
3106 }
3107}
3108
3109/// A layered span as a playback stream: its composed frames, one per picture
3110/// change, decoded on a thread of their own. Each is `view`-sized and numbered
3111/// the way a decoder numbers its pictures -- the span's first source frame plus
3112/// the speed's step -- so the playback clock maps it like any other clip.
3113pub(crate) fn layered_stream(
3114 project: Project,
3115 view: VideoMeta,
3116 out_color: ColorDescription,
3117 span: crate::project::Span,
3118 paths: Option<Vec<PathBuf>>,
3119) -> crate::decode::FrameStream {
3120 let stack = stack_at(&project, span.start);
3121 let base = span.from.map_or(0, |(_, in_frame)| in_frame);
3122 crate::decode::DecodeSession::spawn_stream(
3123 "layers",
3124 crate::decode::Backend::Software,
3125 move |tx, cancel| {
3126 let Ok(mut layers) =
3127 LayerStack::open(&project, &view, &stack, out_color.matrix, paths.as_deref(), None)
3128 else {
3129 return;
3130 };
3131 let mut last = None;
3132 for offset in 0..span.len {
3133 if cancel.load(Ordering::Relaxed) {
3134 return;
3135 }
3136 // One picture per source step, as a decoder yields one per frame:
3137 // a slowed clip's repeats are held by the clock, not decoded again.
3138 let step = span.source_offset(offset);
3139 if last == Some(step) {
3140 continue;
3141 }
3142 last = Some(step);
3143 let Ok(Some((y, u, v))) = layers.picture(span.start + offset) else {
3144 return;
3145 };
3146 let bgra = crate::convert::i420_to_bgra(
3147 &out_color,
3148 &y,
3149 &u,
3150 &v,
3151 view.width as usize,
3152 view.height as usize,
3153 );
3154 let frame = crate::decode::Frame {
3155 index: base + step,
3156 width: view.width,
3157 height: view.height,
3158 bgra,
3159 };
3160 if tx.send(frame).is_err() {
3161 return;
3162 }
3163 }
3164 },
3165 )
3166}
3167
3168/// The cross-dissolve this span's tail owes its successor, or `None` for a
3169/// hard cut. `(b_source, b_in_frame, window, b_start)`: which source and
3170/// source frame the dissolve's B side starts reading, how many *output*
3171/// frames the blend ramps across, and where B sits on the timeline (which is
3172/// what its own grade and fit are keyed on, [`Project::composite_color_at`]
3173/// and [`Project::composite_fit_at`]).
3174///
3175/// [`Clip::transition_out`] is trusted only after adjacency is checked again
3176/// here: a trim or a split since it was set leaves the stored number in
3177/// place but not its meaning, so a stale one plays as the hard cut it now
3178/// is rather than as a dissolve into a clip that no longer follows.
3179pub(crate) fn dissolve_window(
3180 project: &Project,
3181 span: &crate::project::Span,
3182) -> Option<(usize, u32, u32, u32)> {
3183 // A layered picture is composed beneath its top clip, and a dissolve of that
3184 // clip would blend a picture of one clip alone -- the layers are not blended.
3185 if layered_at(project, span.start) {
3186 return None;
3187 }
3188 let (source, _) = span.from?;
3189 let (lane, idx) = project.composite_clip_at(span.start)?;
3190 let clips = project.lane(lane);
3191 let a = clips.get(idx)?;
3192 if a.source != source || a.transition_out == 0 {
3193 return None;
3194 }
3195 let b = clips.get(idx + 1)?;
3196 if a.end() != b.start {
3197 return None; // trimmed or split apart since the dissolve was set
3198 }
3199 // The span must run uninterrupted all the way to A's own end: a higher
3200 // video lane taking over before that means there is no tail of A left
3201 // here to blend into anything.
3202 if span.start + span.len != a.end() {
3203 return None;
3204 }
3205 let window = a
3206 .transition_out
3207 .min(a.frames())
3208 .min(b.frames())
3209 .min(span.len);
3210 (window > 0).then_some((b.source, b.in_frame, window, b.start))
3211}
3212
3213/// `B`'s weight in [`crate::scale::blend_i420`] at output frame `idx_in_window` of `window`
3214/// (`idx_in_window < window`): a ramp from just above 0 to just below 1 that
3215/// never actually reaches either end, so the first blended frame still shows
3216/// a trace of A and the last still a trace of B -- the cut a hard transition
3217/// would have made lands one frame *after* the window, at full B, rather than
3218/// inside it.
3219pub(crate) fn dissolve_weight(idx_in_window: u32, window: u32) -> f32 {
3220 (idx_in_window + 1) as f32 / (window + 1) as f32
3221}
3222
3223/// The picture's black fade at timeline `frame`: the share of the picture that
3224/// survives, `None` where no fade reaches it. The clip on screen
3225/// ([`Project::composite_clip_at`]) owns its own fades -- [`Clip::fade_in`] ramps
3226/// from black on its first frame to the whole picture at `fade_in`, and
3227/// [`Clip::fade_out`] ramps back to black over its last `fade_out` frames, the
3228/// same edges [`crate::project::Fade`] ramps the sound on. A linear ramp: the
3229/// first frame of a fade-in is pure black and the frame a fade-out ends on is
3230/// one step short of it, so nothing shows the picture at full strength while
3231/// the ramp is still running.
3232pub(crate) fn picture_fade_at(project: &Project, frame: u32) -> Option<f32> {
3233 let (lane, idx) = project.composite_clip_at(frame)?;
3234 clip_fade(project.lane(lane).get(idx)?, frame)
3235}
3236
3237/// [`picture_fade_at`] for one clip: the share of its picture that survives at
3238/// `frame`. A layered picture asks it of each clip, so a fade belongs to the
3239/// clip it is on.
3240fn clip_fade(clip: &crate::project::Clip, frame: u32) -> Option<f32> {
3241 if clip.fade_in == 0 && clip.fade_out == 0 {
3242 return None;
3243 }
3244 let pos = frame.checked_sub(clip.start)?;
3245 let total = clip.frames();
3246 let mut k = 1.0f32;
3247 if clip.fade_in > 0 && pos < clip.fade_in {
3248 k = pos as f32 / clip.fade_in as f32;
3249 }
3250 if clip.fade_out > 0 && pos >= total.saturating_sub(clip.fade_out) {
3251 k = k.min((total - pos) as f32 / clip.fade_out as f32);
3252 }
3253 (k < 1.0).then_some(k)
3254}
3255
3256/// Whether any frame of `span` is inside a picture fade ([`picture_fade_at`]):
3257/// the span's pixels then have to be touched, which a zero-copy span never is.
3258fn picture_faded_in(project: &Project, span: &crate::project::Span) -> bool {
3259 (span.start..span.start.saturating_add(span.len))
3260 .any(|frame| picture_fade_at(project, frame).is_some())
3261}
3262
3263/// Whether any video clip on the timeline has a picture fade -- the
3264/// picture-side twin of [`faded`], which asks the same of sound: a fade is
3265/// pixel math, so a stream copy cannot carry one.
3266fn picture_faded(project: &Project) -> bool {
3267 project
3268 .lanes()
3269 .into_iter()
3270 .filter(|lane| lane.kind == LaneKind::Video)
3271 .any(|lane| {
3272 project
3273 .lane(lane)
3274 .iter()
3275 .any(|c| c.fade_in > 0 || c.fade_out > 0)
3276 })
3277}
3278
3279/// `planes` drawn toward black by `k` ([`picture_fade_at`]): luma moves toward
3280/// 16 and chroma toward 128, the black a gap is composed as, so a faded frame
3281/// and a gap agree on what black is.
3282fn fade_planes<T: Sample>(planes: (&[T], &[T], &[T]), k: f32) -> Planes<T> {
3283 let toward = |s: &[T], black: T| -> Vec<T> {
3284 s.iter()
3285 .map(|&p| {
3286 let (black, p) = (black.code() as f32, p.code() as f32);
3287 T::from_f32(black + (p - black) * k)
3288 })
3289 .collect()
3290 };
3291 (
3292 toward(planes.0, T::BLACK),
3293 toward(planes.1, T::NEUTRAL),
3294 toward(planes.2, T::NEUTRAL),
3295 )
3296}
3297
3298/// A dissolve's B side, open beside A's own decoder for this span's tail:
3299/// its own decoder, and everything [`place_picture`] needs to put its frames
3300/// on the same canvas, in the same space, graded the way B is graded rather
3301/// than the way A is -- [`Project::composite_color_at`]/`composite_fit_at`
3302/// asked at B's own start, not at the timeline position the blend writes to,
3303/// which is still inside A's span.
3304struct Dissolve<'a> {
3305 /// How many output frames the blend ramps across.
3306 window: u32,
3307 kind: crate::transitions::TransitionKind,
3308 /// The first output frame of this span's tail that is inside the window.
3309 tail_start: u32,
3310 decoder: ClipDecoder,
3311 mapper: Option<&'a ToneMapper>,
3312 remap: Option<Remap>,
3313 grade: Option<crate::color::ColorParams>,
3314 transform: TransformParams,
3315 /// B's own file's display-matrix turn, [`place_picture`]'s first stage;
3316 /// B is a different file and may be turned differently from A.
3317 rotation: Rotation,
3318 /// B's own file's sample aspect, [`place_picture`]'s second stage, for
3319 /// the same reason the turn is per file.
3320 pixel_aspect: crate::demux::PixelAspect,
3321 canvas: Composer,
3322 /// The turn's, the grade's and the transform's scratch, exactly as A's
3323 /// span keeps them: refilled per picture, allocated once.
3324 rotated: (Vec<u8>, Vec<u8>, Vec<u8>),
3325 /// The stretch's own scratch, [`place_picture`]'s second stage -- the
3326 /// pixel aspect's, beside the turn's.
3327 stretched: (Vec<u8>, Vec<u8>, Vec<u8>),
3328 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
3329 transformed: (Vec<u8>, Vec<u8>, Vec<u8>),
3330 /// The 10-bit scratch of B's placement, for a 10-bit export.
3331 scratch16: Scratch16,
3332}
3333
3334/// The Videos folder a default export lands in: the user's own (`XDG_VIDEOS_DIR`,
3335/// else the one `~/.config/user-dirs.dirs` names, else `~/Videos`), then the
3336/// project's folder, never the media's own folder by default.
3337pub fn default_export_folder(project: &Path) -> PathBuf {
3338 let home = std::env::var_os("HOME").map(PathBuf::from);
3339 let xdg = std::env::var_os("XDG_VIDEOS_DIR").map(PathBuf::from).or_else(|| {
3340 let home = home.as_ref()?;
3341 let text = std::fs::read_to_string(home.join(".config/user-dirs.dirs")).ok()?;
3342 let line = text.lines().find_map(|l| l.trim().strip_prefix("XDG_VIDEOS_DIR="))?;
3343 let value = line.trim().trim_matches('"');
3344 Some(PathBuf::from(value.replace("$HOME", &home.to_string_lossy())))
3345 });
3346 let videos = xdg.filter(|d| d.is_dir()).or_else(|| home.map(|h| h.join("Videos")).filter(|d| d.is_dir()));
3347 videos
3348 .or_else(|| project.parent().filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf))
3349 .unwrap_or_else(|| PathBuf::from("."))
3350}
3351
3352/// The track's cues where the *exported* timeline puts them, which is the only
3353/// clock the file has: the export writes timeline frame 0 onwards and nothing
3354/// else, exactly as the sound is mixed from frame 0 and resized to the
3355/// timeline's own length ([`encode_audio`]).
3356///
3357/// Which clock the cues arrive in is what the track itself says:
3358///
3359/// * a track out of a *file* (`SubtitleTrack::track`) is timed against that
3360/// file, so each cue is carried through the spans that play it -- a cue over
3361/// a stretch that was cut out is gone, one straddling a cut keeps the half
3362/// that is still there, and one after a rippled delete moves back with the
3363/// picture it belongs to. The *edges* a cut clips to are frames -- that is
3364/// what a cut is -- but a cue nothing clipped keeps its own microseconds, so
3365/// an untouched timeline exports the times the source states.
3366/// * a *standalone* file (`subs.srt`) is timed against nothing else -- there is
3367/// no clip to hang it on and no offset in the project to shift it by -- so it
3368/// is the timeline's own clock, which is where it was drawn while editing
3369/// (`Player::subtitle_overlay`). Clipped to the exported length and no more.
3370///
3371/// This is also what the *preview* draws: the plate over the picture and the
3372/// timeline strip both ask it through
3373/// [`PlaybackSession::timeline_cues`](crate::PlaybackSession::timeline_cues), so
3374/// what a rippled timeline shows and what its export writes are one answer by
3375/// construction rather than two maps kept in step by hand.
3376///
3377/// Pure and cheap enough to ask per repaint (a walk of the spans and of the
3378/// cues, no file opened), which is how a front-end asks it.
3379pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<Cue> {
3380 timeline_cues_indexed(project, track, fps).into_iter().map(|(_, cue)| cue).collect()
3381}
3382
3383fn timeline_cues_indexed(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<(usize, Cue)> {
3384 let frames = project.timeline_frames();
3385 let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64;
3386 let end = us(frames);
3387 // The file the cues are timed against, when there is one on this timeline.
3388 // A track whose media has since been dropped from the project has no span
3389 // to be carried through and falls back to the timeline's clock, which is
3390 // what it was drawn on.
3391 //
3392 // Through the same `canonical` a source is indexed by, or the two spellings
3393 // of one file (an argv `../assets/film.mkv`, a symlinked folder) would read
3394 // as two files and the cues would quietly fall back to the timeline's clock.
3395 let source = track.track.and_then(|_| {
3396 let path = crate::project::canonical(&track.path);
3397 project.sources().iter().position(|s| s.path == path)
3398 });
3399 let Some(source) = source else {
3400 return track
3401 .cues
3402 .iter()
3403 .enumerate()
3404 .filter_map(|(i, cue)| {
3405 let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end));
3406 (end_us > start_us).then_some((i, Cue {
3407 start_us,
3408 end_us,
3409 text: cue.text.clone(),
3410 image: cue.image.clone(),
3411 words: crate::subtitle::map_words(&cue.words, (start_us, end_us), (start_us, end_us)),
3412 karaoke: crate::subtitle::map_karaoke(&cue.karaoke, (start_us, end_us), (start_us, end_us)),
3413 }))
3414 })
3415 .collect();
3416 };
3417 let mut out = Vec::new();
3418 for span in stack_spans_from(project, 0) {
3419 let Some((_, in_frame)) = span.from.filter(|&(from, _)| from == source) else {
3420 continue;
3421 };
3422 // What of the file this span plays, as *time in the file*: a clip counts
3423 // the timeline's frames whatever its file was shot at ([`Rate`]), which
3424 // is what makes those frames the same seconds a cue is timed in.
3425 let (first, last) = match span.source_window() {
3426 Some((_, lo, hi)) => (us(lo), us(hi)),
3427 None => (us(in_frame), us(in_frame + span.source_len())),
3428 };
3429 // Where that lands, and how fast: a cue is carried by the same factor
3430 // the pictures under it are, so a slowed clip stretches its subtitles
3431 // with it instead of leaving them behind.
3432 let start = us(span.start);
3433 // `rel` is the time since the span's head in the file's own direction of play:
3434 // forwards from `first`, and for a reversed clip back from `last` (the cue
3435 // [s, e] is mirrored to [last - e, last - s]).
3436 let onto = |rel: i64| {
3437 let Some(_) = span.ramp else {
3438 return start + (rel as f64 / span.speed.as_f64()).round() as i64;
3439 };
3440 // A ramp has no one factor: carry the cue through the ramp's own
3441 // inverse (`Span::timeline_at`), interpolating between whole frames.
3442 let f = (rel as f64 / 1e6 * fps).max(0.0);
3443 let (lo, hi) = (f.floor() as u32, f.ceil() as u32);
3444 let at = |s: u32| f64::from(span.timeline_at(in_frame + s).min(span.start + span.len) - span.start);
3445 let (a, b) = (at(lo), at(hi));
3446 let frames = if hi == lo { b } else { a + (b - a) * (f - f64::from(lo)) };
3447 start + (frames / fps * 1e6).round() as i64
3448 };
3449 for (i, cue) in track.cues.iter().enumerate() {
3450 let (a, b) = (cue.start_us.max(first), cue.end_us.min(last));
3451 if b <= a {
3452 continue; // wholly outside what this span kept
3453 }
3454 let (from, to) = if span.reverse { (last - b, last - a) } else { (a - first, b - first) };
3455 out.push((i, Cue {
3456 start_us: onto(from),
3457 end_us: onto(to).min(end),
3458 text: cue.text.clone(),
3459 image: cue.image.clone(),
3460 // Each word through the same mapping as the cue, so a ramp places it where
3461 // its own sound plays; a reversed clip keeps none, its cue shown whole.
3462 words: if span.reverse {
3463 Vec::new()
3464 } else {
3465 cue.words
3466 .iter()
3467 .filter(|(s, _, _)| *s < b)
3468 .map(|(s, e, w)| {
3469 let at = |t: i64| onto(t.clamp(a, b) - first).min(end);
3470 (at(*s), at(*e), w.clone())
3471 })
3472 .collect()
3473 },
3474 karaoke: if span.reverse {
3475 Vec::new()
3476 } else {
3477 cue.karaoke
3478 .iter()
3479 .filter(|k| k.start_us < b)
3480 .map(|k| {
3481 let at = |t: i64| onto(t.clamp(a, b) - first).min(end);
3482 crate::subtitle::Syllable { start_us: at(k.start_us), end_us: at(k.end_us), ..k.clone() }
3483 })
3484 .collect()
3485 },
3486 }));
3487 }
3488 }
3489 // The spans come in timeline order but a cue's *own* order across them does
3490 // not: a Matroska muxer writes blocks as they come up.
3491 out.sort_by_key(|(_, cue)| cue.start_us);
3492 out
3493}
3494
3495/// What [`start`] would do about the subtitles, in the words a card shows: what
3496/// travels, and the reason beside every pick that does not. Pure, like
3497/// [`planned_audio`]: no file is opened, so it may be asked per repaint.
3498///
3499/// `picks` is any run of indices into [`Project::subtitles`] -- an
3500/// [`ExportSettings::subtitles`] list (`picks.iter().copied()`) as much as a
3501/// single `Some(row)`, which is what a front-end holding one row still hands it.
3502pub fn planned_subtitles(
3503 project: &Project,
3504 format: Format,
3505 picks: impl IntoIterator<Item = usize>,
3506) -> String {
3507 planned_subtitles_in(project, format, picks, None, 0.0)
3508}
3509
3510/// [`planned_subtitles`] for an export of `range` (the frames a ranged file keeps) at `fps`: a
3511/// track or lane with no cue left in the range is named as dropped for that reason, since the
3512/// file would carry it empty. `None` is the whole timeline, and `fps` is then not read.
3513pub fn planned_subtitles_in(
3514 project: &Project,
3515 format: Format,
3516 picks: impl IntoIterator<Item = usize>,
3517 range: Option<(u32, u32)>,
3518 fps: f64,
3519) -> String {
3520 let picks: Vec<usize> = picks.into_iter().collect();
3521 let lanes = placed_lanes(project);
3522 // WebM is the one container that names no subtitle track here, placed or
3523 // picked: said first and once, as the reason nothing travels.
3524 if format == Format::Webm && (!picks.is_empty() || !lanes.is_empty()) {
3525 return "none — a WebM file carries no subtitles".into();
3526 }
3527 if format == Format::ProRes && (!picks.is_empty() || !lanes.is_empty()) {
3528 return "none — a ProRes QuickTime file carries no subtitles".into();
3529 }
3530 // An mp4 of a timeline with no picture is the sound alone too: no track of
3531 // either kind is written, placed or picked ([`export_subtitles`]).
3532 if format.ext() == "mp4" && !has_picture(project) {
3533 return "none — a timeline with no picture is the sound alone".into();
3534 }
3535 // One statement about the *file*, said before any about a track: a format
3536 // that is the sound alone has nowhere to put a single one of them, and the
3537 // reason a pick would not have travelled anyway (a picture track, no cues)
3538 // is not the reason it does not travel here. Nothing picked is "none" --
3539 // there is nothing to say a container cannot carry.
3540 if !format.has_video() && (!picks.is_empty() || !lanes.is_empty()) {
3541 return "none — this format is the sound alone".into();
3542 }
3543 // The lanes are the words placed on the timeline and go as they are placed
3544 // ([`export_subtitles`]); each picked track no lane places is written whole,
3545 // beside them. The clauses go in the order the file writes the tracks
3546 // ([`soft_order`]), which is the order the caller gave them.
3547 let (mut embedded, mut dropped) = (Vec::new(), Vec::new());
3548 let (mut lane_count, mut trailing) = (0, false);
3549 for entry in soft_order(project, &lanes, &picks) {
3550 let pick = match entry {
3551 SoftEntry::Lane(lane) => {
3552 let (e, d, t) = planned_lanes(project, &[lane], &picks, range, fps);
3553 lane_count += e.len();
3554 embedded.extend(e);
3555 dropped.extend(d);
3556 trailing |= t;
3557 continue;
3558 }
3559 SoftEntry::Track(pick) => pick,
3560 };
3561 // A pick the project has no row for: a caller holding an index the list
3562 // no longer has (a removed row shifts every later one down). Every other
3563 // reason a pick does not travel is named on this card, so this one is
3564 // too -- a bug that says nothing is a bug found in the finished file.
3565 let Some(track) = project.subtitles().get(pick) else {
3566 dropped.push(format!("#{pick} — no such track"));
3567 continue;
3568 };
3569 if let Some(why) = &track.refused {
3570 dropped.push(format!("{} — {why}", track.label));
3571 } else if track.is_bitmap() {
3572 // Drawn over the picture, written into no file: the exported track
3573 // is text and these cues are bitmaps. Said whatever the format,
3574 // because it is the track and not the container that cannot be
3575 // carried.
3576 dropped.push(format!("{} — pictures; drawn, not written", track.label));
3577 } else if !track_has_cues(project, track, range, fps) {
3578 dropped.push(format!("{} — {}", track.label, no_cues_word(range)));
3579 } else {
3580 // Whichever container: a Matroska carries the track as
3581 // `S_TEXT/UTF8` blocks and an mp4 as a `tx3g` timed-text track, and
3582 // a pick travels either way. There is no container refusal left on
3583 // this card -- the sound-alone one above is about the *file* and the
3584 // ones beside it about the *track*.
3585 embedded.push(track.label.clone());
3586 }
3587 }
3588 // Lanes only are named as lanes; a picked track in the mix makes them tracks.
3589 let noun = if lane_count == embedded.len() { "lanes" } else { "tracks" };
3590 // A Matroska block numbers its track in one byte, so a file carries at most
3591 // MAX_SUB_TRACKS of them, placed or picked; the muxer refuses more again.
3592 if format.is_mkv() && embedded.len() > crate::mux::MAX_SUB_TRACKS {
3593 return format!(
3594 "{} subtitle {noun}: a Matroska block writes its track number in one byte, so one file \
3595 carries at most {}",
3596 embedded.len(),
3597 crate::mux::MAX_SUB_TRACKS
3598 );
3599 }
3600 let mut parts = match embedded.len() {
3601 0 => Vec::new(),
3602 1 => vec![format!("{} → embedded", embedded[0])],
3603 n => vec![format!("{n} {noun} → embedded ({})", embedded.join(", "))],
3604 };
3605 parts.extend(dropped);
3606 if trailing {
3607 parts.push("cues past the last picture are cut off there".into());
3608 }
3609 match parts.is_empty() {
3610 true => "none".into(),
3611 false => parts.join("; "),
3612 }
3613}
3614
3615/// [`planned_subtitles`] for a timeline that *places* its words: one clause per
3616/// subtitle lane, named by the lane and by the palette row it shows, in the
3617/// order the file will declare them ([`lane_subtitles`]).
3618///
3619/// Every reason a lane does not travel is said here rather than found in the
3620/// file: a picture track placed on it, a track that could not be read, a palette
3621/// row that has since gone, a lane sitting entirely past the last picture, and
3622/// -- before a byte is written -- more lanes than a Matroska block can number
3623/// ([`crate::mux::MAX_SUB_TRACKS`], which the muxer refuses again).
3624fn planned_lanes(
3625 project: &Project,
3626 lanes: &[Lane],
3627 picks: &[usize],
3628 range: Option<(u32, u32)>,
3629 fps: f64,
3630) -> (Vec<String>, Vec<String>, bool) {
3631 let end = project.media_frames();
3632 let (mut embedded, mut dropped, mut trailing) = (Vec::new(), Vec::new(), false);
3633 for &lane in lanes {
3634 let placed = project.sub_lane(lane);
3635 // An empty lane is a lane nobody has used yet, not a refusal. A lane no
3636 // pick reaches is not in this file at all, so it is not named either.
3637 let Some(first) = placed.first() else {
3638 continue;
3639 };
3640 if !picked(placed, picks) {
3641 continue;
3642 }
3643 let row = |s: &crate::project::SubClip| project.subtitles().get(s.track);
3644 let (label, head) = (lane.label(), row(first));
3645 let name = head.map_or_else(String::new, |t| format!("{} ", t.label));
3646 if let Some(gone) = placed.iter().find(|s| row(s).is_none()) {
3647 dropped.push(format!("{label} — #{} is no longer a track", gone.track));
3648 } else if let Some((t, why)) = placed
3649 .iter()
3650 .find_map(|s| row(s).and_then(|t| t.refused.as_ref().map(|why| (t, why))))
3651 {
3652 dropped.push(format!("{label} {} — {why}", t.label));
3653 } else if let Some(t) = placed.iter().find_map(|s| row(s).filter(|t| t.is_bitmap())) {
3654 // Drawn over the picture, written into no file -- the same sentence
3655 // a picked track gets, because it is the track and not the lane that
3656 // cannot be carried.
3657 dropped.push(format!(
3658 "{label} {} — pictures; drawn, not written",
3659 t.label
3660 ));
3661 } else if first.start >= end {
3662 dropped.push(format!("{label} {name}— past the last picture"));
3663 } else if range.is_some() && lane_subtitle(project, lane, fps, range, picks).is_none() {
3664 dropped.push(format!("{label} {name}— {}", no_cues_word(range)));
3665 } else {
3666 embedded.push(format!("{label} {}", name.trim_end()));
3667 // Something on it hangs past the end of the media: the timeline is
3668 // held open under it ([`Project::timeline_frames`]) but the file
3669 // stops with the last picture, so those cues are cut off there.
3670 trailing |= placed.last().is_some_and(|s| s.end() > end);
3671 }
3672 }
3673 (embedded, dropped, trailing)
3674}
3675
3676/// What [`start`] would encode the picture with, probed the way the export
3677/// probes it -- the very encoder is opened and closed again -- so this is a
3678/// measurement and not a promise. `None` for a format that carries no picture.
3679///
3680/// Costs that open (~100 ms here): ask it off a render thread and keep the
3681/// answer until the format, the resolution or the bitrate changes.
3682pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> {
3683 settings
3684 .format
3685 .has_video()
3686 .then(|| match hw_seat(
3687 meta,
3688 settings,
3689 settings.video_bit_depth == Some(10) || settings.hdr.transfer != HdrTransfer::Sdr,
3690 ColorDescription::output_sized(meta.width, meta.height),
3691 ) {
3692 Ok(hw) => video_label(settings.format, hw.is_some(), settings.intra_only),
3693 // The seat the settings demand and this machine has not: the very
3694 // refusal [`start`] would settle with, said on the card instead.
3695 Err(_) => NO_HW_SEAT,
3696 })
3697}
3698
3699/// What [`start`] would open for *this* timeline: the picture's seat -- or the
3700/// copy that means there is no encoder at all -- and the sound's, asked of the
3701/// very gates the export asks ([`CopyPlan::of`] and [`copy_audio`]'s) rather
3702/// than of the format alone.
3703///
3704/// This exists because the card and the running export used to disagree in both
3705/// directions on the same file: the card named a software HEVC encode for a cut
3706/// the engine copied, and named an AAC copy for a Matroska source whose sound
3707/// no sample table holds and which therefore always re-encodes. A prediction
3708/// that is not the decision is worse than no prediction, because a person plans
3709/// their evening around it.
3710///
3711/// Costs what [`planned_video`] costs (an encoder opened and closed) plus a
3712/// header read per source and, once per file, its cluster walk: ask it off a
3713/// render thread and keep the answer until the timeline or the settings change.
3714pub fn planned_seats(
3715 project: &Project,
3716 meta: &VideoMeta,
3717 settings: &ExportSettings,
3718) -> (Option<&'static str>, &'static str) {
3719 // The canvas the file is drawn at, which is what the seat and the copy gate are about.
3720 let meta = &output_meta(meta, settings);
3721 let video = settings.format.has_video().then(|| {
3722 match CopyPlan::of(project, meta, settings).is_some() {
3723 true => "copy (source packets)",
3724 false => planned_video(meta, settings).unwrap_or(NO_HW_SEAT),
3725 }
3726 });
3727 // The half [`audio_label`] cannot know from the format: a copy is a *sample
3728 // table's* packets ([`copy_audio`] hands them to `copy_multi_streams`), and
3729 // a Matroska file has none -- so every mkv source re-encodes, however
3730 // untouched its lane is. Extension only, which is what `is_matroska`
3731 // reads, so this costs nothing beyond what is already open. A standalone
3732 // audio file (mp3, wav, flac...) has no sample table either: its sound is
3733 // decoded and encoded again, as [`copy_multi_streams`] refusing it sends it.
3734 let copyable = !settings.reencode_audio
3735 && !forces_encode(project, settings.range.is_some())
3736 && !project.sources().iter().any(|source|
3737 {
3738 crate::demux::is_matroska(&source.path)
3739 || crate::demux::is_mpeg_system(&source.path)
3740 || crate::is_audio(&source.path)
3741 });
3742 let sound = match undecodable_sound(project) {
3743 Some(label) if has_sound(project) => label,
3744 // A Matroska file that is encoded (not copied) takes Opus or AAC as the mix decides, so
3745 // the card names the one this mix will get, read from the sources' headers.
3746 None if has_sound(project)
3747 && !copyable
3748 && settings.format.is_mkv()
3749 && settings.format != Format::Webm =>
3750 {
3751 match mkv_mix_is_opus(project, meta.frame_rate) {
3752 true => "Opus · SW encode (ec-opus)",
3753 false => "AAC · SW encode (ec-aac)",
3754 }
3755 }
3756 _ => audio_label(
3757 project,
3758 settings.format,
3759 has_sound(project),
3760 Some(copyable),
3761 settings.range.is_some(),
3762 settings.reencode_audio,
3763 ),
3764 };
3765 (video, sound)
3766}
3767
3768/// Whether the mix a Matroska export encodes would be written as Opus: the rule
3769/// [`encode_audio`] applies after the mix is open -- 48 kHz, mono or stereo -- worked
3770/// out from the lanes' sources' headers instead ([`AudioSession::probe`]), since no mix
3771/// is opened to ask. The mix runs at the highest source rate, 48 kHz when every source
3772/// is below 44.1 kHz ([`crate::audio`]'s `mix_rate`), and as wide as the widest source.
3773/// The fidelity gate that can still hand the track back to AAC is measured only once
3774/// the encode has run, so this is the prediction the export's own line corrects.
3775fn mkv_mix_is_opus(project: &Project, fps: f64) -> bool {
3776 let sources = project.audio_sources();
3777 let mut rates = Vec::new();
3778 let mut channels = 0u16;
3779 for lane in project.audio_segments_from(0, fps) {
3780 for (source, ..) in lane {
3781 let Some((path, stream)) = source.and_then(|i| sources.get(i)) else {
3782 continue;
3783 };
3784 if crate::is_image(path) {
3785 continue;
3786 }
3787 if let Ok(Some(probe)) = AudioSession::probe(path, *stream) {
3788 rates.push(probe.sample_rate);
3789 channels = channels.max(probe.channels);
3790 }
3791 }
3792 }
3793 let rate = rates.into_iter().max().map(|r| if r < 44_100 { OPUS_RATE } else { r });
3794 rate == Some(OPUS_RATE) && (1..=2).contains(&channels)
3795}
3796
3797/// The sound a timeline's sources cannot give: `Some(label)` when every source
3798/// on the audio lanes is one [`AudioSession::unsupported`] names as undecodable,
3799/// which is what the export's own open answers with no sound at all ("no audio
3800/// to write"). `None` when any source decodes, or when a source has no sound
3801/// this question can name.
3802fn undecodable_sound(project: &Project) -> Option<&'static str> {
3803 let reasons: Vec<Option<String>> = project
3804 .audio_sources()
3805 .iter()
3806 .map(|(path, _)| AudioSession::unsupported(path).ok().flatten())
3807 .collect();
3808 if reasons.is_empty() || reasons.iter().any(Option::is_none) {
3809 return None;
3810 }
3811 // The reason's first words name the codec: a Matroska file by its codec id
3812 // ("the A_DTS track ..."), an mp4 by its media type ("the dts audio track
3813 // ..."). Only DTS is named by name; any other codec this engine cannot decode
3814 // gets the general words.
3815 let dts = reasons.iter().flatten().all(|reason| {
3816 let reason = reason.to_ascii_lowercase();
3817 reason.starts_with("the a_dts ") || reason.starts_with("the dts ")
3818 });
3819 Some(match dts {
3820 true => "none — DTS can't be decoded",
3821 false => "none — this codec can't be decoded",
3822 })
3823}
3824
3825/// The tone map a picture export puts on its HDR sources, as a sentence for the
3826/// start line and the plan: the picture is written 8-bit BT.709 SDR, so a PQ or
3827/// HLG source is tone-mapped down silently otherwise. `None` where no picture
3828/// is tone-mapped -- a sound-only format, a preview that keeps its source's
3829/// curve ([`ExportSettings::keep_source_colour`]), or no HDR source in the
3830/// project. Asked of every source, as [`planned_seats`] asks its sound.
3831///
3832/// Header reads only, one per source, the same colour the export's own tone map
3833/// is built from ([`source_rate`]).
3834pub fn planned_tone(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<String> {
3835 if !settings.format.has_video() || settings.keep_source_colour {
3836 return None;
3837 }
3838 // The matrix the file is tagged with: the one [`start`] writes for this canvas
3839 // ([`ColorDescription::output_sized`]), so the words name what the file says.
3840 let out = output_meta(meta, settings);
3841 let matrix = match ColorDescription::output_sized(out.width, out.height).matrix {
3842 Matrix::Bt601 => "BT.601",
3843 _ => "BT.709",
3844 };
3845 let mut transfers = project.sources().iter().filter_map(|source| {
3846 if crate::is_image(&source.path) || crate::is_audio(&source.path) {
3847 return None;
3848 }
3849 Demuxer::open(&source.path).ok().map(|(meta, _)| meta.color.transfer)
3850 });
3851 transfers.find_map(|transfer| match transfer {
3852 Transfer::Pq => Some(format!("HDR (PQ) source tone-mapped to SDR {matrix}")),
3853 Transfer::Hlg => Some(format!("HDR (HLG) source tone-mapped to SDR {matrix}")),
3854 Transfer::Sdr => None,
3855 })
3856}
3857
3858fn settle(shared: &Shared, result: crate::Result<()>) {
3859 *shared.outcome.lock().unwrap() = Some(result);
3860 // Published last: a caller that sees the flag is guaranteed the outcome.
3861 shared.finished.store(true, Ordering::Release);
3862}
3863
3864/// The audio track an export writes, and how it was made -- a copy is the
3865/// source's own packets, bit for bit, and anything else is this project's
3866/// encoder over the decoded mix. [`run`] publishes which of the two really
3867/// happened, so the encoder line a user reads is measured and not promised.
3868pub(crate) struct ExportAudio {
3869 pub params: crate::AacTrackParams,
3870 pub packets: Vec<crate::AacPacket>,
3871 /// Whether those packets are the source's, untouched.
3872 pub copied: bool,
3873 /// The track's pre-skip in samples where those packets are **Opus** and not
3874 /// AAC ([`encode_opus`]), which is what the Matroska track entry states in
3875 /// its `OpusHead` and its `CodecDelay`. `None` is an AAC track, which is
3876 /// every copy and every mp4.
3877 pub opus_pre_skip: Option<u16>,
3878 /// The language the track is tagged with ([`audio_language`]), `None` for
3879 /// `und`. Set once where the track is made, from the project it came from.
3880 pub language: Option<String>,
3881 /// The sound's length in PCM frames per channel, where the packets were
3882 /// encoded from a mix of exactly that many: the count the encoder was fed,
3883 /// not the packets' sum, which runs on past it by the encoder's priming and
3884 /// the last frame's padding. `None` for a copy, whose length is the
3885 /// source's own packets.
3886 pub pcm_frames: Option<u64>,
3887}
3888
3889/// The timeline's audio track for a file that carries picture: copied packet for
3890/// packet where a copy says exactly what the timeline says, and decoded, mixed
3891/// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane,
3892/// a speeded clip, an equalizer, a source that is not AAC inside an mp4 sample
3893/// table. Nothing is refused for being uncopyable any more; the only refusals
3894/// left below the copy are about sound this engine cannot *decode* either, and
3895/// those come out of the decode path by name.
3896///
3897/// The copy is still the default and still bit-exact: a timeline nobody has
3898/// touched leaves as the very packets its source holds.
3899///
3900/// corner-cut: this holds the whole exported AAC track in memory (~3 kB per
3901/// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming
3902/// `copy_segments` that yields packets instead of collecting them.
3903#[allow(clippy::too_many_arguments)]
3904fn copy_audio(
3905 project: &Project,
3906 meta: &VideoMeta,
3907 kbps: u32,
3908 mkv: bool,
3909 webm: bool,
3910 reencode: bool,
3911 shared: &Shared,
3912 sample_rate: Option<u32>,
3913 range: Option<(u32, u32)>,
3914) -> crate::Result<Option<ExportAudio>> {
3915 // WebM's sound is Opus, which no source's packets are: always the mix. A loudness target is a
3916 // gain over the mix, which a copied packet cannot carry. A rate the caller chose is a re-encode.
3917 if webm || reencode || shared.loudness.is_some() {
3918 return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, range);
3919 }
3920 // A ranged export needs an exact offset and an exact length, which a
3921 // packet copy cannot give -- it carries whole segments named by
3922 // `audio_segments_from(0, ..)`, not an arbitrary window into them. The
3923 // decoded path already resamples per segment, so it is the one that can
3924 // start and stop anywhere; this falls to it exactly as a speeded or
3925 // equalized lane already does.
3926 if range.is_some() {
3927 return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, range);
3928 }
3929 // The segments name their source, and the copy carries its packet-rounding
3930 // debt across a source join exactly as across a cut, so a timeline spanning
3931 // files stays in sync. A source whose AAC parameters disagree with the
3932 // first one is an `Err` from there -- import refuses those up front, this
3933 // is the backstop -- and the caller deletes the `.part`.
3934 //
3935 // The stream each source is copied from is the one it plays: `audio_sources`
3936 // is the same list `PlaybackSession::seek` hands the decoder, so an export
3937 // of a timeline playing a file's second audio track carries *that* track.
3938 //
3939 // One lane is the only shape a *copy* has: summing two means decoding both,
3940 // and a sum is not a copy. Two or more go to [`encode_audio`], which is the
3941 // very mix the WAV path writes -- it used to be a refusal, and a refusal is
3942 // what a file missing half its sound deserves, not what a mix does.
3943 //
3944 // *Which* lane is the same question `audio_segments_from` answers for
3945 // playback, and it is asked here rather than assumed: the lane that holds
3946 // the sound need not be `A1` (a project may leave `A1` empty and place
3947 // everything on `A2`), and copying `A1`'s list in that case would write a
3948 // file with no audio track at all -- silently, which is the failure this
3949 // whole comment is about.
3950 let mut lanes = project.audio_segments_from(0, meta.frame_rate);
3951 // ...cut to what the picture writes ([`export_spans`]). The play list is
3952 // the *timeline's* ([`Project::timeline_frames`]), so a caption hanging past
3953 // the last picture ends every audio lane with a trailing gap -- silence this
3954 // path would copy out past the last frame, three seconds of it on the film
3955 // this was found on. Only a gap can be out there (`media_frames` is the last
3956 // clip's own end), and the mixed paths already resize to the same length
3957 // ([`encode_audio`]); a copy carries source packets and has no resize.
3958 let over = f64::from(project.timeline_frames() - project.media_frames()) / meta.frame_rate;
3959 for lane in &mut lanes {
3960 match lane.last_mut() {
3961 Some((None, _, len)) if *len > over => *len -= over,
3962 Some((None, _, _)) if over > 0.0 => {
3963 lane.pop();
3964 }
3965 _ => {}
3966 }
3967 }
3968 let [segments] = &lanes[..] else {
3969 return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None);
3970 };
3971 // ...and the same list names *which* lane those clips sit on, which is the
3972 // only way to ask what has been done to them.
3973 let lane = project.audio_lanes()[0];
3974 // ...and the same list decides whether any clip this would copy plays at a
3975 // rate other than the one it was recorded at. A copy hands the muxer the
3976 // very AAC packets the source holds and there is no rate inside a packet to
3977 // change: the picture would come out re-timed (the walk in [`run`] honours
3978 // it) over sound at 1.00x, which is the drift a person finds only after the
3979 // file has gone somewhere. Decoded and resampled instead, by the same worker
3980 // playback feeds from.
3981 //
3982 // ...and whether any clip on it carries an equalizer, which is sample math a
3983 // copy never reaches: copying such a lane would write the clip *flat*,
3984 // silently.
3985 //
3986 // A frame *rate* of its own is not one of those, and that is deliberate: do
3987 // not "fix" this into a re-encode. A clip counts the **timeline's** frames
3988 // whatever its file was shot at ([`crate::project::Rate`]), so the window
3989 // this copy trims a source's sound to is `start..end` in whole timeline
3990 // frames -- exactly the seconds the picture covers -- and the file is read
3991 // at the pitch it was recorded at, which is what playing at the rate it was
3992 // shot at means. There is no per-clip stretch to express, so the packets are
3993 // already the right sound in the right place; re-encoding a conformed lane
3994 // would buy nothing and cost a generation of loss on every mixed-rate export
3995 // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot`
3996 // measures the copied sound against the picture). A *speed* is different
3997 // because it resamples, which is why it leaves through the re-encode above.
3998 //
3999 // Only these: a timeline nobody has touched still leaves through the copy
4000 // below, packet for packet, so no passthrough quietly becomes a generation
4001 // of loss.
4002 // ...and whether the mix itself does anything a packet never went through:
4003 // a lane volume is applied at the sum and a limiter over it, so copying
4004 // such a lane would write it at unity and unlimited, silently.
4005 // ...asked as the very predicate [`forces_encode`] is, over the one lane
4006 // the segments came off, so what a card predicted and what this decides are
4007 // one answer. `lane` here is that lane, and not `A1` by assumption:
4008 // [`Project::audio_lanes`] is the list built for, and filtered by, these
4009 // very segments.
4010 if sample_altered(project, &[lane]) {
4011 return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None);
4012 }
4013 // What is left is a copy the *sources* may still not be able to give: AAC
4014 // inside a Matroska file (readable, but not out of a sample table this walks
4015 // -- there is none), an mp3 or a wav on the timeline, an AC-3 track, two
4016 // sources whose AAC parameters disagree. Every one of them decodes, and what
4017 // decodes can be encoded again, so the copy's refusal is now a route: the
4018 // error a *decode* cannot get past -- Opus or AC-3 inside a Matroska file,
4019 // which symphonia has no decoder for at any version -- is the one that comes
4020 // back, by name, from [`encode_audio`].
4021 match AudioSession::copy_multi_streams(&project.audio_sources(), segments) {
4022 Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio {
4023 params,
4024 packets,
4025 copied: true,
4026 // A copy is the source's own AAC packets: there is no Opus copy
4027 // path here, since the packets an mkv source holds never reach this
4028 // (they are not in a sample table) and every one of them re-encodes.
4029 opus_pre_skip: None,
4030 language: None,
4031 pcm_frames: None,
4032 })),
4033 Err(_) => encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None),
4034 }
4035}
4036
4037/// The picture's half of [`copy_audio`]: a Matroska export whose every span is
4038/// its source's own coded blocks, written back out without a decoder or an
4039/// encoder anywhere in the path.
4040///
4041/// **When.** A copy is entered only where it says *exactly* what the timeline
4042/// says, which is the audio gate's rule and not a looser one: the file this
4043/// export writes is Matroska, the source's codec is the one that file would
4044/// carry ([`Format::Hevc`] over HEVC, [`Format::Av1`] over AV1), and nothing on
4045/// the way has touched a sample -- no grade, no speed, no rate conversion, no
4046/// gap to fill with black, no source of another size to place on the canvas,
4047/// no `ContentEncodings` packing to undo. Anything else re-encodes exactly as
4048/// it always did; there is no half-copied file.
4049///
4050/// **All or nothing, per export.** A copied span and an encoded one cannot
4051/// share one track: this project's encoders write 8-bit SDR streams whose
4052/// parameter sets are their own, so splicing them into (say) a Main 10 HDR
4053/// source would change bit depth and colour mid-track, and a container states
4054/// its configuration record once. So the head and tail fragments of a cut that
4055/// lands mid-GOP are *not* re-encoded into the copy -- they are what makes the
4056/// whole export fall back to the encoder. What a copy needs instead is that
4057/// every span begins on a sync point and ends where the next one begins, which
4058/// is what a cut placed on a keyframe gives it.
4059///
4060/// **What a cut costs.** An open-GOP source (x265's default) writes leading
4061/// pictures after a sync point that are shown *before* it and reference the
4062/// group before it. At the start of a copied region those references are not in
4063/// the file, so they are dropped -- the picture before the cut is held for those
4064/// few frames (four at this film's B-depth, a sixth of a second) rather than
4065/// being written as pictures that cannot decode. The region still starts at the
4066/// timeline frame it owns, so the sound never drifts.
4067///
4068/// corner-cut: mp4 is not copied (its `hvc1` sample entry forbids in-band
4069/// parameter sets, and the mp4 muxer here writes its sample table from a frame
4070/// counter), and neither is H.264, which this project only writes into mp4. The
4071/// upgrade path for both is a sample-table writer that takes explicit
4072/// timestamps, which is what [`MkvMuxer::write_block`] already is for Matroska.
4073struct CopyPlan {
4074 /// Every source a region reads, by the index the project names it with;
4075 /// `None` for a source no clip plays from.
4076 sources: Vec<Option<MkvDemuxer>>,
4077 regions: Vec<CopyRegion>,
4078 codec_id: &'static [u8],
4079 /// The `CodecPrivate` every region's source agrees on -- a track is declared
4080 /// once, so two sources that disagree about their parameter sets are not one
4081 /// copy.
4082 private: Vec<u8>,
4083 /// The picture's language as the first source states it ([`video_language`]), which the
4084 /// copied track declares.
4085 language: Option<String>,
4086 /// The container's colour tags exactly as the source wrote them, which the
4087 /// copied track declares: a field the source left out stays left out, and
4088 /// nothing is resolved in its place ([`MkvDemuxer::colour_tags`]).
4089 colour: Tags,
4090 /// The coded shape the copied track declares: the samples under it are the
4091 /// source's own, so the header names what they are stored at -- not the
4092 /// shape they are drawn at.
4093 width: u32,
4094 height: u32,
4095 /// The aspect the copied samples are drawn at, written into the file as
4096 /// display metadata ([`CopyParams::pixel_aspect`]): square for every
4097 /// ordinary source, so the header gains nothing.
4098 pixel_aspect: crate::demux::PixelAspect,
4099}
4100
4101/// A run of source blocks copied in one piece: what a cut leaves behind, and
4102/// what two spans that continue each other in the same file merge back into.
4103struct CopyRegion {
4104 source: usize,
4105 /// Blocks of that source, in the file's own decode order.
4106 blocks: std::ops::Range<usize>,
4107 /// The *output* frame the region's first picture is shown at -- the
4108 /// project's own timeline frame less the range's own start, since a
4109 /// ranged export's file starts a fresh clock at zero.
4110 start: u32,
4111}
4112
4113/// Why [`ExportSettings::exact`] cannot be honoured for this project right
4114/// now, or `None` where [`CopyPlan`] already carries the whole file. A state
4115/// report, not an instruction: it says what the file *is* rather than what to
4116/// pick instead.
4117///
4118/// Two shapes of reason, told apart because only one of them is permanent.
4119/// **The container cannot carry the source's own codec at all** -- Exact was
4120/// asked of an mp4, or of a Matroska file whose codec is not the source's own
4121/// -- which is [`CopyPlan`]'s own corner-cut (mp4 copies nothing yet) and
4122/// [`CopyPlan::of`]'s codec check, so it is checked here the same way rather
4123/// than duplicated with different words. **The edit is what stops it** -- a
4124/// cut off a sync point, a grade, a speed, a dissolve, a moved or scaled
4125/// clip -- which the same format would carry exactly if the edit let it, so
4126/// those six [`CopyPlan::of`] gates are named together rather than picked
4127/// apart into six different sentences.
4128pub fn exact_refusal(
4129 project: &Project,
4130 meta: &VideoMeta,
4131 settings: &ExportSettings,
4132) -> Option<String> {
4133 if !settings.exact || CopyPlan::of(project, meta, settings).is_some() {
4134 return None;
4135 }
4136 // An anamorphic source asked of a format that cannot state the aspect: the
4137 // blocks would copy, but the sample entry this writer produces has no
4138 // `pasp` box to carry it in, and a header that declares the coded pair
4139 // while the pixels are drawn 4/3 wide is a file that lies about its own
4140 // shape. Refused by name -- the sentence a reader is owed -- before the
4141 // container's codec question, because this is the *nearer* reason: a
4142 // Matroska copy needs no refusal at all (its track carries the aspect
4143 // beside the blocks, [`CopyParams::pixel_aspect`], which is ffmpeg's own
4144 // copy behaviour), so an anamorphic source's Exact row only ever dies on
4145 // this for an mp4.
4146 if settings.burn_subtitles.is_some() {
4147 return Some(
4148 "captions are drawn into the picture, so it is decoded and encoded again rather \
4149 than copied byte for byte"
4150 .to_string(),
4151 );
4152 }
4153 if !project.titles().is_empty() {
4154 return Some(
4155 "titles are drawn into the picture, so it is decoded and encoded again rather \
4156 than copied byte for byte"
4157 .to_string(),
4158 );
4159 }
4160 if picture_faded(project) {
4161 return Some(
4162 "a picture fade is pixel math, so it is decoded and encoded again rather than \
4163 copied byte for byte"
4164 .to_string(),
4165 );
4166 }
4167 if !settings.format.is_mkv() {
4168 let anamorphic = project.sources().iter().any(|source| {
4169 Demuxer::open(&source.path)
4170 .ok()
4171 .is_some_and(|(source_meta, _)| !source_meta.pixel_aspect.is_square())
4172 });
4173 if anamorphic {
4174 return Some(
4175 "a copy would lose the pixel aspect — this format cannot state it beside the \
4176 coded picture, so the export re-encodes it into the square pixels it is drawn at"
4177 .to_string(),
4178 );
4179 }
4180 }
4181 let codec = match settings.format {
4182 Format::Hevc => Codec::Hevc,
4183 Format::Av1 => Codec::Av1,
4184 _ => {
4185 return Some(format!(
4186 "{} cannot carry a source's own coded picture byte for byte — pick an HEVC or AV1 Matroska to copy it exactly",
4187 settings.format.name()
4188 ));
4189 }
4190 };
4191 // The turn-baking corner-cut (a copied packet is the source's own coded
4192 // picture; this export bakes a display-matrix turn into the pixels) and
4193 // the rest of the reasons a copy says something other than what the
4194 // timeline says are [`CopyPlan::of`]'s own gates, so the container and
4195 // edit sentences below are checked the same way rather than duplicated
4196 // with different words.
4197 let carries = project.sources().iter().all(|source| {
4198 crate::demux::is_matroska(&source.path)
4199 && Demuxer::open(&source.path)
4200 .ok()
4201 .is_some_and(|(source_meta, _)| source_meta.codec == codec)
4202 });
4203 Some(match carries {
4204 false => format!(
4205 "{} cannot carry the source's own codec byte for byte",
4206 settings.format.name()
4207 ),
4208 true => "the edit does not let this file copy the source exactly — a cut off a sync \
4209 point, a grade, a speed, a transform or a canvas the source is not forces a \
4210 re-encode"
4211 .to_string(),
4212 })
4213}
4214
4215impl CopyPlan {
4216 /// The plan for this timeline, or `None` where anything at all makes a copy
4217 /// say something other than what the timeline says -- in which case the
4218 /// caller encodes, which is what it always did.
4219 fn of(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<Self> {
4220 // Burned-in captions and titles are drawn into pixels, which a copy
4221 // never has.
4222 if settings.burn_subtitles.is_some()
4223 || !project.titles().is_empty()
4224 || picture_faded(project)
4225 {
4226 return None;
4227 }
4228 // An explicit picture depth is a request for samples the source may not
4229 // have (8 bits from a 10-bit HEVC, say), which a copy would silently
4230 // keep: the picture is re-encoded at the depth asked for.
4231 if settings.video_bit_depth.is_some() {
4232 return None;
4233 }
4234 // An HDR transfer is a statement the encoder writes into its own stream
4235 // (VUI, SEIs); a copy carries the source's.
4236 if settings.hdr.transfer != HdrTransfer::Sdr {
4237 return None;
4238 }
4239 let (codec_id, codec): (&'static [u8], Codec) = match settings.format {
4240 Format::Hevc => (b"V_MPEGH/ISO/HEVC", Codec::Hevc),
4241 Format::Av1 => (b"V_AV1", Codec::Av1),
4242 _ => return None,
4243 };
4244 let entries = project.sources();
4245 let mut sources: Vec<Option<MkvDemuxer>> = (0..entries.len()).map(|_| None).collect();
4246 // The DRAWN pair each source is displayed at, kept beside its demuxer:
4247 // the fit gate below asks what a clip's policy does with this source's
4248 // picture on this canvas, and the picture the encoder places is the
4249 // drawn one ([`VideoMeta::width`]/`height`] -- the coded one with the
4250 // file's turn and its pixel aspect already applied), not the pair the
4251 // samples are stored at. A non-square source at its own displayed size
4252 // is therefore the identity again, which is what a copy of one is: the
4253 // aspect travels beside the track in the `Display*` elements rather
4254 // than being resampled into it.
4255 let mut drawn: Vec<Option<(u32, u32)>> = (0..entries.len()).map(|_| None).collect();
4256 let mut declared: Option<(Vec<u8>, Tags, crate::demux::PixelAspect)> = None;
4257 let mut regions: Vec<CopyRegion> = Vec::new();
4258 let r_start = settings.range.map_or(0, |(s, _)| s);
4259 for span in export_spans(project, settings.range) {
4260 let out_start = span.start - r_start;
4261 // A gap is black frames, which only an encoder makes.
4262 let (source, in_frame) = span.from?;
4263 if !span.speed.is_normal() || span.ramp.is_some() || span.reverse {
4264 return None;
4265 }
4266 // A layered picture is composed from more than one clip; no packet
4267 // of one of them is the picture.
4268 if layered_at(project, span.start) {
4269 return None;
4270 }
4271 // A copied packet is the source's own picture, never a blend: a
4272 // live dissolve on this span's tail forces the whole video track
4273 // through the encoder, exactly as a grade or a speed does below.
4274 //
4275 // corner-cut: the whole file falls back rather than only the
4276 // clips either side of the dissolve -- [`CopyPlan`] is already
4277 // all-or-nothing per export ([`CopyPlan`]'s own doc comment
4278 // states why), so one dissolve on a two-hour film re-encodes all
4279 // of it. Upgrade path: splice a re-encoded region between two
4280 // copied ones, which needs the sample-table writer that doc
4281 // comment already names as the cost of a finer copy.
4282 if dissolve_window(project, &span).is_some() {
4283 return None;
4284 }
4285 // The grade playback shows, which a copied packet never went
4286 // through. `None` and the identity are the same untouched picture.
4287 if project
4288 .composite_color_at(span.start)
4289 .is_some_and(|params| !params.is_identity())
4290 {
4291 return None;
4292 }
4293 // A moved, scaled, rotated or cropped clip is a different picture
4294 // than the source's own packets, exactly as a grade is.
4295 if project
4296 .composite_transform_at(span.start)
4297 .is_some_and(|params| !params.is_identity())
4298 {
4299 return None;
4300 }
4301 let path = &entries.get(source)?.path;
4302 if sources.get(source)?.is_none() {
4303 if !crate::demux::is_matroska(path) {
4304 return None;
4305 }
4306 let (source_meta, demuxer) = Demuxer::open(path).ok()?;
4307 let Demuxer::Mkv(demuxer) = demuxer else {
4308 return None;
4309 };
4310 // The stream this file would carry, at the size and the rate the
4311 // timeline is in: anything else is a picture that has to be
4312 // coded again to become this file's.
4313 //
4314 // A source whose display matrix asks for a turn is one of
4315 // those: a copied packet is the source's own coded picture, and
4316 // this export bakes the turn into the pixels -- so a copy would
4317 // ship the file sideways. Re-encoding is the only honest
4318 // answer here.
4319 //
4320 // The size the copy declares is the source's *coded* pair, so
4321 // that is what the comparison asks: coded to coded. A display
4322 // comparison would refuse every anamorphic source that happens
4323 // to sit at the project's displayed shape and then write a
4324 // track that lies about its own samples -- and a square
4325 // source's coded pair is its display pair, so this asks nothing
4326 // new of the ordinary file.
4327 //
4328 // A source whose samples are not square is the *other* kind of
4329 // picture a copy cannot carry here: the blocks are its own
4330 // coded pixels and this engine's Matroska writer can now state
4331 // the aspect beside them -- but only this engine's
4332 // ([`MkvMuxer::create_copy`] writes the `Display*` elements),
4333 // and the copy's declared shape must stay the coded one. The
4334 // aspect travels with the track instead of being baked in,
4335 // which is ffmpeg's own copy behaviour, so an anamorphic
4336 // source is copyable *into Matroska* and nowhere else.
4337 if !source_meta.rotation.is_none()
4338 || source_meta.codec != codec
4339 || source_meta.coded_width != meta.coded_width
4340 || source_meta.coded_height != meta.coded_height
4341 || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()?
4342 != Rate::REAL_TIME
4343 || !demuxer.plain_blocks()
4344 {
4345 return None;
4346 }
4347 // Two sources that disagree about their pixel aspect are two
4348 // displayed pictures under one track; the copy declares one
4349 // aspect or none.
4350 let declares = (
4351 demuxer.codec_private().to_vec(),
4352 demuxer.colour_tags(),
4353 source_meta.pixel_aspect,
4354 );
4355 if declared.get_or_insert(declares.clone()) != &declares {
4356 return None;
4357 }
4358 sources[source] = Some(*demuxer);
4359 drawn[source] = Some((source_meta.width, source_meta.height));
4360 }
4361 let demuxer = sources.get_mut(source)?.as_mut()?;
4362 // **The canvas gate** -- the condition this path was missing, and
4363 // the one that decides whether a copy can state the project's size.
4364 //
4365 // A copied packet is the source's own coded picture; the file this
4366 // export writes has to be the size the *project* is, and those are
4367 // two different pairs held in two different fields:
4368 //
4369 // * `meta.coded_width`/`coded_height` is the pair a *copied* track
4370 // declares -- what the samples are stored at, and what the check
4371 // above compares every source against. Only a *source* ever moves
4372 // it.
4373 // * `meta.width`/`meta.height` is the canvas -- what a person chose
4374 // with [`crate::playback::PlaybackSession::set_resolution`],
4375 // which writes those two and leaves the coded pair exactly where
4376 // it was. The encode door sizes everything from it
4377 // ([`Composer`]), so this is the size the file must have.
4378 //
4379 // ...and the two meet in the *drawn* pair: what this span is
4380 // composed from is the source's picture as a decoder delivers it,
4381 // turn and pixel aspect already applied
4382 // ([`VideoMeta::width`]/`height`]), which is what the check below is
4383 // asked about.
4384 //
4385 // A canvas that differs from the source's drawn pair means every
4386 // span is a picture the export has to *place onto* that canvas, and
4387 // there is no resampler on this path at all -- so a copy would ship
4388 // the source's frame size under the project's name, with the seat
4389 // line reading "copy · …" all the way out. That is the defect: not
4390 // a wrong rate or a wrong codec but the wrong geometry, silently,
4391 // on the one door that is supposed to be exact.
4392 //
4393 // Asked as a *placement* rather than as two separate conditions --
4394 // is this clip's policy the identity for this source on this canvas
4395 // -- because that is the one thing a condition has to mean here:
4396 // [`fit_is_identity`] computes it from [`scale::fit_rect`] itself,
4397 // so it holds for `Fill` on a canvas the size of the picture the
4398 // source draws at (there is nothing to crop there) and refuses a
4399 // canvas of another size under *every* policy, and a
4400 // [`crate::scale::FitPolicy`] added later is judged by what it
4401 // places rather than by being absent from a list here.
4402 if !fit_is_identity(
4403 drawn.get(source).copied().flatten()?,
4404 (meta.width, meta.height),
4405 project.composite_fit_at(span.start),
4406 ) {
4407 return None;
4408 }
4409 // The window this span reads, in the blocks the whole engine counts
4410 // a source's frames in. It has to *be* whole groups of pictures: a
4411 // copy that began between two sync points would hand a decoder
4412 // pictures whose references are not in the file, and one that ended
4413 // between them would drop a reference the pictures before it need.
4414 let (start, end) = (in_frame as usize, in_frame as usize + span.len as usize);
4415 if end > demuxer.block_count()
4416 || !demuxer.is_sync(start)
4417 || (end < demuxer.block_count() && !demuxer.is_sync(end))
4418 {
4419 return None;
4420 }
4421 // Two spans that continue each other in one file are one region:
4422 // nothing was cut between them, so the leading pictures across that
4423 // boundary still have every reference they need.
4424 match regions.last_mut() {
4425 Some(last)
4426 if last.source == source
4427 && last.blocks.end == start
4428 && last.start + (last.blocks.end - last.blocks.start) as u32
4429 == out_start =>
4430 {
4431 last.blocks.end = end;
4432 }
4433 _ => regions.push(CopyRegion {
4434 source,
4435 blocks: start..end,
4436 start: out_start,
4437 }),
4438 }
4439 }
4440 let (private, colour, pixel_aspect) = declared?;
4441 Some(Self {
4442 sources,
4443 regions,
4444 codec_id,
4445 private,
4446 language: video_language(project),
4447 colour,
4448 // The track the copy declares is the source's coded shape -- the
4449 // samples under it are the source's own -- with the aspect beside
4450 // it as the display metadata ([`CopyParams::pixel_aspect`]).
4451 width: meta.coded_width,
4452 height: meta.coded_height,
4453 pixel_aspect,
4454 })
4455 }
4456
4457 /// The file itself: one Matroska muxer, every region's blocks through it in
4458 /// the order and at the timing their source states.
4459 #[allow(
4460 clippy::too_many_arguments,
4461 reason = "the copy's one run: its inputs are passed positionally at its one call site, and a struct would only rename them"
4462 )]
4463 fn run(
4464 mut self,
4465 out: &Path,
4466 meta: &VideoMeta,
4467 shared: &Shared,
4468 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
4469 subs: Vec<SubParams>,
4470 total: u32,
4471 chapters: &[(u64, String)],
4472 ) -> crate::Result<()> {
4473 let mut muxer = MkvMuxer::create_copy(
4474 out,
4475 &CopyParams {
4476 width: self.width,
4477 height: self.height,
4478 frame_rate: meta.frame_rate,
4479 codec_id: self.codec_id,
4480 codec_private: &self.private,
4481 colour: self.colour,
4482 pixel_aspect: self.pixel_aspect,
4483 language: self.language.clone(),
4484 },
4485 audio,
4486 subs,
4487 )?;
4488 muxer.set_chapters(chapters)?;
4489 // Nanoseconds a timeline frame lasts, which is what a region's own
4490 // position on the timeline is measured in.
4491 let frame_ns = 1e9 / meta.frame_rate;
4492 let mut done = 0u32;
4493 for region in &self.regions {
4494 let demuxer = self.sources[region.source]
4495 .as_mut()
4496 .ok_or("a copied region names a source that was never opened")?;
4497 let base = (f64::from(region.start) * frame_ns).round() as i64;
4498 // When the region's first picture is shown on its source's clock;
4499 // everything after it is written that far along from `base`.
4500 let mut origin: Option<i64> = None;
4501 for index in region.blocks.clone() {
4502 cancelled(shared)?;
4503 let Some(block) = demuxer.coded_block(index)? else {
4504 break;
4505 };
4506 let origin = *origin.get_or_insert(block.ts_ns);
4507 // The leading pictures of the group this region opens on: shown
4508 // before it, coded against the group before it, and that group
4509 // is not in this file. Dropped rather than written as pictures
4510 // no decoder can put back together.
4511 if block.ts_ns < origin {
4512 continue;
4513 }
4514 muxer.write_block(block.bytes, block.key, base + block.ts_ns - origin)?;
4515 done += 1;
4516 shared
4517 .progress
4518 .fetch_max(picture_progress(done, total), Ordering::Relaxed);
4519 }
4520 }
4521 // Everything up to here is still cancellable, exactly as the encoded
4522 // path is up to its own `finish`.
4523 cancelled(shared)?;
4524 muxer.finish()?;
4525 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
4526 Ok(())
4527 }
4528}
4529
4530/// Whether `policy` places the picture `source` is DRAWN at onto this `canvas`
4531/// without touching a sample: the whole picture, at the whole canvas, 1:1.
4532///
4533/// The 1:1 is the half the rects cannot state: a source scaled onto a canvas
4534/// of another aspect is placed whole and cropped nowhere, which is a resize
4535/// and not an identity -- so the pairs themselves are compared first.
4536///
4537/// The pair asked about is the **drawn** one ([`VideoMeta::width`]/`height`]),
4538/// never the coded one: what the fit is composed against is what a decoder
4539/// hands the canvas after the file's turn and its pixel aspect have been
4540/// applied, so a 1440x1080 file with a 4:3 sample aspect is a 1920x1080
4541/// picture, and a project at 1920x1080 is copying it exactly. The coded pair
4542/// has its own question -- what a copied track *declares* -- and the coded-to-
4543/// coded check in [`CopyPlan::of`] already asks that one; asking it twice, in
4544/// the geometry's stead, refuses a copy main performs byte for byte.
4545///
4546/// Asked from [`scale::fit_rect`] -- the one function that *is* a fit policy's
4547/// meaning -- rather than from the policy itself, which is what makes this
4548/// canvas-aware twice over: `Fill` on a canvas the size of the source's own
4549/// samples is the identity (nothing is cropped, because there is nothing to
4550/// crop), while `Fit` on a canvas of another aspect is not (it bars or crops).
4551/// A policy added to [`FitPolicy`] later is judged by what it places, not by
4552/// being absent from a list here.
4553fn fit_is_identity(
4554 source: (u32, u32),
4555 canvas: (u32, u32),
4556 policy: crate::scale::FitPolicy,
4557) -> bool {
4558 // The pairs themselves: a picture is the canvas only when it *is* the
4559 // canvas, and the rects below cannot say so -- a source scaled onto a
4560 // canvas of another aspect is still placed whole and still cropped
4561 // nowhere, which is a resize, and a resize is exactly what a copied packet
4562 // cannot be.
4563 if source != canvas {
4564 return false;
4565 }
4566 let (placed, cropped) = crate::scale::fit_rect(source.0, source.1, canvas.0, canvas.1, policy);
4567 placed
4568 == crate::scale::Rect {
4569 x: 0,
4570 y: 0,
4571 w: canvas.0,
4572 h: canvas.1,
4573 }
4574 && cropped
4575 == crate::scale::Rect {
4576 x: 0,
4577 y: 0,
4578 w: source.0,
4579 h: source.1,
4580 }
4581}
4582
4583/// The same lane, *decoded*: what a packet copy cannot carry comes out here as
4584/// AAC written by this project's own encoder.
4585///
4586/// The samples are the very ones [`run_audio`] would put in a WAV -- the same
4587/// opener with the same equalizers, the same rates and the same resize onto the
4588/// timeline's own length -- so an mp4 and a WAV of one timeline are one mix,
4589/// not two that could disagree.
4590///
4591/// AAC-LC's encoder delay is one 1024-frame block, which is exactly the priming
4592/// a reader drops when the file carries no edit list (`audio::DEFAULT_PRIMING`,
4593/// and [`crate::mux::Mp4Muxer`] writes none): the first packet is that delay, so
4594/// the sound starts at timeline frame 0 as a copied track's does.
4595///
4596/// corner-cut: the mix sits in memory as f32 before it is encoded (~46 MB a
4597/// minute of 48 kHz stereo), for [`run_audio`]'s reason -- sizing the track
4598/// against the timeline, publishing the mix third of the bar as it goes and
4599/// answering a cancel before the encode are whole-mix concerns here. The
4600/// upgrade path is a chunked push: `ec_aac`'s encoder itself streams.
4601#[allow(clippy::too_many_arguments)]
4602fn encode_audio(
4603 project: &Project,
4604 meta: &VideoMeta,
4605 kbps: u32,
4606 mkv: bool,
4607 webm: bool,
4608 shared: &Shared,
4609 sample_rate: Option<u32>,
4610 range: Option<(u32, u32)>,
4611) -> crate::Result<Option<ExportAudio>> {
4612 let sources = project.audio_sources();
4613 let range_start = range.map_or(0, |(s, _)| s);
4614 let pre = warm_up(project, range_start, meta.frame_rate);
4615 let offset = range_start - pre;
4616 let segs = project.audio_segments_from(offset, meta.frame_rate);
4617 let eqs = project.audio_eqs_from(offset, meta.frame_rate);
4618 let speeds = project.audio_speeds_from(offset, meta.frame_rate);
4619 let fades = project.audio_fades_from(offset, meta.frame_rate);
4620 // Coarse stage timers, in the same voice as `export video: copy` below: an
4621 // export of a feature film spends minutes in here before a byte of picture
4622 // is written, and which minutes went where is the first question asked of a
4623 // slow export. Three lines an export, so they stay on.
4624 let mixed = std::time::Instant::now();
4625 let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade(
4626 &sources,
4627 &segs,
4628 &eqs,
4629 &speeds,
4630 &fades,
4631 meta.frame_rate,
4632 &project.audio_gains(),
4633 &project.audio_ducks(),
4634 &project.audio_voices(),
4635 project.limiter(),
4636 sample_rate,
4637 )?
4638 else {
4639 return Ok(None); // no audio to write, exactly as a copy of nothing is
4640 };
4641 let freq_index = ec_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| {
4642 format!(
4643 "{} Hz is not an AAC sample rate: export WAV, FLAC, MP3 or OGG, which write it as \
4644 it is",
4645 audio.sample_rate
4646 )
4647 })?;
4648 let channels = usize::from(audio.channels.max(1));
4649 // The timeline's length, not the mix's: a segment resolves its window to
4650 // whole samples on its own, so the sum can miss by a sample or two and a
4651 // source that ran out early would leave the track short under a picture
4652 // that is not. One resize settles both, as [`run_audio`]'s does.
4653 let out_frames = range.map_or(project.media_frames(), |(s, e)| {
4654 e.min(project.media_frames()).saturating_sub(s)
4655 });
4656 let total = (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round()
4657 as usize
4658 * channels;
4659 let skip = warm_up_samples(range_start, pre, meta.frame_rate, audio.sample_rate, channels);
4660 let mut samples: Vec<f32> = Vec::with_capacity(total + skip);
4661 for chunk in chunks {
4662 // The only place a cancelled export can be answered before the whole
4663 // timeline has been mixed. This pass runs on a thread of its own now
4664 // ([`run`]), so without this a cancel left it mixing a feature film
4665 // for minutes behind a job nobody is waiting for any more, writing
4666 // into a `Shared` whose outcome was already settled.
4667 cancelled(shared)?;
4668 samples.extend(chunk.samples);
4669 // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of
4670 // the three stages and the only one that can be counted as it goes.
4671 //
4672 // `fetch_max` and not `store`, for the reason [`Shared::progress`]
4673 // states: this runs on the audio thread while the picture publishes
4674 // numbers above [`AUDIO_BAND`] from the other, and a `store` of this
4675 // small one pulled the bar backwards 5,458 times over one film export.
4676 shared.progress.fetch_max(
4677 (samples.len().saturating_sub(skip).min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32,
4678 Ordering::Relaxed,
4679 );
4680 // The range is in: the mix past its end would only be cut off below.
4681 if samples.len() >= skip + total {
4682 break;
4683 }
4684 }
4685 samples.drain(..skip.min(samples.len()));
4686 samples.resize(total, 0.0);
4687 if let Some(target) = shared.loudness {
4688 level_to_target(&mut samples, audio.sample_rate, audio.channels.max(1), target);
4689 }
4690 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!(
4691 "export audio: mixed {:.1} s of sound in {:.1} s",
4692 total as f64 / f64::from(audio.sample_rate.max(1)) / channels as f64,
4693 mixed.elapsed().as_secs_f64()
4694 ); }
4695
4696 // Opus where the container carries it and the mix is inside the envelope
4697 // this encoder is *measured* correct in ([`encode_opus`]): a Matroska file,
4698 // 48 kHz, mono or stereo. An Opus source edited into an mkv export
4699 // therefore leaves as Opus instead of being turned into AAC on the way
4700 // out, which is the one generation of loss an all-Opus timeline used to
4701 // pay for being cut.
4702 //
4703 // Everything else falls through to the AAC below and is unchanged by this:
4704 // every mp4, a 44.1 kHz timeline. The rate is the mix's own -- there is no
4705 // resampler on this path, and inventing one to reach 48 kHz would resample
4706 // a whole timeline to satisfy a codec, which is a bigger change to the
4707 // sound than the codec is.
4708 // ...and again before either encoder is entered: both of them run to the
4709 // end of the mix without a checkpoint of their own, so this is the last
4710 // moment a cancel costs seconds rather than the whole encode.
4711 cancelled(shared)?;
4712 if mkv
4713 && audio.sample_rate == OPUS_RATE
4714 && (1..=2).contains(&channels)
4715 && let Some((packets, pre_skip)) = encode_opus(&samples, kbps, channels)?
4716 {
4717 return Ok(Some(ExportAudio {
4718 params: crate::AacTrackParams {
4719 freq_index,
4720 chan_conf: channels as u8,
4721 sample_rate: OPUS_RATE,
4722 },
4723 packets,
4724 copied: false,
4725 opus_pre_skip: Some(pre_skip),
4726 language: None,
4727 pcm_frames: Some(samples.len() as u64 / channels as u64),
4728 }));
4729 }
4730
4731 // A WebM file carries Opus or nothing: a track the gate handed back is named
4732 // here rather than written as AAC into a file no WebM reader will open.
4733 if webm {
4734 return Err(
4735 "the sound could not be coded as Opus, the only sound a WebM file \
4736 carries: export a Matroska instead"
4737 .into(),
4738 );
4739 }
4740 // The caller's rate, never the encoder's own 128 default -- see
4741 // [`DEFAULT_AUDIO_KBPS`] for why the untouched figure is 256.
4742 let mut encoder = ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig {
4743 bitrate_bps: kbps * 1_000,
4744 ..Default::default()
4745 });
4746 encoder.push_pcm(&samples, audio.channels.max(1), audio.sample_rate)?;
4747 encoder.finish();
4748 let mut packets = Vec::new();
4749 // `next_packet` after `finish` yields packets until `Eof` and nothing else,
4750 // so the loop ends on the only error it can see.
4751 while let Ok(packet) = encoder.next_packet() {
4752 cancelled(shared)?;
4753 packets.push(crate::AacPacket {
4754 bytes: packet.data,
4755 samples: packet.duration,
4756 });
4757 }
4758 Ok(Some(ExportAudio {
4759 params: crate::AacTrackParams {
4760 freq_index,
4761 // 1 and 2 are the ISO channel configurations for mono and stereo,
4762 // and what the opener hands the timeline is one of those whatever
4763 // the source carried ([`crate::audio::downmix`]).
4764 chan_conf: audio.channels.max(1) as u8,
4765 sample_rate: audio.sample_rate,
4766 },
4767 packets,
4768 copied: false,
4769 opus_pre_skip: None,
4770 language: None,
4771 pcm_frames: Some(samples.len() as u64 / channels as u64),
4772 }))
4773}
4774
4775/// The one rate Opus codes at. The container may state another one in its
4776/// `OpusHead` and every decoder still runs at 48 kHz (RFC 7845 §5.1), so a
4777/// timeline at any other rate is not "encoded at its own rate" here -- it is
4778/// resampled or it is not Opus, and [`encode_audio`] picks the second.
4779pub(crate) const OPUS_RATE: u32 = 48_000;
4780
4781/// 20 ms at [`OPUS_RATE`], the frame every Opus muxer in the wild writes:
4782/// long enough that the per-packet overhead is nothing, short enough that a
4783/// Matroska block timestamp in whole milliseconds is exact.
4784const OPUS_FRAME: usize = 960;
4785
4786/// The most this project asks of the Opus encoder, in kbps, and why it is a cap
4787/// rather than the four rates the Sound row offers.
4788///
4789/// History, because the number moved once already and the reason it could is
4790/// part of the record. Under `opus-rs 0.1.26` the ceiling was 128: that encoder
4791/// fell off a cliff at a rate that depended on the *content*, and above it a
4792/// conformant decoder got noise back. Measured on three one-second spans of a
4793/// real 5.1 Opus film, encoded there and decoded with `ruopus` -- which was not
4794/// the suspect, since it decoded ffmpeg's own libopus at 256 kbps to
4795/// correlation 1.00000 on the same material:
4796///
4797/// ```text
4798/// kbps 120 128 136 144 152 160
4799/// span A 0.945 0.937 0.452 0.206 0.223 0.163
4800/// span B 0.986 0.989 0.697 0.153 0.114 0.149
4801/// span C 0.999 0.994 0.951 0.335 0.266 0.326
4802/// libopus 0.997 0.998 -- -- -- 0.996 (same spans, control)
4803/// ```
4804///
4805/// So: usable to 128, ruined by 136 on real film sound -- and mono worse, at
4806/// every rate, which is why a mono mix kept the AAC path entirely. `ec-opus`
4807/// has no such cliff: its own suite holds every rate of the format's table to
4808/// the reference decoders, mono, stereo and 5.1 alike, and this project
4809/// re-measures the high band and the mono path where the old encoder failed
4810/// (`the_opus_encoder_is_pinned_to_the_band_it_was_measured_in`).
4811///
4812/// It is still not *trusted*: every track is decoded again and measured before
4813/// it is written ([`opus_fidelity`]), because a rate nobody measured on *your*
4814/// sound is not something a constant can be safe against on its own.
4815/// The ceiling is the Sound row's ([`AUDIO_KBPS`]), not the format's 510 kbps:
4816/// a rate nothing in the product can ask for is a rate nothing here measures.
4817/// 320 covers the row honestly, including the 256 default
4818/// ([`DEFAULT_AUDIO_KBPS`]) the old cap silently halved on a Matroska export.
4819pub(crate) const OPUS_MAX_KBPS: u32 = 320;
4820
4821/// How well a track has to survive its own round trip to be written as Opus:
4822/// the correlation between the mix and the decode of what was encoded from it.
4823/// A good encoder scores 0.98-0.999 on this material (libopus, measured above);
4824/// the failure mode is not subtle at all, scoring 0.1-0.7. 0.95 sits in the gap
4825/// with room on both sides, and what fails it is written as AAC -- the export's
4826/// own encoder line then says AAC, so the fallback is visible rather than
4827/// silent.
4828const OPUS_MIN_FIDELITY: f64 = 0.95;
4829
4830/// The encoder's lookahead at [`OPUS_RATE`] in the mode this envelope always
4831/// selects (CELT-only: 2.5 ms). The pre-skip a file states is this *plus* the
4832/// warm-up frame [`encode_opus`] throws away. Measured by
4833/// cross-correlating the decode against the source, not taken from the crate --
4834/// it exposes no lookahead getter -- and asserted at both ends of the rate band
4835/// in `tests/opus_export.rs`, which is what catches a version that changes it.
4836const OPUS_PRE_SKIP: u16 = 120;
4837
4838/// The mix as Opus packets, one per [`OPUS_FRAME`], plus the pre-skip that has
4839/// to be declared in front of them. Mono or stereo, at [`OPUS_RATE`] -- the
4840/// caller checks all of it, because outside that envelope this encoder is not
4841/// one this project is willing to write files with ([`OPUS_MAX_KBPS`]).
4842///
4843/// The tail frame is padded with silence rather than dropped: Opus codes whole
4844/// frames and a track a few milliseconds short under a picture that is not is
4845/// the drift every other path here is written to avoid. The pre-skip trims the
4846/// front; the container's duration trims the back.
4847fn encode_opus(
4848 samples: &[f32],
4849 kbps: u32,
4850 channels: usize,
4851) -> crate::Result<Option<(Vec<crate::AacPacket>, u16)>> {
4852 let mut encoder = ec_opus::Encoder::new(OPUS_RATE, channels, ec_opus::Application::Audio)
4853 .map_err(|e| format!("the Opus encoder refused 48 kHz {channels}-channel sound: {e}"))?;
4854 // CBR, the crate's default: every packet exactly the rate's size. The old
4855 // seat ran opus-rs's VBR; the gate below measures either, and a fixed
4856 // packet size is the friendlier neighbour to a muxer's block budget.
4857 encoder.set_bitrate(kbps.min(OPUS_MAX_KBPS) * 1_000);
4858 // No complexity knob on this crate: the reference's default (9) is baked
4859 // into its rate arithmetic, one percent of equiv rate away from the 10 the
4860 // old encoder was asked for.
4861 let mut packets = Vec::new();
4862 let mut frame = vec![0f32; OPUS_FRAME * channels];
4863 // 1275 bytes is the most one Opus frame may weigh (RFC 6716 §3.2); this is
4864 // that with room for the TOC and a padded frame, so `encode_float` never
4865 // has to refuse for want of a buffer.
4866 let mut out = vec![0u8; 1500];
4867 // The head, coded **twice**. An encoder's very first frame has no history
4868 // behind it and comes out ramped and out of phase -- measured on a 440 Hz
4869 // fixture, the first 20 ms of the export correlated 0.09 with the source
4870 // where every later window correlated 0.9997 -- and 20 ms of wrong sound at
4871 // the head of a file is the kind of thing nobody hears in a test and
4872 // everybody hears in the first frame of a cut. So the first frame is fed in
4873 // once to warm the encoder, and thrown away again by the pre-skip: exactly
4874 // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet.
4875 let coded = std::time::Instant::now();
4876 let warm = samples.len().min(OPUS_FRAME * channels);
4877 // ...and one silent frame after the sound, for the same delay seen from the
4878 // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so
4879 // without a frame to push them out the last 2.5 ms of the timeline stay
4880 // inside it and the track ends short under a picture that does not.
4881 let blocks = std::iter::once(&samples[..warm])
4882 .chain(samples.chunks(OPUS_FRAME * channels))
4883 .chain(std::iter::once(&samples[..0]));
4884 for block in blocks {
4885 frame[..block.len()].copy_from_slice(block);
4886 frame[block.len()..].fill(0.0);
4887 let len = encoder
4888 .encode_float(&frame, OPUS_FRAME, &mut out)
4889 .map_err(|e| format!("Opus encode failed: {e}"))?;
4890 packets.push(crate::AacPacket {
4891 bytes: out[..len].to_vec(),
4892 samples: OPUS_FRAME as u32,
4893 });
4894 }
4895 // ...and now the part that is not optimism: what was just written is
4896 // decoded again and measured against what went in, and a track that does
4897 // not come back is not written at all ([`OPUS_MIN_FIDELITY`]). The caller
4898 // falls through to AAC, which is exactly where it stood before this seat
4899 // existed -- a worse codec is a fair trade for a track that is the sound.
4900 //
4901 // corner-cut: this costs one Opus decode of the whole track (a minute of
4902 // sound in a few hundred milliseconds, against a video encode that is
4903 // minutes). Upgrade path is deleting it, the day this encoder can be
4904 // trusted at the rate it is asked for.
4905 let encoded = coded.elapsed().as_secs_f64();
4906 let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16;
4907 let measured = std::time::Instant::now();
4908 let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip), channels);
4909 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!(
4910 "export audio: Opus encode {encoded:.1} s, fidelity {fidelity:.4} measured in {:.1} s",
4911 measured.elapsed().as_secs_f64()
4912 ); }
4913 Ok((fidelity >= OPUS_MIN_FIDELITY).then_some((packets, pre_skip)))
4914}
4915
4916/// Packets one sampled window listens to: 5 s at [`OPUS_FRAME`].
4917const FIDELITY_WINDOW: usize = 250;
4918
4919/// How many of them a long track is judged on -- a minute of sound, wherever
4920/// the track's length puts them, and a constant cost rather than one that grows
4921/// with the film ([`opus_fidelity`]).
4922const FIDELITY_WINDOWS: usize = 12;
4923
4924/// Packets decoded into a window and thrown away before it is measured. CELT
4925/// predicts across frames, so a decoder started cold mid-stream is behind its
4926/// own history for a few frames; 100 ms is far more than it needs and is not
4927/// worth counting.
4928const FIDELITY_WARMUP: usize = 5;
4929
4930/// How much sound a window must carry before its correlation means anything:
4931/// mean square per sample. A window of digital silence -- the head of a film,
4932/// the gap between a feature and its credits -- correlates with nothing, and
4933/// failing a track for it would send perfectly good sound to AAC.
4934const FIDELITY_FLOOR: f64 = 1e-9;
4935
4936/// The correlation between `samples` and the decode of `packets` with the first
4937/// `pre_skip` frames dropped: 1.0 is the same waveform, and this codec's failure
4938/// mode lands near 0.1. Streamed packet by packet -- the decode is never held,
4939/// only three running sums -- because the mix behind it is already the biggest
4940/// thing in an export ([`encode_audio`]'s corner-cut).
4941///
4942/// A packet the decoder refuses is 0.0 and no argument: a track this project
4943/// cannot read is exactly what this is here to catch.
4944///
4945/// **Sampled above a minute of sound, and the median window is the answer.**
4946/// This decode was the whole cost of exporting a feature film under the
4947/// previous decoder: `ruopus` ran its inverse MDCT at 0.2x real time (measured,
4948/// 24.2 s for 121.5 s of stereo; `ec-opus`, the decoder here now, is far
4949/// quicker, and the sampling survives it because it costs almost nothing to
4950/// keep),
4951/// so judging every packet of a two-and-a-half-hour film costs half an hour
4952/// before a byte of picture is written -- which is what it did, and what made a
4953/// copy export that has no encoding to do at all sit at zero for twenty minutes.
4954/// [`FIDELITY_WINDOWS`] windows spread evenly across the track cost the same
4955/// minute of decode whatever the film's length, and what they are looking for
4956/// survives sampling: [`OPUS_MAX_KBPS`]'s cliff is a *rate* the encoder falls
4957/// off everywhere that rate is used, not a defect of one bar of music.
4958///
4959/// The **median** and not the worst, and that is measured rather than cautious.
4960/// Forty five-second windows of a real 5.1 film's mix, encoded here at 128 kbps
4961/// and decoded back, in order:
4962///
4963/// ```text
4964/// 0.803 0.835 0.938 0.940 0.960 0.987 0.994 ... median 0.998 ... 0.999
4965/// ```
4966///
4967/// Five of the thirty-nine that carried sound sit under [`OPUS_MIN_FIDELITY`] on
4968/// a track that is *good* -- which is the same thing the table in
4969/// [`OPUS_MAX_KBPS`] shows, where a span scoring 0.937 at 128 kbps is inside the
4970/// usable band. A worst-window rule at 0.95 therefore refuses films this encoder
4971/// handles perfectly well, while the failure it exists for is the opposite
4972/// shape: at 136 kbps the same three measured spans read 0.452, 0.697, 0.951,
4973/// and at 256 kbps the whole track correlates 0.06. Half a track cannot be
4974/// ruined without the middle of the list moving, so the median separates the two
4975/// by a margin no single window can (0.998 against under 0.7) -- and a track
4976/// under a minute is one window, where median and whole-track correlation are
4977/// the same number the gate always used.
4978fn opus_fidelity(
4979 packets: &[crate::AacPacket],
4980 samples: &[f32],
4981 pre_skip: usize,
4982 channels: usize,
4983) -> f64 {
4984 // Short enough to hear all of: every fixture, every unit test, and any
4985 // track under a minute. There is nothing to sample from.
4986 let all = FIDELITY_WINDOW * FIDELITY_WINDOWS;
4987 if packets.len() <= all {
4988 return window_fidelity(packets, samples, pre_skip, channels, 0, 0, packets.len())
4989 .unwrap_or(1.0);
4990 }
4991 // Evenly spread, first window at the head: the head is where an encoder's
4992 // own warm-up would show, and the last starts a window short of the end so
4993 // no window runs past the packets.
4994 let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);
4995 let mut scores: Vec<f64> = Vec::with_capacity(FIDELITY_WINDOWS);
4996 for w in 0..FIDELITY_WINDOWS {
4997 let at = w * step;
4998 let from = at.saturating_sub(FIDELITY_WARMUP);
4999 let Some(fidelity) = window_fidelity(
5000 packets,
5001 samples,
5002 pre_skip,
5003 channels,
5004 from,
5005 at,
5006 at + FIDELITY_WINDOW,
5007 ) else {
5008 continue; // silence: nothing to correlate, and not a failure
5009 };
5010 scores.push(fidelity);
5011 }
5012 // Every window silent is a silent track, which this codec writes as silence.
5013 if scores.is_empty() {
5014 return 1.0;
5015 }
5016 scores.sort_by(f64::total_cmp);
5017 scores[scores.len() / 2]
5018}
5019
5020/// [`opus_fidelity`] over `packets[measure..to]`, with `packets[from..measure]`
5021/// -- the warm-up -- decoded for its state and thrown away. `None` where the
5022/// source window carries no sound worth correlating ([`FIDELITY_FLOOR`]).
5023fn window_fidelity(
5024 packets: &[crate::AacPacket],
5025 samples: &[f32],
5026 pre_skip: usize,
5027 channels: usize,
5028 from: usize,
5029 measure: usize,
5030 to: usize,
5031) -> Option<f64> {
5032 let (streams, coupled, mapping) = match channels {
5033 1 => (1, 0, vec![0u8]),
5034 // One coupled stream: the stereo shape every fixture and every mix
5035 // here decodes back through.
5036 _ => (1, 1, vec![0, 1]),
5037 };
5038 let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, streams, coupled, &mapping);
5039 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
5040 // Where in the mix this window's first decoded sample lands: every packet
5041 // is [`OPUS_FRAME`] long, and the pre-skip is what the front of the stream
5042 // owes before the first of them is the timeline's frame 0.
5043 let mut at = (from * OPUS_FRAME * channels).saturating_sub(pre_skip * channels);
5044 let mut drop = (pre_skip * channels).saturating_sub(from * OPUS_FRAME * channels);
5045 let mut counted = 0usize;
5046 for (index, packet) in packets.iter().enumerate().take(to).skip(from) {
5047 let Ok(pcm) = decoder.decode_packet(&packet.bytes) else {
5048 return Some(0.0);
5049 };
5050 let pcm = &pcm[drop.min(pcm.len())..];
5051 drop = drop.saturating_sub(packet.samples as usize * channels);
5052 // The warm-up is decoded for its state and not for its numbers.
5053 if index < measure {
5054 at += pcm.len();
5055 continue;
5056 }
5057 for (want, got) in samples[at.min(samples.len())..].iter().zip(pcm) {
5058 let (x, y) = (f64::from(*want), f64::from(*got));
5059 num += x * y;
5060 da += x * x;
5061 db += y * y;
5062 at += 1;
5063 counted += 1;
5064 }
5065 }
5066 (da / counted.max(1) as f64 > FIDELITY_FLOOR).then(|| num / (da.sqrt() * db.sqrt()).max(1e-12))
5067}
5068
5069/// The audio pass, running beside the picture: what [`run`] holds while it
5070/// encodes and joins where the file it is writing needs the track.
5071type AudioJob = thread::JoinHandle<crate::Result<Option<ExportAudio>>>;
5072
5073/// The pass while [`run`] holds it, joined however that function leaves --
5074/// including through a `?`.
5075///
5076/// A [`JoinHandle`](thread::JoinHandle) that is merely dropped *detaches* its
5077/// thread, and the one error that matters here is the hardware encoder's
5078/// process dying ([`crate::hwproc`]): the whole export is then written again by
5079/// [`start`], which starts an audio pass of its own. The abandoned one would go
5080/// on mixing and encoding the same sound beside it -- two passes of a feature
5081/// film's audio at once, on the machine that has just lost its GPU. Joined
5082/// instead, so an export has one audio pass at a time and none outlives it.
5083struct AudioPass(Option<AudioJob>);
5084
5085impl AudioPass {
5086 /// Whether the pass has landed, so the picture loop may collect it without
5087 /// waiting.
5088 fn is_finished(&self) -> bool {
5089 self.0.as_ref().is_some_and(thread::JoinHandle::is_finished)
5090 }
5091
5092 /// Whether a pass is still to be collected -- which is what "the sound is
5093 /// still being worked out" means on the encoder line.
5094 fn running(&self) -> bool {
5095 self.0.is_some()
5096 }
5097
5098 /// The handle, for the one caller that is about to join it itself.
5099 fn take(&mut self) -> Option<AudioJob> {
5100 self.0.take()
5101 }
5102}
5103
5104impl Drop for AudioPass {
5105 fn drop(&mut self) {
5106 if let Some(job) = self.0.take() {
5107 let _ = job.join();
5108 }
5109 }
5110}
5111
5112/// The pass's answer, or the failure that is the export's failure. A panicked
5113/// audio thread reads as an error rather than as silence: an export that wrote
5114/// its picture and quietly no sound is the one outcome this must not have.
5115fn join_audio(job: AudioJob) -> crate::Result<Option<ExportAudio>> {
5116 job.join()
5117 .map_err(|_| crate::Error::from("the audio pass stopped without a picture or a reason"))?
5118}
5119
5120/// The encoder line a running export shows: the seat the picture is really
5121/// being written by, and what the sound is -- or that the sound is still being
5122/// worked out, which an overlapped audio pass is until it is collected.
5123fn publish_seats(
5124 shared: &Shared,
5125 seat: &str,
5126 project: &Project,
5127 settings: &ExportSettings,
5128 sound: Option<bool>,
5129 opus: bool,
5130 waiting: bool,
5131) {
5132 let audio = match waiting {
5133 // Still mixing on the other thread. The same half-line the copied-
5134 // picture path has always shown, and for the same reason: what is
5135 // published is never a codec that did not run.
5136 true => "working out the sound…",
5137 false => measured_audio_label(project, settings.format, sound, opus),
5138 };
5139 *shared.encoders.lock().unwrap() = Some(format!("{seat} · {audio}"));
5140}
5141
5142/// Hands a mix that finished mixing early to the mp4 it belongs in, the
5143/// moment both exist: `late` may land before the first coded picture has
5144/// opened `muxer` at all, so this is tried both right where the mix lands
5145/// and after every picture written afterwards, and does nothing once
5146/// `*fed` says an earlier try already succeeded. Declaring the track and
5147/// queuing its packets here is what lets [`crate::mux::Mp4Muxer`]'s own
5148/// hold interleave them under the pictures still to come, rather than the
5149/// track landing all at once after the picture is done.
5150fn feed_late_audio(
5151 muxer: &mut Option<Muxer>,
5152 late: &Option<ExportAudio>,
5153 fed: &mut bool,
5154) -> crate::Result<()> {
5155 if *fed {
5156 return Ok(());
5157 }
5158 let (Some(track), Some(Muxer::Mp4(mp4))) = (late.as_ref(), muxer.as_mut()) else {
5159 return Ok(());
5160 };
5161 mp4.add_audio_track(&params_of(track))?;
5162 for packet in &track.packets {
5163 mp4.write_audio_packet(&packet.bytes)?;
5164 }
5165 *fed = true;
5166 Ok(())
5167}
5168
5169/// The language the timeline's sound is in, for the export to tag its audio track with: the one
5170/// language every audio clip's stream states. `None` when the clips disagree, when one of them
5171/// states none (`und`), or when there are no audio clips, and the track stays `und`.
5172pub(crate) fn audio_language(project: &Project) -> Option<String> {
5173 let sources = project.sources();
5174 shared_language(
5175 project
5176 .audio_lanes()
5177 .into_iter()
5178 .flat_map(|lane| project.lane(lane).iter())
5179 .map(|clip| sources.get(clip.source).and_then(|src| stream_language(&src.path, src.audio_stream))),
5180 )
5181}
5182
5183/// The one language every stream in `langs` states, or `None` when there are none, when one
5184/// states none, or when they differ.
5185fn shared_language(langs: impl IntoIterator<Item = Option<String>>) -> Option<String> {
5186 let mut shared: Option<String> = None;
5187 for lang in langs {
5188 let lang = lang?;
5189 match &shared {
5190 None => shared = Some(lang),
5191 Some(s) if *s == lang => {}
5192 Some(_) => return None,
5193 }
5194 }
5195 shared
5196}
5197
5198/// The language audio stream `audio_stream` of `path` states in its header, with `und` (none
5199/// stated) as `None`. Read from the header alone.
5200fn stream_language(path: &Path, audio_stream: usize) -> Option<String> {
5201 crate::probe_media(path)
5202 .streams
5203 .into_iter()
5204 .find(|s| s.kind == crate::StreamKind::Audio && s.index == audio_stream)?
5205 .language
5206 .filter(|l| l != "und")
5207}
5208
5209/// The language the picture is tagged with, for the Matroska video track to state: the first
5210/// source's picture track, the one the export takes its picture from ([`source_colour_tags`]).
5211/// `None` where that track states none (`und`), or no source can be read.
5212fn video_language(project: &Project) -> Option<String> {
5213 let path = &project.sources().first()?.path;
5214 crate::probe_media(path)
5215 .streams
5216 .into_iter()
5217 .find(|s| s.kind == crate::StreamKind::Video && s.index == 0)?
5218 .language
5219 .filter(|l| l != "und")
5220}
5221
5222/// The colour tags of the first source, exactly as its container states them:
5223/// what a file that keeps its source's colour declares, unspecified fields left
5224/// unspecified. Nothing when no source can be read, which declares nothing.
5225fn source_colour_tags(project: &Project) -> Tags {
5226 project
5227 .sources()
5228 .first()
5229 .and_then(|source| crate::demux::Demuxer::open(&source.path).ok())
5230 .map(|(_, demuxer)| demuxer.colour_tags())
5231 .unwrap_or_default()
5232}
5233
5234fn params_of(track: &ExportAudio) -> AudioParams {
5235 AudioParams {
5236 freq_index: track.params.freq_index,
5237 chan_conf: track.params.chan_conf,
5238 sample_rate: track.params.sample_rate,
5239 opus_pre_skip: track.opus_pre_skip,
5240 language: track.language.clone(),
5241 }
5242}
5243
5244fn run(
5245 project: &Project,
5246 meta: &VideoMeta,
5247 out: &Path,
5248 shared: &Arc<Shared>,
5249 settings: &ExportSettings,
5250 sample_rate: Option<u32>,
5251) -> crate::Result<()> {
5252 // The media's length and not the timeline's: a caption placed past the last
5253 // picture holds the *timeline* open ([`Project::timeline_frames`]) and there
5254 // is nothing to write under it -- the picture loop walks the composite spans
5255 // and stops with them, so a file padded to the caption's end would be
5256 // trailing silence over a frozen last frame. The export ends with the last
5257 // picture or sound, the cues are cut off there ([`lane_subtitles`]), and
5258 // [`planned_subtitles`] says so before the button is pressed.
5259 // The range's own length where one is marked, the media's otherwise --
5260 // `export_spans` walks the same window, so `done` ends on this `total`
5261 // exactly as it always did.
5262 let total = settings.range.map_or(project.media_frames(), |(s, e)| {
5263 e.min(project.media_frames()).saturating_sub(s)
5264 });
5265 // The two preview switches are the H.264 mp4 pair's alone. Only that
5266 // container carries a colour of its own back out ([`write_video`] tags it
5267 // there), so asking any other for a source-space file would write pictures
5268 // in one space and a header in another; and only that codec's seats honour
5269 // `intra_only` -- the H.264 and HEVC pairs do, and an AV1 one would quietly
5270 // write the long-GOP file it always did.
5271 if settings.keep_source_colour && settings.format != Format::Mp4 {
5272 return Err(format!(
5273 "{} cannot be written in its source's colour space",
5274 settings.format.name()
5275 )
5276 .into());
5277 }
5278 if settings.intra_only && !matches!(settings.format, Format::Mp4 | Format::Hevc | Format::HevcMp4) {
5279 return Err(format!("{} cannot be written intra-only", settings.format.name()).into());
5280 }
5281 if settings.keyframe_s.is_some() && settings.intra_only {
5282 return Err("keyframe_s sets the key frame interval, and intra_only codes every picture a key frame: pass one".into());
5283 }
5284 if settings.faststart && !settings.format.is_mp4_family() {
5285 return Err(format!("faststart lays out an mp4 file, and {} is not one", settings.format.name()).into());
5286 }
5287 if let Some(why) = exact_refusal(project, meta, settings) {
5288 return Err(why.into());
5289 }
5290 let hdr_colour = hdr_colour_of(settings)?;
5291 let sources = project.sources();
5292 // The picture's decision first, before a sample of sound is touched: it is
5293 // the answer that decides what the whole export *is*, it costs one header
5294 // read per source, and it is what the line on screen has been missing --
5295 // an export that copies its picture used to say nothing at all for as long
5296 // as its sound took, which on a feature film was minutes. Half a line now,
5297 // completed by the measured codec once the sound is known below: what is
5298 // published is never a codec that did not run.
5299 let plan = CopyPlan::of(project, meta, settings);
5300 if plan.is_some() {
5301 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export video: copy (source packets)"); }
5302 *shared.encoders.lock().unwrap() = Some("copy · working out the sound…".into());
5303 }
5304 // ...then the audio, on a thread of its own, started before anything is
5305 // opened for the picture.
5306 //
5307 // Where it is *waited* for is the whole of this: a Matroska file interleaves
5308 // its audio into the clusters from the header on, so that path needs every
5309 // packet before the first coded picture and there is nothing to overlap. An
5310 // mp4 writes its audio track after the whole picture -- and now declares it
5311 // there too ([`MkvMuxer`]'s opposite, `Mp4Muxer::add_audio_track`) -- so the
5312 // picture's loop needs nothing at all from this until it has finished, and
5313 // the mix, its encode and the encode of every frame run at once. An export
5314 // used to cost the sound *plus* the picture; an mp4 one now costs the longer
5315 // of the two. On this project's own film that is 168 s of AC-3 that no
5316 // longer stands in front of 733 s of hardware H.264.
5317 // What a file keeping its source's colour declares, read once: the picture
5318 // is written in that space, so the tags are the source's own, not resolved.
5319 let source_colour = match settings.keep_source_colour {
5320 true => source_colour_tags(project),
5321 false => Tags::default(),
5322 };
5323 // The picture's language, which the Matroska video track states (`und` where none).
5324 let source_language = video_language(project);
5325 // A ProRes file's sound is PCM (24-bit unless asked for 16) mixed on a thread of its own and written
5326 // after the picture ([`PcmPass`]); no AAC pass runs beside it.
5327 let bits = prores_audio_bits(settings);
5328 let pcm_job = match settings.format.is_prores() {
5329 true => {
5330 let (project, meta, settings, shared) =
5331 (project.clone(), *meta, settings.clone(), Arc::clone(shared));
5332 PcmPass(Some(
5333 thread::Builder::new()
5334 .name("export-pcm".into())
5335 .spawn(move || mix_pcm16(&project, &meta, &shared, &settings, sample_rate, bits))?,
5336 ))
5337 }
5338 false => PcmPass(None),
5339 };
5340 let audio_job = if settings.format.is_prores() { None } else { Some({
5341 let (project, meta, settings, shared) =
5342 (project.clone(), *meta, settings.clone(), Arc::clone(shared));
5343 thread::Builder::new()
5344 .name("export-audio".into())
5345 .spawn(move || {
5346 let track = copy_audio(
5347 &project,
5348 &meta,
5349 audio_kbps_of(&settings),
5350 settings.format.is_mkv(),
5351 settings.format == Format::Webm,
5352 settings.reencode_audio,
5353 &shared,
5354 // WebM's sound is mixed at the rate Opus codes at, so the
5355 // one encoder path it takes is the one that resamples.
5356 match settings.format {
5357 Format::Webm => Some(OPUS_RATE),
5358 _ => sample_rate,
5359 },
5360 settings.range,
5361 )?;
5362 // The language the sound is in, on the copy and the mix alike:
5363 // the one tag the whole track carries.
5364 Ok(track.map(|track| ExportAudio {
5365 language: audio_language(&project),
5366 ..track
5367 }))
5368 })?
5369 }) };
5370 // A Matroska file (and a copied one, whose muxer is the same) collects it
5371 // here; an mp4 leaves it running and collects it under the picture below.
5372 // Held in a guard from here on, so no way out of this function leaves the
5373 // pass running behind it ([`AudioPass`]).
5374 let mut audio_job = AudioPass(audio_job);
5375 // The condition is the *format*, and the copied-picture path below relies
5376 // on that covering it too: `plan` hands its packets straight to a Matroska
5377 // muxer, so it may only exist where this has already collected them --
5378 // which holds because [`CopyPlan::of`] returns `None` for every format
5379 // that is not `Hevc` or `Av1`, both of which are `is_mkv`. Said out loud
5380 // because a copy plan for an mp4 would otherwise reach `plan.run` with the
5381 // sound still being mixed on the other thread.
5382 debug_assert!(
5383 settings.format.is_mkv() || plan.is_none(),
5384 "a copy plan outside Matroska would run before its sound is collected"
5385 );
5386 let mut pcm_job = pcm_job;
5387 let audio = match settings.format.is_mkv() {
5388 true => join_audio(audio_job.take().expect("the job was just made"))?,
5389 false => None,
5390 };
5391 let audio_params = audio.as_ref().map(params_of);
5392 // What the track *is*, kept before the packets are handed to a muxer: the
5393 // encoder line names a copy or an encode and only `copy_audio` knows which.
5394 // `None` on the mp4 path until the pass is collected -- the line says it is
5395 // still working the sound out, which is what it is doing.
5396 let mut sound = audio.as_ref().map(|track| track.copied);
5397 // ...and *which* encoder, for the same line: the card predicts Opus from the
5398 // format alone and cannot know the mix's rate or width ([`audio_label`]),
5399 // while this is after the mix was opened, so it is the measured answer.
5400 let mut opus = audio
5401 .as_ref()
5402 .is_some_and(|track| track.opus_pre_skip.is_some());
5403 // Taken by the Matroska muxer at creation; the mp4 one writes its track
5404 // after the picture, so for that path this is filled in at the end.
5405 let mut packets = audio.map(|track| track.packets);
5406 // ...and the cues with them, for the same reason: the subtitle track is
5407 // declared in the header and its blocks are interleaved into the clusters,
5408 // so the muxer needs the lot before the first picture is written.
5409 let mut subs = export_subtitles(project, meta, settings);
5410 // Whatever the sound has reached, the picture's share starts here
5411 // ([`AUDIO_BAND`]) -- and the bar only ever moves forwards, which is what
5412 // `fetch_max` below keeps true while an audio pass is still publishing its
5413 // own third of that band from the other thread.
5414 shared.progress.fetch_max(AUDIO_BAND, Ordering::Relaxed);
5415
5416 // Before an encoder is opened at all: a timeline nobody has touched, whose
5417 // sources this file can hold as they are, is written by copying their coded
5418 // blocks -- the picture's half of what `copy_audio` just did for the sound,
5419 // and the difference between an export bounded by the *edited* spans and one
5420 // that re-encodes a whole film to change a cut. [`CopyPlan`] states the
5421 // whole rule; anything at all outside it falls through to the walk below.
5422 if let Some(plan) = plan {
5423 *shared.encoders.lock().unwrap() = Some(format!(
5424 "copy · {}",
5425 // The measured codec, exactly as the encoder path below publishes
5426 // it: the mix has been opened by now, so a line that fell back to
5427 // AAC says AAC. Naming the prediction here would make the fallback
5428 // invisible on precisely the exports that are over in seconds.
5429 measured_audio_label(project, settings.format, sound, opus)
5430 ));
5431 return plan.run(
5432 out,
5433 meta,
5434 shared,
5435 audio_params.as_ref().zip(packets.take()),
5436 std::mem::take(&mut subs),
5437 total,
5438 &settings.chapters,
5439 );
5440 }
5441
5442 // One header parse per source, before any of them is decoded: what rate
5443 // each file was shot at against the timeline's ([`Rate`]), which is how the
5444 // clip's timeline frames below become frames of the file, and what its
5445 // samples *mean* ([`ColorDescription`]), which is what decides whether they
5446 // are remapped on the way in. Real time for a still, a song and a
5447 // single-rate project, where every conversion below is the identity.
5448 let rates: Vec<(
5449 Rate,
5450 ColorDescription,
5451 Option<f32>,
5452 Rotation,
5453 crate::demux::PixelAspect,
5454 )> = sources
5455 .iter()
5456 .map(|source| source_rate(&source.path, meta.frame_rate))
5457 .collect();
5458 // ...and, for a source on an HDR curve, the tone map that brings its samples
5459 // down to the SDR this file is written in ([`crate::tonemap`]). Once per
5460 // source stream: the table costs a couple of milliseconds to build and a
5461 // span reopens its file, so building it here rather than in the loop below
5462 // is the difference between paying that once and paying it per cut. An SDR
5463 // source -- the whole of an ordinary project -- builds no table at all.
5464 //
5465 // Through the project's own preset ([`tonemap::Preset`]) and each source's
5466 // own declared peak, which is the pair playback's decode funnel builds its
5467 // tables with: preview and export are the same rendition of the same film
5468 // because they are told the same two things, not because two numbers happen
5469 // to agree.
5470 let preset = project.tone();
5471 let tone: Vec<Option<ToneMapper>> = rates
5472 .iter()
5473 .map(|(_, color, peak, _, _)| match color.transfer {
5474 // A preview file keeps the film's own curve and is tone-mapped when
5475 // it is *shown* ([`ExportSettings::keep_source_colour`]), which is
5476 // both cheaper and the only way the preset can still be changed
5477 // after the stand-in was made.
5478 _ if settings.keep_source_colour => None,
5479 // An HDR export keeps the HDR sources' own curve: no tone map to SDR
5480 // ([`ExportSettings::hdr`], [`hdr_colour_of`] refuses a curve change).
5481 _ if hdr_colour.is_some() => None,
5482 Transfer::Sdr => None,
5483 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)),
5484 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)),
5485 })
5486 .collect();
5487 // ...and the one space they are all written in, the same rule a reader with
5488 // no tags to read would apply to this file's height -- or, for a preview
5489 // file, the source's own, which is what makes every remap below the
5490 // identity and the file's `colr` box its film's.
5491 // The software seat's depth ([`wide_ten_bit`]): a 10-bit timeline is
5492 // decoded and encoded at 10 bits wherever its pictures pass through untouched.
5493 for (_, color, ..) in &rates {
5494 let clash = hdr_colour.is_some_and(|out| color.transfer != Transfer::Sdr && color.transfer != out.transfer);
5495 if clash {
5496 let out = hdr_colour.expect("a clash needs an HDR output");
5497 return Err(format!(
5498 "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",
5499 transfer_name(color.transfer),
5500 transfer_name(out.transfer)
5501 )
5502 .into());
5503 }
5504 }
5505 let ten_bit = wide_ten_bit(settings, || {
5506 sources
5507 .iter()
5508 .any(|s| Demuxer::open(&s.path).is_ok_and(|(_, d)| d.bit_depth() >= 10))
5509 })?;
5510 // The colour a 10-bit SDR export declares: its sources' own matrix, where every
5511 // clip is SDR in one matrix ([`source_sdr_colour`]). Every other export keeps the
5512 // output rule, and so does the encoder's declared colour when there is no such one.
5513 let source_sdr = match ten_bit && !settings.keep_source_colour {
5514 // An HDR export declares its own colour, whatever the sources are.
5515 true if hdr_colour.is_some() => hdr_colour,
5516 true => source_sdr_colour(&rates.iter().map(|(_, c, ..)| *c).collect::<Vec<_>>()),
5517 false => None,
5518 };
5519 let rule = ColorDescription::output_sized(meta.width, meta.height);
5520 let out_color = match settings.keep_source_colour {
5521 true => meta.color,
5522 false => source_sdr.unwrap_or(rule),
5523 };
5524 let container_colour = source_sdr.map_or(source_colour, Tags::of);
5525
5526 // The captions drawn into each picture, if the export burns any in ([`Burn`]).
5527 let mut burn = Burn::new(project, settings, meta.frame_rate, out_color.full_range)?;
5528 let mut encoder = Enc::open(meta, settings, ten_bit, source_sdr.unwrap_or(rule))?;
5529 // What this file is really being written by, for a progress line to name.
5530 // Published *after* the seat is open, so a hardware encoder the driver
5531 // refused reads as the software one that took over rather than as the hope
5532 // it replaced -- and the sound says whether it was copied or encoded, which
5533 // only `copy_audio` knows and, on the overlapped path, does not know yet.
5534 let seat = encoder.label();
5535 publish_seats(
5536 shared,
5537 seat,
5538 project,
5539 settings,
5540 sound,
5541 opus,
5542 audio_job.running(),
5543 );
5544 // When the picture started, so the stage line below can say where under it
5545 // the sound landed -- the one number that says whether the two passes
5546 // really overlapped, in the same voice as `encode_audio`'s own timers.
5547 let picture_started = std::time::Instant::now();
5548 // The sound, once the pass beside this one has finished with it: joined
5549 // here the moment it lands rather than only after the picture, so
5550 // `feed_late_audio` below can hand it to the muxer while pictures are
5551 // still being coded and let `Mp4Muxer`'s own hold interleave the two
5552 // ([`crate::mux::Mp4Muxer`]).
5553 let mut late: Option<ExportAudio> = None;
5554 // Set once `late`'s track has been handed to the muxer -- so the final
5555 // join below, which still exists for a mix that never lands mid-picture,
5556 // knows not to declare the track or write its packets a second time.
5557 let mut audio_fed = false;
5558 let mut muxer = None;
5559 // A ProRes file is declared up front: the encoder knows its own sample entry.
5560 if let Some(params) = encoder.prores_params() {
5561 muxer = Some(Muxer::Mov(crate::prores_out::MovWriter::create(
5562 out,
5563 params,
5564 crate::mux::frame_timing(meta.frame_rate)?,
5565 )?));
5566 }
5567 let mut done = 0u32;
5568 // ...and how many of the edit's frames a file could not give, summed over
5569 // the spans that ran out under their clip ([`Shared::truncated`]).
5570 let mut skipped = 0u32;
5571 let black = Black::new(meta);
5572 // Software decoders that spans leave behind for the next span of the same
5573 // file to continue (see [`Parked`]).
5574 let parked = Arc::new(Parked::default());
5575 // Spans, not clips: a gap in the video is part of the timeline and gets
5576 // encoded too, as black frames. The picture count is therefore
5577 // `media_frames` however the lanes are arranged -- [`export_spans`] is that
5578 // walk cut to it, so `done` ends on the `total` above instead of running
5579 // past it under a trailing caption -- and *which* lane a span comes from is
5580 // `composite_spans_from`'s answer, the same one playback shows, so an
5581 // export is what was watched.
5582 let spans = export_spans(project, settings.range);
5583 let spans = match (&burn, ten_bit && matches!(encoder, Enc::HevcHw(_, _, true))) {
5584 (Some(b), true) => split_spans(spans, |f| b.quiet(f, f + 1)),
5585 _ => spans,
5586 };
5587 let dma = encoder.dma_want(meta);
5588 let mut plans: Vec<Option<OpenPlan>> = spans
5589 .iter()
5590 .map(|span| {
5591 let keyed_color = color_keyed_alone_at(project, span.start).filter(|_| ten_bit);
5592 let (source, in_frame) = span.from.filter(|_| !(layered_at(project, span.start) && keyed_color.is_none()))?;
5593 let entry = sources.get(source)?;
5594 let (rate, color, _peak, rotation, pixel_aspect) = rates[source];
5595 let deint = span_deint(project, span.start, &entry.path);
5596 let rate = crate::deinterlace::counted_rate(deint, rate);
5597 let mapper = tone[source].as_ref();
5598 let dissolve = dissolve_window(project, span);
5599 if crate::is_audio(&entry.path)
5600 || project.composite_visualizer_at(span.start) & 1 != 0
5601 || span.reverse
5602 || crate::is_image(&entry.path)
5603 {
5604 return None;
5605 }
5606 let span = *span;
5607 let untouched = mapper.is_none()
5608 && keyed_color.is_none()
5609 && burn.as_ref().is_none_or(|b| ten_bit && b.quiet(span.start, span.end()))
5610 && remap_into(Some(color), false, out_color.matrix).is_none()
5611 && project
5612 .composite_color_at(span.start)
5613 .is_none_or(|params| params.is_identity())
5614 && project
5615 .composite_transform_at(span.start)
5616 .is_none_or(|params| params.is_identity())
5617 // A file whose display matrix asks for a turn is *not*
5618 // untouched, whatever else the timeline says: its pictures
5619 // have to be turned, which is a read-back no GPU buffer
5620 // survives. The sample aspect is the same refusal one
5621 // stage later: its pictures have to be stretched to the
5622 // square-pixel raster before an encoder sees them, which
5623 // is the same kind of touch.
5624 && rotation.is_none()
5625 && pixel_aspect.is_square()
5626 && dissolve.is_none()
5627 && !picture_faded_in(project, &span);
5628 Some(OpenPlan {
5629 path: entry.path.clone(),
5630 start: rate.source_at(in_frame),
5631 untouched,
5632 deint,
5633 tail: span.source_window().map_or(u32::MAX, |(_, _, end)| rate.source_at(end)),
5634 })
5635 })
5636 .collect();
5637 let mut ahead: Option<((OpenPlan, Option<DmaWant>), ClipDecoder)> = None;
5638 for (index, span) in spans.iter().copied().enumerate() {
5639 // Every clip reopens its own source file at its own in point; the
5640 // encoder is *not* reopened, so the export is one continuous stream
5641 // whose GOP boundaries need not line up with the cuts -- nor with the
5642 // file boundaries, which are just cuts that change the path.
5643 // Whether this span's tail dissolves into its successor -- decided
5644 // before A's own decoder is opened, because it is what decides
5645 // whether A may take the DMA fast path at all: the blend below needs
5646 // A's pixels on the CPU, so a dissolving span never asks for a GPU
5647 // buffer, not even outside its own window.
5648 //
5649 // A layered span (two or more clips on the stack, [`layered_at`]) takes
5650 // no decoder of its own: its pictures are composed by a [`LayerStack`]
5651 // opened beside it, placed and faded per clip, so it never dissolves,
5652 // never takes the DMA path and never runs the single-clip placement.
5653 let keyed_color = color_keyed_alone_at(project, span.start).filter(|_| ten_bit);
5654 let layered_here = layered_at(project, span.start) && keyed_color.is_none();
5655 let dissolve = dissolve_window(project, &span);
5656 let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) =
5657 match span.from.filter(|_| !layered_here) {
5658 Some((source, in_frame)) => {
5659 let entry = sources
5660 .get(source)
5661 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
5662 let (rate, color, _peak, rotation, pixel_aspect) = rates[source];
5663 // A field-mode clip of an interlaced file counts fields, two a frame.
5664 let deint = span_deint(project, span.start, &entry.path);
5665 let rate = crate::deinterlace::counted_rate(deint, rate);
5666 let mapper = tone[source].as_ref();
5667 // Nothing on the way from this span's decoder to the encoder
5668 // touches a sample: no tone map, no matrix remap, no grade --
5669 // which is what lets the *decoded buffer itself* be encoded,
5670 // never read back and never written out again. The canvas is
5671 // the fourth thing that would touch it, and the decoder answers
5672 // that one: a picture of another size than this file's is one
5673 // the plugin hands back as pixels ([`HwSession::next_frame_dma`]).
5674 let plan = plans[index].take();
5675 let want = plan.as_ref().is_some_and(|p| p.untouched).then(|| encoder.dma_want(meta)).flatten();
5676 // Opened at the file's own frame, which is the only place the
5677 // file's numbering is used -- the span's are the timeline's.
5678 let flags = project.composite_visualizer_at(span.start);
5679 let pictures = if crate::is_audio(&entry.path) || flags & 1 != 0 {
5680 ClipDecoder::visualizer(
5681 &entry.path,
5682 entry.audio_stream,
5683 rate.source_at(in_frame),
5684 (meta.width, meta.height),
5685 meta.frame_rate,
5686 flags,
5687 project.composite_viz_paint_at(span.start),
5688 )?
5689 } else if span.reverse && !crate::is_image(&entry.path) {
5690 // Played backwards: from the file frame the span starts on, down
5691 // to the lowest it reads. The loop below counts the pictures it
5692 // takes off the decoder, which is how it reads a forward one.
5693 let lo = span.source_window().map_or(0, |(_, lo, _)| rate.source_at(lo));
5694 ClipDecoder::reversed(&entry.path, rate.source_at(in_frame), lo, deint)
5695 } else {
5696 let tail = span.source_window().map_or(u32::MAX, |(_, _, end)| rate.source_at(end));
5697 match (ahead.take(), plan) {
5698 (Some((key, decoder)), Some(plan)) if key == (plan.clone(), want) => decoder,
5699 _ => ClipDecoder::open_span(&entry.path, rate.source_at(in_frame), want, Some(&parked), ten_bit, deint, tail)?,
5700 }
5701 };
5702 (
5703 Some(pictures),
5704 rate,
5705 in_frame,
5706 Some(color),
5707 mapper,
5708 rotation,
5709 pixel_aspect,
5710 )
5711 }
5712 // A gap's black is 16/128/128, which is black in every matrix here
5713 // and on every curve: nothing to remap and nothing to tone-map,
5714 // which is what `None` says. A gap is no file either, so nothing
5715 // turns it.
5716 None => (
5717 None,
5718 Rate::REAL_TIME,
5719 0,
5720 None,
5721 None,
5722 Rotation::None,
5723 crate::demux::PixelAspect::SQUARE,
5724 ),
5725 };
5726 ahead = None;
5727 if let Some(Some(next)) = plans.get(index + 1)
5728 && span.from.and_then(|(s, _)| sources.get(s)).is_none_or(|e| e.path != next.path)
5729 {
5730 let want = next.untouched.then_some(dma).flatten();
5731 if let Ok(decoder) = ClipDecoder::open_span(&next.path, next.start, want, Some(&parked), ten_bit, next.deint, next.tail) {
5732 ahead = Some(((next.clone(), want), decoder));
5733 }
5734 }
5735 // Mixed spaces on one timeline: a clip coded against another matrix than
5736 // the one this file declares is rewritten into it, *after* the grade --
5737 // playback grades in the source's own space and converts for the screen
5738 // ([`crate::decode`]), so a grade applied to remapped samples is a
5739 // different picture than the one the canvas showed. Same-space clips --
5740 // the whole of an ordinary project -- take `None` and not a byte is
5741 // touched.
5742 //
5743 // ...and what the samples mean when that remap sees them is not always
5744 // what the file said, which is [`remap_into`]'s whole question.
5745 let remap = remap_into(color, mapper.is_some(), out_color.matrix);
5746 // What this span is graded by -- the same answer playback's decoder
5747 // carries, so the export is the picture that was watched. `None` for a
5748 // gap and for an ungraded clip, and that is the path where not a byte
5749 // is touched. Scratch outside the frame loop: it is refilled per frame
5750 // and its allocation survives the whole span.
5751 // A layered span's clips carry their own grades and transforms, in the
5752 // [`LayerStack`] that composes them; the top clip's do not apply here.
5753 let grade = match layered_here {
5754 true => None,
5755 false => project.composite_color_at(span.start).copied(),
5756 };
5757 let transform = match layered_here {
5758 true => TransformParams::default(),
5759 false => project
5760 .composite_transform_at(span.start)
5761 .copied()
5762 .unwrap_or_default(),
5763 };
5764 // The composing stack for a layered span, open for the whole span.
5765 let mut layers = match layered_here {
5766 true => Some(LayerStack::open(
5767 project,
5768 meta,
5769 &stack_at(project, span.start),
5770 out_color.matrix,
5771 None,
5772 Some((&shared.cancel, &shared.measuring)),
5773 )?
5774 .park_in(&parked)),
5775 false => None,
5776 };
5777 // A 10-bit export composes a layered picture at 10 bits too ([`LayerStack::picture16`]).
5778 let layered_wide = ten_bit && layers.is_some();
5779 let mut graded = (Vec::new(), Vec::new(), Vec::new());
5780 let mut transformed = (Vec::new(), Vec::new(), Vec::new());
5781 // The 10-bit scratch of A's placement, and the 10-bit copies of an 8-bit
5782 // picture (or of B's) that composes at 10 bits ([`widen_into`]).
5783 let mut scratch16 = Scratch16::default();
5784 let mut widened_a: Planes16 = Planes16::default();
5785 let mut widened_b: Planes16 = Planes16::default();
5786 // A lone clip's effects stack on this path draws on copies of its placed
5787 // picture, at whichever depth it was placed ([`color_keyed_alone_at`]).
5788 let fx_clip = keyed_color.filter(|clip| crate::effects::active(&clip.effects));
5789 let (mut fx8, mut fx16): (Planes, Planes16) = Default::default();
5790 let mut fx_scratch8 = crate::effects::Scratch::<u8>::default();
5791 let mut fx_scratch16 = crate::effects::Scratch::<u16>::default();
5792 // ...and one more for the file's own display-matrix turn, which happens
5793 // before all of those (see [`place_picture`]): empty for every source
5794 // that states no turn. `stretched` is its twin for the pixel aspect,
5795 // which happens right after it.
5796 let mut rotated = (Vec::new(), Vec::new(), Vec::new());
5797 let mut stretched = (Vec::new(), Vec::new(), Vec::new());
5798 // ...and the canvas it is placed on, which is where a source of another
5799 // resolution becomes a picture at the project's. The same `Composer`
5800 // playback composes with, given the same policy, so an export is what
5801 // was watched down to the letterbox; a clip already the project's size
5802 // passes through it untouched.
5803 let mut canvas = Composer::new(
5804 meta.width,
5805 meta.height,
5806 project.composite_fit_at(span.start),
5807 );
5808 // The 10-bit canvas: its own composer, because the 8-bit placement above
5809 // borrows `canvas` in the same frame. It places the same fit.
5810 let mut canvas16 = Composer::new(
5811 meta.width,
5812 meta.height,
5813 project.composite_fit_at(span.start),
5814 );
5815 // Scratch for the 8-bit composition of a 10-bit picture ([`narrowed`]),
5816 // one for A's picture and one for B's.
5817 let mut narrow_a: [Vec<u8>; 3] = Default::default();
5818 let mut narrow_b: [Vec<u8>; 3] = Default::default();
5819 // B's own decoder, opened beside A's: the two streams come off their
5820 // files together for exactly the frames the tail below blends, and
5821 // nothing else in this span ever touches it.
5822 let mut b = dissolve
5823 .map(
5824 |(b_source, b_in_frame, window, b_start)| -> crate::Result<_> {
5825 let entry = sources.get(b_source).ok_or_else(|| {
5826 format!("clip names source {b_source} of {}", sources.len())
5827 })?;
5828 let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source];
5829 // The blended tail of a dissolve takes one picture per timeline
5830 // frame, so it never counts fields: `Field` is its `Frame`.
5831 let b_deint = frame_counting(span_deint(project, b_start, &entry.path));
5832 let b_rate = crate::deinterlace::counted_rate(b_deint, b_rate);
5833 let b_mapper = tone[b_source].as_ref();
5834 let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix);
5835 Ok(Dissolve {
5836 window,
5837 kind: crate::transitions::kind_at(project, span.start),
5838 tail_start: span.len - window,
5839 decoder: if crate::is_audio(&entry.path)
5840 || project.composite_visualizer_at(b_start) & 1 != 0
5841 {
5842 ClipDecoder::visualizer(
5843 &entry.path,
5844 entry.audio_stream,
5845 b_rate.source_at(b_in_frame),
5846 (meta.width, meta.height),
5847 meta.frame_rate,
5848 project.composite_visualizer_at(b_start),
5849 project.composite_viz_paint_at(b_start),
5850 )?
5851 } else {
5852 ClipDecoder::open_with(&entry.path, b_rate.source_at(b_in_frame), None, Some(&parked), ten_bit, b_deint)?
5853 },
5854 mapper: b_mapper,
5855 remap: b_remap,
5856 grade: project.composite_color_at(b_start).copied(),
5857 transform: project
5858 .composite_transform_at(b_start)
5859 .copied()
5860 .unwrap_or_default(),
5861 rotation: b_rotation,
5862 pixel_aspect: b_pixel_aspect,
5863 canvas: Composer::new(
5864 meta.width,
5865 meta.height,
5866 project.composite_fit_at(b_start),
5867 ),
5868 rotated: (Vec::new(), Vec::new(), Vec::new()),
5869 stretched: (Vec::new(), Vec::new(), Vec::new()),
5870 graded: (Vec::new(), Vec::new(), Vec::new()),
5871 transformed: (Vec::new(), Vec::new(), Vec::new()),
5872 scratch16: Scratch16::default(),
5873 })
5874 },
5875 )
5876 .transpose()?;
5877 // Timeline frames, taken a *source* frame at a time: at a rate other
5878 // than real time the two are not the same count, and the span says which
5879 // source frame each timeline frame shows ([`Speed::source_at`]) -- the
5880 // very frame playback is holding there, because the two conversions are
5881 // one floor/ceil pair (`speed_maps_both_ways`). A speed-up decodes the
5882 // frames it skips and drops them, because the pictures after them
5883 // reference those; a slow-down encodes the picture it is holding again
5884 // rather than decoding it twice. At real time `repeats` is 1 and `want`
5885 // advances by one, which is the loop this always ran.
5886 let mut done_here = 0u32;
5887 // Source frames already taken out of this span's decoder.
5888 let mut taken = 0u32;
5889 // The whole of the mapping, in the order it composes: the speed says
5890 // which of the clip's (timeline-rate) frames a timeline frame shows,
5891 // and the rate says which frame of the *file* that is -- counted from
5892 // the one the decoder was opened at. At real time and at the timeline's
5893 // own rate this is `Speed::source_at` and nothing else, which is the
5894 // walk a single-rate project has always taken.
5895 let opened_at = rate.source_at(in_frame);
5896 let source_at =
5897 |offset: u32| rate.source_at(in_frame + span.source_offset(offset)) - opened_at;
5898 while done_here < span.len {
5899 cancelled(shared)?;
5900 // The sound's failure is the export's, and it is heard the moment
5901 // it happens rather than after the last frame: a mix this engine
5902 // cannot decode used to refuse in seconds, before any picture was
5903 // encoded, and an overlapped pass that reported only at the end
5904 // would spend the whole encode first. Also where its measured
5905 // codec reaches the line on screen.
5906 let hold_full = audio_job.running() && matches!(&muxer, Some(Muxer::Mp4(m)) if m.holding_long());
5907 if audio_job.is_finished() || hold_full {
5908 late = join_audio(audio_job.take().expect("just seen to be there"))?;
5909 sound = late.as_ref().map(|track| track.copied);
5910 opus = late
5911 .as_ref()
5912 .is_some_and(|track| track.opus_pre_skip.is_some());
5913 publish_seats(shared, seat, project, settings, sound, opus, false);
5914 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!(
5915 "export audio: done {:.1} s into the picture",
5916 picture_started.elapsed().as_secs_f64()
5917 ); }
5918 feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
5919 }
5920 if let Some(Muxer::Mp4(mp4)) = muxer.as_mut() {
5921 mp4.audio_pending = audio_job.running();
5922 }
5923 let want = source_at(done_here);
5924 // A colour-keyed clip on the 10-bit path: this picture's grade is the
5925 // keys' value at its first timeline frame (a slowed picture repeated
5926 // over several frames keeps it).
5927 let grade = match keyed_color {
5928 Some(clip) => Some(crate::project::clip_color_at(
5929 clip,
5930 grade.unwrap_or_default(),
5931 span.start + done_here,
5932 )),
5933 None => grade,
5934 };
5935 // How many timeline frames from here show that same picture: one at
5936 // real time, more when the clip is slowed or its file is slower
5937 // than the timeline. Encoded again rather than decoded twice.
5938 // A layered span composes every timeline frame, so it never repeats one.
5939 // ...nor does a lone clip whose effects move from frame to frame (a
5940 // shake); a static stack is drawn once and its picture held like any other.
5941 let repeats = match layered_here || fx_clip.is_some_and(|c| crate::effects::animated(&c.effects)) {
5942 true => 1,
5943 false => (done_here..span.len)
5944 .take_while(|&offset| source_at(offset) == want)
5945 .count() as u32,
5946 };
5947 // The composed picture of a layered span, owned for this frame.
5948 let mut composed: Option<Planes> = None;
5949 let mut composed16: Option<Planes16> = None;
5950 let picture = match (&mut layers, &mut pictures) {
5951 (Some(stack), _) if layered_wide => match stack.picture16(span.start + done_here)? {
5952 Some(planes) => {
5953 let planes = composed16.insert(planes);
5954 Some(Frame::Wide(
5955 &planes.0[..],
5956 &planes.1[..],
5957 &planes.2[..],
5958 meta.width,
5959 meta.height,
5960 ))
5961 }
5962 None => None,
5963 },
5964 (Some(stack), _) => match stack.picture(span.start + done_here)? {
5965 Some(planes) => {
5966 let planes = composed.insert(planes);
5967 Some(Frame::Pixels(
5968 &planes.0[..],
5969 &planes.1[..],
5970 &planes.2[..],
5971 meta.width,
5972 meta.height,
5973 ))
5974 }
5975 None => None,
5976 },
5977 (None, Some(pictures)) => {
5978 let mut ran_out = false;
5979 while taken < want && !ran_out {
5980 ran_out = pictures.next()?.is_none();
5981 taken += 1;
5982 }
5983 match ran_out {
5984 true => None,
5985 false => {
5986 taken += 1;
5987 pictures.next()?
5988 }
5989 }
5990 }
5991 (None, None) => {
5992 let (y, u, v, width, height) = black.picture();
5993 Some(Frame::Pixels(y, u, v, width, height))
5994 }
5995 };
5996 let Some(frame) = picture else {
5997 // The file ran out before its clip did: this span's tail never
5998 // gets a picture -- and *only* this span's tail, because the
5999 // span loop this break sits in carries on with the spans after
6000 // it and writes every picture they have. Counted, not
6001 // swallowed: the bar reaches its end whatever happens, so
6002 // without this a truncated file reads as a whole one. The same
6003 // sentence `planned_subtitles` gives cues that hang past the
6004 // last picture, said after the fact here because how many
6005 // pictures a *file* holds is only known by opening it.
6006 //
6007 // `span.len > done_here` holds by the loop's own condition, and
6008 // the sum over every break is exactly `total - done` at the end
6009 // of the walk: the spans are disjoint and cover the whole edit.
6010 skipped += span.len - done_here;
6011 break; // source ran out early; the clip list outlives the file
6012 };
6013 // A picture still on the GPU has nothing waiting for it here: the
6014 // span was opened that way only where none of what follows would
6015 // have touched a sample of it, so it is placed by nobody and goes
6016 // into the encoder as the buffer the decoder wrote.
6017 // A 10-bit picture goes to the encoder whole only where nothing on the
6018 // way touches a sample: no layer, dissolve, tone map, remap, grade,
6019 // transform, turn, stretch, caption or fade. Anything else composes at
6020 // 8 bits as it always did, narrowed here.
6021 let untouched = ten_bit
6022 && !layered_here
6023 && b.is_none()
6024 && mapper.is_none()
6025 && remap.is_none()
6026 && grade.is_none()
6027 && transform == TransformParams::default()
6028 && matches!(rotation, Rotation::None)
6029 && pixel_aspect.is_square()
6030 && burn
6031 .as_ref()
6032 .is_none_or(|b| b.quiet(span.start + done_here, span.start + done_here + repeats))
6033 && (done_here..done_here + repeats)
6034 .all(|off| picture_fade_at(project, span.start + off).is_none());
6035 // A 10-bit export composes at 10 bits wherever the picture is touched at
6036 // all. The exceptions stay at 8 bits: a tone map (HDR), a turn or a
6037 // stretch, and a layered picture (composed per clip).
6038 let wide16 = ten_bit
6039 && (layered_wide || !layered_here)
6040 && !untouched;
6041 let frame = match frame {
6042 Frame::Wide(_, _, _, width, height)
6043 if !wide16 && !(untouched && width == meta.width && height == meta.height) =>
6044 {
6045 narrowed(frame, &mut narrow_a)
6046 }
6047 other => other,
6048 };
6049 // The picture at 10 bits, composed: a 10-bit one as it is, an 8-bit one widened.
6050 let placed16 = match (wide16, &frame) {
6051 (true, Frame::Wide(y, u, v, width, height)) => Some(place_picture16(
6052 y,
6053 u,
6054 v,
6055 *width,
6056 *height,
6057 rotation,
6058 pixel_aspect,
6059 grade,
6060 transform,
6061 remap.filter(|_| !layered_here),
6062 mapper,
6063 &mut scratch16,
6064 &mut canvas16,
6065 )),
6066 (true, Frame::Pixels(y, u, v, width, height)) => {
6067 widen_into(y, &mut widened_a.0);
6068 widen_into(u, &mut widened_a.1);
6069 widen_into(v, &mut widened_a.2);
6070 Some(place_picture16(
6071 &widened_a.0[..],
6072 &widened_a.1[..],
6073 &widened_a.2[..],
6074 *width,
6075 *height,
6076 rotation,
6077 pixel_aspect,
6078 grade,
6079 transform,
6080 remap.filter(|_| !layered_here),
6081 mapper,
6082 &mut scratch16,
6083 &mut canvas16,
6084 ))
6085 }
6086 _ => None,
6087 };
6088 let placed = match frame {
6089 Frame::Dma(_) => None,
6090 // Encoded whole below, at 10 bits.
6091 Frame::Wide(..) => None,
6092 // Composed at 10 bits above.
6093 Frame::Pixels(..) if wide16 => None,
6094 // A layered picture is composed already, per clip: nothing here
6095 // places it again.
6096 Frame::Pixels(y, u, v, width, height) if layered_here => {
6097 Some((y, u, v, width, height))
6098 }
6099 Frame::Pixels(y, u, v, width, height) => Some(place_picture(
6100 y,
6101 u,
6102 v,
6103 width,
6104 height,
6105 rotation,
6106 pixel_aspect,
6107 grade,
6108 transform,
6109 remap,
6110 mapper,
6111 &mut rotated,
6112 &mut stretched,
6113 &mut graded,
6114 &mut transformed,
6115 &mut canvas,
6116 )),
6117 };
6118 // A lone clip's effects, drawn on its placed picture and laid over black.
6119 let (placed16, placed) = match fx_clip {
6120 None => (placed16, placed),
6121 Some(clip) => {
6122 let secs = f64::from(span.start + done_here) / meta.frame_rate;
6123 let src = crate::project::key_sample_pos(clip, span.start + done_here);
6124 let placed16 = placed16.map(|(y, u, v, w, h)| {
6125 fx16 = (y.to_vec(), u.to_vec(), v.to_vec());
6126 effected(&clip.effects, &mut fx16, w, h, secs, src, out_color.matrix, &mut fx_scratch16);
6127 (&fx16.0[..], &fx16.1[..], &fx16.2[..], w, h)
6128 });
6129 let placed = placed.map(|(y, u, v, w, h)| {
6130 fx8 = (y.to_vec(), u.to_vec(), v.to_vec());
6131 effected(&clip.effects, &mut fx8, w, h, secs, src, out_color.matrix, &mut fx_scratch8);
6132 (&fx8.0[..], &fx8.1[..], &fx8.2[..], w, h)
6133 });
6134 (placed16, placed)
6135 }
6136 };
6137 // Once per timeline frame this source frame covers: one at real time
6138 // and faster, more when the clip is slowed -- the picture is already
6139 // graded and placed, so a held frame costs an encode and no decode.
6140 for r in 0..repeats {
6141 // Inside the window every *output* frame gets its own B
6142 // picture -- decoded fresh here rather than once for the
6143 // whole held A frame -- which is what makes a slowed A's
6144 // tail still ramp one weight per frame shown rather than one
6145 // per source frame.
6146 let in_window = b.as_ref().is_some_and(|d| done_here + r >= d.tail_start);
6147 let coded = match (&mut b, in_window) {
6148 (Some(d), true) if placed16.is_some() => {
6149 let (ay, au, av, aw, ah) = placed16.expect("checked by the guard");
6150 let t = dissolve_weight(done_here + r - d.tail_start, d.window);
6151 let blended: Option<Planes16> = match d.decoder.next()? {
6152 // B's file ran out inside the window: A's own picture carries the frame.
6153 None => None,
6154 Some(b) => {
6155 // B at 10 bits: a 10-bit picture as it is, an 8-bit one widened.
6156 let (by, bu, bv, bw, bh): (&[u16], &[u16], &[u16], u32, u32) = match b {
6157 Frame::Wide(y, u, v, w, h) => (y, u, v, w, h),
6158 Frame::Pixels(y, u, v, w, h) => {
6159 widen_into(y, &mut widened_b.0);
6160 widen_into(u, &mut widened_b.1);
6161 widen_into(v, &mut widened_b.2);
6162 (&widened_b.0[..], &widened_b.1[..], &widened_b.2[..], w, h)
6163 }
6164 Frame::Dma(_) => unreachable!("b's decoder is never a DMA buffer"),
6165 };
6166 let (y, u, v, _, _) = place_picture16(
6167 by,
6168 bu,
6169 bv,
6170 bw,
6171 bh,
6172 d.rotation,
6173 d.pixel_aspect,
6174 d.grade,
6175 d.transform,
6176 d.remap,
6177 d.mapper,
6178 &mut d.scratch16,
6179 &mut d.canvas,
6180 );
6181 Some(crate::transitions::blend_planes(
6182 d.kind,
6183 (ay, au, av),
6184 (y, u, v),
6185 t,
6186 aw as usize,
6187 ah as usize,
6188 ))
6189 }
6190 };
6191 let frame_at = span.start + done_here + r;
6192 let (y, u, v) = match &blended {
6193 Some(p) => borrow_planes(p),
6194 None => (ay, au, av),
6195 };
6196 let faded = picture_fade_at(project, frame_at).map(|k| fade_planes((y, u, v), k));
6197 let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes);
6198 let (y, u, v) = burned16(&mut burn, frame_at, aw, ah, (y, u, v)).unwrap_or((y, u, v));
6199 encoder.encode_wide(y, u, v, aw, ah)?
6200 }
6201 (Some(d), true) => {
6202 let (ay, au, av, aw, ah) =
6203 placed.expect("a dissolving span always decodes to pixels");
6204 match d.decoder.next()?.map(|f| narrowed(f, &mut narrow_b)) {
6205 // B's file ran out inside the window: A's own
6206 // picture carries the frame rather than the
6207 // export losing it.
6208 None => {
6209 let frame_at = span.start + done_here + r;
6210 let faded = picture_fade_at(project, frame_at)
6211 .map(|k| fade_planes((ay, au, av), k));
6212 let (ay, au, av) =
6213 faded.as_ref().map_or((ay, au, av), borrow_planes);
6214 let painted = burned(&mut burn, frame_at, aw, ah, (ay, au, av));
6215 let (ay, au, av) = painted.as_ref().map_or((ay, au, av), borrow_planes);
6216 encoder.encode(ay, au, av, aw, ah, settings.intra_only)?
6217 }
6218 Some(Frame::Dma(_) | Frame::Wide(..)) => {
6219 unreachable!("b's decoder was opened with no DMA want and is narrowed")
6220 }
6221 Some(Frame::Pixels(by, bu, bv, bw, bh)) => {
6222 let (by, bu, bv, _, _) = place_picture(
6223 by,
6224 bu,
6225 bv,
6226 bw,
6227 bh,
6228 d.rotation,
6229 d.pixel_aspect,
6230 d.grade,
6231 d.transform,
6232 d.remap,
6233 d.mapper,
6234 &mut d.rotated,
6235 &mut d.stretched,
6236 &mut d.graded,
6237 &mut d.transformed,
6238 &mut d.canvas,
6239 );
6240 let idx_in_window = done_here + r - d.tail_start;
6241 let t = dissolve_weight(idx_in_window, d.window);
6242 let (y, u, v) = crate::transitions::blend_planes(
6243 d.kind,
6244 (ay, au, av),
6245 (by, bu, bv),
6246 t,
6247 aw as usize,
6248 ah as usize,
6249 );
6250 let frame_at = span.start + done_here + r;
6251 let faded = picture_fade_at(project, frame_at)
6252 .map(|k| fade_planes((&y[..], &u[..], &v[..]), k));
6253 let (y, u, v) =
6254 faded.as_ref().map_or((&y[..], &u[..], &v[..]), borrow_planes);
6255 let painted =
6256 burned(&mut burn, frame_at, aw, ah, (y, u, v));
6257 let (y, u, v) =
6258 painted.as_ref().map_or((y, u, v), borrow_planes);
6259 encoder.encode(y, u, v, aw, ah, settings.intra_only)?
6260 }
6261 }
6262 }
6263 _ => match (&frame, placed16) {
6264 (_, Some((y, u, v, width, height))) => {
6265 let frame_at = span.start + done_here + r;
6266 // A layered picture's fades were applied per clip in its stack.
6267 let faded = picture_fade_at(project, frame_at)
6268 .filter(|_| !layered_here)
6269 .map(|k| fade_planes((y, u, v), k));
6270 let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes);
6271 let (y, u, v) = burned16(&mut burn, frame_at, width, height, (y, u, v)).unwrap_or((y, u, v));
6272 encoder.encode_wide(y, u, v, width, height)?
6273 }
6274 (Frame::Dma(dma), None) => encoder.encode_dma(dma, settings.intra_only)?,
6275 (Frame::Wide(y, u, v, width, height), None) => {
6276 encoder.encode_wide(y, u, v, *width, *height)?
6277 }
6278 (Frame::Pixels(..), None) => {
6279 let (y, u, v, width, height) =
6280 placed.expect("a picture with pixels was placed");
6281 let frame_at = span.start + done_here + r;
6282 // A layered picture's fades were applied per clip in
6283 // its stack; the top clip's does not fade the frame.
6284 let faded = picture_fade_at(project, frame_at)
6285 .filter(|_| !layered_here)
6286 .map(|k| fade_planes((y, u, v), k));
6287 let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes);
6288 let painted = burned(&mut burn, frame_at, width, height, (y, u, v));
6289 let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes);
6290 encoder.encode(y, u, v, width, height, settings.intra_only)?
6291 }
6292 },
6293 };
6294 if let Some((au, key)) = coded {
6295 write_video(
6296 &mut muxer,
6297 out,
6298 meta,
6299 settings,
6300 container_colour,
6301 source_language.as_deref(),
6302 audio_params.as_ref(),
6303 &mut packets,
6304 &mut subs,
6305 au,
6306 key,
6307 ten_bit,
6308 )?;
6309 // Retried here rather than only where the mix lands: the
6310 // very first coded picture is what creates `muxer`, and a
6311 // mix that lands before it (a short film, or a slow first
6312 // frame) has nothing to hand it to until now.
6313 feed_late_audio(&mut muxer, &late, &mut audio_fed)?;
6314 inject_export_test_panic(out);
6315 }
6316 done += 1;
6317 // Forwards only: an audio pass still running beside this one
6318 // publishes its own share of [`AUDIO_BAND`], and a bar that
6319 // went backwards every time it did would be worse than one
6320 // that stood still.
6321 shared
6322 .progress
6323 .fetch_max(picture_progress(done, total), Ordering::Relaxed);
6324 }
6325 done_here += repeats;
6326 }
6327 }
6328 // The whole walk is over, so what it could not write is known to the frame
6329 // and is published once. `fetch_max` and not `fetch_add`, because a
6330 // hardware seat that died has the *whole* walk run again from its first
6331 // frame ([`start`]): the same project and the same picture counts, so a
6332 // second run must not double a number that is already on the line.
6333 shared.truncated.fetch_max(skipped, Ordering::Relaxed);
6334 while let Some((au, key)) = encoder.drain()? {
6335 write_video(
6336 &mut muxer,
6337 out,
6338 meta,
6339 settings,
6340 container_colour,
6341 source_language.as_deref(),
6342 audio_params.as_ref(),
6343 &mut packets,
6344 &mut subs,
6345 au,
6346 key,
6347 ten_bit,
6348 )?;
6349 }
6350 // Progress reads 100% from here on, but nothing is published yet: draining,
6351 // the audio pass and `finish` are all still cancellable.
6352 cancelled(shared)?;
6353
6354 let Some(muxer) = muxer else {
6355 return Err("export produced no coded pictures".into());
6356 };
6357 // The mp4's audio and subtitle tracks after its picture -- the Matroska one
6358 // interleaved its own as it went and left `packets` and `subs` empty behind
6359 // it. The text last, so its samples are written knowing how long the picture
6360 // turned out to be.
6361 let muxer = match muxer {
6362 Muxer::Mp4(mut mp4) => {
6363 // The sound, collected where this file first needs it: it has been
6364 // mixing and encoding under the whole picture, and an mp4 declares
6365 // its audio track here rather than at the open precisely so that
6366 // could happen ([`Mp4Muxer::add_audio_track`]).
6367 let track = match audio_job.take() {
6368 Some(job) => {
6369 let track = join_audio(job)?;
6370 // The picture finished first and this waited for the
6371 // sound: the pair of stage lines is what says which of the
6372 // two an export is really bounded by.
6373 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!(
6374 "export audio: waited for after {:.1} s of picture",
6375 picture_started.elapsed().as_secs_f64()
6376 ); }
6377 // ...and the line on screen finished with it. The loop above
6378 // publishes the measured codec the moment the pass lands
6379 // under the picture, but a picture that outran the mix never
6380 // reaches that branch -- and "working out the sound…" would
6381 // then be the last thing the card ever said about a track it
6382 // had long since written.
6383 publish_seats(
6384 shared,
6385 seat,
6386 project,
6387 settings,
6388 track.as_ref().map(|track| track.copied),
6389 track
6390 .as_ref()
6391 .is_some_and(|track| track.opus_pre_skip.is_some()),
6392 false,
6393 );
6394 track
6395 }
6396 // `late` was already handed to `mp4` inside the picture loop
6397 // ([`feed_late_audio`]) unless the mix never landed there, in
6398 // which case it is still `None` and there was nothing to feed.
6399 None if audio_fed => None,
6400 None => late,
6401 };
6402 if let Some(track) = &track {
6403 mp4.add_audio_track(&params_of(track))?;
6404 }
6405 for packet in track.into_iter().flat_map(|track| track.packets) {
6406 mp4.write_audio_packet(&packet.bytes)?;
6407 }
6408 mp4.set_faststart(settings.faststart);
6409 mp4.set_chapters(&settings.chapters)?;
6410 mp4.write_subtitles(&subs)?;
6411 Muxer::Mp4(mp4)
6412 }
6413 Muxer::Mov(mut mov) => {
6414 // The sound, PCM at the asked width, laid to the picture's length.
6415 if let Some(job) = pcm_job.take()
6416 && let Some((mut samples, rate, channels)) = join_pcm(job)?
6417 {
6418 let want = (f64::from(done) / meta.frame_rate * f64::from(rate)).round() as usize
6419 * usize::from(channels.max(1));
6420 samples.resize(want, 0);
6421 mov.write_sound(&samples, rate, channels, prores_audio_bits(settings))?;
6422 }
6423 Muxer::Mov(mov)
6424 }
6425 muxer => muxer,
6426 };
6427 cancelled(shared)?;
6428 muxer.finish()?;
6429 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
6430 Ok(())
6431}
6432
6433/// The cues a burn of track `pick` draws, on this timeline's clock: what the
6434/// screen shows. Once a track is placed on a subtitle lane, its placements are
6435/// the answer -- a cut sentence is gone, a trimmed or moved one sits where it
6436/// was put, and a hidden lane draws nothing -- with each cue's words read from
6437/// its palette track, so a retyped cue burns retyped. A track no lane places is
6438/// drawn as the export writes it whole ([`timeline_cues`]), whatever else is
6439/// placed, so a burn and a soft track of the same pick never disagree.
6440///
6441/// `Err` for a pick that is not a track of the project.
6442pub fn burn_cues(project: &Project, pick: usize, fps: f64) -> crate::Result<Vec<Cue>> {
6443 Ok(burn_cues_indexed(project, pick, fps)?.into_iter().map(|(_, cue)| cue).collect())
6444}
6445
6446fn burn_cues_indexed(project: &Project, pick: usize, fps: f64) -> crate::Result<Vec<(usize, Cue)>> {
6447 let track = project
6448 .subtitles()
6449 .get(pick)
6450 .ok_or_else(|| format!("burn_subtitles: no subtitle track {pick} in this project"))?;
6451 if !placed_tracks(project).contains(&pick) {
6452 return Ok(timeline_cues_indexed(project, track, fps));
6453 }
6454 let mut cues: Vec<(usize, Cue)> = project
6455 .subtitle_lanes()
6456 .into_iter()
6457 .flat_map(|lane| project.sub_lane_cue_spans(lane, fps))
6458 .filter(|s| s.track == pick)
6459 .filter_map(|s| {
6460 let c = track.cues.get(s.cue)?;
6461 Some((s.cue, Cue {
6462 start_us: s.start_us,
6463 end_us: s.end_us,
6464 text: c.text.clone(),
6465 image: c.image.clone(),
6466 words: crate::subtitle::map_words(&c.words, s.window, (s.start_us, s.end_us)),
6467 karaoke: crate::subtitle::map_karaoke(&c.karaoke, s.window, (s.start_us, s.end_us)),
6468 }))
6469 })
6470 .collect();
6471 cues.sort_by_key(|(_, c)| c.start_us);
6472 Ok(cues)
6473}
6474
6475/// The index of the cue on screen at timeline frame `frame`, if one is: a cue
6476/// is shown from the instant of its start up to, not including, its end, read
6477/// off the frame's own start time the way [`timeline_cues`] times the frames.
6478/// Cues with no text (a picture track's, or a blank line) show nothing.
6479pub fn cue_on_screen(cues: &[Cue], frame: u32, fps: f64) -> Option<usize> {
6480 let t = (f64::from(frame) / fps * 1e6).round() as i64;
6481 cues.iter().position(|c| {
6482 c.image.is_none() && c.start_us <= t && t < c.end_us && !c.text.trim().is_empty()
6483 })
6484}
6485
6486/// The indices of every cue on screen at timeline frame `frame`, in the order
6487/// `cues` lists them (start order from [`burn_cues`]). The same test as
6488/// [`cue_on_screen`], for a burn that draws all the cues up at once.
6489pub fn cues_on_screen(cues: &[Cue], frame: u32, fps: f64) -> Vec<usize> {
6490 let t = (f64::from(frame) / fps * 1e6).round() as i64;
6491 cues.iter()
6492 .enumerate()
6493 .filter(|(_, c)| {
6494 c.image.is_none() && c.start_us <= t && t < c.end_us && !c.text.trim().is_empty()
6495 })
6496 .map(|(i, _)| i)
6497 .collect()
6498}
6499
6500/// Three planes of one picture, owned: what a burned-in frame is encoded from.
6501type Planes<T = u8> = (Vec<T>, Vec<T>, Vec<T>);
6502
6503/// A picture at 10 bits a sample ([`Enc::encode_wide`]).
6504type Planes16 = Planes<u16>;
6505
6506fn borrow_planes<T>(p: &Planes<T>) -> (&[T], &[T], &[T]) {
6507 (&p.0, &p.1, &p.2)
6508}
6509
6510/// What one export draws into its pictures: the titles, then the captions
6511/// ([`ExportSettings::burn_subtitles`]). The overlay of the cue last drawn is
6512/// kept, so a caption on screen for a second is laid out once rather than once
6513/// a frame, and each title's overlay is kept the same way.
6514struct Burn {
6515 cues: Vec<Cue>,
6516 style: TextStyle,
6517 fps: f64,
6518 full_range: bool,
6519 /// The cues drawn last, by index, with the size, the animation state
6520 /// ([`crate::captionanim::blocks_key`]) and the stacked overlay.
6521 last: Option<(Vec<usize>, u32, u32, u64, Overlay)>,
6522 titles: Vec<Title>,
6523 /// One per title, the overlay it was last drawn as, with what made it ([`TitleKey`]).
6524 title_last: Vec<Option<(TitleKey, Overlay)>>,
6525 native: Option<Native>,
6526 spare: Option<Planes>,
6527 narrow: Planes,
6528 merged: Planes16,
6529}
6530
6531struct Native {
6532 captions: crate::assrender::Captions,
6533 sources: Vec<usize>,
6534}
6535
6536fn native_script(project: &Project, pick: usize, style: &TextStyle) -> Option<crate::assrender::Captions> {
6537 if !style.native {
6538 return None;
6539 }
6540 let track = project.subtitles().get(pick)?;
6541 if track.track.is_some() || track.cues.iter().any(|c| c.real_karaoke().is_some()) {
6542 return None;
6543 }
6544 crate::assrender::Captions::from_file(&track.path)
6545}
6546
6547fn native_shown(cues: &[Cue], sources: &[usize], on: &[usize]) -> Vec<crate::assrender::Shown> {
6548 on.iter()
6549 .map(|&i| crate::assrender::Shown {
6550 event: sources[i],
6551 start_us: cues[i].start_us,
6552 end_us: cues[i].end_us,
6553 })
6554 .collect()
6555}
6556
6557/// What a title's overlay is made from: a frame's size, how much of its text shows and its
6558/// motion. A title that does not move keeps the same key, so it is laid out once.
6559#[derive(Clone, Debug, PartialEq)]
6560struct TitleKey {
6561 width: u32,
6562 height: u32,
6563 size: u32,
6564 dx: i32,
6565 dy: i32,
6566 /// The letters drawn, or `None` for all of them.
6567 shown: Option<usize>,
6568}
6569
6570/// What a title draws at one frame, as a key: its size, where it is moved and how much of its
6571/// text shows, for a `width` x `height` picture. Preview and export both draw a title from this
6572/// same motion ([`Title::motion_at`]), so the animation reads the same in both.
6573fn title_key(title: &Title, motion: &Motion, width: u32, height: u32) -> TitleKey {
6574 let size = ((title.style.size as f32 * motion.scale).round() as u32)
6575 .clamp(crate::text::SIZE_RANGE.0, crate::text::SIZE_RANGE.1);
6576 TitleKey {
6577 width,
6578 height,
6579 size,
6580 dx: (motion.dx * width as f32).round() as i32,
6581 dy: (motion.dy * height as f32).round() as i32,
6582 shown: motion.revealed(&title.text).map(|s| s.ink),
6583 }
6584}
6585
6586/// The overlay a title's key stands for: the whole text laid out in the key's size and moved,
6587/// with the letters past its reveal left out of the drawing but not out of the layout.
6588fn title_overlay(title: &Title, key: &TitleKey) -> Overlay {
6589 let style = TextStyle { size: key.size, ..title.style.clone() };
6590 let lines: Vec<String> = title.text.split('\n').map(str::to_string).collect();
6591 let mut ov = match key.shown {
6592 None => overlay(&style, key.width, key.height, &lines),
6593 Some(ink) => crate::text::overlay_revealed(&style, key.width, key.height, &lines, ink),
6594 };
6595 if (key.dx, key.dy) != (0, 0) {
6596 ov = ov.moved(key.dx, key.dy);
6597 }
6598 ov
6599}
6600
6601impl Burn {
6602 /// What the settings and the timeline ask drawn in, or `None` for a picture
6603 /// left alone. A pick that is not a track of the project is named, not ignored.
6604 fn new(
6605 project: &Project,
6606 settings: &ExportSettings,
6607 fps: f64,
6608 full_range: bool,
6609 ) -> crate::Result<Option<Self>> {
6610 let titles = project.titles().to_vec();
6611 let (cues, style, native) = match &settings.burn_subtitles {
6612 Some((pick, style)) => {
6613 let (sources, cues): (Vec<usize>, Vec<Cue>) = burn_cues_indexed(project, *pick, fps)?.into_iter().unzip();
6614 let native = native_script(project, *pick, style).map(|captions| Native { captions, sources });
6615 (cues, style.clamped(), native)
6616 }
6617 None => (Vec::new(), TextStyle::default(), None),
6618 };
6619 if cues.is_empty() && titles.is_empty() && settings.burn_subtitles.is_none() {
6620 return Ok(None);
6621 }
6622 Ok(Some(Self {
6623 cues,
6624 style,
6625 fps,
6626 full_range,
6627 last: None,
6628 title_last: vec![None; titles.len()],
6629 titles,
6630 native,
6631 spare: None,
6632 narrow: Default::default(),
6633 merged: Default::default(),
6634 }))
6635 }
6636
6637 /// The picture at timeline frame `frame` with the titles on screen and the
6638 /// caption drawn in, or `None` where nothing is on screen and the planes go
6639 /// on untouched.
6640 fn quiet(&self, from: u32, to: u32) -> bool {
6641 (from..to).all(|f| {
6642 cues_on_screen(&self.cues, f, self.fps).is_empty() && self.titles.iter().all(|t| t.motion_at(f).is_none())
6643 })
6644 }
6645
6646 fn paint(
6647 &mut self,
6648 frame: u32,
6649 width: u32,
6650 height: u32,
6651 planes: (&[u8], &[u8], &[u8]),
6652 ) -> Option<Planes> {
6653 let mut out: Option<Planes> = None;
6654 for (i, t) in self.titles.iter().enumerate() {
6655 let Some(motion) = t.motion_at(frame) else {
6656 continue;
6657 };
6658 let alpha = motion.alpha;
6659 if alpha == 0 {
6660 continue;
6661 }
6662 let key = title_key(t, &motion, width, height);
6663 if !matches!(&self.title_last[i], Some((k, _)) if *k == key) {
6664 let ov = title_overlay(t, &key);
6665 self.title_last[i] = Some((key, ov));
6666 }
6667 let Some((_, ov)) = &self.title_last[i] else {
6668 continue;
6669 };
6670 let mut planes = out
6671 .take()
6672 .unwrap_or_else(|| copied(self.spare.take(), planes));
6673 if alpha == 255 {
6674 ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range);
6675 } else {
6676 ov.faded(alpha).blend_i420(
6677 &mut planes.0,
6678 &mut planes.1,
6679 &mut planes.2,
6680 self.full_range,
6681 );
6682 }
6683 out = Some(planes);
6684 }
6685 let on = cues_on_screen(&self.cues, frame, self.fps);
6686 if let Some(native) = self.native.as_mut() {
6687 if !on.is_empty() {
6688 let shown = native_shown(&self.cues, &native.sources, &on);
6689 let t_us = (f64::from(frame) / self.fps * 1e6).round() as i64;
6690 let mut planes = out
6691 .take()
6692 .unwrap_or_else(|| copied(self.spare.take(), planes));
6693 native.captions.draw_i420(
6694 (&mut planes.0, &mut planes.1, &mut planes.2),
6695 (width, height),
6696 self.full_range,
6697 &shown,
6698 t_us,
6699 );
6700 out = Some(planes);
6701 }
6702 return out;
6703 }
6704 if !on.is_empty() {
6705 // A static style is keyed by the cues alone, so a cache hit builds nothing.
6706 // A karaoke cue moves with the clock whatever the style, so it is planned too.
6707 let lit = on.iter().any(|&i| self.cues[i].real_karaoke().is_some());
6708 let planned = (!self.style.caption.is_plain() || lit)
6709 .then(|| crate::captionanim::plan(&self.style, &self.cues, &on, frame, self.fps));
6710 let key = planned.as_deref().map_or(0, crate::captionanim::blocks_key);
6711 let hit = matches!(&self.last, Some((i, w, h, k, _))
6712 if i == &on && (*w, *h) == (width, height) && *k == key);
6713 if !hit {
6714 let blocks = planned.unwrap_or_else(|| {
6715 crate::captionanim::plan(&self.style, &self.cues, &on, frame, self.fps)
6716 });
6717 let ov = overlay_blocks(&self.style, width, height, &blocks);
6718 self.last = Some((on, width, height, key, ov));
6719 }
6720 if let Some((_, _, _, _, ov)) = self.last.as_ref() {
6721 let mut planes = out
6722 .take()
6723 .unwrap_or_else(|| copied(self.spare.take(), planes));
6724 ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range);
6725 out = Some(planes);
6726 }
6727 }
6728 out
6729 }
6730}
6731
6732/// [`Burn::paint`] through an optional burn: the picture as it is when there is
6733/// no burn, and as it is with the caption drawn in when there is one.
6734fn burned(
6735 burn: &mut Option<Burn>,
6736 frame: u32,
6737 width: u32,
6738 height: u32,
6739 planes: (&[u8], &[u8], &[u8]),
6740) -> Option<Planes> {
6741 burn.as_mut()?.paint(frame, width, height, planes)
6742}
6743
6744/// A lone clip's effects stack drawn on its placed `w` x `h` picture in place, and
6745/// the result laid over black where the stack keys, masks or blends it -- what the
6746/// layered path draws for the same clip with nothing beneath ([`LayerStack::picture`]).
6747#[allow(clippy::too_many_arguments)]
6748fn effected<T: Sample>(
6749 effects: &[crate::effects::Effect],
6750 planes: &mut Planes<T>,
6751 w: u32,
6752 h: u32,
6753 secs: f64,
6754 src: f64,
6755 matrix: Matrix,
6756 scratch: &mut crate::effects::Scratch<T>,
6757) {
6758 let (w, h) = (w as usize, h as usize);
6759 let out = crate::effects::apply(effects, (&mut planes.0, &mut planes.1, &mut planes.2), w, h, secs, src, matrix, scratch);
6760 crate::effects::over_black((&mut planes.0, &mut planes.1, &mut planes.2), &out, matrix, w, h);
6761}
6762
6763/// One 8-bit code at 10 bits, as the encoder upshifts it (`v << 2 | v >> 6`), so a
6764/// widened black is the black of the 10-bit span.
6765fn widen_code(v: u8) -> u16 {
6766 (u16::from(v) << 2) | (u16::from(v) >> 6)
6767}
6768
6769/// [`widen_code`] over a plane, into `out`.
6770fn widen_into(src: &[u8], out: &mut Vec<u16>) {
6771 out.clear();
6772 out.extend(src.iter().map(|&v| widen_code(v)));
6773}
6774
6775/// [`burned`] at 10 bits. A caption or a title is an 8-bit overlay, so the picture is
6776/// narrowed for it; where the overlay changed a code, that code is written back
6777/// widened, and every other code keeps its 10-bit value.
6778fn copied(spare: Option<Planes>, planes: (&[u8], &[u8], &[u8])) -> Planes {
6779 let mut out = spare.unwrap_or_default();
6780 for (dst, src) in [(&mut out.0, planes.0), (&mut out.1, planes.1), (&mut out.2, planes.2)] {
6781 dst.clear();
6782 dst.extend_from_slice(src);
6783 }
6784 out
6785}
6786
6787fn narrow_into(src: &[u16], out: &mut Vec<u8>) {
6788 out.clear();
6789 out.extend(src.iter().map(|&c| (c >> 2) as u8));
6790}
6791
6792fn merge_into(orig: &[u16], before: &[u8], after: &[u8], out: &mut Vec<u16>) {
6793 out.clear();
6794 out.extend_from_slice(orig);
6795 const RUN: usize = 64;
6796 for ((o, b), a) in out.chunks_mut(RUN).zip(before.chunks(RUN)).zip(after.chunks(RUN)) {
6797 if a != b {
6798 for ((o, &b), &a) in o.iter_mut().zip(b).zip(a) {
6799 if a != b {
6800 *o = widen_code(a);
6801 }
6802 }
6803 }
6804 }
6805}
6806
6807fn burned16<'a>(
6808 burn: &'a mut Option<Burn>,
6809 frame: u32,
6810 width: u32,
6811 height: u32,
6812 planes: (&[u16], &[u16], &[u16]),
6813) -> Option<(&'a [u16], &'a [u16], &'a [u16])> {
6814 let burn = burn.as_mut()?;
6815 let mut narrow = std::mem::take(&mut burn.narrow);
6816 narrow_into(planes.0, &mut narrow.0);
6817 narrow_into(planes.1, &mut narrow.1);
6818 narrow_into(planes.2, &mut narrow.2);
6819 let painted = burn.paint(frame, width, height, (&narrow.0[..], &narrow.1[..], &narrow.2[..]));
6820 let Some(painted) = painted else {
6821 burn.narrow = narrow;
6822 return None;
6823 };
6824 merge_into(planes.0, &narrow.0, &painted.0, &mut burn.merged.0);
6825 merge_into(planes.1, &narrow.1, &painted.1, &mut burn.merged.1);
6826 merge_into(planes.2, &narrow.2, &painted.2, &mut burn.merged.2);
6827 burn.narrow = narrow;
6828 burn.spare = Some(painted);
6829 Some((&burn.merged.0[..], &burn.merged.1[..], &burn.merged.2[..]))
6830}
6831
6832/// The 10-bit placement's scratch: the turn, the pixel-aspect stretch, the grade and the
6833/// transform each want a buffer the planes come back borrowed from.
6834#[derive(Default)]
6835struct Scratch16 {
6836 turned: Planes16,
6837 stretched: Planes16,
6838 graded: Planes16,
6839 transformed: Planes16,
6840}
6841
6842/// [`place_picture`] at 10 bits: the pixel aspect, the display turn, the tone map, the grade,
6843/// the matrix and range remap and the transform, all on 10-bit samples, in the 8-bit order.
6844#[expect(clippy::too_many_arguments, reason = "one span's whole 10-bit picture path")]
6845fn place_picture16<'a>(
6846 y: &'a [u16],
6847 u: &'a [u16],
6848 v: &'a [u16],
6849 width: u32,
6850 height: u32,
6851 rotation: Rotation,
6852 pixel_aspect: crate::demux::PixelAspect,
6853 grade: Option<crate::color::ColorParams>,
6854 transform: TransformParams,
6855 remap: Option<Remap>,
6856 mapper: Option<&ToneMapper>,
6857 scratch: &'a mut Scratch16,
6858 canvas: &'a mut Composer,
6859) -> (&'a [u16], &'a [u16], &'a [u16], u32, u32) {
6860 let Scratch16 { turned, stretched, graded, transformed } = scratch;
6861 let (y, u, v, width, height) = if pixel_aspect.is_square() {
6862 (y, u, v, width, height)
6863 } else {
6864 let display_width = pixel_aspect.width_factor(width);
6865 let (dcw, dch) = (display_width.div_ceil(2) as usize, height.div_ceil(2) as usize);
6866 stretched.0.resize(display_width as usize * height as usize, 0);
6867 stretched.1.resize(dcw * dch, 0);
6868 stretched.2.resize(dcw * dch, 0);
6869 crate::scale::scale_i420(
6870 y,
6871 u,
6872 v,
6873 width as usize,
6874 height as usize,
6875 &mut stretched.0,
6876 &mut stretched.1,
6877 &mut stretched.2,
6878 display_width as usize,
6879 height as usize,
6880 );
6881 (&stretched.0[..], &stretched.1[..], &stretched.2[..], display_width, height)
6882 };
6883 let (y, u, v, width, height) = match rotation.is_none() {
6884 true => (y, u, v, width, height),
6885 false => {
6886 let (w, h) = crate::scale::rotate_i420_90s_into(y, u, v, width, height, rotation.steps(), turned);
6887 (&turned.0[..], &turned.1[..], &turned.2[..], w, h)
6888 }
6889 };
6890 let params = grade.filter(|p| !p.is_identity());
6891 let (y, u, v) = match (params, remap, mapper) {
6892 (None, None, None) => (y, u, v),
6893 (params, remap, mapper) => {
6894 let (gy, gu, gv) = graded;
6895 gy.clear();
6896 gy.extend_from_slice(y);
6897 gu.clear();
6898 gu.extend_from_slice(u);
6899 gv.clear();
6900 gv.extend_from_slice(v);
6901 if let Some(mapper) = mapper {
6902 mapper.map16(gy, gu, gv, width as usize, height as usize);
6903 }
6904 if let Some(params) = params {
6905 crate::color::apply_yuv_wide(&params, gy, gu, gv, width as usize, remap.is_some_and(|r| r.limit));
6906 }
6907 if let Some(remap) = remap {
6908 if remap.limit {
6909 crate::colorspace::limit_range::<u16>(gy, gu, gv);
6910 }
6911 crate::colorspace::remap::<u16>(remap.from, remap.to, gy, gu, gv, width as usize);
6912 }
6913 (&gy[..], &gu[..], &gv[..])
6914 }
6915 };
6916 if transform.is_identity() {
6917 canvas.place_wide(y, u, v, width, height)
6918 } else {
6919 let (py, pu, pv, w, h) = canvas.place_transformed_wide(y, u, v, width, height, &transform);
6920 *transformed = (py, pu, pv);
6921 (&transformed.0[..], &transformed.1[..], &transformed.2[..], w, h)
6922 }
6923}
6924
6925/// One decoded picture turned, graded, tone-mapped, remapped and placed on the
6926/// canvas -- everything between a source's own samples and the ones an encoder
6927/// is fed, which is exactly the work a zero-copy span has none of.
6928///
6929/// `rotation` first, before the grade: it is the file's own display matrix, the
6930/// turn a player would make before showing the picture at all, and everything
6931/// after this -- the grade, the letterbox, the encoder -- is about the picture
6932/// as it is *meant* to be seen. `turned`, `graded` and `canvas` are the span's
6933/// scratch: the planes come back borrowed from one of them, or from the picture
6934/// itself where not a byte was touched.
6935#[expect(clippy::too_many_arguments, reason = "one span's whole picture path")]
6936fn place_picture<'a>(
6937 y: &'a [u8],
6938 u: &'a [u8],
6939 v: &'a [u8],
6940 width: u32,
6941 height: u32,
6942 rotation: Rotation,
6943 pixel_aspect: crate::demux::PixelAspect,
6944 grade: Option<crate::color::ColorParams>,
6945 transform: TransformParams,
6946 remap: Option<Remap>,
6947 mapper: Option<&ToneMapper>,
6948 turned: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
6949 stretched: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
6950 graded: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
6951 transformed: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>),
6952 canvas: &'a mut Composer,
6953) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) {
6954 // The pixel aspect, applied exactly once -- the same single conversion to
6955 // the square-pixel raster the decode funnel makes, in the same order
6956 // (stretch the coded width, *then* turn, [`crate::decode::Render::frame`]'s
6957 // comment carries the 1440x1440 failure the other order produces). A
6958 // square-pixel file -- every file whose samples are one to one -- borrows
6959 // the planes through.
6960 let (y, u, v, width, height) = if pixel_aspect.is_square() {
6961 (y, u, v, width, height)
6962 } else {
6963 let display_width = pixel_aspect.width_factor(width);
6964 let (dcw, dch) = (
6965 display_width.div_ceil(2) as usize,
6966 height.div_ceil(2) as usize,
6967 );
6968 stretched
6969 .0
6970 .resize(display_width as usize * height as usize, 0);
6971 stretched.1.resize(dcw * dch, 0);
6972 stretched.2.resize(dcw * dch, 0);
6973 crate::scale::scale_i420(
6974 y,
6975 u,
6976 v,
6977 width as usize,
6978 height as usize,
6979 &mut stretched.0,
6980 &mut stretched.1,
6981 &mut stretched.2,
6982 display_width as usize,
6983 height as usize,
6984 );
6985 (
6986 &stretched.0[..],
6987 &stretched.1[..],
6988 &stretched.2[..],
6989 display_width,
6990 height,
6991 )
6992 };
6993 // The file's own turn, taken exactly as playback's decode funnel takes it
6994 // ([`crate::decode`]): a phone's portrait video is landscape in the file,
6995 // and the encoder must be fed what the preview showed. A file that states
6996 // no turn skips this entirely -- the planes go on borrowed.
6997 let (y, u, v, width, height) = match rotation.is_none() {
6998 true => (y, u, v, width, height),
6999 false => {
7000 let (w, h) = crate::scale::rotate_i420_90s_into(
7001 y,
7002 u,
7003 v,
7004 width,
7005 height,
7006 rotation.steps(),
7007 turned,
7008 );
7009 (&turned.0[..], &turned.1[..], &turned.2[..], w, h)
7010 }
7011 };
7012 // The planes are borrowed from the decoder (and `Black::picture` hands the
7013 // same slice as both u and v), so a grade cannot be applied in place: it
7014 // goes onto a copy, which the encoder then reads instead.
7015 let params = grade.filter(|p| !p.is_identity());
7016 let (y, u, v) = match (params, remap, mapper) {
7017 (None, None, None) => (y, u, v),
7018 (params, remap, mapper) => {
7019 let (gy, gu, gv) = graded;
7020 gy.clear();
7021 gy.extend_from_slice(y);
7022 gu.clear();
7023 gu.extend_from_slice(u);
7024 gv.clear();
7025 gv.extend_from_slice(v);
7026 // Tone-map first, so the grade is applied to the SDR picture the
7027 // canvas showed and not to HDR codes; then remap the graded result.
7028 // The order playback renders in, and the only order in which
7029 // preview and export agree.
7030 if let Some(mapper) = mapper {
7031 mapper.map(gy, gu, gv, width as usize, height as usize);
7032 }
7033 if let Some(params) = params {
7034 crate::color::apply_yuv(&params, gy, gu, gv, width as usize, remap.is_some_and(|r| r.limit));
7035 }
7036 if let Some(remap) = remap {
7037 // Range before matrix: the matrix arithmetic is written for limited
7038 // codes, so a full-range picture is brought into that span first.
7039 if remap.limit {
7040 crate::colorspace::limit_range(gy, gu, gv);
7041 }
7042 crate::colorspace::remap(remap.from, remap.to, gy, gu, gv, width as usize);
7043 }
7044 (&gy[..], &gu[..], &gv[..])
7045 }
7046 };
7047 // Grade first, place second: the grade is the clip's own pixels and the
7048 // bars around them are not the clip (see `scale::Composer`).
7049 if transform.is_identity() {
7050 canvas.place(y, u, v, width, height)
7051 } else {
7052 let (py, pu, pv, w, h) = canvas.place_transformed(y, u, v, width, height, &transform);
7053 *transformed = (py, pu, pv);
7054 (
7055 &transformed.0[..],
7056 &transformed.1[..],
7057 &transformed.2[..],
7058 w,
7059 h,
7060 )
7061 }
7062}
7063
7064/// How a span's samples are rewritten on the way into a file whose own matrix is
7065/// `to` and whose range is limited ([`ColorDescription::output`]): the matrix they
7066/// are coded against, and whether they span the full byte and so need scaling
7067/// into the limited span first ([`crate::colorspace::limit_range`]).
7068#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7069struct Remap {
7070 from: Matrix,
7071 to: Matrix,
7072 limit: bool,
7073}
7074
7075/// What [`place_picture`] rewrites a span's samples by -- `None` when they are
7076/// already coded against the output's matrix and span its range, and for a gap,
7077/// whose 16/128/128 black is black in every matrix here.
7078///
7079/// `toned` says the tone map ran on this span: it hands back BT.709 SDR whatever
7080/// the source was coded as, so an HDR clip is never *also* given the matrix
7081/// treatment its BT.2020 tag would ask for -- one conversion or the other, never
7082/// both on one frame -- while a tone-mapped clip on a canvas below 720 lines
7083/// still takes its 709 -> 601 step. It is also limited range already, so only an
7084/// untouched full-range source is scaled here.
7085fn remap_into(color: Option<ColorDescription>, toned: bool, out: Matrix) -> Option<Remap> {
7086 let from = match toned {
7087 true => Matrix::Bt709,
7088 false => color?.matrix,
7089 };
7090 let limit = !toned && color?.full_range;
7091 (from != out || limit).then_some(Remap {
7092 from,
7093 to: out,
7094 limit,
7095 })
7096}
7097
7098/// The picture at timeline `frame`, composed the way [`run`] composes it: the
7099/// same span and source frame, placed by [`place_picture`] (turn, pixel aspect,
7100/// grade, transform, tone map, fit), dissolved into its successor over the
7101/// tail window, and written as the BGRA picture the encoder would have been
7102/// given. A gap is black. Visualizer and still clips take the same decoders
7103/// export does.
7104///
7105/// The output is the project's resolution scaled to fit a `width` x `height`
7106/// box at the project's aspect (so a 16:9 project asked for 640x480 comes back
7107/// 640x360). Each call opens its own decoder for the one source frame it needs,
7108/// so it costs a decoder start; it is for the frame an agent asks for, not a
7109/// sequence.
7110pub fn compose_at(
7111 project: &Project,
7112 meta: &VideoMeta,
7113 frame: u32,
7114 width: u32,
7115 height: u32,
7116) -> crate::Result<crate::decode::Frame> {
7117 compose_at_with(project, meta, frame, width, height, None)
7118}
7119
7120/// [`compose_at`] with every clip's grade taken off (its colour, its keys and
7121/// its LUT): the picture as shot, which is the preview's "before" side and the
7122/// frame Auto reads. A copy of the timeline is graded-off, so `project` is left
7123/// as it is; nothing here is exported. Sequences a compound clip plays keep
7124/// their own grades.
7125pub fn compose_ungraded_at(project: &Project, meta: &VideoMeta, frame: u32, width: u32, height: u32) -> crate::Result<crate::decode::Frame> {
7126 let mut plain = project.clone();
7127 for lane in plain.lanes() {
7128 for idx in 0..plain.lane(lane).len() {
7129 if !plain.color_keys_of(lane, idx).is_empty() {
7130 plain.set_color_keys(lane, idx, Vec::new());
7131 }
7132 plain.set_color(lane, idx, None);
7133 }
7134 }
7135 compose_at(&plain, meta, frame, width, height)
7136}
7137
7138/// [`compose_at`] with captions drawn in: `burn` is the subtitle track's index
7139/// in [`Project::subtitles`] and the style, as [`ExportSettings::burn_subtitles`]
7140/// takes them, and the cue on screen at `frame` is drawn over the output at its
7141/// own size. `None` is exactly [`compose_at`].
7142pub fn compose_at_with(
7143 project: &Project,
7144 meta: &VideoMeta,
7145 frame: u32,
7146 width: u32,
7147 height: u32,
7148 burn: Option<(usize, TextStyle)>,
7149) -> crate::Result<crate::decode::Frame> {
7150 let end = project.media_frames();
7151 if frame >= end {
7152 return Err(format!("frame {frame} is past the end of the timeline ({end} frames)").into());
7153 }
7154 if width == 0 || height == 0 {
7155 return Err("compose_at: the output size must be non-zero".into());
7156 }
7157 let out = ColorDescription::output_sized(meta.width, meta.height);
7158 let span = export_spans(project, None)
7159 .into_iter()
7160 .find(|s| s.start <= frame && frame - s.start < s.len);
7161 let layered = layered_at(project, frame);
7162 let (y, u, v) = match span {
7163 // Two or more clips cover the frame: each is decoded at this frame and
7164 // composed bottom to top, exactly as the export composes it.
7165 _ if layered => {
7166 let stack = stack_at(project, frame);
7167 let mut layers = LayerStack::open(project, meta, &stack, out.matrix, None, None)?;
7168 layers
7169 .picture(frame)?
7170 .ok_or_else(|| -> crate::Error {
7171 format!("compose_at: a clip ends before frame {frame}").into()
7172 })?
7173 }
7174 Some(s) if s.from.is_some() => {
7175 let (source, in_frame) = s.from.expect("checked above");
7176 let offset = frame - s.start;
7177 let mut a = placed_info(project, meta, source)?;
7178 let deint = span_deint(project, s.start, &a.path);
7179 a.rate = crate::deinterlace::counted_rate(deint, a.rate);
7180 let source_frame = a.rate.source_at(s.source_at(in_frame, offset));
7181 let (ay, au, av) = picture_at(project, meta, &a, source_frame, s.start, out.matrix, deint)?;
7182 match dissolve_window(project, &s) {
7183 Some((b_source, b_in, window, b_start))
7184 if offset >= s.len.saturating_sub(window) =>
7185 {
7186 let k = offset - (s.len - window);
7187 let mut b = placed_info(project, meta, b_source)?;
7188 let b_deint = frame_counting(span_deint(project, b_start, &b.path));
7189 b.rate = crate::deinterlace::counted_rate(b_deint, b.rate);
7190 let b_frame = b.rate.source_at(b_in) + k;
7191 let (by, bu, bv) = picture_at(project, meta, &b, b_frame, b_start, out.matrix, b_deint)?;
7192 crate::transitions::blend_planes(
7193 crate::transitions::kind_at(project, s.start),
7194 (&ay, &au, &av),
7195 (&by, &bu, &bv),
7196 dissolve_weight(k, window),
7197 meta.width as usize,
7198 meta.height as usize,
7199 )
7200 }
7201 _ => (ay, au, av),
7202 }
7203 }
7204 _ => {
7205 let (w, h) = (meta.width as usize, meta.height as usize);
7206 (
7207 vec![16; w * h],
7208 vec![128; w.div_ceil(2) * h.div_ceil(2)],
7209 vec![128; w.div_ceil(2) * h.div_ceil(2)],
7210 )
7211 }
7212 };
7213 // A layered picture's fades were applied per clip inside its stack.
7214 let (y, u, v) = match picture_fade_at(project, frame).filter(|_| !layered) {
7215 Some(k) => fade_planes((&y, &u, &v), k),
7216 None => (y, u, v),
7217 };
7218 let bgra =
7219 crate::convert::i420_to_bgra(&out, &y, &u, &v, meta.width as usize, meta.height as usize);
7220 let (tw, th) = fit_box(meta.width, meta.height, width, height);
7221 let mut bgra = if (tw, th) == (meta.width, meta.height) {
7222 bgra
7223 } else {
7224 resize_bgra(&bgra, meta.width, meta.height, tw, th)
7225 };
7226 // The titles, then the caption, drawn at the size the caller gets, so their
7227 // size reads the same whatever the output box was asked for.
7228 for title in project.titles() {
7229 let Some(motion) = title.motion_at(frame) else {
7230 continue;
7231 };
7232 let alpha = motion.alpha;
7233 if alpha == 0 {
7234 continue;
7235 }
7236 let ov = title_overlay(title, &title_key(title, &motion, tw, th));
7237 if alpha == 255 {
7238 ov.blend_bgra(&mut bgra);
7239 } else {
7240 ov.faded(alpha).blend_bgra(&mut bgra);
7241 }
7242 }
7243 if let Some((pick, style)) = burn {
7244 let (sources, cues): (Vec<usize>, Vec<Cue>) = burn_cues_indexed(project, pick, meta.frame_rate)?.into_iter().unzip();
7245 let on = cues_on_screen(&cues, frame, meta.frame_rate);
7246 match native_script(project, pick, &style).map(|c| c.for_video_height(meta.height)) {
7247 Some(mut captions) => {
7248 let shown = native_shown(&cues, &sources, &on);
7249 let t_us = (f64::from(frame) / meta.frame_rate * 1e6).round() as i64;
7250 captions.draw_bgra(&mut bgra, (tw, th), &shown, t_us);
7251 }
7252 None if !on.is_empty() => {
7253 let style = style.clamped();
7254 let blocks = crate::captionanim::plan(&style, &cues, &on, frame, meta.frame_rate);
7255 overlay_blocks(&style, tw, th, &blocks).blend_bgra(&mut bgra);
7256 }
7257 None => {}
7258 }
7259 }
7260 Ok(crate::decode::Frame {
7261 index: frame,
7262 width: tw,
7263 height: th,
7264 bgra,
7265 })
7266}
7267
7268/// A source as [`run`] reads it for placement: its path and audio stream, its
7269/// rate against the timeline, its colour, the tone map its curve asks for, and
7270/// its display-matrix turn and pixel aspect.
7271struct Placed {
7272 path: PathBuf,
7273 stream: usize,
7274 rate: Rate,
7275 color: ColorDescription,
7276 mapper: Option<ToneMapper>,
7277 rotation: Rotation,
7278 pixel_aspect: crate::demux::PixelAspect,
7279}
7280
7281/// The deinterlace setting of the clip the composite shows at `frame`, as it
7282/// applies to `path` (`Frame` for anything but interlaced H.264).
7283fn span_deint(project: &Project, frame: u32, path: &Path) -> Deinterlace {
7284 let mode = project
7285 .composite_clip_at(frame)
7286 .map_or(Deinterlace::Frame, |(lane, idx)| project.deinterlace_of(lane, idx));
7287 crate::deinterlace::effective(mode, path)
7288}
7289
7290/// `Field` counts two pictures a frame, which a picture-per-timeline-frame reader
7291/// cannot follow: it takes `Frame` (the same first field at the file's own rate).
7292fn frame_counting(mode: Deinterlace) -> Deinterlace {
7293 if mode == Deinterlace::Field { Deinterlace::Frame } else { mode }
7294}
7295
7296fn placed_info(project: &Project, meta: &VideoMeta, source: usize) -> crate::Result<Placed> {
7297 let sources = project.sources();
7298 let entry = sources
7299 .get(source)
7300 .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?;
7301 let (rate, color, peak, rotation, pixel_aspect) = source_rate(&entry.path, meta.frame_rate);
7302 let mapper = match color.transfer {
7303 Transfer::Sdr => None,
7304 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, project.tone(), peak)),
7305 Transfer::Hlg => Some(ToneMapper::new(
7306 tonemap::Transfer::Hlg,
7307 project.tone(),
7308 peak,
7309 )),
7310 };
7311 Ok(Placed {
7312 path: entry.path.clone(),
7313 stream: entry.audio_stream,
7314 rate,
7315 color,
7316 mapper,
7317 rotation,
7318 pixel_aspect,
7319 })
7320}
7321
7322/// One source picture at `source_frame`, placed as [`run`] places it, as owned
7323/// planes at the project's size. `key` is the timeline frame whose grade,
7324/// transform, fit and visualizer state apply.
7325fn picture_at(
7326 project: &Project,
7327 meta: &VideoMeta,
7328 info: &Placed,
7329 source_frame: u32,
7330 key: u32,
7331 out: Matrix,
7332 deint: Deinterlace,
7333) -> crate::Result<(Vec<u8>, Vec<u8>, Vec<u8>)> {
7334 let flags = project.composite_visualizer_at(key);
7335 let mut decoder = if crate::is_audio(&info.path) || flags & 1 != 0 {
7336 ClipDecoder::visualizer(
7337 &info.path,
7338 info.stream,
7339 source_frame,
7340 (meta.width, meta.height),
7341 meta.frame_rate,
7342 flags,
7343 project.composite_viz_paint_at(key),
7344 )?
7345 } else {
7346 ClipDecoder::open_with(&info.path, source_frame, None, None, false, deint)?
7347 };
7348 let Some(picture) = decoder.next()? else {
7349 return Err(format!("{} ends before frame {source_frame}", info.path.display()).into());
7350 };
7351 let Frame::Pixels(y, u, v, width, height) = picture else {
7352 return Err("a single-frame decode produced no pixels".into());
7353 };
7354 let remap = remap_into(Some(info.color), info.mapper.is_some(), out);
7355 let grade = project.composite_color_at(key).copied();
7356 let transform = project
7357 .composite_transform_at(key)
7358 .copied()
7359 .unwrap_or_default();
7360 let mut canvas = Composer::new(meta.width, meta.height, project.composite_fit_at(key));
7361 let (mut rotated, mut stretched, mut graded, mut transformed) = Default::default();
7362 let (py, pu, pv, _, _) = place_picture(
7363 y,
7364 u,
7365 v,
7366 width,
7367 height,
7368 info.rotation,
7369 info.pixel_aspect,
7370 grade,
7371 transform,
7372 remap,
7373 info.mapper.as_ref(),
7374 &mut rotated,
7375 &mut stretched,
7376 &mut graded,
7377 &mut transformed,
7378 &mut canvas,
7379 );
7380 Ok((py.to_vec(), pu.to_vec(), pv.to_vec()))
7381}
7382
7383/// The largest size with the project's `w:h` aspect that fits in `bw` x `bh`.
7384fn fit_box(w: u32, h: u32, bw: u32, bh: u32) -> (u32, u32) {
7385 let (w, h, bw, bh) = (w as u64, h as u64, bw as u64, bh as u64);
7386 let th = (bw * h / w).max(1);
7387 if th <= bh {
7388 (bw as u32, th as u32)
7389 } else {
7390 let tw = (bh * w / h).max(1);
7391 (tw as u32, bh as u32)
7392 }
7393}
7394
7395/// Box-filter resize of a tightly packed BGRA picture. Each destination pixel
7396/// averages the source pixels it covers, so an upscale is nearest-neighbour
7397/// and a downscale is an area average; no float, so it is byte-stable.
7398fn resize_bgra(src: &[u8], sw: u32, sh: u32, dw: u32, dh: u32) -> Vec<u8> {
7399 fn cover(i: usize, src: usize, dst: usize) -> (usize, usize) {
7400 let a = i * src / dst;
7401 let b = ((i + 1) * src / dst).max(a + 1).min(src);
7402 (a, b)
7403 }
7404 let (sw, sh, dw, dh) = (sw as usize, sh as usize, dw as usize, dh as usize);
7405 let mut out = vec![0u8; dw * dh * 4];
7406 for dy in 0..dh {
7407 let (y0, y1) = cover(dy, sh, dh);
7408 for dx in 0..dw {
7409 let (x0, x1) = cover(dx, sw, dw);
7410 let mut acc = [0u32; 4];
7411 for y in y0..y1 {
7412 for x in x0..x1 {
7413 let p = (y * sw + x) * 4;
7414 for (c, a) in acc.iter_mut().enumerate() {
7415 *a += src[p + c] as u32;
7416 }
7417 }
7418 }
7419 let n = ((y1 - y0) * (x1 - x0)) as u32;
7420 let q = (dy * dw + dx) * 4;
7421 for (c, a) in acc.iter().enumerate() {
7422 out[q + c] = ((a + n / 2) / n) as u8;
7423 }
7424 }
7425 }
7426 out
7427}
7428
7429/// What rate `path` was shot at against a timeline at `timeline_fps`
7430/// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own
7431/// -- a still, a song -- and for one that will not open here: the decoder is
7432/// opened a few lines later and fails the export by name, which is a better
7433/// error than this one could raise.
7434fn source_rate(
7435 path: &Path,
7436 timeline_fps: f64,
7437) -> (
7438 Rate,
7439 ColorDescription,
7440 Option<f32>,
7441 Rotation,
7442 crate::demux::PixelAspect,
7443) {
7444 if crate::is_image(path) || crate::is_audio(path) {
7445 // A still is BT.601 by construction whatever it was authored as:
7446 // `decode::rgb_to_i420` is the one matrix that turns its pixels into
7447 // planes. A song has no picture and the answer is never read. Neither
7448 // has a display matrix to be turned by, nor an aspect to be widened
7449 // by: both are authored square. A still's *EXIF* turn is not in this
7450 // arm either, and for a better reason -- `decode::Still::open` already
7451 // made it before the planes were written, so `place_picture` is handed
7452 // the picture the preview showed and must not be told to turn it again.
7453 return (
7454 Rate::REAL_TIME,
7455 ColorDescription::default(),
7456 None,
7457 Rotation::None,
7458 crate::demux::PixelAspect::SQUARE,
7459 );
7460 }
7461 match Demuxer::open(path) {
7462 // ...and one whose rate cannot be named against the timeline's, which
7463 // `matches_timeline` refuses at import, so nothing on a timeline is on
7464 // this arm either.
7465 //
7466 // The declared peak comes off the same open the space does, which is
7467 // what keeps export on the number playback's decode funnel read: one
7468 // header parse, both answers.
7469 Ok((meta, demuxer)) => (
7470 Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME),
7471 meta.color,
7472 demuxer.light().peak(),
7473 // The file's own turn, so the encoder is fed the picture the
7474 // preview shows: the same header read, one more answer.
7475 meta.rotation,
7476 // ...and its own sample aspect, for the same reason on the same
7477 // read: the encoder is fed the shape the preview showed.
7478 meta.pixel_aspect,
7479 ),
7480 // Unreadable here means unreadable below too, where the span dies with a
7481 // real message; the file's own space is the least of that.
7482 Err(_) => (
7483 Rate::REAL_TIME,
7484 ColorDescription::default(),
7485 None,
7486 Rotation::None,
7487 crate::demux::PixelAspect::SQUARE,
7488 ),
7489 }
7490}
7491
7492/// The audio lanes alone, summed, as a WAV or a FLAC.
7493///
7494/// Nothing here re-derives the edit: the play lists are
7495/// [`Project::audio_segments_from`] and they are handed to the very
7496/// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written
7497/// is what was heard -- every lane, mixed the same way, gaps included, which
7498/// arrive as real silence from that choke point rather than as a hole this would
7499/// have to invent.
7500///
7501/// The length is the *timeline's*: each segment resolves its window to whole
7502/// samples on its own, so the sum can miss the timeline by a sample or two, and
7503/// a source that runs out early would leave the file short. Both are settled by
7504/// one `resize` at the end -- padding with silence, trimming what overshot --
7505/// so an exported file is exactly as long as what was edited.
7506/// The timeline frames a picture export covers: its range, clipped to the media, or the whole media.
7507fn picture_span(project: &Project, settings: &ExportSettings) -> (u32, u32) {
7508 let media = project.media_frames();
7509 match settings.range {
7510 Some((from, to)) => {
7511 let from = from.min(media);
7512 (from, to.min(media).max(from))
7513 }
7514 None => (0, media),
7515 }
7516}
7517
7518/// The picture at timeline frame `frame` as a PNG file's bytes, at the project's own size. What
7519/// the still formats write: [`compose_at_with`] draws it as the export would, titles and burnt
7520/// captions included.
7521fn still_png(project: &Project, meta: &VideoMeta, frame: u32, settings: &ExportSettings) -> crate::Result<Vec<u8>> {
7522 let picture = compose_at_with(project, meta, frame, meta.width, meta.height, settings.burn_subtitles.clone())?;
7523 crate::decode::to_png_bytes(&picture)
7524}
7525
7526/// A numbered PNG run ([`Format::PngSequence`]) into the folder `out`, one file per frame,
7527/// named after the folder: `name_00001.png`. A run that fails part way leaves no files behind.
7528fn run_png_sequence(
7529 project: &Project,
7530 meta: &VideoMeta,
7531 out: &Path,
7532 shared: &Arc<Shared>,
7533 settings: &ExportSettings,
7534) -> crate::Result<()> {
7535 let (from, to) = picture_span(project, settings);
7536 let total = to - from;
7537 std::fs::create_dir_all(out)?;
7538 let name = out.file_name().and_then(|n| n.to_str()).unwrap_or("frame").to_string();
7539 let mut written: Vec<PathBuf> = Vec::new();
7540 let result = (|| -> crate::Result<()> {
7541 for k in 0..total {
7542 cancelled(shared)?;
7543 let path = out.join(format!("{name}_{:05}.png", k + 1));
7544 std::fs::write(&path, still_png(project, meta, from + k, settings)?)?;
7545 written.push(path);
7546 shared.progress.fetch_max(picture_progress(k + 1, total), Ordering::Relaxed);
7547 }
7548 Ok(())
7549 })();
7550 if result.is_err() {
7551 for path in &written {
7552 let _ = std::fs::remove_file(path);
7553 }
7554 }
7555 result
7556}
7557
7558/// The poster frame ([`Format::Still`]): the picture at the start of the range, written to `part`
7559/// for the caller to publish.
7560fn run_still(project: &Project, meta: &VideoMeta, part: &Path, settings: &ExportSettings) -> crate::Result<()> {
7561 let frame = settings.range.map_or(0, |(from, _)| from);
7562 std::fs::write(part, still_png(project, meta, frame, settings)?)?;
7563 Ok(())
7564}
7565
7566/// The animated GIF ([`Format::Gif`]): the range sampled at [`GifSettings::fps`], each picture
7567/// composed at [`GifSettings::width`], handed to the GIF writer one frame at a time.
7568fn run_gif(
7569 project: &Project,
7570 meta: &VideoMeta,
7571 part: &Path,
7572 shared: &Arc<Shared>,
7573 settings: &ExportSettings,
7574) -> crate::Result<()> {
7575 let gif = settings.gif;
7576 // The encoder holds every frame until `finish`, so a GIF is bounded in what it can hold.
7577 if gif.width == 0 || gif.width > GIF_MAX_WIDTH || gif.fps == 0 || gif.fps > 60 {
7578 return Err(format!("a GIF is 1 to {GIF_MAX_WIDTH} pixels wide and 1 to 60 frames a second").into());
7579 }
7580 let (from, to) = picture_span(project, settings);
7581 if f64::from(to - from) / meta.frame_rate > GIF_MAX_SECS {
7582 return Err(format!("a GIF is at most {GIF_MAX_SECS} s long: export a shorter range").into());
7583 }
7584 let (width, height) = fit_box(meta.width, meta.height, gif.width, GIF_MAX_WIDTH);
7585 let mut writer = GifWriter::open(width, height, gif.loop_forever)?;
7586 let fps = f64::from(gif.fps);
7587 let frames = ((f64::from(to - from) * fps) / meta.frame_rate).ceil() as u32;
7588 if frames == 0 {
7589 return Err("the range holds no frames".into());
7590 }
7591 for i in 0..frames {
7592 cancelled(shared)?;
7593 // The timeline frame this GIF frame shows, and how long it holds: the hundredths of a
7594 // second between this frame's start and the next, so the rounding never drifts.
7595 let at = ((f64::from(i) * meta.frame_rate) / fps) as u32;
7596 let shown = from + at.min(to - from - 1);
7597 let next = (f64::from(i + 1) * 100.0 / fps).round() as u32;
7598 let delay = (next - (f64::from(i) * 100.0 / fps).round() as u32).max(1) as u16;
7599 let picture = compose_at_with(project, meta, shown, width, height, settings.burn_subtitles.clone())?;
7600 let rgba: Vec<u8> = picture
7601 .bgra
7602 .as_chunks::<4>()
7603 .0
7604 .iter()
7605 .flat_map(|px| [px[2], px[1], px[0], 255])
7606 .collect();
7607 writer.push(&rgba, delay)?;
7608 shared.progress.fetch_max(picture_progress(i + 1, frames), Ordering::Relaxed);
7609 }
7610 std::fs::write(part, writer.finish()?)?;
7611 Ok(())
7612}
7613
7614/// The widest GIF, and the longest: the encoder keeps every frame until it is finished.
7615const GIF_MAX_WIDTH: u32 = 720;
7616const GIF_MAX_SECS: f64 = 30.0;
7617
7618/// The GIF writer, over `ec_image::gif_encode`: 256 colours with dithering (video gradients band
7619/// badly without it), looping forever or playing once.
7620struct GifWriter(ec_image::gif_encode::Encoder);
7621
7622impl GifWriter {
7623 fn open(width: u32, height: u32, loop_forever: bool) -> crate::Result<Self> {
7624 let opts = ec_image::gif_encode::GifOptions {
7625 loop_count: if loop_forever { Some(0) } else { None },
7626 max_colors: 256,
7627 dither: true,
7628 };
7629 let encoder = ec_image::gif_encode::Encoder::new(width as u16, height as u16, opts)
7630 .map_err(|e| format!("GIF: {e}"))?;
7631 Ok(Self(encoder))
7632 }
7633
7634 fn push(&mut self, rgba: &[u8], delay_cs: u16) -> crate::Result<()> {
7635 self.0.push_rgba8(rgba, delay_cs).map_err(|e| format!("GIF: {e}").into())
7636 }
7637
7638 fn finish(self) -> crate::Result<Vec<u8>> {
7639 self.0.finish().map_err(|e| format!("GIF: {e}").into())
7640 }
7641}
7642
7643fn run_audio(
7644 project: &Project,
7645 meta: &VideoMeta,
7646 out: &Path,
7647 shared: &Shared,
7648 settings: &ExportSettings,
7649 sample_rate: Option<u32>,
7650) -> crate::Result<()> {
7651 let format = settings.format;
7652 let (samples, audio) = mix_pcm(project, meta, shared, settings, sample_rate, 16)?
7653 .ok_or("this timeline has no audio to export")?;
7654 // Written in one go and still cancellable up to here, exactly as the mp4
7655 // path is up to its `finish`: the `.part` is what either gets renamed or
7656 // deleted.
7657 cancelled(shared)?;
7658 match format {
7659 Format::Wav => write_wav(out, &samples, &audio)?,
7660 Format::Flac => write_flac(out, &samples, &audio)?,
7661 Format::Mp3 => write_mp3(out, &samples, &audio, audio_kbps_of(settings))?,
7662 Format::Ogg => write_ogg(out, &samples, &audio)?,
7663 Format::Opus => write_opus(out, &samples, &audio, project, settings, shared)?,
7664 _ => unreachable!("the picture formats are `run`"),
7665 }
7666 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
7667 Ok(())
7668}
7669
7670/// The sample width of a ProRes file's PCM sound: 24 unless
7671/// [`ExportSettings::audio_bit_depth`] says 16.
7672fn prores_audio_bits(settings: &ExportSettings) -> u8 {
7673 match settings.audio_bit_depth {
7674 Some(16) => 16,
7675 _ => 24,
7676 }
7677}
7678
7679/// The ProRes file's sound pass: the mix as `bits`-wide samples, `(samples, rate,
7680/// channels)`, or `None` for a timeline with no sound. Runs beside the picture.
7681fn mix_pcm16(
7682 project: &Project,
7683 meta: &VideoMeta,
7684 shared: &Shared,
7685 settings: &ExportSettings,
7686 sample_rate: Option<u32>,
7687 bits: u8,
7688) -> crate::Result<Option<(Vec<i32>, u32, u16)>> {
7689 Ok(mix_pcm(project, meta, shared, settings, sample_rate, bits)?
7690 .map(|(samples, audio)| (samples, audio.sample_rate, audio.channels)))
7691}
7692
7693/// A running ProRes sound pass, joined when dropped for the reason [`AudioPass`] is.
7694struct PcmPass(Option<PcmJob>);
7695
7696/// The ProRes sound pass's thread: `(samples, rate, channels)` or `None` for no sound.
7697type PcmJob = thread::JoinHandle<crate::Result<Option<(Vec<i32>, u32, u16)>>>;
7698
7699impl PcmPass {
7700 fn take(&mut self) -> Option<PcmJob> {
7701 self.0.take()
7702 }
7703}
7704
7705impl Drop for PcmPass {
7706 fn drop(&mut self) {
7707 if let Some(job) = self.0.take() {
7708 let _ = job.join();
7709 }
7710 }
7711}
7712
7713fn join_pcm(job: PcmJob) -> crate::Result<Option<(Vec<i32>, u32, u16)>> {
7714 job.join()
7715 .map_err(|_| crate::Error::from("the sound pass stopped without a picture or a reason"))?
7716}
7717
7718/// The audio lanes mixed to 16-bit samples (in an `i32`), the length of the
7719/// range: [`run_audio`]'s body up to the write, so a WAV and a ProRes file's PCM
7720/// track are the same mix. `None` where the timeline has no sound.
7721fn mix_pcm(
7722 project: &Project,
7723 meta: &VideoMeta,
7724 shared: &Shared,
7725 settings: &ExportSettings,
7726 sample_rate: Option<u32>,
7727 bits: u8,
7728) -> crate::Result<Option<(Vec<i32>, AudioMeta)>> {
7729 let format = settings.format;
7730 // Full scale of the sample width asked for: 32767 or 8388607. The f32 mix is
7731 // scaled straight to it, so a 24-bit file is not a widened 16-bit one.
7732 let full = ((1i64 << (bits - 1)) - 1) as f32;
7733 let sources = project.audio_sources();
7734 let range_start = settings.range.map_or(0, |(s, _)| s);
7735 let pre = warm_up(project, range_start, meta.frame_rate);
7736 let offset = range_start - pre;
7737 let segs = project.audio_segments_from(offset, meta.frame_rate);
7738 // The equalizers with them, so what is written is what is heard down to the
7739 // filter: the worker applies them per segment before the lanes are summed
7740 // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point
7741 // playback's feeder reads from -- there is no second place here that could
7742 // apply them differently.
7743 let eqs = project.audio_eqs_from(offset, meta.frame_rate);
7744 // ...and the rates with them, for exactly the same reason: a speeded clip is
7745 // resampled inside the worker playback feeds from, so a WAV of a timeline at
7746 // 2x is half as long and holds the samples that were heard -- not a
7747 // second pass here that could disagree with what the ear got.
7748 let speeds = project.audio_speeds_from(offset, meta.frame_rate);
7749 // ...and the fades with them, the same choke-point reason again: a clip's
7750 // envelope runs inside the worker playback feeds from too.
7751 let fades = project.audio_fades_from(offset, meta.frame_rate);
7752 // ...and the mix over both: each lane's volume into the sum, the master
7753 // limiter out of it. The same opener playback's feeder reads from, so a
7754 // file is written at the levels it was heard at -- there is no second
7755 // place here that could mix it differently.
7756 let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade(
7757 &sources,
7758 &segs,
7759 &eqs,
7760 &speeds,
7761 &fades,
7762 meta.frame_rate,
7763 &project.audio_gains(),
7764 &project.audio_ducks(),
7765 &project.audio_voices(),
7766 project.limiter(),
7767 sample_rate,
7768 )?
7769 else {
7770 return Ok(None);
7771 };
7772 // The picture path's line, for a file that is sound alone: there is sound
7773 // by the line above, so this names the encoder writing it. A picture file
7774 // publishes its own.
7775 if !format.has_video() {
7776 *shared.encoders.lock().unwrap() =
7777 Some(audio_label(project, format, true, None, settings.range.is_some(), settings.reencode_audio).to_string());
7778 }
7779 let channels = usize::from(audio.channels);
7780 let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| {
7781 e.min(project.media_frames()).saturating_sub(s)
7782 });
7783 let frames =
7784 (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as u64;
7785 let total = frames as usize * channels;
7786 // corner-cut: the whole export sits in memory (4 bytes a sample, so ~23 MB
7787 // per minute of 48 kHz stereo). `ec-flac` takes it that way and
7788 // the mp4 path already collects its copied AAC track the same. Upgrade path
7789 // is ec-riff's incremental writer, fed one block at a time.
7790 let skip = warm_up_samples(range_start, pre, meta.frame_rate, audio.sample_rate, channels);
7791 let mut samples: Vec<i32> = Vec::with_capacity(total + skip);
7792 // Only for a loudness target: the mix at f32, measured and levelled once whole.
7793 let mut wide: Vec<f32> = Vec::new();
7794 for chunk in chunks {
7795 cancelled(shared)?;
7796 if shared.loudness.is_some() {
7797 wide.extend_from_slice(&chunk.samples);
7798 // The same range-only progress as the plain path below.
7799 let done = wide.len().saturating_sub(skip).min(total) * PROGRESS_SCALE as usize / total.max(1);
7800 if !format.has_video() { shared.progress.store(done as u32, Ordering::Relaxed); }
7801 if wide.len() >= skip + total {
7802 break;
7803 }
7804 continue;
7805 }
7806 // Already equalized: the chunks come out of the per-lane workers, which
7807 // filter each segment before the mix (`open_mixed_streams_eq` above).
7808 samples.extend(
7809 chunk
7810 .samples
7811 .iter()
7812 .map(|s| (s.clamp(-1.0, 1.0) * full).round() as i32),
7813 );
7814 // Only the range counts towards the bar: not the pre-roll, not the mix past the end.
7815 let done = samples.len().saturating_sub(skip).min(total) * PROGRESS_SCALE as usize / total.max(1);
7816 if !format.has_video() { shared.progress.store(done as u32, Ordering::Relaxed); }
7817 if samples.len() >= skip + total {
7818 break;
7819 }
7820 }
7821 if let Some(target) = shared.loudness {
7822 // The voice warm-up is dropped first, so the gain is measured over the range alone.
7823 wide.drain(..skip.min(wide.len()));
7824 wide.resize(total, 0.0);
7825 level_to_target(&mut wide, audio.sample_rate, audio.channels.max(1), target);
7826 samples.extend(
7827 wide.iter().map(|s| (s.clamp(-1.0, 1.0) * full).round() as i32),
7828 );
7829 if !format.has_video() { shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); }
7830 } else {
7831 // The pre-roll is in the samples in 16-bit form too, so it goes before the length is set.
7832 samples.drain(..skip.min(samples.len()));
7833 }
7834 samples.resize(total, 0);
7835 Ok(Some((samples, audio)))
7836}
7837
7838/// The sound alone as AAC in an mp4 box: the `.m4a` file, and the `.mp4` of a
7839/// timeline with no picture. The track is the one a picture export carries --
7840/// copied packet for packet where a copy says what the timeline says
7841/// ([`copy_audio`]), encoded where it cannot -- so the two files hold the same
7842/// samples and differ in the brand alone ([`Mp4Muxer::create_audio_only`]).
7843fn run_aac(
7844 project: &Project,
7845 meta: &VideoMeta,
7846 out: &Path,
7847 shared: &Shared,
7848 settings: &ExportSettings,
7849 sample_rate: Option<u32>,
7850) -> crate::Result<()> {
7851 let track = copy_audio(
7852 project,
7853 meta,
7854 audio_kbps_of(settings),
7855 false,
7856 false,
7857 settings.reencode_audio,
7858 shared,
7859 sample_rate,
7860 settings.range,
7861 )?
7862 .ok_or("this timeline has no audio to export")?;
7863 let track = ExportAudio {
7864 language: audio_language(project),
7865 ..track
7866 };
7867 *shared.encoders.lock().unwrap() = Some(
7868 audio_label(
7869 project,
7870 settings.format,
7871 true,
7872 Some(track.copied),
7873 settings.range.is_some(),
7874 settings.reencode_audio,
7875 )
7876 .to_string(),
7877 );
7878 let mut mp4 = Mp4Muxer::create_audio_only(
7879 out,
7880 &params_of(&track),
7881 settings.format == Format::M4a,
7882 )?;
7883 if let Some(frames) = track.pcm_frames {
7884 mp4.set_audio_frames(frames)?;
7885 }
7886 let count = track.packets.len().max(1);
7887 for (i, packet) in track.packets.iter().enumerate() {
7888 cancelled(shared)?;
7889 mp4.write_audio_packet(&packet.bytes)?;
7890 shared
7891 .progress
7892 .fetch_max((i * PROGRESS_SCALE as usize / count) as u32, Ordering::Relaxed);
7893 }
7894 cancelled(shared)?;
7895 mp4.set_faststart(settings.faststart);
7896 mp4.set_chapters(&settings.chapters)?;
7897 mp4.finish()?;
7898 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
7899 Ok(())
7900}
7901
7902/// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in
7903/// this engine, so what the decoder handed over is what the header says.
7904fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
7905 // Every sample is in hand, so the frame count is known before the header
7906 // is written: a long enough export gets RF64 instead of a RIFF that would
7907 // overflow its 32-bit sizes.
7908 let channels = u64::from(audio.channels.max(1));
7909 let options = ec_riff::WavOptions {
7910 expected_frames: samples.len() as u64 / channels,
7911 ..Default::default()
7912 };
7913 let mut writer = ec_riff::WavWriter::create_with_options(
7914 out,
7915 ec_riff::WavSpec {
7916 channels: audio.channels,
7917 sample_rate: audio.sample_rate,
7918 bits_per_sample: 16,
7919 sample_format: ec_riff::SampleType::Int,
7920 },
7921 options,
7922 )?;
7923 for &sample in samples {
7924 writer.write_sample(sample as i16)?;
7925 }
7926 // Not `drop`: this is what rewrites the RIFF sizes in the header, and its
7927 // failure is the difference between a finished file and a truncated one.
7928 writer.finalize()?;
7929 Ok(())
7930}
7931
7932/// The same samples as MPEG-1 Layer III, `ec-mp3` doing the encoding -- the
7933/// family's own, taking the seat at the same contract (CBR in, frames out,
7934/// `Mp3EncoderConfig`'s fields are the old seat's names), so the swap cost the
7935/// call sites nothing.
7936///
7937/// CBR at the caller's rate, [`DEFAULT_AUDIO_KBPS`] where there was none. Every
7938/// offered rate is already a legal Layer III value, so the encoder's snap is a
7939/// backstop and not a silent substitution; a sample rate MPEG has no frame for
7940/// (anything but the nine MPEG rates 8-48 kHz) is refused there by name rather
7941/// than written as something else.
7942///
7943/// corner-cut: CBR only -- the card offers rates and not a quality index. Upgrade
7944/// path is `Mp3EncoderConfig::vbr_quality` behind a setting of its own.
7945fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta, kbps: u32) -> crate::Result<()> {
7946 let mut encoder = ec_mp3::encode::Mp3Encoder::new(ec_mp3::encode::Mp3EncoderConfig {
7947 bitrate_kbps: kbps,
7948 vbr_quality: None,
7949 });
7950 // The samples are the 16-bit ones a WAV of this timeline holds, so the two
7951 // files are one mix -- and `push_pcm_s16` divides by 32768 exactly as this
7952 // engine's own decoders do.
7953 let pcm: Vec<i16> = samples.iter().map(|&s| s as i16).collect();
7954 encoder
7955 .push_pcm_s16(&pcm, audio.channels, audio.sample_rate)
7956 .map_err(|e| format!("mp3 encode: {e}"))?;
7957 encoder.finish();
7958 let mut file = BufWriter::new(File::create(out)?);
7959 // `next_packet` after `finish` yields frames until `Eof`, the Xing/Info
7960 // header first: the loop ends on the only error it can see.
7961 while let Ok(frame) = encoder.next_packet() {
7962 file.write_all(&frame)?;
7963 }
7964 file.flush()?;
7965 Ok(())
7966}
7967
7968/// Where the Vorbis rate loop starts, on `ec-vorbis`'s normalised `[0, 1]`
7969/// scale, beside [`VORBIS_TARGET_BPS`] -- the two numbers every `.ogg` this
7970/// program writes is coded at.
7971///
7972/// A measured operating point, not a taste (2026-09-13 bench, every output
7973/// decoded back with **symphonia** -- an independent decoder, and the very one
7974/// [`crate::audio`] reopens an export with). The incumbent seat's own 0.85 --
7975/// its top quality that still decoded every fixture to exactly its own length
7976/// -- measured 124-176 kbps across this suite's fixtures with correlation
7977/// 0.9947-0.9957 against the source. The quality knob alone on the new seat
7978/// saturates well under that band (0.98 lands ~87 kbps on a 30-second music
7979/// clip), so the seat is driven the way its own rate gates are measured: the
7980/// loop starts at 0.85 and is held to a 128 kbps target, which landed
7981/// 124-134 kbps actual on the same inputs and beat the incumbent at its own
7982/// operating point on every one of them -- correlation 0.9968 against 0.9947
7983/// on the music clip, +3.1 dB PSNR -- at the same size of file. Against
7984/// ffmpeg's own libvorbis at `-q 5` (125.8 kbps actual on the same clip) it
7985/// reads 0.9968 against 0.9973: par at the same rate.
7986const VORBIS_QUALITY: f32 = 0.85;
7987
7988/// The rate [`VORBIS_QUALITY`]'s loop is held to, in bits per second. Measured
7989/// landing within +1..+5% of target across the bench's inputs; the Sound row
7990/// stays refused for this format because this target is the encoder's measured
7991/// operating point, not a number a card may offer.
7992const VORBIS_TARGET_BPS: i32 = 128_000;
7993
7994/// The same samples as Vorbis I in an Ogg container: `ec-vorbis` encodes,
7995/// `ec-ogg` pages. Pure Rust on both halves, like every other encoder here.
7996///
7997/// The old seat's two corrections are gone with it, and the going is measured
7998/// rather than assumed (2026-09-13, every output decoded back with symphonia).
7999/// This encoder numbers its packets the spec's way -- the first audio packet
8000/// at granule 0, every packet after at the absolute sample position its block
8001/// ends on -- and clamps its final granule to the sample count it was fed, so
8002/// a decoder trims the block grid's tail on its own. Written straight through,
8003/// every file decodes to exactly the timeline's frame count with the
8004/// correlation peak at lag zero, which is what the one-hop pre-roll and the
8005/// two granule corrections this function used to carry around the old encoder
8006/// were for.
8007///
8008/// **Stereo, always.** The format row promises stereo, so a mono mix is
8009/// written as dual mono, both channels bit-identical (measured: `max|L-R|` is
8010/// exactly 0; the encoder's own channel coupling codes the empty side channel
8011/// for almost nothing). The encoder would serve a mono stream, but the row
8012/// says stereo and folding the file back down must give exactly what was
8013/// mixed. Wider than stereo cannot reach here -- [`crate::audio`] folds 5.1
8014/// to stereo when the source is opened -- but it is refused by name rather
8015/// than left to the library's own message.
8016///
8017/// corner-cut: one operating point, [`VORBIS_QUALITY`] +
8018/// [`VORBIS_TARGET_BPS`], with no user control -- the Sound row is refused for
8019/// this format. Upgrade path is a quality picker of its own, worth building
8020/// the day the card has a control that speaks in quality rather than kbps.
8021fn write_ogg(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
8022 if audio.channels > 2 {
8023 return Err(format!(
8024 "Ogg Vorbis is written in stereo here and this mix has {} channels",
8025 audio.channels
8026 )
8027 .into());
8028 }
8029 // The mp3 path's conversion, so the two files are one mix -- the same
8030 // /32768 scaling this engine's own decoders do -- plus (for a mono mix)
8031 // the dual-mono widening: the same sample in both channels is the same
8032 // signal, not a widening of it, so what a player folds back down is what
8033 // was mixed.
8034 let pcm: Vec<f32> = match audio.channels < 2 {
8035 true => samples
8036 .iter()
8037 .flat_map(|&s| [f32::from(s as i16) / 32768.0; 2])
8038 .collect(),
8039 false => samples
8040 .iter()
8041 .map(|&s| f32::from(s as i16) / 32768.0)
8042 .collect(),
8043 };
8044 let frames = samples.len() / usize::from(audio.channels).max(1);
8045
8046 let mut encoder = ec_vorbis::VorbisEncoder::new(ec_vorbis::EncoderConfig {
8047 sample_rate: audio.sample_rate,
8048 channels: 2,
8049 bitrate_bps: VORBIS_TARGET_BPS,
8050 quality: VORBIS_QUALITY,
8051 })
8052 .map_err(|e| format!("vorbis encode: {e}"))?;
8053 encoder
8054 .push_interleaved(&pcm)
8055 .map_err(|e| format!("vorbis encode: {e}"))?;
8056 encoder.finish();
8057 let mut packets = Vec::new();
8058 loop {
8059 match encoder.next_packet() {
8060 Ok(packet) => packets.push(packet),
8061 Err(ec_core::Error::Eof) => break,
8062 Err(ec_core::Error::NeedMore) => continue,
8063 Err(e) => return Err(format!("vorbis encode: {e}").into()),
8064 }
8065 }
8066 // The three setup headers travel with the encoder, not in the packet
8067 // stream; with no audio packets there is no stream to page.
8068 if packets.is_empty() {
8069 return Err("vorbis encode: no audio packets is not a stream".into());
8070 }
8071 let headers = encoder.headers();
8072 let extradata =
8073 ec_ogg::xiph_lace(&headers).ok_or("vorbis encode: the three headers would not lace")?;
8074
8075 let time_base =
8076 TimeBase::try_new(1, i64::from(audio.sample_rate)).map_err(|e| format!("ogg mux: {e}"))?;
8077 let mut params = CodecParameters::new(CodecId::Vorbis);
8078 params.extradata = Some(Buf::from(extradata));
8079 params.media = MediaParameters::Audio(AudioParameters {
8080 sample_rate: audio.sample_rate,
8081 layout: ChannelLayout::Stereo,
8082 ..AudioParameters::default()
8083 });
8084 let mut stream = StreamInfo::new(0, time_base, params);
8085 stream.duration = Some(frames as i64);
8086 stream.start_time = Some(0);
8087 let mut muxer = ec_ogg::OggMuxer::new(File::create(out)?);
8088 // Without this every audio packet of a short export lands on one page, and
8089 // the muxer's own note records what that costs: a first-audio-page-is-also-
8090 // EOS stream decodes short by half a small block in a reference decoder.
8091 muxer.set_page_target_bytes(Some(OGG_PAGE_BYTES));
8092 muxer
8093 .add_stream(stream)
8094 .map_err(|e| format!("ogg mux: {e}"))?;
8095 for packet in &packets {
8096 // The granule is the encoder's own: the absolute sample position this
8097 // packet ends at, clamped to the mix's length on the last one. It goes
8098 // in as side data, which is where `ec-ogg` reads it, because a packet's
8099 // `pts + duration` would state the position one block late.
8100 let mut out_packet =
8101 Packet::new(0, time_base, packet.data.clone()).with_duration(packet.samples);
8102 out_packet
8103 .side_data
8104 .push(ec_ogg::granule_side_data(packet.granule));
8105 muxer
8106 .write_packet(&out_packet)
8107 .map_err(|e| format!("ogg mux: {e}"))?;
8108 }
8109 muxer.finish().map_err(|e| format!("ogg mux: {e}"))?;
8110 Ok(())
8111}
8112
8113/// The same samples as Opus in Ogg ([`crate::opus_write`]), at the Sound row's
8114/// rate clamped into Opus's own range (6-510 kbps, [`crate::opus_write::DEFAULT_KBPS`]
8115/// where none was asked for), with the language and chapters in `OpusTags`.
8116/// Cancellable per packet, like the mix before it.
8117fn write_opus(
8118 out: &Path,
8119 samples: &[i32],
8120 audio: &AudioMeta,
8121 project: &Project,
8122 settings: &ExportSettings,
8123 shared: &Shared,
8124) -> crate::Result<()> {
8125 if audio.sample_rate != OPUS_RATE {
8126 return Err(format!("Opus is coded at 48 kHz and this mix came out at {} Hz", audio.sample_rate).into());
8127 }
8128 let pcm: Vec<f32> = samples.iter().map(|&s| f32::from(s as i16) / 32768.0).collect();
8129 let language = audio_language(project);
8130 let tags = crate::opus_write::Tags { language: language.as_deref(), chapters: &settings.chapters };
8131 crate::opus_write::write(
8132 out,
8133 &pcm,
8134 usize::from(audio.channels.max(1)),
8135 audio.sample_rate,
8136 settings.audio_kbps.unwrap_or(crate::opus_write::DEFAULT_KBPS),
8137 &tags,
8138 &mut |_| cancelled(shared),
8139 )
8140}
8141
8142/// The page size [`write_ogg`] asks the Ogg muxer to aim at, in bytes. RFC 3533
8143/// describes pages as "usually 4-8 kB", which is also the muxer's own suggested
8144/// general-purpose value.
8145const OGG_PAGE_BYTES: usize = 4096;
8146
8147/// The same samples, losslessly compressed, through [`crate::flac_write`]. The
8148/// export is always 16-bit: the samples were scaled to `i16` above.
8149fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> {
8150 crate::flac_write::write(out, samples, usize::from(audio.channels), 16, audio.sample_rate)
8151}
8152
8153/// The I420 planes of one black picture, allocated once for a whole export: a
8154/// gap in the video lane is encoded, not skipped, or every frame after it would
8155/// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention
8156/// [`crate::convert`] decodes with.
8157struct Black {
8158 y: Vec<u8>,
8159 uv: Vec<u8>,
8160 width: u32,
8161 height: u32,
8162}
8163
8164impl Black {
8165 fn new(meta: &VideoMeta) -> Self {
8166 let (w, h) = (meta.width as usize, meta.height as usize);
8167 Self {
8168 y: vec![16; w * h],
8169 uv: vec![128; w.div_ceil(2) * h.div_ceil(2)],
8170 width: meta.width,
8171 height: meta.height,
8172 }
8173 }
8174
8175 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
8176 (&self.y, &self.uv, &self.uv, self.width, self.height)
8177 }
8178}
8179
8180/// `Err` once a cancel has been asked for. Called at every point where the work
8181/// left is more than an instant, so an `esc` at 99.9% still stops the export
8182/// instead of quietly completing it.
8183fn cancelled(shared: &Shared) -> crate::Result<()> {
8184 if shared.cancel.load(Ordering::Relaxed) {
8185 return Err("export cancelled".into());
8186 }
8187 Ok(())
8188}
8189
8190/// The two containers an export writes, so the picture loop above is one loop:
8191/// H.264 goes into mp4, AV1 into Matroska, and nothing else is offered.
8192enum Muxer {
8193 Mp4(Mp4Muxer),
8194 Mkv(MkvMuxer),
8195 /// ProRes in QuickTime ([`crate::prores_out::MovWriter`]).
8196 Mov(crate::prores_out::MovWriter),
8197}
8198
8199impl Muxer {
8200 fn finish(self) -> crate::Result<()> {
8201 match self {
8202 Self::Mp4(mp4) => mp4.finish(),
8203 Self::Mkv(mkv) => mkv.finish(),
8204 Self::Mov(mov) => mov.finish(),
8205 }
8206 }
8207}
8208
8209/// Test-only panic point, so the worker's own `catch_unwind` branch in
8210/// [`start`] is reachable without a codec parser that actually panics: the
8211/// variable names the one `.part` whose export dies, and no export but that
8212/// one ever matches it, so a concurrent export in the same process is safe.
8213fn inject_export_test_panic(out: &Path) {
8214 if crate::envcfg::var_os("VE_EXPORT_TEST_PANIC").is_some_and(|target| target == out.as_os_str()) {
8215 panic!("export test panic: the .part is on disk");
8216 }
8217}
8218
8219/// Writes one access unit, creating the file on the first one -- the parameter
8220/// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once
8221/// the encoder has coded something. Units with no coded slice are skipped: a
8222/// software encoder may hand back an empty buffer while it buffers, and the
8223/// muxer rejects a sample that would carry no picture.
8224#[allow(
8225 clippy::too_many_arguments,
8226 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"
8227)]
8228fn write_video(
8229 muxer: &mut Option<Muxer>,
8230 out: &Path,
8231 meta: &VideoMeta,
8232 settings: &ExportSettings,
8233 source_colour: Tags,
8234 source_language: Option<&str>,
8235 audio: Option<&AudioParams>,
8236 packets: &mut Option<Vec<crate::AacPacket>>,
8237 subs: &mut Vec<SubParams>,
8238 au: &[u8],
8239 key: bool,
8240 ten_bit: bool,
8241) -> crate::Result<()> {
8242 if settings.format.is_prores() {
8243 // The encoder's own frame, one sample per picture; the track is declared
8244 // by the first one, the sound is written after the last.
8245 let Some(Muxer::Mov(mov)) = muxer else {
8246 unreachable!("the ProRes seat opens its own muxer")
8247 };
8248 return mov.write_frame(au);
8249 }
8250 if settings.format.is_hevc() {
8251 // The parameter sets are in the access unit -- every intra AU carries
8252 // VPS, SPS and PPS -- and the record built from them is what *both*
8253 // containers declare the track with: an mp4's `hvcC` box and a
8254 // Matroska `CodecPrivate` are the same bytes, so the two files are one
8255 // stream written twice rather than two.
8256 let sample =
8257 crate::mux::annex_b_to_hvcc(au).ok_or("a coded HEVC unit with no slice in it")?;
8258 if settings.format == Format::Hevc {
8259 let muxer = match muxer {
8260 Some(Muxer::Mkv(mkv)) => mkv,
8261 Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
8262 none => {
8263 let hvcc = hevc_params(au, ten_bit)?;
8264 let sound = audio.zip(packets.take());
8265 let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create_hevc(
8266 out,
8267 &HevcParams {
8268 width: meta.width,
8269 height: meta.height,
8270 frame_rate: meta.frame_rate,
8271 hvcc: &hvcc,
8272 language: source_language.map(str::to_owned),
8273 colour: (settings.hdr.transfer != HdrTransfer::Sdr).then_some(source_colour),
8274 light: (settings.hdr.transfer != HdrTransfer::Sdr)
8275 .then(|| crate::mux::hdr_light(&settings.hdr)),
8276 },
8277 sound,
8278 std::mem::take(subs),
8279 )?)) else {
8280 unreachable!("just inserted a Matroska muxer")
8281 };
8282 mkv.set_chapters(&settings.chapters)?;
8283 mkv
8284 }
8285 };
8286 return muxer.write_frame(&sample, key);
8287 }
8288 let muxer = match muxer {
8289 Some(Muxer::Mp4(mp4)) => mp4,
8290 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
8291 none => {
8292 let hvcc = hevc_params(au, ten_bit)?;
8293 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_hevc(
8294 out,
8295 &HevcParams {
8296 width: meta.width,
8297 height: meta.height,
8298 frame_rate: meta.frame_rate,
8299 hvcc: &hvcc,
8300 // mp4 does not state a picture's language yet.
8301 language: None,
8302 colour: None,
8303 light: None,
8304 },
8305 audio,
8306 )?)) else {
8307 unreachable!("just inserted an mp4 muxer")
8308 };
8309 // The same `colr` rule as AV1's: the colour a 10-bit SDR export
8310 // declares, which the bitstream's VUI states as well.
8311 if source_colour != Tags::default() {
8312 mp4.set_colour(source_colour);
8313 }
8314 if settings.hdr.transfer != HdrTransfer::Sdr {
8315 mp4.set_hdr(&settings.hdr);
8316 }
8317 mp4
8318 }
8319 };
8320 return muxer.write_coded_sample(&sample, key);
8321 }
8322 if settings.format.is_av1() {
8323 // Every AV1 stream opens on a keyframe, and a keyframe carries the
8324 // sequence header the track has to declare: an encoder that handed back
8325 // neither has produced nothing a decoder can start. The same header goes
8326 // into a `CodecPrivate` and into an `av1C` -- one record, two containers.
8327 fn params<'a>(
8328 meta: &VideoMeta,
8329 au: &'a [u8],
8330 language: Option<&str>,
8331 ten_bit: bool,
8332 colour: Tags,
8333 ) -> crate::Result<Av1Params<'a>> {
8334 Ok(Av1Params {
8335 width: meta.width,
8336 height: meta.height,
8337 frame_rate: meta.frame_rate,
8338 config: crate::mux::av1_sequence_header(au)
8339 .ok_or("the first coded picture carries no AV1 sequence header")?,
8340 language: language.map(str::to_owned),
8341 ten_bit,
8342 colour: (colour != Tags::default()).then_some(colour),
8343 })
8344 }
8345 if matches!(settings.format, Format::Av1 | Format::Webm) {
8346 let muxer = match muxer {
8347 Some(Muxer::Mkv(mkv)) => mkv,
8348 Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
8349 none => {
8350 // The sound with it, all of it: the Matroska muxer writes the
8351 // packets into the clusters of the pictures they play under.
8352 let sound = audio.zip(packets.take());
8353 let created = match settings.format {
8354 // WebM has no subtitle track to take ([`export_subtitles`]).
8355 Format::Webm => MkvMuxer::create_webm(out, &params(meta, au, source_language, ten_bit, source_colour)?, sound)?,
8356 _ => {
8357 MkvMuxer::create(
8358 out,
8359 &params(meta, au, source_language, ten_bit, source_colour)?,
8360 sound,
8361 std::mem::take(subs),
8362 )?
8363 }
8364 };
8365 let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(created)) else {
8366 unreachable!("just inserted a Matroska muxer")
8367 };
8368 mkv.set_chapters(&settings.chapters)?;
8369 mkv
8370 }
8371 };
8372 return muxer.write_frame(au, key);
8373 }
8374 let muxer = match muxer {
8375 Some(Muxer::Mp4(mp4)) => mp4,
8376 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
8377 none => {
8378 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1(
8379 out,
8380 &params(meta, au, None, ten_bit, source_colour)?,
8381 audio,
8382 )?)) else {
8383 unreachable!("just inserted an mp4 muxer")
8384 };
8385 // The `colr` box states the colour a 10-bit SDR export declares; an
8386 // export with no colour of its own keeps the output rule's box.
8387 if source_colour != Tags::default() {
8388 mp4.set_colour(source_colour);
8389 }
8390 mp4
8391 }
8392 };
8393 return muxer.write_coded_sample(au, key);
8394 }
8395 if !crate::mux::has_coded_slice(au) {
8396 return Ok(());
8397 }
8398 let muxer = match muxer {
8399 Some(Muxer::Mp4(mp4)) => mp4,
8400 Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
8401 none => {
8402 let (sps, pps) = crate::mux::parameter_sets(au)
8403 .ok_or("the first coded picture carries no SPS/PPS")?;
8404 let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create(
8405 out,
8406 &VideoParams {
8407 width: meta.width,
8408 height: meta.height,
8409 frame_rate: meta.frame_rate,
8410 sps,
8411 pps,
8412 },
8413 audio,
8414 )?)) else {
8415 unreachable!("just inserted an mp4 muxer")
8416 };
8417 // A file written in its source's own space says so, rather than
8418 // claiming the space its height would imply
8419 // ([`ExportSettings::keep_source_colour`]).
8420 if settings.keep_source_colour || source_colour != Tags::default() {
8421 mp4.set_colour(source_colour);
8422 }
8423 mp4
8424 }
8425 };
8426 muxer.write_video_au(au)
8427}
8428
8429/// The `hvcC` record of the first coded unit, or the refusal by name. Split out
8430/// because both HEVC containers ask it in the same words.
8431fn hevc_params(au: &[u8], ten_bit: bool) -> crate::Result<Vec<u8>> {
8432 crate::mux::hvcc_record_at(au, ten_bit)
8433 .ok_or_else(|| crate::Error::from("the first coded picture carries no HEVC VPS/SPS/PPS"))
8434}
8435
8436fn bitrate_for(meta: &VideoMeta) -> u64 {
8437 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;
8438 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)
8439}
8440
8441fn forced(var: &str) -> bool {
8442 crate::envcfg::var_os(var).is_some_and(|v| v == "1")
8443}
8444
8445/// Hardware where it is available, software everywhere else -- chosen once for
8446/// the whole export, so the stream never changes encoder mid-file. Both codecs
8447/// have both seats: an AV1 export runs on the plugin's VA-API encoder where the
8448/// GPU has one and on `rav1e` where it has not, which is the same pair H.264 has
8449/// had and the same silent fallback.
8450enum Enc {
8451 Hw(HwEncoder),
8452 Sw {
8453 encoder: Encoder,
8454 /// The access unit currently lent out: the encoder hands back an owned
8455 /// `Vec` where the seat's contract lends a slice, so one lives here
8456 /// between the two.
8457 au: Vec<u8>,
8458 },
8459 /// AV1 on the GPU, through the same plugin the H.264 seat uses.
8460 Av1Hw(HwEncoder),
8461 /// HEVC on the GPU, through that same plugin -- and intra-only there too,
8462 /// so this and [`Enc::Hevc`] write the same kind of file.
8463 HevcHw(HwEncoder, bool, bool),
8464 /// AV1 software at 10 bits: `rav1e`'s 16-bit context. A picture that passes
8465 /// through the span untouched arrives as 16-bit planes off the 10-bit decode
8466 /// ([`Enc::encode_wide`]); an 8-bit picture (one composed on the way) is shifted
8467 /// up to the same scale in [`Enc::encode`].
8468 Av1Sw16 {
8469 context: rav1e::Context<u16>,
8470 ready: std::collections::VecDeque<(Vec<u8>, bool)>,
8471 au: Vec<u8>,
8472 flushed: bool,
8473 scratch: [Vec<u16>; 3],
8474 },
8475 Av1Sw {
8476 context: rav1e::Context<u8>,
8477 /// Temporal units the encoder has finished but the caller has not
8478 /// collected: `rav1e` reorders and may hand back several at once, while
8479 /// this interface is one picture in, one unit out (the plugin's own
8480 /// `ready` queue exists for the same reason).
8481 ready: std::collections::VecDeque<(Vec<u8>, bool)>,
8482 /// The unit currently lent out, for the same reason `Sw` owns one.
8483 au: Vec<u8>,
8484 flushed: bool,
8485 },
8486 /// HEVC, intra-only and software: `ec-h265` codes every picture an IDR
8487 /// carrying its own VPS/SPS/PPS. A batch of frames codes on as many lane
8488 /// encoders as there are pictures, and each encoder's wavefront splits
8489 /// whatever cores the lanes leave over -- the same shape as the seat it
8490 /// replaced, the cores spent on frames and inside one picture at the same
8491 /// time. Asked for by [`ExportSettings::intra_only`].
8492 Hevc(HevcEnc),
8493 /// HEVC, I+P GOPs, software: `ec-h265`'s sequence coder on a worker thread.
8494 /// The default HEVC seat ([`Enc::open_hevc_gop`]).
8495 HevcGop(HevcGop),
8496 /// ProRes, software: `ec-prores` codes one whole frame per call (its own
8497 /// worker threads inside), so one picture in is one sample out. The 4:2:0
8498 /// pictures of the walk are widened to 10 bits and chroma-upsampled to the
8499 /// profile's layout ([`crate::prores_out`]).
8500 ProRes {
8501 encoder: ec_prores::ProResEncoder,
8502 /// The sample currently lent out.
8503 au: Vec<u8>,
8504 /// 4:4:4 profiles (4444, 4444 XQ) code full chroma.
8505 full_chroma: bool,
8506 },
8507}
8508
8509/// The intra HEVC seat. Frames arrive one at a time (the export walk is one
8510/// picture per timeline frame) and are held until there is a lane for each,
8511/// then coded in parallel and queued in **display order**. `ec-h265`'s
8512/// wavefront spreads one picture across the workers it is given and the lanes
8513/// spread the frames across the machine, so decode and render keep filling
8514/// the next batch while this one codes -- a seat that coded one picture at a
8515/// time would serialize the whole walk behind its encoder (measured: 7.4 fps
8516/// against 11.8 at 1080p on the same box, which is the regression this
8517/// batching exists to prevent).
8518///
8519/// corner-cut: a batch of display-size planes sits in memory (~3 MB a frame
8520/// at 1080p, so ~37 MB at 12 lanes) and the tail of a timeline is coded on
8521/// fewer lanes than the middle. Upgrade path is a pipeline that keeps every
8522/// lane fed from a decoder running ahead of the encoder rather than a batch
8523/// barrier.
8524struct HevcEnc {
8525 /// Display-size I420 pictures waiting for a lane, in display order. The
8526 /// encoder pads to its own coded grid, so nothing is pre-padded here.
8527 pending: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)>,
8528 /// Coded access units not yet collected, in the same order.
8529 ready: std::collections::VecDeque<Vec<u8>>,
8530 /// The unit currently lent out, for the reason `Sw` owns one: the encoder
8531 /// hands back an owned `Vec`, the seat's contract lends a slice.
8532 au: Vec<u8>,
8533 /// One encoder per lane. `ec-h265` is stateless from picture to picture
8534 /// (every picture is an IDR), so a lane coding frame *n* needs nothing
8535 /// the other lanes know.
8536 lanes: Vec<HevcEncoder>,
8537 /// The display width the planes arrive at; the height lives in each
8538 /// encoder's config, where the coded grid is derived from it.
8539 width: usize,
8540 /// Whether the lanes code at 10 bits: `pending` then holds little-endian
8541 /// 16-bit samples, which [`HevcEnc::code_batch`] reads back.
8542 ten_bit: bool,
8543}
8544
8545impl Enc {
8546 /// Which seat this *is*, said the way [`video_label`] says it -- so the
8547 /// name a running export shows is the name the card showed, or the honest
8548 /// difference where the probe and the open disagreed.
8549 fn label(&self) -> &'static str {
8550 match self {
8551 Self::Hw(_) => video_label(Format::Mp4, true, false),
8552 Self::Sw { .. } => video_label(Format::Mp4, false, false),
8553 Self::Av1Hw(_) => video_label(Format::Av1, true, false),
8554 Self::Av1Sw { .. } | Self::Av1Sw16 { .. } => video_label(Format::Av1, false, false),
8555 Self::HevcHw(_, intra, _) => video_label(Format::Hevc, true, *intra),
8556 Self::Hevc(_) => video_label(Format::Hevc, false, true),
8557 Self::HevcGop(_) => video_label(Format::Hevc, false, false),
8558 Self::ProRes { .. } => video_label(Format::ProRes, false, true),
8559 }
8560 }
8561
8562 /// The ProRes seat's codec parameters (the sample entry's fourcc rides in
8563 /// the extradata); `None` for every other seat.
8564 fn prores_params(&self) -> Option<&ec_core::registry::CodecParameters> {
8565 match self {
8566 Self::ProRes { encoder, .. } => Some(ec_core::registry::Encoder::codec_parameters(encoder)),
8567 _ => None,
8568 }
8569 }
8570
8571 /// `ten_bit` is [`wide_ten_bit`]'s answer; it means something to AV1 and HEVC only.
8572 /// `colour` is what the file declares, in the bitstream as well as the container.
8573 fn open(
8574 meta: &VideoMeta,
8575 settings: &ExportSettings,
8576 ten_bit: bool,
8577 colour: ColorDescription,
8578 ) -> crate::Result<Self> {
8579 // Which *codec* the picture is, not which container it goes in: both AV1
8580 // formats run the same encoder, and so do both HEVC ones.
8581 if settings.format.is_av1() {
8582 return Self::open_av1(meta, settings, ten_bit, colour);
8583 }
8584 if settings.format.is_hevc() {
8585 return Self::open_hevc(meta, settings, ten_bit, colour);
8586 }
8587 if settings.format.is_prores() {
8588 return Self::open_prores(meta, settings, colour);
8589 }
8590 // A caller's number goes through the same clamp as the computed one: a
8591 // zero bitrate switches the software encoder's lookahead on, which would
8592 // break the one-picture-per-call contract `encode` documents below.
8593 let bitrate = bitrate_of(meta, settings);
8594 // The plugin wants an exact rational, and the muxer already picks one
8595 // that is exact at every rate we can read -- `fps * 1000 / 1000` would
8596 // hand 24000/1001 over as a rounded 23.976, which is the same
8597 // truncation the container timing had.
8598 crate::mux::frame_timing(meta.frame_rate)?;
8599 if let Some(hw) = hw_seat(meta, settings, false, colour)? {
8600 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware (VA-API plugin)"); }
8601 return Ok(Self::Hw(hw));
8602 }
8603 if settings.qp.is_some() {
8604 return Err(QP_SOFTWARE_REFUSAL.into());
8605 }
8606 // H.264 codes 16x16 macroblocks, and ec-h264's floor is the
8607 // macroblock itself -- the old encoder took any positive even size.
8608 // Named here, where a card can show it, rather than let the encoder's
8609 // error surface from inside an export already under way.
8610 if meta.width < 16 || meta.height < 16 {
8611 return Err(format!(
8612 "{}x{} cannot be written as H.264: the picture is smaller \
8613 than one 16x16 macroblock",
8614 meta.width, meta.height
8615 )
8616 .into());
8617 }
8618 // 4:2:0 addresses its conformance window in *chroma* samples, so an odd
8619 // picture cannot be cropped back to itself -- and an odd dimension has
8620 // no chroma plane of its own to begin with. Named rather than padded to
8621 // something a decoder would then show a column of: the same refusal the
8622 // HEVC seat makes, and x264's and ffmpeg's own for 4:2:0 H.264.
8623 if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) {
8624 return Err(format!(
8625 "{}x{} cannot be written as H.264: 4:2:0 needs even dimensions",
8626 meta.width, meta.height
8627 )
8628 .into());
8629 }
8630 let mut cfg = EncoderConfig::new(meta.width, meta.height);
8631 cfg.framerate = meta.frame_rate as f32;
8632 cfg.bitrate = bitrate.min(u32::MAX as u64) as u32;
8633 // Two seconds between key frames, and no B-frames on either path: the
8634 // muxer times everything by duration alone, which reordering would
8635 // break. A proxy asks for one frame a GOP, which is every frame its own
8636 // starting point ([`ExportSettings::intra_only`]).
8637 cfg.gop_size = match settings.intra_only {
8638 true => 1,
8639 false => gop_frames(meta, settings).unwrap_or((meta.frame_rate * 2.0).round().max(1.0) as u32),
8640 };
8641 // Fast, the rung a fallback is allowed to cost -- the cheaper arm of
8642 // the preset ladder, the one the old seat's own S1 also picked when its
8643 // Balanced rung halved the rate for the same bitrate.
8644 cfg.preset = Preset::Fast;
8645 // 8x8 transform off. At this rung it is half the pure-encode cost
8646 // (17.2 ms/frame against 35.1 at 720p across all cores, measured at
8647 // the swap) for at most 0.7 dB BD-PSNR -- against an old seat that ran
8648 // Constrained Baseline and never had the transform in the first
8649 // place. The export stays Main-profile CABAC, which is where the
8650 // quality over the old seat lives; a constant-QP mode would be the
8651 // place to revisit the rung whole.
8652 cfg.transform_8x8 = false;
8653 let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?;
8654 Ok(Self::Sw {
8655 encoder,
8656 au: Vec::new(),
8657 })
8658 }
8659
8660 /// The AV1 pair. The hardware seat is the plugin's, opened by a symbol of
8661 /// its own (`vh_enc_av1_open`) so a plugin built before AV1 encode existed
8662 /// simply has none and this falls through -- the same "no" a GPU without an
8663 /// AV1 encode entrypoint gives, and the same silent fallback either way.
8664 ///
8665 /// It is **asked for by name**, which is the one place this pair does not
8666 /// mirror the H.264 one: the vendored cros-codecs AV1 encoder hung the GPU
8667 /// on this project's own radeonsi box -- `engine_hw: operation failed`,
8668 /// then an amdgpu hard recovery and a lost context, measured 2026-08-10
8669 /// exporting the 720p fixture. A software encoder that takes half a minute
8670 /// is a worse export than a hardware one; a driver reset is not an export
8671 /// at all. So [`EncoderSeat::Auto`] takes `rav1e` here and only
8672 /// [`EncoderSeat::Hardware`] -- a person picking the GPU for AV1 on the
8673 /// card, under a row that names the risk -- enters the plugin's seat. It
8674 /// was an env pin (`VE_HW_AV1=1`) until the card could ask, which is a
8675 /// switch nobody exporting a film would ever find.
8676 ///
8677 /// corner-cut: the upgrade path is a driver this was reproduced against (or a
8678 /// cros-codecs release that fixes it) plus a probe encode of one frame at
8679 /// open, after which `Auto` can prefer hardware the way H.264 does.
8680 fn open_av1(
8681 meta: &VideoMeta,
8682 settings: &ExportSettings,
8683 ten_bit: bool,
8684 colour: ColorDescription,
8685 ) -> crate::Result<Self> {
8686 let bitrate = bitrate_of(meta, settings);
8687 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
8688 // Two seconds between keyframes, as the H.264 seat does: a seek may only
8689 // land on one, and this is what a cluster of the Matroska file is.
8690 let gop = gop_frames(meta, settings).map_or_else(|| (meta.frame_rate * 2.0).round().max(1.0) as u64, u64::from);
8691 // The 10-bit seat is software: the GPU encode is 8-bit only.
8692 let hw = match ten_bit {
8693 true => None,
8694 false => hw_seat(meta, settings, false, colour)?,
8695 };
8696 if let Some(hw) = hw {
8697 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); }
8698 return Ok(Self::Av1Hw(hw));
8699 }
8700 if settings.qp.is_some() {
8701 return Err(QP_SOFTWARE_REFUSAL.into());
8702 }
8703 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software AV1 (rav1e)"); }
8704 // Seconds per frame, which is what `frame_timing` already has as an
8705 // exact rational -- 1001/24000 rather than a rounded 23.976.
8706 let mut cfg = rav1e::EncoderConfig {
8707 width: meta.width as usize,
8708 height: meta.height as usize,
8709 bit_depth: if ten_bit { 10 } else { 8 },
8710 chroma_sampling: rav1e::prelude::ChromaSampling::Cs420,
8711 time_base: rav1e::prelude::Rational::new(u64::from(fps_den), u64::from(fps_num)),
8712 ..Default::default()
8713 };
8714 cfg.min_key_frame_interval = gop;
8715 cfg.max_key_frame_interval = gop;
8716 cfg.bitrate = bitrate.min(i32::MAX as u64) as i32;
8717 // The fastest preset, with the settings that matter for speed at that
8718 // preset. Tiles spread one frame over the cores (one tile ran on a single
8719 // core); low latency drops the lookahead; CDEF and loop restoration are
8720 // off for speed (a 10 s 1080p export measured the same PSNR against the
8721 // source either way). Measured: 170 s before, about 17 s after, on a box
8722 // with load ~15. The `asm` feature in Cargo.toml is the other half.
8723 cfg.speed_settings = rav1e::prelude::SpeedSettings::from_preset(AV1_SPEED);
8724 cfg.tiles = AV1_TILES;
8725 cfg.low_latency = true;
8726 cfg.speed_settings.cdef = false;
8727 cfg.speed_settings.lrf = false;
8728 cfg.speed_settings.multiref = false;
8729 // What the sequence header says the samples mean, for the reason
8730 // [`video_signal_type`] gives: a container tag is the second answer a
8731 // decoder looks at, not the first. Written as rav1e's own enums rather
8732 // than the H.273 numbers -- the crate has no `from` for the code points,
8733 // and the output rule only ever picks one of these two spaces.
8734 let out = colour;
8735 cfg.pixel_range = rav1e::prelude::PixelRange::Limited;
8736 cfg.color_description = Some(match out.matrix {
8737 Matrix::Bt709 => rav1e::prelude::ColorDescription {
8738 color_primaries: rav1e::prelude::ColorPrimaries::BT709,
8739 transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT709,
8740 matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT709,
8741 },
8742 // A 10-bit SDR export of a BT.2020 source: the source's own space.
8743 Matrix::Bt2020Ncl => rav1e::prelude::ColorDescription {
8744 color_primaries: rav1e::prelude::ColorPrimaries::BT2020,
8745 transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT2020_10Bit,
8746 matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT2020NCL,
8747 },
8748 _ => rav1e::prelude::ColorDescription {
8749 color_primaries: rav1e::prelude::ColorPrimaries::BT601,
8750 transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT601,
8751 matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT601,
8752 },
8753 });
8754 let config = rav1e::Config::new()
8755 .with_encoder_config(cfg)
8756 .with_threads(std::thread::available_parallelism().map_or(1, |n| n.get()));
8757 if ten_bit {
8758 let context = config
8759 .new_context::<u16>()
8760 .map_err(|e| format!("software AV1 encoder: {e}"))?;
8761 return Ok(Self::Av1Sw16 {
8762 context,
8763 ready: std::collections::VecDeque::new(),
8764 au: Vec::new(),
8765 flushed: false,
8766 scratch: Default::default(),
8767 });
8768 }
8769 let context = config
8770 .new_context::<u8>()
8771 .map_err(|e| format!("software AV1 encoder: {e}"))?;
8772 Ok(Self::Av1Sw {
8773 context,
8774 ready: std::collections::VecDeque::new(),
8775 au: Vec::new(),
8776 flushed: false,
8777 })
8778 }
8779
8780 /// The HEVC pair: the plugin's VA-API seat where the GPU has one, and the
8781 /// software intra encoder everywhere else -- below the driver's 384x384
8782 /// floor, on a plugin too old to carry the symbol, on a GPU with no HEVC
8783 /// encode entrypoint. Silent either way, because both write the same kind
8784 /// of file.
8785 ///
8786 /// The default is I+P GOPs, on the hardware seat where there is one and on
8787 /// the software seat ([`Enc::open_hevc_gop`]) where there is not. With
8788 /// [`ExportSettings::intra_only`] it is intra: every picture an IDR, on the
8789 /// hardware seat where there is one and on the lanes below where there is
8790 /// not -- an intraframe master in the shape of ProRes or DNxHD, large
8791 /// files, every frame a cut point.
8792 ///
8793 /// The picture is coded at its own size and padded to whole minimum coding
8794 /// blocks *by the encoder*, which crops the padding back off with the SPS
8795 /// conformance window, so 1920x1080 is a legal export rather than a
8796 /// refusal.
8797 fn open_hevc(
8798 meta: &VideoMeta,
8799 settings: &ExportSettings,
8800 ten_bit: bool,
8801 colour: ColorDescription,
8802 ) -> crate::Result<Self> {
8803 // The muxers time by it and the mp4 one wants an exact rational: asked
8804 // here so an impossible rate fails before a frame is coded. The same
8805 // rational goes into the SPS's VUI, whose timing is also where the
8806 // encoder picks the level from.
8807 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
8808 // 4:2:0 addresses its conformance window in *chroma* samples, so an odd
8809 // picture cannot be cropped back to itself -- and an odd dimension has
8810 // no chroma plane of its own to begin with. Named rather than padded to
8811 // something a decoder would then show a column of.
8812 if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) {
8813 return Err(format!(
8814 "{}x{} cannot be written as HEVC: 4:2:0 needs even dimensions",
8815 meta.width, meta.height
8816 )
8817 .into());
8818 }
8819 if let Some(hw) = hw_seat(meta, settings, ten_bit, colour)? {
8820 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware HEVC (VA-API plugin)"); }
8821 return Ok(Self::HevcHw(hw, settings.intra_only, ten_bit));
8822 }
8823 if !settings.intra_only {
8824 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC I+P (ec-h265)"); }
8825 return Self::open_hevc_gop(meta, settings, (fps_num, fps_den), ten_bit, colour);
8826 }
8827 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC intra (ec-h265)"); }
8828 // The cores are split between the lanes and the wavefront inside one:
8829 // twelve lanes of one worker each on this box's twelve threads,
8830 // fewer lanes on a smaller machine with a wider wavefront each.
8831 let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
8832 let lane_count = cores.clamp(1, HEVC_LANES);
8833 let per_lane = cores.div_ceil(lane_count);
8834 let mut lanes = Vec::with_capacity(lane_count);
8835 for _ in 0..lane_count {
8836 let mut cfg = HevcEncoderConfig::new(meta.width, meta.height);
8837 cfg.bit_depth = if ten_bit { 10 } else { 8 };
8838 // The bitrate row a user picked, mapped through the same measured
8839 // anchor as before ([`hevc_qp`]) and held: a *quality* dial, not a
8840 // rate controller. The encoder's own per-picture target-bits mode
8841 // would chase the number with a correction pass -- named headroom,
8842 // not behaviour this seat takes silently.
8843 cfg.rate_control = RateControl::ConstantQp(settings.qp.map_or_else(|| hevc_qp(meta, settings), |qp| qp as i32));
8844 cfg.timing = Some((fps_den, fps_num));
8845 cfg.video_signal_type = Some(video_signal_type(colour));
8846 apply_hdr(&mut cfg, settings);
8847 cfg.speed = settings.hevc_speed.unwrap_or_default().preset();
8848 cfg.threads = per_lane;
8849 lanes.push(HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?);
8850 }
8851 Ok(Self::Hevc(HevcEnc {
8852 pending: Vec::new(),
8853 ready: std::collections::VecDeque::new(),
8854 au: Vec::new(),
8855 lanes,
8856 width: meta.width as usize,
8857 ten_bit,
8858 }))
8859 }
8860
8861 /// The ProRes seat: the profile's encoder at the picture's size, tagged with
8862 /// the colour the file declares. Progressive, no alpha.
8863 fn open_prores(meta: &VideoMeta, settings: &ExportSettings, colour: ColorDescription) -> crate::Result<Self> {
8864 if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) {
8865 return Err(format!(
8866 "{}x{} cannot be written as ProRes from a 4:2:0 picture: it needs even dimensions",
8867 meta.width, meta.height
8868 )
8869 .into());
8870 }
8871 let profile = settings.prores_profile;
8872 let mut cfg = ec_prores::EncoderConfig::new(profile.codec(), meta.width, meta.height);
8873 let (primaries, transfer, matrix) = colour.codes();
8874 cfg.color = ec_core::frame::ColorInfo {
8875 primaries: primaries as u8,
8876 transfer: transfer as u8,
8877 matrix: matrix as u8,
8878 full_range: false,
8879 };
8880 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software ProRes (ec-prores)"); }
8881 let encoder = ec_prores::ProResEncoder::new(cfg).map_err(|e| format!("ProRes encoder: {e}"))?;
8882 Ok(Self::ProRes { encoder, au: Vec::new(), full_chroma: profile.is_444() })
8883 }
8884
8885 /// One 10-bit picture of 16-bit planes, at 10-bit scale, in and at most one
8886 /// access unit out. Asked only of the 10-bit seat, which [`wide_ten_bit`] opens
8887 /// with the same answer the export loop checks.
8888 fn encode_wide(
8889 &mut self,
8890 y: &[u16],
8891 u: &[u16],
8892 v: &[u16],
8893 width: u32,
8894 height: u32,
8895 ) -> crate::Result<Option<(&[u8], bool)>> {
8896 match self {
8897 Self::Av1Sw16 { context, ready, au, .. } => {
8898 submit_av1_16(context, ready, au, [y, u, v], width, height)
8899 }
8900 Self::HevcGop(gop) if gop.ten_bit => {
8901 gop.push_wide(y, u, v, width, height)?;
8902 Ok(pop_gop(gop))
8903 }
8904 Self::ProRes { encoder, au, full_chroma } => {
8905 let frame =
8906 crate::prores_out::upsampled_frame(y, u, v, width as usize, height as usize, *full_chroma)?;
8907 *au = encoder.encode(&frame).map_err(|e| format!("ProRes encode: {e}"))?;
8908 Ok(Some((&au[..], true)))
8909 }
8910 Self::HevcHw(hw, intra, true) => Ok(hw
8911 .encode16(y, u, v, width, height, *intra)?
8912 .map(|au| (au, hevc_irap(au)))),
8913 Self::Hevc(hevc) if hevc.ten_bit => {
8914 hevc.pending.push((le_bytes(y), le_bytes(u), le_bytes(v)));
8915 if hevc.pending.len() >= hevc.lanes.len() {
8916 hevc.code_batch()?;
8917 }
8918 Ok(pop_hevc(hevc))
8919 }
8920 _ => Err("a 10-bit picture needs a 10-bit seat".into()),
8921 }
8922 }
8923
8924 /// Whether this is an HEVC seat coding at 10 bits.
8925 fn hevc_ten_bit(&self) -> bool {
8926 match self {
8927 Self::HevcGop(gop) => gop.ten_bit,
8928 Self::Hevc(hevc) => hevc.ten_bit,
8929 Self::HevcHw(_, _, ten) => *ten,
8930 _ => false,
8931 }
8932 }
8933
8934 /// One picture in, at most one access unit out, and whether that unit is one
8935 /// a decoder may be started from -- which only the Matroska muxer asks, the
8936 /// mp4 one reading its own sync flag off the IDR slice.
8937 ///
8938 /// The H.264 seat keeps the contract structurally: `ec-h264` buffers
8939 /// nothing -- no lookahead, and B pictures coded as none -- so one call is
8940 /// one access unit by construction. The HEVC seat's lanes hold a small
8941 /// batch of pictures until there is a lane for each, so it says "at most
8942 /// one" and means it; the old H.264 seat only kept the contract because
8943 /// its GOP-buffering lookahead needed a zero bitrate and this path was
8944 /// always CBR.
8945 fn encode(
8946 &mut self,
8947 y: &[u8],
8948 u: &[u8],
8949 v: &[u8],
8950 width: u32,
8951 height: u32,
8952 intra: bool,
8953 ) -> crate::Result<Option<(&[u8], bool)>> {
8954 // A composed 8-bit picture on the 10-bit HEVC seat: shifted up to the
8955 // seat's scale, the same shift the AV1 10-bit seat makes.
8956 if self.hevc_ten_bit() {
8957 let up = |p: &[u8]| p.iter().map(|&v| u16::from(v) << 2 | u16::from(v) >> 6).collect::<Vec<u16>>();
8958 let (y, u, v) = (up(y), up(u), up(v));
8959 return self.encode_wide(&y, &u, &v, width, height);
8960 }
8961 if let Self::ProRes { encoder, au, full_chroma } = self {
8962 // A composed 8-bit picture: widened to 10 bits and upsampled in one pass.
8963 let frame =
8964 crate::prores_out::upsampled_frame_8(y, u, v, width as usize, height as usize, *full_chroma)?;
8965 *au = encoder.encode(&frame).map_err(|e| format!("ProRes encode: {e}"))?;
8966 return Ok(Some((&au[..], true)));
8967 }
8968 match self {
8969 Self::Av1Hw(hw) => {
8970 let au = hw.encode(y, u, v, width, height, false)?;
8971 // What the *bitstream* says, not what was asked for: an AV1
8972 // keyframe carries the sequence header, which is the same mark
8973 // `demux` reads a sync point off. A driver that emitted one
8974 // unasked is then still a seek target, and one that skipped a
8975 // requested keyframe cannot be mistaken for a decoder's start.
8976 Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
8977 }
8978 Self::Av1Sw16 {
8979 context,
8980 ready,
8981 au,
8982 scratch,
8983 ..
8984 } => {
8985 // An 8-bit picture on the 10-bit seat: each sample scaled up to
8986 // the same range (255 maps to 1023, not 1020).
8987 let (w, h) = (width as usize, height as usize);
8988 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
8989 for (dst, (src, n)) in scratch.iter_mut().zip([(y, w * h), (u, cw * ch), (v, cw * ch)]) {
8990 dst.clear();
8991 dst.extend(src[..n].iter().map(|&s| {
8992 let s = u16::from(s);
8993 (s << 2) | (s >> 6)
8994 }));
8995 }
8996 let [sy, su, sv] = &*scratch;
8997 submit_av1_16(context, ready, au, [&sy[..], &su[..], &sv[..]], width, height)
8998 }
8999 Self::Av1Sw {
9000 context, ready, au, ..
9001 } => {
9002 let mut frame = context.new_frame();
9003 let (w, h) = (width as usize, height as usize);
9004 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
9005 frame.planes[0].copy_from_raw_u8(&y[..w * h], w, 1);
9006 frame.planes[1].copy_from_raw_u8(&u[..cw * ch], cw, 1);
9007 frame.planes[2].copy_from_raw_u8(&v[..cw * ch], cw, 1);
9008 if let Err(e) = context.send_frame(frame) {
9009 return Err(format!("software AV1 encode: {e}").into());
9010 }
9011 collect_av1(context, ready)?;
9012 Ok(pop_av1(ready, au))
9013 }
9014 Self::HevcHw(hw, intra, _) => Ok(hw
9015 .encode(y, u, v, width, height, *intra)?
9016 .map(|au| (au, hevc_irap(au)))),
9017 Self::Hevc(hevc) => {
9018 // The display-size planes are kept as they came: `ec-h265`
9019 // pads to its own coded grid and crops back through the SPS
9020 // conformance window.
9021 hevc.pending.push((y.to_vec(), u.to_vec(), v.to_vec()));
9022 if hevc.pending.len() >= hevc.lanes.len() {
9023 hevc.code_batch()?;
9024 }
9025 // Every intra AU is an IDR, so every one of them is a key
9026 // frame -- which is what an intraframe master means.
9027 Ok(pop_hevc(hevc))
9028 }
9029 Self::HevcGop(gop) => {
9030 gop.push(y, u, v, width, height)?;
9031 Ok(pop_gop(gop))
9032 }
9033 // A key frame is asked for on every picture where the file is an
9034 // intraframe one, and the flag says what was asked: the mp4 muxer
9035 // reads its own sync marks off the IDR slices either way, so this
9036 // is what a Matroska one would be told.
9037 Self::Hw(hw) => Ok(hw
9038 .encode(y, u, v, width, height, intra)?
9039 .map(|au| (au, intra))),
9040 Self::ProRes { .. } => unreachable!("the ProRes seat is handled before this match"),
9041 Self::Sw { encoder, au } => {
9042 // The key flag is what the bitstream says -- an IDR where the
9043 // GOP asked for one, every picture on an intraframe export --
9044 // which is what the hardware seat's `intra` carries too. The
9045 // planes go in as borrows; the old seat was handed a copy.
9046 let view = PictureView::i420(width, height, y, u, v);
9047 let coded = encoder
9048 .encode(&view)
9049 .map_err(|e| format!("software encode: {e}"))?;
9050 *au = coded.au;
9051 Ok(Some((&au[..], coded.key_frame)).filter(|(au, _)| !au.is_empty()))
9052 }
9053 }
9054 }
9055
9056 /// What a decoded buffer must look like to reach this seat without ever
9057 /// being read back -- `None` for every seat that reads bytes, which is both
9058 /// software encoders and the intra HEVC one.
9059 ///
9060 /// The AV1 hardware seat is left out on purpose: it is entered only when a
9061 /// person picks it by name because the vendored encoder reset this project's GPU
9062 /// ([`Enc::open_av1`]), and a path that cannot be measured is not one to
9063 /// widen.
9064 /// `&mut` because an isolated seat has to *ask* the process it lives in
9065 /// ([`crate::hwproc`]), which is a round trip on its socket.
9066 fn dma_want(&mut self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> {
9067 match self {
9068 Self::Hw(hw) | Self::HevcHw(hw, _, false) => hw.dma_want(meta.width, meta.height),
9069 Self::HevcHw(hw, _, true) => hw
9070 .dma_want(meta.width, meta.height)
9071 .map(|want| crate::hw::DmaWant { ten_bit: true, ..want }),
9072 _ => None,
9073 }
9074 }
9075
9076 /// One picture the decoder left on the GPU in, at most one access unit out.
9077 /// Same answer as [`Enc::encode`], including which units a decoder may be
9078 /// started from, because it is the same encoder -- only the picture took
9079 /// another way in.
9080 ///
9081 /// `intra` therefore carries here too, and not for symmetry's sake: a proxy
9082 /// of a file already small enough is coded at that file's own size
9083 /// ([`crate::proxy::size_for`]), which is the one case where an intraframe
9084 /// export's decoder and encoder agree on a surface and the buffer goes
9085 /// straight across. An access unit marked as no sync point there would give
9086 /// a stand-in whose whole reason to exist is that every frame is one.
9087 fn encode_dma(&mut self, dma: &DmaFrame, intra: bool) -> crate::Result<Option<(&[u8], bool)>> {
9088 match self {
9089 Self::Hw(hw) => Ok(hw.encode_dma(dma, intra)?.map(|au| (au, intra))),
9090 Self::HevcHw(hw, intra, _) => Ok(hw.encode_dma(dma, *intra)?.map(|au| (au, hevc_irap(au)))),
9091 // Unreachable through [`Enc::dma_want`], which is the only thing
9092 // that puts a span's decoder on this path.
9093 _ => Err("this encoder takes pictures as bytes, not as buffers".into()),
9094 }
9095 }
9096
9097 /// End of stream; call until it returns `None`.
9098 fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> {
9099 match self {
9100 Self::Av1Hw(hw) => {
9101 let au = hw.drain()?;
9102 Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some())))
9103 }
9104 Self::Av1Sw16 {
9105 context,
9106 ready,
9107 au,
9108 flushed,
9109 ..
9110 } => {
9111 if !*flushed {
9112 *flushed = true;
9113 context.flush();
9114 collect_av1(context, ready)?;
9115 }
9116 Ok(pop_av1(ready, au))
9117 }
9118 Self::Av1Sw {
9119 context,
9120 ready,
9121 au,
9122 flushed,
9123 } => {
9124 if !*flushed {
9125 *flushed = true;
9126 context.flush();
9127 collect_av1(context, ready)?;
9128 }
9129 Ok(pop_av1(ready, au))
9130 }
9131 Self::HevcHw(hw, ..) => Ok(hw.drain()?.map(|au| (au, hevc_irap(au)))),
9132 // The tail batch: fewer frames than lanes, coded on as many
9133 // encoders as there are frames left.
9134 Self::Hevc(hevc) => {
9135 if !hevc.pending.is_empty() {
9136 hevc.code_batch()?;
9137 }
9138 Ok(pop_hevc(hevc))
9139 }
9140 Self::HevcGop(gop) => {
9141 gop.finish()?;
9142 Ok(pop_gop(gop))
9143 }
9144 Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))),
9145 // Nothing is held back: every picture `encode` took already came
9146 // back with its access unit, so end of stream is the empty answer.
9147 Self::Sw { .. } | Self::ProRes { .. } => Ok(None),
9148 }
9149 }
9150}
9151
9152impl HevcEnc {
9153 /// The whole pending batch, one frame per lane, collected back in the
9154 /// order it went out -- `std::thread::scope`, because the encode borrows
9155 /// the planes and the lanes rather than copying them again. A panic inside
9156 /// a lane comes back as an error rather than unwinding the export thread.
9157 fn code_batch(&mut self) -> crate::Result<()> {
9158 let width = self.width;
9159 let chroma = width / 2;
9160 let pending = std::mem::take(&mut self.pending);
9161 let ten_bit = self.ten_bit;
9162 let coded: Vec<crate::Result<Vec<u8>>> = std::thread::scope(|scope| {
9163 let lanes: Vec<_> = self
9164 .lanes
9165 .iter()
9166 .zip(pending.iter())
9167 .map(|(encoder, (y, cb, cr))| {
9168 scope.spawn(move || {
9169 let coded = if ten_bit {
9170 let samples = |p: &[u8]| -> Vec<u16> {
9171 p.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect()
9172 };
9173 let (y, cb, cr) = (samples(y), samples(cb), samples(cr));
9174 encoder.encode_idr_samples(&y, width, &cb, chroma, &cr, chroma)
9175 } else {
9176 encoder.encode_idr_planes(y, width, cb, chroma, cr, chroma)
9177 };
9178 coded
9179 .map(|coded| coded.au)
9180 .map_err(|e| crate::Error::from(format!("software HEVC encode: {e}")))
9181 })
9182 })
9183 .collect();
9184 lanes
9185 .into_iter()
9186 .map(|lane| {
9187 lane.join()
9188 .unwrap_or_else(|_| Err("an HEVC encode lane panicked".into()))
9189 })
9190 .collect()
9191 });
9192 for au in coded {
9193 self.ready.push_back(au?);
9194 }
9195 Ok(())
9196 }
9197}
9198
9199/// The oldest coded intra AU, lent out under the same "valid until the next
9200/// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key
9201/// flag is not a guess.
9202fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> {
9203 hevc.au = hevc.ready.pop_front()?;
9204 Some((&hevc.au[..], true))
9205}
9206
9207/// The longest GOP the HEVC seat asks for, in pictures. `ec-h265` codes GOPs
9208/// concurrently only up to this length, and the sequence coder's own limit is
9209/// 256; a 60 fps export is 60 pictures and a faster one takes the serial path.
9210const HEVC_GOP_MAX_KEYINT: usize = 64;
9211
9212/// The longest key interval `ec-h265` codes, in pictures; a `keyframe_s` past it is capped here.
9213const HEVC_KEYINT_MAX: usize = 256;
9214
9215impl Enc {
9216 /// The HEVC I+P seat: `ec-h265`'s sequence coder, an IDR once a second at
9217 /// the picture's own rate with P pictures between, on a worker thread.
9218 ///
9219 /// The export walk pushes one picture at a time and the encoder pulls its
9220 /// frames from an iterator, so the two meet on a bounded channel: the walk
9221 /// is never more than one GOP ahead of the worker. The encoder codes whole
9222 /// GOPs concurrently on [`default_threads`](ec_h265::encoder::default_threads)
9223 /// workers, which is at most six, and hands the pictures back in order.
9224 ///
9225 /// Rate: an explicit bitrate row goes to bitrate control at that rate, the
9226 /// same number the H.264 seat codes at. No bitrate is the automatic quality
9227 /// row, constant QP at [`HEVC_GOP_QP`]: a quality default of its own, not
9228 /// the intra seat's [`hevc_qp`], whose anchor is measured on intra pictures.
9229 fn open_hevc_gop(
9230 meta: &VideoMeta,
9231 settings: &ExportSettings,
9232 (fps_num, fps_den): (u32, u32),
9233 ten_bit: bool,
9234 colour: ColorDescription,
9235 ) -> crate::Result<Self> {
9236 let keyint = gop_frames(meta, settings).map_or_else(|| hevc_gop_keyint(meta.frame_rate), |g| (g as usize).clamp(2, HEVC_KEYINT_MAX));
9237 let mut cfg = HevcEncoderConfig::new(meta.width, meta.height);
9238 cfg.bit_depth = if ten_bit { 10 } else { 8 };
9239 cfg.rate_control = match (settings.qp, settings.bitrate) {
9240 (Some(qp), _) => RateControl::ConstantQp(qp as i32),
9241 (None, Some(_)) => RateControl::Bitrate {
9242 kbps: (bitrate_of(meta, settings) / 1000).max(1) as u32,
9243 fps: meta.frame_rate,
9244 },
9245 (None, None) => RateControl::ConstantQp(HEVC_GOP_QP),
9246 };
9247 cfg.keyint = keyint;
9248 cfg.threads = ec_h265::encoder::default_threads();
9249 cfg.timing = Some((fps_den, fps_num));
9250 cfg.video_signal_type = Some(video_signal_type(colour));
9251 apply_hdr(&mut cfg, settings);
9252 cfg.speed = settings.hevc_speed.unwrap_or_default().preset();
9253 let encoder = HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?;
9254 let (frames_tx, frames_rx) = sync_channel::<VideoFrame>(keyint);
9255 let (au_tx, coded) = std::sync::mpsc::channel::<(Vec<u8>, bool)>();
9256 // The P pictures refer to a second picture parameter set, which the
9257 // samples do not keep: the first unit carries it, so the record the
9258 // container builds from that unit holds it.
9259 let p_pps = encoder.p_picture_parameter_set();
9260 let worker = thread::Builder::new()
9261 .name("ec-h265-gop".into())
9262 .spawn(move || {
9263 let mut picture = 0usize;
9264 encoder
9265 .encode_sequence_with(frames_rx, |pic| {
9266 // Every GOP opens on an IDR, so a picture's key flag is
9267 // its place in the sequence.
9268 let key = picture.is_multiple_of(keyint);
9269 let au = if picture == 0 {
9270 with_parameter_set(pic.au, &p_pps)
9271 } else {
9272 pic.au
9273 };
9274 picture += 1;
9275 // A closed receiver is an export dropped part way: the
9276 // rest is unwanted, and draining it is not an error.
9277 let _ = au_tx.send((au, key));
9278 Ok(())
9279 })
9280 .map_err(|e| e.to_string())
9281 })
9282 .map_err(|e| format!("HEVC software encoder: {e}"))?;
9283 Ok(Self::HevcGop(HevcGop {
9284 frames: Some(frames_tx),
9285 worker: Some(worker),
9286 coded,
9287 ready: std::collections::VecDeque::new(),
9288 au: Vec::new(),
9289 ten_bit,
9290 }))
9291 }
9292}
9293
9294/// The GOP the I+P seat codes at this frame rate: an IDR about a second apart.
9295fn hevc_gop_keyint(frame_rate: f64) -> usize {
9296 (frame_rate.round() as usize).clamp(2, HEVC_GOP_MAX_KEYINT)
9297}
9298
9299/// What an HEVC export codes as, in the words an export start names: the I+P
9300/// GOP and its key interval and rate, or `intra-only`. `None` for any other
9301/// format. The rate is the bitrate the file aims at, or, with no bitrate given,
9302/// the quality mode the automatic row codes at: constant QP ([`HEVC_GOP_QP`]), named
9303/// with its number and with how to ask for a fixed rate instead.
9304pub fn hevc_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<String> {
9305 if !settings.format.is_hevc() {
9306 return None;
9307 }
9308 if settings.intra_only {
9309 return Some(match (settings.qp, settings.bitrate) {
9310 (Some(qp), _) => format!("intra-only, constant QP {qp}"),
9311 (None, Some(_)) => "intra-only".to_string(),
9312 (None, None) => format!(
9313 "intra-only, constant quality QP {} on the software seat (the GPU seat codes at the automatic rate); pass bitrate_kbps for a fixed rate",
9314 hevc_qp(meta, settings)
9315 ),
9316 });
9317 }
9318 let seconds = gop_frames(meta, settings).map_or_else(|| hevc_gop_keyint(meta.frame_rate), |g| g as usize) as f64 / meta.frame_rate;
9319 let every = if (seconds - seconds.round()).abs() < 1e-6 {
9320 format!("{} s", seconds.round() as u64)
9321 } else {
9322 format!("{seconds:.2} s")
9323 };
9324 let rate = match (settings.qp, settings.bitrate) {
9325 (Some(qp), _) => format!("constant QP {qp}"),
9326 (None, Some(_)) => rate_words(bitrate_of(meta, settings) / 1000),
9327 (None, None) => format!("constant quality QP {HEVC_GOP_QP}; pass bitrate_kbps for a fixed rate"),
9328 };
9329 Some(format!("I+P GOP ({every} keyframes), {rate}"))
9330}
9331
9332/// What an AV1 export codes as, in the words an export start names. AV1 is always
9333/// coded at a bitrate, so with none given the automatic target is named as one
9334/// (chosen from the picture size and frame rate). `None` for any other format.
9335pub fn av1_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<String> {
9336 if !settings.format.is_av1() {
9337 return None;
9338 }
9339 if let Some(qp) = settings.qp {
9340 return Some(format!("constant QP {qp}"));
9341 }
9342 let rate = rate_words(bitrate_of(meta, settings) / 1000);
9343 Some(match settings.bitrate {
9344 Some(_) => format!("average bitrate {rate}"),
9345 None => format!("average bitrate {rate} chosen from the picture size and frame rate; pass bitrate_kbps for a fixed rate"),
9346 })
9347}
9348
9349/// A rate in kilobits a second, in the words a reply uses: `4 Mb/s` on a whole megabit, `6.2 Mb/s`
9350/// above one, else `850 kb/s`.
9351fn rate_words(kbps: u64) -> String {
9352 if kbps.is_multiple_of(1000) {
9353 format!("{} Mb/s", kbps / 1000)
9354 } else if kbps >= 1000 {
9355 format!("{:.1} Mb/s", kbps as f64 / 1000.0)
9356 } else {
9357 format!("{kbps} kb/s")
9358 }
9359}
9360
9361/// The words an export start names when the source's chroma is reduced to 4:2:0 on
9362/// the way out, e.g. `VP9 4:4:4 source: chroma reduced to 4:2:0 for export`. `codec`
9363/// and `chroma` are the source's; the chroma is read off the stream
9364/// ([`Demuxer::chroma`]). `None` where nothing is reduced: a 4:2:0 or grey source,
9365/// or a sound-only format, which has no picture to reduce.
9366pub fn chroma_reduction_words(codec: Codec, chroma: Chroma, settings: &ExportSettings) -> Option<String> {
9367 let format = match chroma {
9368 Chroma::C422 => "4:2:2",
9369 Chroma::C444 => "4:4:4",
9370 _ => return None,
9371 };
9372 if !settings.format.has_video() {
9373 return None;
9374 }
9375 Some(format!("{} {format} source: chroma reduced to 4:2:0 for export", codec.name()))
9376}
9377
9378/// The I+P seat's state: the worker running the sequence coder, the channel
9379/// the frames go to it on, and the access units it has handed back.
9380struct HevcGop {
9381 /// The frames for the worker, in display order. `None` once the sequence
9382 /// has ended, which is what lets the worker finish its last GOP.
9383 frames: Option<SyncSender<VideoFrame>>,
9384 worker: Option<thread::JoinHandle<Result<(), String>>>,
9385 /// Access units and their key flags, in coding order, which is display order.
9386 coded: Receiver<(Vec<u8>, bool)>,
9387 /// Units collected from `coded` and not yet handed to the caller.
9388 ready: std::collections::VecDeque<(Vec<u8>, bool)>,
9389 /// The unit currently lent out, for the reason `Sw` owns one.
9390 au: Vec<u8>,
9391 /// Whether the sequence codes at 10 bits: its frames are I010 then.
9392 ten_bit: bool,
9393}
9394
9395impl HevcGop {
9396 fn push(&mut self, y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> crate::Result<()> {
9397 let frame = i420_frame(y, u, v, width, height)?;
9398 self.send(frame)
9399 }
9400
9401 /// One 10-bit picture of 16-bit samples, as the I010 frame the 10-bit sequence takes.
9402 fn push_wide(&mut self, y: &[u16], u: &[u16], v: &[u16], width: u32, height: u32) -> crate::Result<()> {
9403 let frame = i010_frame(y, u, v, width, height)?;
9404 self.send(frame)
9405 }
9406
9407 fn send(&mut self, frame: VideoFrame) -> crate::Result<()> {
9408 if self
9409 .frames
9410 .as_ref()
9411 .is_some_and(|tx| tx.send(frame).is_ok())
9412 {
9413 self.collect();
9414 return Ok(());
9415 }
9416 // The worker has stopped on its own: its error is the answer.
9417 self.finish()?;
9418 Err("the HEVC encoder stopped before the export ended".into())
9419 }
9420
9421 /// Ends the sequence and waits for the worker's last GOP.
9422 fn finish(&mut self) -> crate::Result<()> {
9423 self.frames = None;
9424 if let Some(worker) = self.worker.take() {
9425 match worker.join() {
9426 Ok(Ok(())) => {}
9427 Ok(Err(e)) => return Err(format!("software HEVC encode: {e}").into()),
9428 Err(_) => return Err("the HEVC encoder thread panicked".into()),
9429 }
9430 }
9431 self.collect();
9432 Ok(())
9433 }
9434
9435 fn collect(&mut self) {
9436 while let Ok(unit) = self.coded.try_recv() {
9437 self.ready.push_back(unit);
9438 }
9439 }
9440}
9441
9442/// One I420 picture at the display size, as the sequence coder takes it.
9443fn i420_frame(y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> crate::Result<VideoFrame> {
9444 let (w, h) = (width as usize, height as usize);
9445 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
9446 let planes = vec![
9447 ec_core::frame::Plane::new(y[..w * h].to_vec(), w),
9448 ec_core::frame::Plane::new(u[..cw * ch].to_vec(), cw),
9449 ec_core::frame::Plane::new(v[..cw * ch].to_vec(), cw),
9450 ];
9451 VideoFrame::try_new(ec_core::frame::PixelFormat::I420, width, height, planes)
9452 .map_err(|e| format!("HEVC frame: {e}").into())
9453}
9454
9455/// One 10-bit I010 picture at the display size: 16-bit little-endian samples, the
9456/// stride in bytes, as the sequence coder takes it.
9457fn i010_frame(y: &[u16], u: &[u16], v: &[u16], width: u32, height: u32) -> crate::Result<VideoFrame> {
9458 let (w, h) = (width as usize, height as usize);
9459 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
9460 let planes = vec![
9461 ec_core::frame::Plane::new(le_bytes(&y[..w * h]), w * 2),
9462 ec_core::frame::Plane::new(le_bytes(&u[..cw * ch]), cw * 2),
9463 ec_core::frame::Plane::new(le_bytes(&v[..cw * ch]), cw * 2),
9464 ];
9465 VideoFrame::try_new(ec_core::frame::PixelFormat::I010, width, height, planes)
9466 .map_err(|e| format!("HEVC frame: {e}").into())
9467}
9468
9469/// Little-endian bytes of 16-bit samples.
9470fn le_bytes(samples: &[u16]) -> Vec<u8> {
9471 samples.iter().flat_map(|s| s.to_le_bytes()).collect()
9472}
9473
9474/// `au` with `nal` (one Annex-B unit) placed before its first coded slice, so
9475/// after the parameter sets that open the unit. `au` comes back as it went in
9476/// where it has no slice.
9477fn with_parameter_set(au: Vec<u8>, nal: &[u8]) -> Vec<u8> {
9478 let starts = (0..au.len().saturating_sub(3)).filter(|&i| au[i..i + 3] == [0, 0, 1]);
9479 for start in starts {
9480 // The NAL unit type is the six bits after the forbidden bit.
9481 if (au[start + 3] >> 1) & 0x3F < 32 {
9482 // A four-byte start code keeps its leading zero in front of the new unit.
9483 let at = if start > 0 && au[start - 1] == 0 {
9484 start - 1
9485 } else {
9486 start
9487 };
9488 let mut out = Vec::with_capacity(au.len() + nal.len());
9489 out.extend_from_slice(&au[..at]);
9490 out.extend_from_slice(nal);
9491 out.extend_from_slice(&au[at..]);
9492 return out;
9493 }
9494 }
9495 au
9496}
9497
9498fn pop_gop(gop: &mut HevcGop) -> Option<(&[u8], bool)> {
9499 let (au, key) = gop.ready.pop_front()?;
9500 gop.au = au;
9501 Some((&gop.au[..], key))
9502}
9503/// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a
9504/// user picked -- the card has no QP control and this codec has no rate control,
9505/// so the two are joined by measurement rather than promised to each other.
9506///
9507/// The encoder codes ~0.6 bits per pixel at QP 27 ([`HEVC_BPP_AT_27`], measured
9508/// on the 720p and 1080p benches to within 4% of each other), and a step of 6 QP
9509/// is a factor of two in rate, which is the classic HEVC relation. So the QP
9510/// that would land on a target is `27 + 6 * log2(0.6 / target)` -- and it is
9511/// clamped, because this is a *quality* dial and not a rate controller: below QP
9512/// 22 the file grows without a picture to show for it, and past QP 40 an
9513/// intra-only frame goes blocky in a way no bitrate row asked for. A 1080p30
9514/// timeline at the automatic 6.2 Mbps therefore codes at QP 40 and comes out
9515/// bigger than that, which is what "intra-only, large files" on the format row
9516/// means: the row buys quality, not a size.
9517fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 {
9518 let pixels = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate;
9519 let target = bitrate_of(meta, settings) as f64 / pixels.max(1.0);
9520 let qp = 27.0 + 6.0 * (HEVC_BPP_AT_27 / target.max(f64::MIN_POSITIVE)).log2();
9521 (qp.round() as i32).clamp(HEVC_QP_MIN, HEVC_QP_MAX)
9522}
9523
9524/// What the *bitstream* says the samples mean, in the words a sequence header
9525/// spells them -- the same H.273 code points [`crate::mux`] writes into the
9526/// container, from the same colour the export declares there ([`source_sdr_colour`] or the
9527/// [`ColorDescription::output`] rule), so the two halves of a file cannot drift apart.
9528///
9529/// This exists because a container tag is not enough: libavcodec takes the
9530/// bitstream's answer first, and a stream that says nothing is "unspecified",
9531/// which renders BT.601 -- a visible shift on a 709 export that a player reads
9532/// from the wrong matrix. Every export is limited range, which is what
9533/// `video_full_range_flag = false` says here.
9534fn video_signal_type(colour: ColorDescription) -> HevcVideoSignalType {
9535 let (primaries, transfer, matrix) = colour.codes();
9536 HevcVideoSignalType {
9537 // "Unspecified", which is what every encoder here writes: the field is
9538 // the analogue system a picture came off, and none of these did.
9539 video_format: 5,
9540 video_full_range_flag: false,
9541 colour_description: Some(HevcColourDescription {
9542 colour_primaries: primaries as u8,
9543 transfer_characteristics: transfer as u8,
9544 matrix_coeffs: matrix as u8,
9545 }),
9546 }
9547}
9548
9549/// The HDR extras of an HEVC export, in the bitstream: BT.2020's chroma sample
9550/// location (type 2, top-left) in the VUI, and the mastering display and content
9551/// light SEIs where [`ExportSettings::hdr`] gives them. Nothing for an SDR export,
9552/// whose stream stays byte-identical to what it was.
9553fn apply_hdr(cfg: &mut HevcEncoderConfig, settings: &ExportSettings) {
9554 let hdr = &settings.hdr;
9555 if hdr.transfer == HdrTransfer::Sdr {
9556 return;
9557 }
9558 cfg.chroma_sample_loc = Some((2, 2));
9559 cfg.mastering_display = hdr.mastering_display.map(|m| ec_h265_syntax::sei::MasteringDisplay {
9560 display_primaries: m.primaries,
9561 white_point: m.white_point,
9562 max_luminance: m.max_luminance,
9563 min_luminance: m.min_luminance,
9564 });
9565 cfg.content_light.max_cll = hdr.max_cll.map(f32::from);
9566 cfg.content_light.max_fall = hdr.max_fall.map(f32::from);
9567}
9568
9569/// The colour a 10-bit export declares when every clip is SDR in one matrix: that
9570/// matrix, limited range, the source's own rather than the output rule's. `None`
9571/// for a mixed timeline, an HDR one or an empty one, which keep the rule.
9572fn source_sdr_colour(colours: &[ColorDescription]) -> Option<ColorDescription> {
9573 let first = *colours.first()?;
9574 let same = colours
9575 .iter()
9576 .all(|c| c.transfer == Transfer::Sdr && c.matrix == first.matrix);
9577 (same && first.transfer == Transfer::Sdr).then_some(ColorDescription {
9578 matrix: first.matrix,
9579 transfer: Transfer::Sdr,
9580 full_range: false,
9581 })
9582}
9583
9584/// Whether a software export is written at 10 bits: the setting where it names a
9585/// depth, the source's own where it does not. AV1 and HEVC have the choice --
9586/// H.264 is 8-bit here -- and a depth the file cannot be is refused. A 10-bit
9587/// HEVC export takes the hardware seat (Main10) where there is one ([`open_hevc`]).
9588fn wide_ten_bit(
9589 settings: &ExportSettings,
9590 source_ten_bit: impl FnOnce() -> bool,
9591) -> crate::Result<bool> {
9592 // ProRes is coded at 10 bits whatever the setting says (it has no 8-bit
9593 // sample), so the walk keeps 10-bit sources at 10 bits.
9594 if settings.format.is_prores() {
9595 return Ok(true);
9596 }
9597 if !settings.format.is_av1() && !settings.format.is_hevc() {
9598 return Ok(false);
9599 }
9600 // An HDR transfer is a 10-bit claim: 8 bits of PQ bands visibly.
9601 if settings.hdr.transfer != HdrTransfer::Sdr {
9602 return match settings.video_bit_depth {
9603 Some(8) => Err("an HDR export is 10-bit: PQ and HLG are not carried in 8 bits".into()),
9604 Some(10) | None => Ok(true),
9605 Some(bits) => Err(format!("an AV1 or HEVC export is 8 or 10 bits, not {bits}").into()),
9606 };
9607 }
9608 match settings.video_bit_depth {
9609 None => Ok(source_ten_bit()),
9610 Some(8) => Ok(false),
9611 Some(10) => Ok(true),
9612 Some(bits) => Err(format!("an AV1 or HEVC export is 8 or 10 bits, not {bits}").into()),
9613 }
9614}
9615
9616/// The colour an HDR HEVC export declares, or `None` for an SDR export; `Err`
9617/// where the settings ask for HDR of something that cannot carry it.
9618fn hdr_colour_of(settings: &ExportSettings) -> crate::Result<Option<ColorDescription>> {
9619 let hdr = &settings.hdr;
9620 let Some(colour) = hdr.transfer.colour() else {
9621 if hdr.mastering_display.is_some() || hdr.max_cll.is_some() || hdr.max_fall.is_some() {
9622 return Err("mastering display and MaxCLL/MaxFALL need an HDR transfer (PQ or HLG)".into());
9623 }
9624 return Ok(None);
9625 };
9626 if !settings.format.is_hevc() {
9627 return Err(format!("{} cannot be written as HDR: only HEVC is", settings.format.name()).into());
9628 }
9629 if settings.keep_source_colour {
9630 return Err("an HDR export cannot also keep its source's colour".into());
9631 }
9632 Ok(Some(colour))
9633}
9634
9635fn transfer_name(t: Transfer) -> &'static str {
9636 match t {
9637 Transfer::Sdr => "SDR",
9638 Transfer::Pq => "PQ",
9639 Transfer::Hlg => "HLG",
9640 }
9641}
9642
9643/// Every temporal unit `rav1e` has finished, moved into the queue in display
9644/// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is
9645/// through) are the two ways it says there is nothing more; `Encoded` means a
9646/// picture was coded but not yet packetised, which is a *keep asking* -- taking
9647/// it for an end leaves the tail of the export inside the encoder.
9648fn collect_av1<T: rav1e::prelude::Pixel>(
9649 context: &mut rav1e::Context<T>,
9650 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
9651) -> crate::Result<()> {
9652 use rav1e::prelude::{EncoderStatus, FrameType};
9653 loop {
9654 match context.receive_packet() {
9655 Ok(packet) => ready.push_back((packet.data, packet.frame_type == FrameType::KEY)),
9656 Err(EncoderStatus::Encoded) => {}
9657 Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()),
9658 Err(e) => return Err(format!("software AV1 encode: {e}").into()),
9659 }
9660 }
9661}
9662
9663/// The oldest finished unit, moved into the buffer that is lent out -- the same
9664/// "valid until the next call" contract the plugin's slice has.
9665fn pop_av1<'a>(
9666 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
9667 au: &'a mut Vec<u8>,
9668) -> Option<(&'a [u8], bool)> {
9669 let (unit, key) = ready.pop_front()?;
9670 *au = unit;
9671 Some((&au[..], key))
9672}
9673
9674/// One picture of 16-bit planes into the 10-bit `rav1e` context, and whatever
9675/// unit it finished. The planes are the picture's own size, 4:2:0.
9676fn submit_av1_16<'a>(
9677 context: &mut rav1e::Context<u16>,
9678 ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>,
9679 au: &'a mut Vec<u8>,
9680 planes: [&[u16]; 3],
9681 width: u32,
9682 height: u32,
9683) -> crate::Result<Option<(&'a [u8], bool)>> {
9684 let (w, h) = (width as usize, height as usize);
9685 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
9686 let mut frame = context.new_frame();
9687 // A plane's rows sit `stride` apart from its origin, past any padding.
9688 let fill = |plane: &mut rav1e::prelude::Plane<u16>, src: &[u16], w: usize, h: usize| {
9689 let stride = plane.cfg.stride;
9690 let dst = plane.data_origin_mut();
9691 for (row, line) in src.chunks_exact(w).take(h).enumerate() {
9692 dst[row * stride..row * stride + w].copy_from_slice(line);
9693 }
9694 };
9695 fill(&mut frame.planes[0], &planes[0][..w * h], w, h);
9696 fill(&mut frame.planes[1], &planes[1][..cw * ch], cw, ch);
9697 fill(&mut frame.planes[2], &planes[2][..cw * ch], cw, ch);
9698 if let Err(e) = context.send_frame(frame) {
9699 return Err(format!("software AV1 encode: {e}").into());
9700 }
9701 collect_av1(context, ready)?;
9702 Ok(pop_av1(ready, au))
9703}
9704
9705/// A 10-bit plane narrowed to 8 bits for the composition that runs at 8 bits: the
9706/// same truncation [`crate::decode::narrow_av1`] makes on playback.
9707fn narrow_10(src: &[u16], dst: &mut Vec<u8>) {
9708 dst.clear();
9709 dst.extend(src.iter().map(|&s| (s >> 2) as u8));
9710}
9711
9712/// The frame as an 8-bit composition takes it: a 10-bit picture narrowed into
9713/// `scratch`, anything else as it came.
9714fn narrowed<'a>(frame: Frame<'a>, scratch: &'a mut [Vec<u8>; 3]) -> Frame<'a> {
9715 match frame {
9716 Frame::Wide(y, u, v, width, height) => {
9717 let [sy, su, sv] = scratch;
9718 narrow_10(y, sy);
9719 narrow_10(u, su);
9720 narrow_10(v, sv);
9721 Frame::Pixels(&sy[..], &su[..], &sv[..], width, height)
9722 }
9723 other => other,
9724 }
9725}
9726
9727/// I420 straight out of the decoder: the export never converts to BGRA and back,
9728/// which would cost two conversions and a generation of colour precision.
9729///
9730/// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`,
9731/// which only speaks BGRA. A hardware decode that fails *before* the first
9732/// picture falls back to software, exactly as playback's does -- nothing has
9733/// been encoded yet, so the span can be taken over cleanly. One that fails
9734/// after the first picture fails the export, which then deletes the
9735/// half-written file: a restart there would re-encode what the muxer holds.
9736enum ClipDecoder {
9737 /// A stream, decoded on a thread of its own: the encode of picture *n* and
9738 /// the decode of picture *n + 1* are the two halves an export used to do in
9739 /// turns, each idle while the other worked. The channel is two pictures
9740 /// deep, so the decoder runs no further ahead than that (a 1080p I420
9741 /// picture is 3.1 MB) and a slow encoder still stops it.
9742 ///
9743 /// The thread is also where the plugin is *opened*: a VA-API session is not
9744 /// ours to hand between threads ([`crate::decode::open_worker_deferred`]
9745 /// keeps the same rule), which is why the open's error comes back down the
9746 /// channel rather than out of [`ClipDecoder::open`].
9747 Streamed(Streamed),
9748 /// A still image: one picture, handed out for as long as the span runs.
9749 /// It is decoded here rather than in `run`'s loop for the same reason the
9750 /// other two are opened there -- the span's pictures come from one place,
9751 /// and no thread can make one picture arrive sooner.
9752 Still(crate::decode::Still),
9753 /// A clip played backwards ([`Reversed`]): its pictures, last to first.
9754 Reversed(Box<Reversed>),
9755 /// An audio file playing as a picture: each `next` paints one visualizer
9756 /// frame from peaks already decoded ([`crate::decode::visualizer_i420`]).
9757 Visualizer {
9758 peaks: Vec<(f32, f32)>,
9759 width: u32,
9760 height: u32,
9761 fps: f64,
9762 next: u32,
9763 flags: u8,
9764 paint: u64,
9765 /// This seat's own painting scratch, kept for the whole export: the
9766 /// same reuse the playback worker's thread does.
9767 scratch: crate::decode::VizScratch,
9768 y: Vec<u8>,
9769 u: Vec<u8>,
9770 v: Vec<u8>,
9771 },
9772}
9773
9774/// One 8-bit picture owned: its three planes and the size.
9775type Owned = (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32);
9776
9777/// A clip's pictures in reverse ([`ClipDecoder::reversed`]).
9778struct Reversed {
9779 path: PathBuf,
9780 walk: crate::reverse::Walk,
9781 /// The block being served, oldest first: the next picture is the last one.
9782 block: Vec<Owned>,
9783 /// The picture last handed out, which `next` lends.
9784 current: Option<Owned>,
9785 /// The clip's deinterlace setting; `Field` makes the numbers above fields.
9786 deint: Deinterlace,
9787}
9788
9789impl Reversed {
9790 fn next(&mut self) -> crate::Result<Option<Frame<'_>>> {
9791 if self.block.is_empty() && !self.fill()? {
9792 return Ok(None);
9793 }
9794 self.current = self.block.pop();
9795 Ok(self
9796 .current
9797 .as_ref()
9798 .map(|(y, u, v, w, h)| Frame::Pixels(y, u, v, *w, *h)))
9799 }
9800
9801 /// Decodes the next block down, forwards, into `block`. `false` when the window
9802 /// has no frames left, or the file gave none.
9803 fn fill(&mut self) -> crate::Result<bool> {
9804 let Some((start, end)) = self.walk.next() else {
9805 return Ok(false);
9806 };
9807 let mut decoder = ClipDecoder::open_with(&self.path, start, None, None, false, self.deint)?;
9808 for _ in start..end {
9809 match decoder.next()? {
9810 Some(Frame::Pixels(y, u, v, w, h)) => {
9811 if self.block.is_empty() {
9812 // The pictures' real size is known now: hold as many as the
9813 // budget allows from the next block on.
9814 let bytes = y.len() + u.len() + v.len();
9815 self.walk.set_cap(crate::reverse::block_cap(bytes));
9816 }
9817 self.block.push((y.to_vec(), u.to_vec(), v.to_vec(), w, h));
9818 }
9819 Some(_) => return Err("a reversed clip's decoder produced no pixels".into()),
9820 None => break,
9821 }
9822 }
9823 Ok(!self.block.is_empty())
9824 }
9825}
9826
9827/// The planes of one 10-bit picture, borrowed from its seat: luma, the two
9828/// chroma planes, and the size.
9829type Wide16View<'a> = (&'a [u16], &'a [u16], &'a [u16], u32, u32);
9830
9831/// The receiving half of a decode thread, plus the picture it last handed out
9832/// -- which is what lets `next` keep lending planes rather than moving them.
9833///
9834/// The first two fields are in this order on purpose, and it is the order
9835/// [`crate::decode::FrameStream`] states for the same pair: Rust drops fields as
9836/// they are declared, so the receiver disconnects *first* -- the only thing that
9837/// wakes a decoder parked in a full `send` -- and the join inside
9838/// [`DecodeThread::drop`] runs second. The other way round is a hang and not a
9839/// slow path.
9840struct Streamed {
9841 frames: Receiver<crate::Result<Option<Yuv>>>,
9842 /// Held only to be dropped: joining is all it does, and it must happen
9843 /// after the receiver above (`_lib` in `crate::hw` is kept the same way).
9844 /// Its result is the software decoder a stopped span leaves behind, if any.
9845 _thread: DecodeThread<Option<Kept>>,
9846 current: Option<Yuv>,
9847 /// Whether the thread has said "no more pictures" in as many words. What
9848 /// separates a stream that ended from a thread that vanished: after this,
9849 /// the channel is disconnected because the decoder is *done*, and a further
9850 /// ask is end of stream rather than a failure.
9851 ended: bool,
9852 /// Where the decoder goes when this span is done with it, if it may be kept.
9853 park: Option<Park>,
9854}
9855
9856/// What a decode thread leaves behind when it is stopped or runs out: the
9857/// decoder, and the pictures from the last one its span took on, in order.
9858/// A hardware session carries the file frame it decodes next.
9859type Kept = (Held, VecDeque<Yuv>);
9860
9861enum Held {
9862 Sw(Box<SwDecoder>),
9863 Hw(Box<HwSession>, u32),
9864}
9865
9866#[derive(Clone, PartialEq)]
9867struct OpenPlan {
9868 path: PathBuf,
9869 start: u32,
9870 untouched: bool,
9871 deint: Deinterlace,
9872 tail: u32,
9873}
9874
9875/// The way back from a span's [`Streamed`] to the [`Parked`] lot: the lot, the
9876/// file, and the flag that asks the decode thread to stop at its next picture.
9877struct Park {
9878 lot: Arc<Parked>,
9879 path: PathBuf,
9880 stop: Arc<AtomicBool>,
9881}
9882
9883/// Software H.264 decoders from spans that have ended, kept so that the next
9884/// span of the same file can carry on from where they stopped instead of
9885/// seeking back to a sync sample and decoding the whole GOP in front of its in
9886/// point again (a long-GOP source pays up to a GOP per clip that way).
9887///
9888/// Only a software decoder that is *resumable* is ever taken: see [`resumable`].
9889/// A hardware session is taken by file and repositioned with its own seek.
9890#[derive(Default)]
9891struct Parked(Mutex<VecDeque<ParkedDecoder>>);
9892
9893/// Most decoders kept at once. Each holds a demuxer and its reference pictures,
9894/// so the lot stays small: a dissolve needs two, and a multi-source edit a few.
9895const PARKED_MAX: usize = 4;
9896
9897/// One decoder in the lot: the file it reads, the decoder itself, and the
9898/// pictures it decoded that no span took (see [`Kept`]).
9899struct ParkedDecoder {
9900 path: PathBuf,
9901 decoder: Held,
9902 backlog: VecDeque<Yuv>,
9903}
9904
9905struct ParkedSw {
9906 decoder: Box<SwDecoder>,
9907 backlog: VecDeque<Yuv>,
9908}
9909
9910impl Parked {
9911 fn keep(&self, entry: ParkedDecoder) {
9912 let Ok(mut lot) = self.0.lock() else { return };
9913 lot.push_back(entry);
9914 while lot.len() > PARKED_MAX {
9915 lot.pop_front();
9916 }
9917 }
9918
9919 /// The decoder that can serve a span of `path` starting at `start`, taken
9920 /// out of the lot and wound forward to that picture: whatever it holds
9921 /// before `start` is dropped, and the rest is what the span decodes from.
9922 fn take(&self, path: &Path, start: u32) -> Option<ParkedSw> {
9923 let mut lot = self.0.lock().ok()?;
9924 let at = lot
9925 .iter()
9926 .position(|entry| entry.path == path && entry.serves(start))?;
9927 let ParkedDecoder { decoder: Held::Sw(mut decoder), mut backlog, .. } = lot.remove(at)? else {
9928 return None;
9929 };
9930 let start = i64::from(start);
9931 while backlog.front().is_some() && decoder.index() - (backlog.len() as i64) < start {
9932 backlog.pop_front();
9933 }
9934 decoder.start = start as u32;
9935 Some(ParkedSw { decoder, backlog })
9936 }
9937
9938 fn take_hw(&self, path: &Path, start: u32, dma: bool) -> Option<(Box<HwSession>, VecDeque<Yuv>, u32)> {
9939 let mut lot = self.0.lock().ok()?;
9940 let at = lot
9941 .iter()
9942 .position(|entry| entry.path == path && matches!(entry.decoder, Held::Hw(..)))?;
9943 let ParkedDecoder { decoder: Held::Hw(mut hw, mut next), mut backlog, .. } = lot.remove(at)? else {
9944 return None;
9945 };
9946 drop(lot);
9947 let first = next.saturating_sub(backlog.len() as u32);
9948 let usable = (first..next).contains(&start) && (dma || !backlog.iter().any(|f| matches!(f, Yuv::Dma(_))));
9949 if usable {
9950 backlog.drain(..(start - first) as usize);
9951 } else {
9952 backlog.clear();
9953 if start != next {
9954 if !hw.seek(start) {
9955 return None;
9956 }
9957 next = start;
9958 }
9959 }
9960 Some((hw, backlog, next))
9961 }
9962}
9963
9964impl ParkedDecoder {
9965 /// Whether this decoder can serve a span starting at `start`: asked of the
9966 /// file itself, where a fresh decoder would seek to.
9967 fn serves(&self, start: u32) -> bool {
9968 let Held::Sw(decoder) = &self.decoder else {
9969 return false;
9970 };
9971 let Ok((_, mut demuxer)) = Demuxer::open(&self.path) else {
9972 return false;
9973 };
9974 let restart = demuxer.seek_to_sync_at_or_before(start);
9975 resumable(
9976 decoder.index(),
9977 self.backlog.len(),
9978 decoder.origin(),
9979 restart,
9980 i64::from(start),
9981 )
9982 }
9983}
9984
9985/// Whether a decoder can carry on for a span starting at display frame `start`
9986/// instead of a fresh one opened there. `next` is the display index of the
9987/// picture it produces next, `backlog` how many decoded pictures sit before
9988/// that, unclaimed; `origin` is the sync sample it was started at, and
9989/// `restart` the sync sample a fresh decoder for `start` would start at.
9990///
9991/// Two things must hold. The span's first picture must still be held or not
9992/// yet decoded, since a decoder cannot go back. And the decoder must have been
9993/// started at the sample a fresh one would start at, so that it has read the
9994/// same access units from the same point and produces the same pictures -- a
9995/// later sync sample is a restart the decoder did not make, and one that is not
9996/// an IDR would be decoded from references the fresh one does not have.
9997fn resumable(next: i64, backlog: usize, origin: i64, restart: i64, start: i64) -> bool {
9998 next - (backlog as i64) <= start && restart == origin
9999}
10000
10001/// A decode thread, joined when its span's decoder is dropped -- the rule
10002/// [`crate::decode::Worker`] is written for: a thread abandoned mid
10003/// `vaInitialize` outlives the process, and Mesa's `atexit` handlers then free
10004/// the state it is still reading, which is a SIGSEGV at exit long after the
10005/// export succeeded.
10006struct DecodeThread<T = ()>(Option<thread::JoinHandle<T>>);
10007
10008impl<T> DecodeThread<T> {
10009 /// The thread's result, once it has finished. Joins it if it has not.
10010 fn finish(&mut self) -> Option<T> {
10011 self.0.take().and_then(|handle| handle.join().ok())
10012 }
10013}
10014
10015impl<T> Drop for DecodeThread<T> {
10016 fn drop(&mut self) {
10017 if let Some(handle) = self.0.take() {
10018 // The receiver is already gone (see `Streamed`'s field order), so a
10019 // decoder blocked on `send` has been woken and this waits only for
10020 // the thread to unwind its VA-API session.
10021 let _ = handle.join();
10022 }
10023 }
10024}
10025
10026impl Drop for Streamed {
10027 fn drop(&mut self) {
10028 let Some(park) = self.park.take() else {
10029 return;
10030 };
10031 // Ask the decoder to stop, then take what it sends until it does: its
10032 // next send is answered by this drain and its next look at the flag
10033 // ends it, dropping the sender, which is what the drain waits for.
10034 park.stop.store(true, Ordering::Relaxed);
10035 let mut backlog: VecDeque<Yuv> = self.current.take().into_iter().collect();
10036 while let Ok(item) = self.frames.recv() {
10037 if let Ok(Some(frame)) = item {
10038 backlog.push_back(frame);
10039 }
10040 }
10041 if let Some((decoder, rest)) = self._thread.finish().flatten() {
10042 backlog.extend(rest);
10043 park.lot.keep(ParkedDecoder {
10044 path: park.path,
10045 decoder,
10046 backlog,
10047 });
10048 }
10049 }
10050}
10051
10052/// One picture on its way from a decode thread to the encoder: its bytes, or
10053/// the GPU buffer they are still in.
10054enum Yuv {
10055 Pixels {
10056 y: Vec<u8>,
10057 u: Vec<u8>,
10058 v: Vec<u8>,
10059 width: u32,
10060 height: u32,
10061 },
10062 /// The same picture at 16 bits a sample, at 10-bit scale: what a 10-bit export
10063 /// encodes whole ([`Enc::encode_wide`]).
10064 Wide {
10065 y: Vec<u16>,
10066 u: Vec<u16>,
10067 v: Vec<u16>,
10068 width: u32,
10069 height: u32,
10070 },
10071 /// Never read back and never copied: a DRM-PRIME handle the encoder imports
10072 /// on the other side of the channel. Sending it is sending an integer, and
10073 /// what keeps the buffer from being decoded over is the channel's own depth
10074 /// (see [`crate::hw::HwSession::next_frame_dma`]).
10075 Dma(DmaFrame),
10076}
10077
10078impl Yuv {
10079 /// The decoder's own buffer copied out, which is what it costs to hand a
10080 /// picture to another thread when the pixels have to travel.
10081 fn pixels(y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> Self {
10082 Self::Pixels {
10083 y: y.to_vec(),
10084 u: u.to_vec(),
10085 v: v.to_vec(),
10086 width,
10087 height,
10088 }
10089 }
10090}
10091
10092/// What [`ExportHandle::stage`] calls a stabilised clip's shake being measured.
10093pub const MEASURING_SHAKE: &str = "Measuring shake";
10094
10095/// How a layer opened for an export measures a stabilised clip with no finished
10096/// analysis ([`LayerFeed::open`]): under this cancel flag, reporting to this
10097/// stage ([`Shared::measuring`]).
10098type Measure<'a> = (&'a AtomicBool, &'a AtomicU32);
10099
10100/// The luma of file frames `lo..hi` of `path` as a layer's decoder hands them to
10101/// [`LayerFeed::advance`] -- before the file's display turn and pixel stretch --
10102/// for the stabilise analysis, whose maps move those same planes. `each` takes
10103/// the frame number, the luma plane and its size, and stops the walk with `false`.
10104pub(crate) fn each_layer_luma(
10105 path: &Path,
10106 lo: u32,
10107 hi: u32,
10108 mut each: impl FnMut(u32, &[u8], u32, u32) -> bool,
10109) -> crate::Result<()> {
10110 let mut decoder = ClipDecoder::open(path, lo, None, None, false)?;
10111 for index in lo..hi {
10112 match decoder.next()? {
10113 Some(Frame::Pixels(y, _, _, w, h)) => {
10114 if !each(index, y, w, h) {
10115 break;
10116 }
10117 }
10118 Some(_) => return Err("stabilise: the decoder gave no 8-bit pixels".into()),
10119 None => break,
10120 }
10121 }
10122 Ok(())
10123}
10124
10125/// One picture as the export loop sees it: planes to grade and place, or a
10126/// buffer that goes straight into the encoder.
10127enum Frame<'a> {
10128 Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32),
10129 /// A 10-bit picture at 10-bit scale, which only a 10-bit export asks for.
10130 Wide(&'a [u16], &'a [u16], &'a [u16], u32, u32),
10131 Dma(&'a DmaFrame),
10132}
10133
10134impl ClipDecoder {
10135 /// A decoder for `path` from `start_frame`. `parked` is the lot a span's
10136 /// software decoder may be taken from and returned to; `None` never keeps one.
10137 fn open(
10138 path: &Path,
10139 start_frame: u32,
10140 want: Option<DmaWant>,
10141 parked: Option<&Arc<Parked>>,
10142 wide: bool,
10143 ) -> crate::Result<Self> {
10144 Self::open_with(path, start_frame, want, parked, wide, Deinterlace::Frame)
10145 }
10146
10147 fn open_with(
10148 path: &Path,
10149 start_frame: u32,
10150 want: Option<DmaWant>,
10151 parked: Option<&Arc<Parked>>,
10152 wide: bool,
10153 deint: Deinterlace,
10154 ) -> crate::Result<Self> {
10155 Self::open_span(path, start_frame, want, parked, wide, deint, u32::MAX)
10156 }
10157
10158 /// [`open`](Self::open) for a clip with a deinterlace setting. `Field` over an
10159 /// interlaced file makes `start_frame` a field number and every picture a field.
10160 /// From file frame `tail` on, GPU buffers are no longer asked for.
10161 fn open_span(
10162 path: &Path,
10163 start_frame: u32,
10164 want: Option<DmaWant>,
10165 parked: Option<&Arc<Parked>>,
10166 wide: bool,
10167 deint: Deinterlace,
10168 tail: u32,
10169 ) -> crate::Result<Self> {
10170 // Before either decoder: an image is not a stream, so `start_frame`
10171 // means nothing to it -- every frame of a still span is the same
10172 // picture, which is what playback shows for it too.
10173 if crate::is_image(path) {
10174 return Ok(Self::Still(crate::decode::Still::open_at(path, start_frame)?));
10175 }
10176 let path = path.to_path_buf();
10177 let (tx, frames) = sync_channel(2);
10178 let stop = Arc::new(AtomicBool::new(false));
10179 let park = parked.map(|lot| Park {
10180 lot: Arc::clone(lot),
10181 path: path.clone(),
10182 stop: Arc::clone(&stop),
10183 });
10184 let thread_park = parked.map(|lot| (Arc::clone(lot), Arc::clone(&stop)));
10185 let handle = thread::Builder::new()
10186 .name("export-decode".into())
10187 .spawn(move || decode_stream(&path, start_frame, want, &tx, thread_park, wide, deint, tail))?;
10188 Ok(Self::Streamed(Streamed {
10189 frames,
10190 _thread: DecodeThread(Some(handle)),
10191 current: None,
10192 ended: false,
10193 park,
10194 }))
10195 }
10196
10197 fn visualizer(
10198 path: &Path,
10199 stream: usize,
10200 start_frame: u32,
10201 (width, height): (u32, u32),
10202 fps: f64,
10203 flags: u8,
10204 paint: u64,
10205 ) -> crate::Result<Self> {
10206 let peaks = crate::waveform::peaks(path, stream, crate::decode::VIZ_BUCKETS_PER_SEC)
10207 .ok()
10208 .flatten()
10209 .unwrap_or_default();
10210 let fps = if fps.is_finite() && fps > 0.0 {
10211 fps
10212 } else {
10213 30.0
10214 };
10215 Ok(Self::Visualizer {
10216 peaks,
10217 width,
10218 height,
10219 fps,
10220 next: start_frame,
10221 flags,
10222 paint,
10223 scratch: crate::decode::VizScratch::default(),
10224 y: Vec::new(),
10225 u: Vec::new(),
10226 v: Vec::new(),
10227 })
10228 }
10229
10230 /// The pictures of `path` from file frame `top` down to `lo`, last to first:
10231 /// a clip played backwards. Decoded forwards a block at a time and served from
10232 /// the back, so the memory held is one block ([`crate::reverse`]), and always
10233 /// 8-bit software pictures -- the block is copied out of the decoder, which a GPU
10234 /// buffer or a 10-bit plane does not allow.
10235 fn reversed(path: &Path, top: u32, lo: u32, deint: Deinterlace) -> Self {
10236 let mut sync = crate::reverse::sync_frames(path);
10237 if deint == Deinterlace::Field {
10238 sync.iter_mut().for_each(|f| *f *= 2);
10239 }
10240 Self::Reversed(Box::new(Reversed {
10241 deint,
10242 path: path.to_path_buf(),
10243 walk: crate::reverse::Walk::new(
10244 sync,
10245 lo,
10246 top + 1,
10247 // Until a picture says how big they are: the biggest the engine takes.
10248 crate::reverse::block_cap(3840 * 2160 * 3 / 2),
10249 ),
10250 block: Vec::new(),
10251 current: None,
10252 }))
10253 }
10254
10255 /// The next picture, borrowed until the call after -- as tightly packed
10256 /// I420, or as the GPU buffer the decoder wrote it into.
10257 fn next(&mut self) -> crate::Result<Option<Frame<'_>>> {
10258 match self {
10259 Self::Still(still) => {
10260 let (y, u, v, width, height) = still.picture();
10261 Ok(Some(Frame::Pixels(y, u, v, width, height)))
10262 }
10263 Self::Reversed(reversed) => reversed.next(),
10264 Self::Visualizer {
10265 peaks,
10266 width,
10267 height,
10268 fps,
10269 next,
10270 flags,
10271 paint,
10272 scratch,
10273 y,
10274 u,
10275 v,
10276 } => {
10277 let (yy, uu, vv) = crate::decode::visualizer_i420(
10278 scratch,
10279 peaks,
10280 f64::from(*next) / *fps,
10281 *width,
10282 *height,
10283 *flags,
10284 *paint,
10285 );
10286 *y = yy;
10287 *u = uu;
10288 *v = vv;
10289 *next += 1;
10290 Ok(Some(Frame::Pixels(y, u, v, *width & !1, *height & !1)))
10291 }
10292 Self::Streamed(stream) if stream.ended => Ok(None),
10293 Self::Streamed(stream) => match stream.frames.recv() {
10294 Ok(Ok(Some(frame))) => Ok(Some(match stream.current.insert(frame) {
10295 Yuv::Pixels {
10296 y,
10297 u,
10298 v,
10299 width,
10300 height,
10301 } => Frame::Pixels(y, u, v, *width, *height),
10302 Yuv::Wide {
10303 y,
10304 u,
10305 v,
10306 width,
10307 height,
10308 } => Frame::Wide(y, u, v, *width, *height),
10309 Yuv::Dma(dma) => Frame::Dma(dma),
10310 })),
10311 Ok(Ok(None)) => {
10312 stream.ended = true;
10313 Ok(None)
10314 }
10315 Ok(Err(e)) => Err(e),
10316 Err(_) => Err("the decoder stopped without a picture or a reason".into()),
10317 },
10318 }
10319 }
10320}
10321
10322/// One span's decode, on its own thread: open the file (hardware if the plugin
10323/// will have it, software otherwise) and send every picture until the encoder
10324/// stops taking them.
10325///
10326/// Hardware that fails, before the first picture or after some, hands the rest
10327/// of the span to the software seat at the first picture not yet sent.
10328///
10329/// Every way this returns says which way it was, down the channel: a picture, an
10330/// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not
10331/// one of them -- a silent close is a panicked thread, and the receiver treats
10332/// it as the failure it is rather than as a source that ran out.
10333///
10334/// With `parked`, a software decode takes a parked decoder for this file when
10335/// one can serve `start_frame`, and a decoder that is asked to stop (its span
10336/// was dropped) is handed back: see [`Streamed`]'s drop.
10337fn decode_stream(
10338 path: &Path,
10339 start_frame: u32,
10340 want: Option<DmaWant>,
10341 tx: &SyncSender<crate::Result<Option<Yuv>>>,
10342 parked: Option<(Arc<Parked>, Arc<AtomicBool>)>,
10343 wide: bool,
10344 deint: Deinterlace,
10345 tail: u32,
10346) -> Option<Kept> {
10347 // A 10-bit export asks the hardware seat for whole 10-bit pictures ([`Pictures::Hw`]).
10348 let kept = (!forced("VE_SW"))
10349 .then(|| parked.as_ref().and_then(|(lot, _)| lot.take_hw(path, start_frame, want.is_some())))
10350 .flatten();
10351 let mut next = start_frame;
10352 let opened = match (forced("VE_SW"), kept) {
10353 (false, Some((hw, backlog, at))) => {
10354 next = at;
10355 Some((Pictures::Hw(hw, wide), backlog))
10356 }
10357 // The decode door's own gate ([`crate::decode::open_hw`]): a VP9 4:2:2 or 4:4:4
10358 // stream is never offered to the GPU, which would refuse it on stderr.
10359 (false, None) => crate::decode::open_hw(path, start_frame).map(|hw| (Pictures::Hw(Box::new(hw), wide), VecDeque::new())),
10360 (true, _) => None,
10361 };
10362 if std::env::var_os("EDITH_DEBUG").is_some() {
10363 eprintln!("export decode: {}{}", if opened.is_some() { "hardware" } else { "software" }, if wide { ", 10-bit" } else { "" });
10364 }
10365 // Pictures decoded ahead of the span that a parked decoder still holds.
10366 let (mut decoder, mut backlog) = match opened {
10367 Some(hw) => hw,
10368 None => match parked
10369 .as_ref()
10370 .and_then(|(lot, _)| lot.take(path, start_frame))
10371 {
10372 Some(kept) => (Pictures::Sw(kept.decoder), kept.backlog),
10373 None => match Pictures::software(path, start_frame, wide, deint) {
10374 Ok(sw) => (sw, VecDeque::new()),
10375 Err(e) => {
10376 let _ = tx.send(Err(e));
10377 return None;
10378 }
10379 },
10380 },
10381 };
10382 // Pictures handed down the channel. Hardware that dies hands the rest of the
10383 // span to the software seat at `start_frame + decoded`: the first picture
10384 // not yet sent, so nothing already encoded is repeated.
10385 let mut decoded = 0u32;
10386 loop {
10387 // Asked to stop: the span is over, and a software decoder that has not
10388 // reached its end is what the next span may take up.
10389 if parked
10390 .as_ref()
10391 .is_some_and(|(_, stop)| stop.load(Ordering::Relaxed))
10392 {
10393 return match decoder {
10394 Pictures::Sw(sw) if sw.parkable() && !sw.flushed() => Some((Held::Sw(sw), backlog)),
10395 Pictures::Hw(hw, _) => Some((Held::Hw(hw, next), backlog)),
10396 _ => None,
10397 };
10398 }
10399 // Hardware that ends before its first picture has failed the same way
10400 // one that errors there has: the mid-GOP AV1 seek ends the stream with
10401 // nothing (see `decode::run_hw`), and it falls back here too.
10402 let pulled = match backlog.pop_front() {
10403 Some(frame) => Ok(Some(frame)),
10404 None => {
10405 next += 1;
10406 decoder.next(want.filter(|_| next <= tail))
10407 }
10408 };
10409 let pulled = match pulled {
10410 Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(..)) => {
10411 Err("hardware gave no picture from the start frame".into())
10412 }
10413 other => other,
10414 };
10415 let frame = match pulled {
10416 Ok(Some(frame)) => frame,
10417 Ok(None) => {
10418 let _ = tx.send(Ok(None));
10419 return match decoder {
10420 Pictures::Hw(hw, _) if parked.is_some() => Some((Held::Hw(hw, next - 1), backlog)),
10421 _ => None,
10422 };
10423 }
10424 Err(e) => {
10425 if matches!(decoder, Pictures::Hw(..)) {
10426 // Before the first picture, or after some: either way the
10427 // software seat takes the span from the first picture not yet
10428 // sent (`decoded` is 0 in the first case), so nothing is
10429 // encoded twice and nothing is skipped.
10430 if std::env::var_os("EDITH_DEBUG").is_some() || decoded > 0 { eprintln!(
10431 "export decode: hardware failed at frame {} ({e}); falling back to software",
10432 start_frame + decoded
10433 ); }
10434 match Pictures::software(path, start_frame + decoded, wide, deint) {
10435 Ok(sw) => {
10436 decoder = sw;
10437 continue;
10438 }
10439 Err(sw_refusal) => {
10440 let _ = tx.send(Err(sw_refusal));
10441 return None;
10442 }
10443 }
10444 }
10445 let _ = tx.send(Err(e));
10446 return None;
10447 }
10448 };
10449 // The consumer went away: the span ended early, or the export was
10450 // cancelled. Either way there is nothing left to decode for. A parked
10451 // span drains the channel before it drops it, so this is not reached.
10452 if tx.send(Ok(Some(frame))).is_err() {
10453 return None;
10454 }
10455 decoded += 1;
10456 }
10457}
10458
10459/// The stream decoders, on the thread that opened them.
10460enum Pictures {
10461 /// With whether the export is 10-bit, which asks for whole 10-bit pictures.
10462 Hw(Box<HwSession>, bool),
10463 /// `ec-h264`, on this thread.
10464 Sw(Box<SwDecoder>),
10465 /// `ec-av1`, on a thread of its own -- see [`Av1Stream`].
10466 Av1(Box<Av1Stream>),
10467}
10468
10469impl Pictures {
10470 /// The software seat for `path`: `ec-h264` for H.264, `ec-av1` on its own
10471 /// thread for AV1, and the pulled seats (`ec-h265`, `ec-vp9`, `ec-vp8`) for the
10472 /// rest. The codec is read once here, so it decides which seat takes the file.
10473 fn software(path: &Path, start_frame: u32, wide: bool, deint: Deinterlace) -> crate::Result<Self> {
10474 let (meta, demuxer) = Demuxer::open(path)?;
10475 match meta.codec {
10476 Codec::H264 => Ok(Self::Sw(Box::new(SwDecoder::new(demuxer, start_frame, wide, deint)))),
10477 Codec::Av1 => Ok(Self::Av1(Box::new(Av1Stream::spawn(demuxer, start_frame, wide)?))),
10478 _ => Ok(Self::Sw(Box::new(SwDecoder::open(path, start_frame, wide, deint)?))),
10479 }
10480 }
10481
10482 /// The next picture, owned, ready to cross the channel. `want` is what the
10483 /// export's encoder can read straight off the GPU: where the hardware
10484 /// decoder can hand such a buffer over there is no copy here at all, and
10485 /// everything else is the 3 MB memcpy out of the decoder's own buffer that
10486 /// buys the decode and the encode their overlap.
10487 fn next(&mut self, want: Option<DmaWant>) -> crate::Result<Option<Yuv>> {
10488 match (self, want) {
10489 (Self::Hw(hw, true), None) => Ok(match hw.next_frame_wide()? {
10490 Some(crate::hw::HwFrame::Wide(bytes, width, height)) => Some(wide_yuv(bytes, width, height)),
10491 Some(crate::hw::HwFrame::Narrow((y, u, v, width, height))) => Some(Yuv::pixels(y, u, v, width, height)),
10492 None => None,
10493 }),
10494 (Self::Hw(hw, _), Some(want)) => Ok(match hw.next_frame_dma(want)? {
10495 Some(HwPicture::Dma(dma)) => Some(Yuv::Dma(dma)),
10496 Some(HwPicture::Wide(bytes, width, height)) => Some(wide_yuv(bytes, width, height)),
10497 Some(HwPicture::Pixels(y, u, v, width, height)) => {
10498 Some(Yuv::pixels(y, u, v, width, height))
10499 }
10500 None => None,
10501 }),
10502 (Self::Hw(hw, _), None) => Ok(hw
10503 .next_frame()?
10504 .map(|(y, u, v, width, height)| Yuv::pixels(y, u, v, width, height))),
10505 (Self::Av1(av1), _) => av1.next(),
10506 (Self::Sw(sw), _) => {
10507 if !sw.advance()? {
10508 return Ok(None);
10509 }
10510 if let Some((y, u, v, width, height)) = sw.picture16() {
10511 return Ok(Some(Yuv::Wide {
10512 y: y.to_vec(),
10513 u: u.to_vec(),
10514 v: v.to_vec(),
10515 width,
10516 height,
10517 }));
10518 }
10519 let (y, u, v, width, height) = sw.picture();
10520 Ok(Some(Yuv::pixels(y, u, v, width, height)))
10521 }
10522 }
10523 }
10524}
10525
10526/// The software decoder one export span reads from: H.264 with its own reorder
10527/// and flush, or one of the pulled seats playback's spans read too.
10528struct SwDecoder {
10529 demuxer: Demuxer,
10530 /// The first display index the export takes. Pictures before it are decoded
10531 /// (the target references them) and then dropped.
10532 start: u32,
10533 seat: SwSeat,
10534}
10535
10536enum SwSeat {
10537 H264(Box<H264Seat>),
10538 /// `wide` is the 10-bit plane buffer when this seat decodes at 10 bits.
10539 Pulled {
10540 stream: Box<Pulled>,
10541 out: I420,
10542 wide: Option<Wide>,
10543 },
10544}
10545
10546struct H264Seat {
10547 decoder: H264Decoder,
10548 /// Display index of the next picture the decoder will produce. Signed: a
10549 /// sync sample inside what the edit list trims is before frame 0.
10550 index: i64,
10551 /// The display index the decoder started at (its sync sample), what
10552 /// [`resumable`] compares a later span's restart against.
10553 origin: i64,
10554 /// Set once the demuxer runs dry: `flush` has then released what the
10555 /// decoder's reorder still held, and only those pictures are left.
10556 flushed: bool,
10557 frame: Option<VideoFrame>,
10558 /// Whether the export is 10-bit, and the High 10 picture taken for it.
10559 wide: bool,
10560 deep: crate::decode::Deep,
10561 /// Deinterlaces an interlaced stream (a pass-through for every other).
10562 deint: crate::deinterlace::Deinterlacer,
10563 /// Pictures the deinterlacer released that `advance` has not handed over yet:
10564 /// the second field of a frame in field mode.
10565 pending: VecDeque<(i64, VideoFrame)>,
10566}
10567
10568impl SwDecoder {
10569 fn open(path: &Path, start_frame: u32, wide: bool, deint: Deinterlace) -> crate::Result<Self> {
10570 let (meta, mut demuxer) = Demuxer::open(path)?;
10571 // Decoding restarts at a sync sample, so pictures between it and the in
10572 // point are decoded (the target references them) and then dropped.
10573 let seat = match Pulled::open(meta.codec, &mut demuxer, start_frame, deint) {
10574 Some(stream) => SwSeat::Pulled {
10575 stream: Box::new(stream),
10576 out: I420::default(),
10577 // Only HEVC and the intra-only professional codecs have a 10-bit seat; the others narrow as they always did.
10578 wide: (wide && (matches!(meta.codec, Codec::Hevc | Codec::ProRes | Codec::Dnxhd) || (meta.codec == Codec::Raw && demuxer.bit_depth() >= 10))).then(Wide::default),
10579 },
10580 None if meta.codec == Codec::H264 => {
10581 SwSeat::H264(H264Seat::open(&mut demuxer, start_frame, wide, deint))
10582 }
10583 // AV1 never gets here: `Pictures::software` gives it `Av1Stream`.
10584 None => return Err(format!("{} has no export seat", meta.codec.name()).into()),
10585 };
10586 Ok(Self {
10587 demuxer,
10588 start: start_frame,
10589 seat,
10590 })
10591 }
10592
10593 /// Decodes up to and including the next picture at or after the in point.
10594 /// `false` at end of stream.
10595 fn advance(&mut self) -> crate::Result<bool> {
10596 match &mut self.seat {
10597 SwSeat::H264(seat) => seat.advance(&mut self.demuxer, self.start),
10598 SwSeat::Pulled { stream, out, wide } => loop {
10599 let next = match wide {
10600 Some(wide) => stream.next_wide(&mut self.demuxer, wide)?,
10601 None => stream.next(&mut self.demuxer, out)?,
10602 };
10603 let Some(due) = next else {
10604 return Ok(false);
10605 };
10606 if due >= i64::from(self.start) {
10607 return Ok(true);
10608 }
10609 },
10610 }
10611 }
10612
10613 /// The 10-bit planes of the picture `advance` stopped on, when this seat
10614 /// decodes at 10 bits; `None` otherwise.
10615 fn picture16(&self) -> Option<Wide16View<'_>> {
10616 match &self.seat {
10617 SwSeat::Pulled { wide: Some(w), .. } => Some((&w.y, &w.u, &w.v, w.width, w.height)),
10618 SwSeat::H264(s) if s.deep.in_wide => {
10619 let w = &s.deep.wide;
10620 Some((&w.y, &w.u, &w.v, w.width, w.height))
10621 }
10622 _ => None,
10623 }
10624 }
10625
10626 /// The picture `advance` stopped on, as planes and size.
10627 fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
10628 match &self.seat {
10629 SwSeat::H264(seat) if seat.deep.on => {
10630 let n = &seat.deep.narrow;
10631 (&n.y, &n.u, &n.v, n.width, n.height)
10632 }
10633 SwSeat::H264(seat) => {
10634 let frame = seat.frame.as_ref().expect("advance stored a picture");
10635 let [y, u, v] = [&frame.planes[0], &frame.planes[1], &frame.planes[2]];
10636 debug_assert_eq!(y.stride, frame.width as usize, "padded luma plane");
10637 (&y.data, &u.data, &v.data, frame.width, frame.height)
10638 }
10639 SwSeat::Pulled { out, .. } => (&out.y, &out.u, &out.v, out.width, out.height),
10640 }
10641 }
10642}
10643
10644/// An AV1 software span: [`decode_av1`] runs on a thread of its own and sends
10645/// every picture down a channel two deep, the same shape [`Streamed`] gives a
10646/// stream decoded elsewhere. The thread is needed because `ec-av1` pushes its
10647/// pictures through a callback rather than handing them out one at a time.
10648struct Av1Stream {
10649 frames: Receiver<crate::Result<Option<Yuv>>>,
10650 /// Held only to be joined: field order matters, as it does for
10651 /// [`Streamed`] -- `frames` drops first and wakes a decoder parked in a
10652 /// full `send`, and the join runs after.
10653 _thread: DecodeThread,
10654 /// Whether the thread has said "no more pictures" in as many words.
10655 ended: bool,
10656}
10657
10658impl Av1Stream {
10659 fn spawn(demuxer: Demuxer, start_frame: u32, wide: bool) -> crate::Result<Self> {
10660 let (tx, frames) = sync_channel(2);
10661 let handle = thread::Builder::new()
10662 .name("export-decode-av1".into())
10663 .spawn(move || decode_av1(demuxer, start_frame, wide, &tx))?;
10664 Ok(Self {
10665 frames,
10666 _thread: DecodeThread(Some(handle)),
10667 ended: false,
10668 })
10669 }
10670
10671 fn next(&mut self) -> crate::Result<Option<Yuv>> {
10672 if self.ended {
10673 return Ok(None);
10674 }
10675 match self.frames.recv() {
10676 Ok(Ok(Some(frame))) => Ok(Some(frame)),
10677 Ok(Ok(None)) => {
10678 self.ended = true;
10679 Ok(None)
10680 }
10681 Ok(Err(e)) => Err(e),
10682 Err(_) => Err("the decoder stopped without a picture or a reason".into()),
10683 }
10684 }
10685}
10686
10687/// The chroma plane size `len` samples can be, for a `width` x `height` luma
10688/// picture: full (4:4:4), half the width (4:2:2) or a quarter (4:2:0, odd sizes
10689/// rounding up). `None` for any other count, which no decoder here produces.
10690pub(crate) fn chroma_shape(len: usize, width: usize, height: usize) -> Option<(usize, usize)> {
10691 let (half_w, half_h) = (width.div_ceil(2), height.div_ceil(2));
10692 [(width, height), (half_w, height), (half_w, half_h)]
10693 .into_iter()
10694 .find(|&(cw, ch)| cw * ch == len)
10695}
10696
10697/// A chroma plane of `cw` x `ch` samples averaged down to `ow` x `oh`, the
10698/// 4:2:0 size of the luma. A dimension that already matches is kept one sample
10699/// to one; one that is larger takes the mean of the (at most two) source
10700/// samples under each output sample, rounded to nearest. Samples keep the
10701/// depth they came in at, so a 10-bit picture averages in 10 bits and
10702/// [`crate::decode::narrow_av1`] shifts it as it would any other.
10703pub(crate) fn chroma_420<T: Copy + Into<u32>>(src: &[T], cw: usize, ch: usize, ow: usize, oh: usize) -> Vec<u32> {
10704 // The source run under output index `i` along one axis.
10705 let run = |src_len: usize, out_len: usize, i: usize| match src_len == out_len {
10706 true => (i, i + 1),
10707 false => (2 * i, (2 * i + 2).min(src_len)),
10708 };
10709 let mut out = Vec::with_capacity(ow * oh);
10710 for oy in 0..oh {
10711 let (y0, y1) = run(ch, oh, oy);
10712 for ox in 0..ow {
10713 let (x0, x1) = run(cw, ow, ox);
10714 let (mut sum, mut n) = (0u32, 0u32);
10715 for sy in y0..y1 {
10716 for sx in x0..x1 {
10717 sum += src[sy * cw + sx].into();
10718 n += 1;
10719 }
10720 }
10721 out.push((sum + n / 2) / n);
10722 }
10723 }
10724 out
10725}
10726
10727/// The AV1 software seat for the export: the same walk `decode::run_av1` makes
10728/// for playback, one chunk at a time. `ec-av1` takes a whole OBU stream, so the
10729/// demuxer's access units are gathered from one sync sample (a sequence header
10730/// leads it) up to the next, and each chunk decodes to its end -- its hidden
10731/// frames are references, and the frames they hold back in output order are
10732/// the tail. Shown pictures before `start_frame` are decoded and dropped.
10733///
10734/// Pictures are narrowed to 8-bit I420 by the same [`narrow_av1`] playback
10735/// uses, so an export and a playback of one file hand the encoder the same
10736/// planes. A 4:2:2 or 4:4:4 picture has its chroma averaged down to 4:2:0 first
10737/// ([`chroma_420`]), since the composer and every software encoder take I420 and
10738/// nothing else. A decode refusal ends the span with the error, after the
10739/// pictures already sent.
10740fn decode_av1(
10741 mut demuxer: Demuxer,
10742 start_frame: u32,
10743 wide: bool,
10744 tx: &SyncSender<crate::Result<Option<Yuv>>>,
10745) {
10746 let depth = demuxer.bit_depth();
10747 // A monochrome stream states it in its sequence header; see the chroma below.
10748 let gray = demuxer.chroma() == Some(Chroma::Gray);
10749 // Decoding restarts at a sync sample; see [`SwDecoder::new`].
10750 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
10751 let mut pending: Option<Vec<u8>> = None;
10752 let mut demux_dry = false;
10753 loop {
10754 // One chunk: the access units from a sync sample up to the next one.
10755 let mut stream = pending.take().unwrap_or_default();
10756 while !demux_dry && pending.is_none() {
10757 match demuxer.next_access_unit() {
10758 Ok(Some(au)) => {
10759 if !stream.is_empty() && crate::decode::leads_with_sequence_header(&au) {
10760 pending = Some(au);
10761 } else {
10762 stream.extend_from_slice(&au);
10763 }
10764 }
10765 Ok(None) => demux_dry = true,
10766 Err(e) => {
10767 let _ = tx.send(Err(e));
10768 return;
10769 }
10770 }
10771 }
10772 if stream.is_empty() {
10773 let _ = tx.send(Ok(None));
10774 return;
10775 }
10776 // Set by the sink when the consumer is gone, or when a picture is
10777 // refused; `Eof` is the sentinel that stops the chunk's decode there.
10778 let mut gone = false;
10779 let mut refused = None;
10780 let decode = decode_stream_with(&stream, |picture, _, shown| {
10781 if !shown {
10782 return Ok(());
10783 }
10784 let due = index;
10785 index += 1;
10786 if due < i64::from(start_frame) {
10787 return Ok(());
10788 }
10789 let (w, h) = (picture.width, picture.height);
10790 let (ow, oh) = (w.div_ceil(2), h.div_ceil(2));
10791 // 4:2:2 and 4:4:4 pictures are averaged down to the 4:2:0 the
10792 // composer and every software encoder take ([`chroma_420`]). A
10793 // monochrome stream carries no chroma, and the decoder hands back
10794 // zeros in its place: the neutral grey is written instead, at the
10795 // depth the samples are held in (512 for 10-bit).
10796 let Some((cw, ch)) = chroma_shape(picture.u.len(), w, h) else {
10797 refused = Some(format!(
10798 "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",
10799 picture.u.len()
10800 ));
10801 return Err(Av1Error::Eof);
10802 };
10803 let half = if gray {
10804 let mid = 1u16 << (depth - 1);
10805 Some(Av1Picture {
10806 width: w,
10807 height: h,
10808 y: picture.y.clone(),
10809 u: vec![mid; ow * oh],
10810 v: vec![mid; ow * oh],
10811 })
10812 } else if (cw, ch) != (ow, oh) {
10813 let down = |plane: &[u16]| -> Vec<u16> {
10814 chroma_420(plane, cw, ch, ow, oh)
10815 .into_iter()
10816 .map(|s| s as u16)
10817 .collect()
10818 };
10819 Some(Av1Picture {
10820 width: w,
10821 height: h,
10822 y: picture.y.clone(),
10823 u: down(&picture.u),
10824 v: down(&picture.v),
10825 })
10826 } else {
10827 None
10828 };
10829 let src = half.as_ref().unwrap_or(picture);
10830 let frame = if wide {
10831 // At 10-bit scale: a 10-bit stream's samples are there already, an
10832 // 8-bit one (in a 10-bit export) is shifted up by two.
10833 // A 12-bit one is rounded down by two.
10834 let plane = |s: &[u16]| -> Vec<u16> {
10835 s.iter()
10836 .map(|&x| match depth {
10837 ..=9 => x << (10 - depth),
10838 10 => x,
10839 _ => ((x + (1 << (depth - 11))) >> (depth - 10)).min(1023),
10840 })
10841 .collect()
10842 };
10843 Yuv::Wide {
10844 y: plane(&src.y),
10845 u: plane(&src.u),
10846 v: plane(&src.v),
10847 width: w as u32,
10848 height: h as u32,
10849 }
10850 } else {
10851 let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new());
10852 crate::decode::narrow_av1(src, depth, &mut y, &mut u, &mut v);
10853 Yuv::Pixels {
10854 y,
10855 u,
10856 v,
10857 width: w as u32,
10858 height: h as u32,
10859 }
10860 };
10861 if tx.send(Ok(Some(frame))).is_err() {
10862 gone = true;
10863 return Err(Av1Error::Eof);
10864 }
10865 Ok(())
10866 });
10867 if gone {
10868 return;
10869 }
10870 if let Some(msg) = refused {
10871 let _ = tx.send(Err(msg.into()));
10872 return;
10873 }
10874 if let Err(e) = decode {
10875 let msg = format!("software AV1 decode failed at picture {index}: {e}");
10876 let _ = tx.send(Err(msg.into()));
10877 return;
10878 }
10879 }
10880}
10881
10882impl SwDecoder {
10883 /// The H.264 seat over an opened demuxer. Decoding restarts at a sync
10884 /// sample, so pictures between it and the in point are decoded (the target
10885 /// references them) and then dropped.
10886 fn new(mut demuxer: Demuxer, start_frame: u32, wide: bool, deint: Deinterlace) -> Self {
10887 let seat = SwSeat::H264(H264Seat::open(&mut demuxer, start_frame, wide, deint));
10888 Self {
10889 demuxer,
10890 start: start_frame,
10891 seat,
10892 }
10893 }
10894
10895 /// Whether this decoder can be parked for a later span: only the H.264 seat
10896 /// has a display index to resume from, so the pulled seats never are.
10897 fn parkable(&self) -> bool {
10898 // An interlaced seat holds a picture back for its successor, so it has
10899 // no display index a later span could resume from.
10900 matches!(&self.seat, SwSeat::H264(s) if !s.deint.is_interlaced())
10901 }
10902
10903 /// The display index the seat's next picture will carry; `0` off the H.264 seat.
10904 fn index(&self) -> i64 {
10905 match &self.seat {
10906 SwSeat::H264(seat) => seat.index,
10907 SwSeat::Pulled { .. } => 0,
10908 }
10909 }
10910
10911 /// The display index the seat started at; `0` off the H.264 seat.
10912 fn origin(&self) -> i64 {
10913 match &self.seat {
10914 SwSeat::H264(seat) => seat.origin,
10915 SwSeat::Pulled { .. } => 0,
10916 }
10917 }
10918
10919 /// Set once the demuxer ran dry. Always `true` off the H.264 seat, which is
10920 /// what keeps a pulled decoder from being parked (see [`SwDecoder::parkable`]).
10921 fn flushed(&self) -> bool {
10922 match &self.seat {
10923 SwSeat::H264(seat) => seat.flushed || seat.deint.is_interlaced(),
10924 SwSeat::Pulled { .. } => true,
10925 }
10926 }
10927}
10928
10929impl H264Seat {
10930 /// A fresh `ec-h264` seat whose first picture is display index `index`.
10931 ///
10932 /// An interlaced stream lands one picture earlier than the in point, so the
10933 /// deinterlacer has the picture before it, as a sequential decode does.
10934 fn open(demuxer: &mut Demuxer, start: u32, wide: bool, mode: Deinterlace) -> Box<Self> {
10935 let deint = crate::deinterlace::Deinterlacer::with_mode(
10936 mode,
10937 demuxer.h264_interlaced(),
10938 i64::from(start),
10939 ec_core::frame::Interlace::Progressive,
10940 )
10941 .cadenced(mode, demuxer);
10942 let index = demuxer.seek_to_sync_at_or_before(deint.landing(start));
10943 Box::new(Self {
10944 deint,
10945 ..*Self::at(index, wide)
10946 })
10947 }
10948
10949 fn at(index: i64, wide: bool) -> Box<Self> {
10950 Box::new(Self {
10951 decoder: H264Decoder::new(CodecParameters::new(CodecId::H264))
10952 .expect("ec-h264 takes its own codec id"),
10953 index,
10954 origin: index,
10955 flushed: false,
10956 frame: None,
10957 wide,
10958 deep: Default::default(),
10959 deint: crate::deinterlace::Deinterlacer::new(false, 0, ec_core::frame::Interlace::Progressive),
10960 pending: VecDeque::new(),
10961 })
10962 }
10963
10964 /// Decodes up to and including the next picture at or after the in point,
10965 /// leaving it in `frame`. `false` at end of stream. Pictures leave the
10966 /// decoder in display order -- clause C.4.5.3, the same contract the
10967 /// playback seat keeps -- so the landing index, itself a display index by
10968 /// the demuxer's contract, counts one to one with them.
10969 fn advance(&mut self, demuxer: &mut Demuxer, start: u32) -> crate::Result<bool> {
10970 loop {
10971 // The second field of the frame the last call took the first of.
10972 if let Some((due, pic)) = self.pending.pop_front() {
10973 if due < i64::from(start) {
10974 continue;
10975 }
10976 self.deep.load(&pic, self.wide);
10977 self.frame = Some(pic);
10978 return Ok(true);
10979 }
10980 if !self.flushed {
10981 match demuxer.next_access_unit()? {
10982 Some(au) => self
10983 .decoder
10984 .send_packet(&Packet::new(0, TimeBase::new(1, 1), au))
10985 .map_err(|e| format!("decode at picture {}: {e}", self.index))?,
10986 None => {
10987 self.flushed = true;
10988 self.decoder
10989 .flush()
10990 .map_err(|e| format!("decode at end of stream: {e}"))?;
10991 }
10992 }
10993 }
10994 match self.decoder.receive_frame() {
10995 Ok(frame) => {
10996 let ec_core::frame::Frame::Video(pic) = frame else {
10997 continue;
10998 };
10999 let tag = self.index;
11000 self.index += 1;
11001 // Held one picture back while the deinterlacer waits for
11002 // the successor; below the in point it only primes. In
11003 // field mode it releases two, queued for the loop's top.
11004 self.pending.extend(self.deint.push_all(tag, pic));
11005 }
11006 // End of stream counts once the flush has happened; before it,
11007 // either answer means go back for the next access unit. The
11008 // last picture an interlaced stream held leaves first.
11009 Err(e) if e.is_eof() && self.flushed => {
11010 self.pending.extend(self.deint.finish_all());
11011 if self.pending.is_empty() {
11012 return Ok(false);
11013 }
11014 }
11015 Err(e) if e.is_need_more() || e.is_eof() => {}
11016 Err(e) => return Err(format!("decode at picture {}: {e}", self.index).into()),
11017 }
11018 }
11019 }
11020}
11021
11022#[cfg(test)]
11023mod tests {
11024 /// A standalone file's soft track is titled with its language's name, or left
11025 /// untitled, and never with its file name; an embedded track keeps the title
11026 /// its container gave it.
11027 #[test]
11028 fn a_soft_track_is_titled_by_its_language_never_its_file_name() {
11029 let file = |language: &str| SubtitleTrack {
11030 path: "/media/talk.fr.srt".into(),
11031 track: None,
11032 language: language.into(),
11033 name: String::new(),
11034 label: "talk.fr.srt".into(),
11035 cues: Vec::new(),
11036 bitmap: false,
11037 refused: None,
11038 };
11039 assert_eq!(subtitle_title(&file("fra")), "French");
11040 assert_eq!(subtitle_title(&file("")), "", "unset: no title, and never the file name");
11041 let embedded = SubtitleTrack {
11042 track: Some(3),
11043 name: "Signs".into(),
11044 ..file("fra")
11045 };
11046 assert_eq!(subtitle_title(&embedded), "Signs");
11047 }
11048
11049 /// Two caption lanes, one per palette track: a pick list names the lanes it
11050 /// keeps, and an empty one keeps them all -- in the plan and in the file.
11051 #[test]
11052 fn a_pick_list_keeps_only_the_lanes_it_names() {
11053 use crate::project::{LaneKind, SubClip};
11054 let track = |label: &str, text: &str| SubtitleTrack {
11055 path: "/nonexistent/film.mkv".into(),
11056 track: Some(1),
11057 language: "eng".into(),
11058 name: label.into(),
11059 label: label.into(),
11060 bitmap: false,
11061 cues: vec![Cue {
11062 start_us: 0,
11063 end_us: 1_000_000,
11064 text: text.into(),
11065 image: None,
11066 words: Vec::new(),
11067 karaoke: Vec::new(),
11068 }],
11069 refused: None,
11070 };
11071 let mut project = Project::single("/nonexistent/a.mp4", 150)
11072 .with_subtitles(vec![track("one", "first words"), track("two", "second words")]);
11073 for track in 0..2 {
11074 let lane = project.add_lane(LaneKind::Subtitle);
11075 project
11076 .place_sub(
11077 lane,
11078 0,
11079 SubClip {
11080 start: 0,
11081 frames: 150,
11082 track,
11083 in_us: 0,
11084 out_us: 1_000_000,
11085 link: None,
11086 },
11087 )
11088 .expect("an empty lane takes the placement");
11089 }
11090 let names = |subs: &[SubParams]| subs.iter().map(|s| s.name.clone()).collect::<Vec<_>>();
11091
11092 let only_zero = lane_subtitles(&project, 30.0, None, &[0]);
11093 assert_eq!(names(&only_zero), ["one"], "pick [0] keeps track 0's lane alone");
11094 assert_eq!(only_zero[0].cues[0].text, "first words");
11095
11096 let all = lane_subtitles(&project, 30.0, None, &[]);
11097 assert_eq!(names(&all), ["one", "two"], "an empty pick list keeps every lane");
11098
11099 let plan = planned_subtitles(&project, Format::Mp4, [0]);
11100 assert!(plan.contains("S1 one") && !plan.contains("two"), "plan: {plan}");
11101 let plan = planned_subtitles(&project, Format::Mp4, Vec::<usize>::new());
11102 assert!(plan.contains("S1 one") && plan.contains("S2 two"), "plan: {plan}");
11103 }
11104
11105 /// Four palette tracks, lanes S1 and S2 holding tracks 0 and 2: the file writes the tracks in
11106 /// the order the caller gave them, placed or not, and the card names them in that order.
11107 #[test]
11108 fn soft_tracks_are_written_in_the_order_the_caller_gave() {
11109 use crate::project::{LaneKind, SubClip};
11110 let track = |label: &str| SubtitleTrack {
11111 path: "/nonexistent/film.srt".into(),
11112 track: None,
11113 language: "eng".into(),
11114 name: label.into(),
11115 label: label.into(),
11116 bitmap: false,
11117 cues: vec![Cue {
11118 start_us: 0,
11119 end_us: 1_000_000,
11120 text: format!("{label} words"),
11121 image: None,
11122 words: Vec::new(),
11123 karaoke: Vec::new(),
11124 }],
11125 refused: None,
11126 };
11127 let mut project = Project::single("/nonexistent/a.mp4", 150)
11128 .with_subtitles(vec![track("one"), track("two"), track("three"), track("four")]);
11129 for track in [0, 2] {
11130 let lane = project.add_lane(LaneKind::Subtitle);
11131 project
11132 .place_sub(
11133 lane,
11134 0,
11135 SubClip {
11136 start: 0,
11137 frames: 150,
11138 track,
11139 in_us: 0,
11140 out_us: 1_000_000,
11141 link: None,
11142 },
11143 )
11144 .expect("an empty lane takes the placement");
11145 }
11146 let lanes = project.subtitle_lanes();
11147 let (s1, s2) = (lanes[0], lanes[1]);
11148
11149 assert_eq!(soft_order(&project, &lanes, &[2, 0]), [SoftEntry::Lane(s2), SoftEntry::Lane(s1)]);
11150 assert_eq!(soft_order(&project, &lanes, &[0, 2]), [SoftEntry::Lane(s1), SoftEntry::Lane(s2)]);
11151 assert_eq!(soft_order(&project, &lanes, &[3, 1]), [SoftEntry::Track(3), SoftEntry::Track(1)]);
11152 assert_eq!(soft_order(&project, &lanes, &[]), [SoftEntry::Lane(s1), SoftEntry::Lane(s2)]);
11153
11154 let plan = planned_subtitles(&project, Format::Mp4, [2, 0]);
11155 assert!(plan.contains("2 lanes → embedded (S2 three, S1 one)"), "plan: {plan}");
11156 let plan = planned_subtitles(&project, Format::Mp4, [3, 1]);
11157 assert!(plan.contains("2 tracks → embedded (four, two)"), "plan: {plan}");
11158 let plan = planned_subtitles(&project, Format::Mp4, [3, 2, 1, 0]);
11159 assert!(plan.contains("4 tracks → embedded (four, S2 three, two, S1 one)"), "plan: {plan}");
11160 }
11161
11162 /// A ranged file names a track with no cue inside the range as dropped, and carries the rest;
11163 /// a standalone ASS script with override blocks is named as styling the file drops.
11164 #[test]
11165 fn a_range_drops_tracks_with_no_cue_in_it_and_ass_styling_is_named() {
11166 use crate::project::{LaneKind, SubClip};
11167 let track = |label: &str, path: &str| SubtitleTrack {
11168 path: path.into(),
11169 track: None,
11170 language: "eng".into(),
11171 name: label.into(),
11172 label: label.into(),
11173 bitmap: false,
11174 cues: vec![Cue {
11175 start_us: 0,
11176 end_us: 1_000_000,
11177 text: format!("{label} words"),
11178 image: None,
11179 words: Vec::new(),
11180 karaoke: Vec::new(),
11181 }],
11182 refused: None,
11183 };
11184 let ass = std::env::temp_dir().join(format!("edith_export_styling_{}.ass", std::process::id()));
11185 std::fs::write(
11186 &ass,
11187 "[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",
11188 )
11189 .expect("a scratch script");
11190 let mut project = Project::single("/nonexistent/a.mp4", 150)
11191 .with_subtitles(vec![track("one", ass.to_str().unwrap()), track("two", "/nonexistent/film.srt")]);
11192 for t in 0..2 {
11193 let lane = project.add_lane(LaneKind::Subtitle);
11194 project
11195 .place_sub(
11196 lane,
11197 0,
11198 SubClip {
11199 start: 0,
11200 frames: 30,
11201 track: t,
11202 in_us: 0,
11203 out_us: 1_000_000,
11204 link: None,
11205 },
11206 )
11207 .expect("an empty lane takes the placement");
11208 }
11209 // Cues sit in the first second (frames 0 to 30 at 30 fps): a range after it has none.
11210 let late = planned_subtitles_in(&project, Format::Mp4, [0, 1], Some((60, 150)), 30.0);
11211 assert!(late.contains("S1 one — no cues in range") && late.contains("S2 two — no cues in range"), "plan: {late}");
11212 assert!(!late.contains("→ embedded"), "plan: {late}");
11213 let early = planned_subtitles_in(&project, Format::Mp4, [0, 1], Some((0, 30)), 30.0);
11214 assert!(early.contains("2 lanes → embedded (S1 one, S2 two)"), "plan: {early}");
11215
11216 assert_eq!(stripped_styling(&project, &[0, 1]), ["one"], "the ASS script's override tags");
11217 assert!(stripped_styling(&project, &[1]).is_empty(), "a plain SRT has no styling to drop");
11218 let _ = std::fs::remove_file(&ass);
11219 }
11220
11221 #[test]
11222 fn fit_picture_clips_sets_every_picture_clip_on_the_copy() {
11223 let mut p = Project::single("/nonexistent/a.mp4", 90);
11224 let before = p.lane(Lane::V1)[0].fit;
11225 assert_eq!(before, FitPolicy::Fit, "a clip starts on its own default");
11226 assert_eq!(
11227 fit_picture_clips(&mut p, FitPolicy::Fill),
11228 FitOutcome { lanes: vec![(Lane::V1, 1)], overlays: 0 },
11229 "one picture clip"
11230 );
11231 assert_eq!(p.lane(Lane::V1)[0].fit, FitPolicy::Fill);
11232 assert_eq!(p.fit_of(Lane::V1, 0), FitPolicy::Fill);
11233 }
11234
11235 /// The I+P seat's automatic quality is its own default, not the intra
11236 /// seat's mapping: at 1080p30 the intra mapping clamps to QP 40 and the
11237 /// GOP seat must name QP 28 instead.
11238 #[test]
11239 fn the_gop_default_is_not_the_intra_seats_clamped_qp() {
11240 let m = meta(1920, 1080);
11241 let auto = ExportSettings { format: Format::HevcMp4, ..Default::default() };
11242 assert_eq!(hevc_qp(&m, &auto), 40, "the intra mapping clamps at 1080p30");
11243 assert_eq!(
11244 hevc_mode_words(&m, &auto),
11245 Some("I+P GOP (1 s keyframes), constant quality QP 28; pass bitrate_kbps for a fixed rate".to_string())
11246 );
11247 }
11248
11249 #[test]
11250 fn hevc_and_av1_words_name_the_quality_or_the_rate() {
11251 let m = meta(1920, 1080);
11252 let auto = |format| ExportSettings { format, ..Default::default() };
11253 let fixed = |format| ExportSettings { format, bitrate: Some(4_000_000), ..Default::default() };
11254 // With no bitrate the HEVC row is constant QP: the number is the one the encoder is given.
11255 assert_eq!(
11256 hevc_mode_words(&m, &auto(Format::HevcMp4)),
11257 Some(format!("I+P GOP (1 s keyframes), constant quality QP {HEVC_GOP_QP}; pass bitrate_kbps for a fixed rate"))
11258 );
11259 assert_eq!(
11260 hevc_mode_words(&m, &fixed(Format::HevcMp4)),
11261 Some("I+P GOP (1 s keyframes), 4 Mb/s".to_string())
11262 );
11263 assert_eq!(hevc_mode_words(&m, &auto(Format::Mp4)), None, "not an HEVC format");
11264 // AV1 is coded at a bitrate: the automatic one is named as the target it is.
11265 let target = av1_mode_words(&m, &auto(Format::Av1)).expect("an AV1 format");
11266 assert!(target.starts_with("average bitrate ") && target.contains("pass bitrate_kbps"), "{target}");
11267 assert_eq!(av1_mode_words(&m, &fixed(Format::Av1Mp4)), Some("average bitrate 4 Mb/s".to_string()));
11268 assert_eq!(rate_words(6220), "6.2 Mb/s");
11269 assert_eq!(rate_words(850), "850 kb/s");
11270 assert_eq!(av1_mode_words(&m, &auto(Format::HevcMp4)), None, "not an AV1 format");
11271 }
11272
11273 #[test]
11274 fn fit_picture_clips_leaves_a_transformed_overlay_on_its_own_fit() {
11275 use crate::transform::TransformParams;
11276 let mut p = Project::single("/nonexistent/a.mp4", 90);
11277 let v2 = Lane::new(LaneKind::Video, 1);
11278 assert_eq!(p.add_lane(LaneKind::Video), v2);
11279 let logo = p.lane(Lane::V1)[0].clone();
11280 assert!(p.place(v2, 0, logo), "a logo on V2");
11281 // The logo as the project has it: 0.3 of the canvas width, 80% opaque, moved up and right.
11282 let placed = TransformParams { pos_x: 0.32, pos_y: -0.32, scale: 0.3, opacity: 0.8, ..Default::default() };
11283 assert!(p.set_transform(v2, 0, Some(placed)));
11284 assert_eq!(
11285 fit_picture_clips(&mut p, FitPolicy::Fill),
11286 FitOutcome { lanes: vec![(Lane::V1, 1)], overlays: 1 },
11287 "the base picture refits, the overlay does not"
11288 );
11289 assert_eq!(p.fit_of(Lane::V1, 0), FitPolicy::Fill);
11290 assert_eq!(p.fit_of(v2, 0), FitPolicy::Fit, "the overlay keeps its own fit");
11291 assert_eq!(p.transform_of(v2, 0), Some(&placed), "and its placement");
11292
11293 // An identity transform is not an overlay: it refits like any full-frame clip.
11294 assert!(p.set_transform(v2, 0, Some(TransformParams::default())));
11295 assert_eq!(fit_picture_clips(&mut p, FitPolicy::Fill).overlays, 0);
11296 assert_eq!(p.fit_of(v2, 0), FitPolicy::Fill);
11297 }
11298
11299 #[test]
11300 fn a_caption_and_a_title_clash_only_in_the_same_place_and_on_screen_together() {
11301 use crate::project::Title;
11302 use crate::text::TextStyle;
11303 let cue = |start_s: f64, end_s: f64, text: &str| Cue {
11304 start_us: (start_s * 1e6) as i64,
11305 end_us: (end_s * 1e6) as i64,
11306 text: text.into(),
11307 image: None,
11308 words: Vec::new(),
11309 karaoke: Vec::new(),
11310 };
11311 let title = |start: u32, frames: u32, text: &str, place: Place| Title {
11312 start,
11313 frames,
11314 text: text.into(),
11315 style: TextStyle { place, ..TextStyle::default() },
11316 fade_in: 0,
11317 fade_out: 0,
11318 in_anim: Default::default(),
11319 out_anim: Default::default(),
11320 anim_frames: 0,
11321 keys: Vec::new(),
11322 };
11323 // Captions 86.0 to 88.0 s; a bottom title from frame 2163 (86.52 s at 25 fps) for 3 s.
11324 let cues = [cue(86.0, 88.0, "hello")];
11325 let titles = [title(2163, 75, "EVENING, MIRADOURO", Place::Bottom)];
11326 let clash = caption_title_clash(&cues, &titles, Place::Bottom, 25.0).expect("same place, on screen together");
11327 assert!((clash.0 - 86.52).abs() < 0.01, "the clash starts where both are up: {clash:?}");
11328 assert_eq!(clash.1, 0);
11329 assert_eq!(caption_title_clash(&cues, &titles, Place::Top, 25.0), None, "a top caption clears a bottom title");
11330 // The title is up after the captions end: no clash.
11331 let late = [title(2300, 25, "LATE", Place::Bottom)];
11332 assert_eq!(caption_title_clash(&cues, &late, Place::Bottom, 25.0), None, "not on screen together");
11333 // A blank cue is no words on the picture.
11334 let blank = [cue(86.0, 88.0, " ")];
11335 assert_eq!(caption_title_clash(&blank, &titles, Place::Bottom, 25.0), None);
11336 }
11337
11338 #[test]
11339 fn h264_levels_follow_table_a1() {
11340 use super::h264_level_idc;
11341 assert_eq!(h264_level_idc(1280, 720, 30, 1), 31);
11342 assert_eq!(h264_level_idc(1920, 1080, 30, 1), 40);
11343 assert_eq!(h264_level_idc(1920, 1080, 60, 1), 42);
11344 assert_eq!(h264_level_idc(2560, 1440, 30, 1), 50);
11345 assert_eq!(h264_level_idc(3840, 1608, 24000, 1001), 51);
11346 assert_eq!(h264_level_idc(3840, 2160, 60, 1), 52);
11347 assert_eq!(h264_level_idc(640, 360, 30, 1), 30);
11348 }
11349
11350 use super::*;
11351
11352 /// The bar of a *feature film*: a picture count times a permille is a
11353 /// product that has to be computed in `u64`, or a timeline past ~4.5 M
11354 /// pictures (42 hours at 30 fps) overflowed the `u32` this used to be --
11355 /// a panic in debug inside the export thread, and a bar that thrashed in
11356 /// release. Every value here is a fraction of the whole, so none of them
11357 /// may leave the scale, and the counts straddle the old overflow point.
11358 #[test]
11359 fn a_films_frame_count_does_not_overflow_the_bar() {
11360 // The straddle, in the very product the old shape computed: `boundary`
11361 // is the largest picture count whose `done * band` still fitted a
11362 // `u32`, and one more is where it began to wrap -- a panic in debug,
11363 // inside the export thread.
11364 let band = u64::from(PROGRESS_SCALE - AUDIO_BAND);
11365 let boundary = u64::from(u32::MAX) / band;
11366 assert!(boundary * band <= u64::from(u32::MAX));
11367 assert!((boundary + 1) * band > u64::from(u32::MAX));
11368 for total in [boundary as u32 + 1, 21_600_000, u32::MAX] {
11369 assert_eq!(picture_progress(total, total), PROGRESS_SCALE, "{total}");
11370 assert_eq!(picture_progress(0, total), AUDIO_BAND, "{total}");
11371 let half = picture_progress(total / 2, total);
11372 assert!(
11373 (AUDIO_BAND..PROGRESS_SCALE).contains(&half),
11374 "half of {total} is {half}"
11375 );
11376 assert!(
11377 picture_progress(total - 1, total) <= PROGRESS_SCALE,
11378 "{total}"
11379 );
11380 }
11381 }
11382
11383 /// How a decode thread ended is never guessed from the channel being shut.
11384 /// A source that genuinely ran out says so, and the span ends on it; a
11385 /// thread that died without a word is a failure, because reading it as end
11386 /// of stream would truncate the picture and *report the export finished*.
11387 #[test]
11388 fn a_decoder_that_dies_without_a_word_is_not_end_of_stream() {
11389 let streamed = |handle, frames| {
11390 ClipDecoder::Streamed(Streamed {
11391 frames,
11392 _thread: DecodeThread(Some(handle)),
11393 current: None,
11394 ended: false,
11395 park: None,
11396 })
11397 };
11398
11399 let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2);
11400 // Said its piece, then finished: the span walks on to its next clip.
11401 let handle = thread::spawn(move || {
11402 tx.send(Ok(None)).expect("the receiver is alive");
11403 None
11404 });
11405 let mut ended = streamed(handle, frames);
11406 assert!(ended.next().expect("a clean end is not an error").is_none());
11407 // ...and asking again is the same answer and not a disconnect error.
11408 assert!(ended.next().expect("still not an error").is_none());
11409
11410 let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2);
11411 // Died holding the sender: the channel shuts with nothing said.
11412 let handle = thread::spawn(move || {
11413 let _tx = tx;
11414 panic!("decoder died");
11415 });
11416 let mut died = streamed(handle, frames);
11417 let Err(e) = died.next() else {
11418 panic!("a silent death must fail the export, not end the clip")
11419 };
11420 assert!(
11421 e.to_string().contains("without a picture or a reason"),
11422 "{e}"
11423 );
11424 }
11425
11426 /// When a parked decoder may carry on for a later span. A decoder cannot go
11427 /// back, so the span must start at or after the first picture it still
11428 /// holds; and it must have been started at the sync sample a fresh decoder
11429 /// would seek to, or the pictures after it would not be the fresh ones.
11430 #[test]
11431 fn a_parked_decoder_resumes_only_where_a_fresh_one_would_match() {
11432 // Stopped at display 330 with two decoded pictures unclaimed (328 and
11433 // 329), started at the sync sample 250.
11434 let stopped = |start| resumable(330, 2, 250, 250, start);
11435 assert!(stopped(328), "the first held picture is the span's first");
11436 assert!(stopped(329), "the second held picture is the span's first");
11437 assert!(stopped(330), "the span starts where the decoder stopped");
11438 assert!(stopped(400), "a span further on decodes on to its picture");
11439 assert!(!stopped(327), "a span before what is held needs a restart");
11440 // Nothing unclaimed: the decoder's own position is the first picture.
11441 assert!(resumable(330, 0, 250, 250, 330));
11442 assert!(!resumable(330, 0, 250, 250, 329));
11443 // A fresh decoder for the span would seek to a later sync sample than
11444 // the one this decoder started at, so this one is not the same decode.
11445 assert!(!resumable(330, 2, 250, 300, 400));
11446 // And one that started at a later sync sample than a fresh one would
11447 // is not the same decode either.
11448 assert!(!resumable(330, 2, 300, 250, 330));
11449 }
11450
11451 /// Three seconds of two tones, one per channel, interleaved: enough shape
11452 /// that a correlation says something and enough length that the encoder
11453 /// settles into a mode.
11454 fn two_tones(secs: usize) -> Vec<f32> {
11455 (0..OPUS_RATE as usize * secs)
11456 .flat_map(|i| {
11457 let t = i as f32 / OPUS_RATE as f32;
11458 let tau = std::f32::consts::TAU;
11459 [
11460 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin(),
11461 0.25 * (tau * 880.0 * t).sin(),
11462 ]
11463 })
11464 .collect()
11465 }
11466
11467 /// Three seconds of the same two tones summed onto one channel: the mono
11468 /// mix `opus-rs 0.1.26` mis-encoded at every rate, which is why a mono
11469 /// export kept the AAC path until `ec-opus` took the seat.
11470 fn mono_tones(secs: usize) -> Vec<f32> {
11471 (0..OPUS_RATE as usize * secs)
11472 .map(|i| {
11473 let t = i as f32 / OPUS_RATE as f32;
11474 let tau = std::f32::consts::TAU;
11475 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin()
11476 })
11477 .collect()
11478 }
11479
11480 /// The best correlation of one channel of `got` against `want`, and the
11481 /// offset it sat at. `stride` is the interleave width: 2 for the stereo
11482 /// fixtures, 1 for mono.
11483 fn align(want: &[f32], got: &[f32], stride: usize) -> (f64, usize) {
11484 let (mut best, mut at) = (-2.0, 0);
11485 let window = OPUS_RATE as usize;
11486 for lag in 0..1400 {
11487 let (mut num, mut da, mut db) = (0.0, 0.0, 0.0);
11488 for (x, y) in want[..window]
11489 .iter()
11490 .step_by(stride)
11491 .zip(got[lag * stride..].iter().step_by(stride))
11492 {
11493 num += f64::from(*x) * f64::from(*y);
11494 da += f64::from(*x) * f64::from(*x);
11495 db += f64::from(*y) * f64::from(*y);
11496 }
11497 let c = num / (da.sqrt() * db.sqrt()).max(1e-12);
11498 if c > best {
11499 (best, at) = (c, lag);
11500 }
11501 }
11502 (best, at)
11503 }
11504
11505 fn ec_decode(packets: &[crate::AacPacket]) -> Vec<f32> {
11506 let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]);
11507 let mut pcm = Vec::new();
11508 for packet in packets {
11509 pcm.extend(
11510 decoder
11511 .decode_packet(&packet.bytes)
11512 .expect("a valid packet"),
11513 );
11514 }
11515 pcm
11516 }
11517
11518 /// [`ec_decode`] for a mono packet stream: one stream, no coupling.
11519 fn ec_decode_mono(packets: &[crate::AacPacket]) -> Vec<f32> {
11520 let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 0, &[0]);
11521 let mut pcm = Vec::new();
11522 for packet in packets {
11523 pcm.extend(
11524 decoder
11525 .decode_packet(&packet.bytes)
11526 .expect("a valid packet"),
11527 );
11528 }
11529 pcm
11530 }
11531
11532 /// Why [`OPUS_MAX_KBPS`] is a cap, why [`OPUS_PRE_SKIP`] is a constant and
11533 /// why [`opus_fidelity`] exists at all -- all three measured here through
11534 /// the same decoder door the product reads every Opus file back with, the
11535 /// decoder being the witness and the *encoder* the one under test.
11536 ///
11537 /// The second half pins the two failures the seat's move here fixed: under
11538 /// `opus-rs 0.1.26` the encoder wrote stereo packets that only its own
11539 /// decoder read back above roughly 165 kbps (fidelity 0.06 at 256), and it
11540 /// mis-encoded mono at every rate -- which is what the old 128 cap and the
11541 /// mono-mix-keeps-AAC rule stood on. Both asserts are survival now, and a
11542 /// regression fails here, loudly: that is the signal to lower
11543 /// [`OPUS_MAX_KBPS`] again, not a reason to widen it quietly.
11544 #[test]
11545 fn the_opus_encoder_is_pinned_to_the_band_it_was_measured_in() {
11546 let pcm = two_tones(3);
11547 for kbps in [96, OPUS_MAX_KBPS] {
11548 let (packets, pre_skip) = encode_opus(&pcm, kbps, 2)
11549 .expect("the encoder opens")
11550 .expect("and inside the band it passes its own round trip");
11551 assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16);
11552 assert_eq!(
11553 packets.len(),
11554 pcm.len().div_ceil(OPUS_FRAME * 2) + 2,
11555 "one packet per 20 ms frame, plus the warm-up and the flush"
11556 );
11557 let decoded = ec_decode(&packets);
11558 let (c, lag) = align(&pcm, &decoded, 2);
11559 // From the first audible sample, head included -- and the head is
11560 // why this is 0.98 and not the 0.999 below: the encoder's first
11561 // audible 20 ms comes out a few dB down (one frame of cold start;
11562 // a second warm-up frame changes the numbers in no decimal place),
11563 // so that ramp is stated rather than hidden behind a loose
11564 // threshold.
11565 assert!(c >= 0.98, "{kbps} kbps came back at correlation {c:.4}");
11566 let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..], 2);
11567 assert!(
11568 settled >= 0.999,
11569 "{kbps} kbps past the first frame: correlation {settled:.4}"
11570 );
11571 // The whole point of the number in the header: drop exactly that
11572 // many samples and the sound starts where the timeline says. A lag
11573 // that is not it is a file that plays late or eats its own head.
11574 assert_eq!(
11575 lag,
11576 usize::from(pre_skip),
11577 "{kbps} kbps: the declared pre-skip is not where the sound starts"
11578 );
11579 // ...and the tail is all there: the flush frame pushed the last
11580 // samples out, so what is left after the pre-skip covers the input.
11581 assert!(
11582 decoded.len() - usize::from(pre_skip) * 2 >= pcm.len(),
11583 "{kbps} kbps: the track ends {} samples short of the timeline",
11584 (pcm.len() + usize::from(pre_skip) * 2 - decoded.len()) / 2
11585 );
11586 // The gate the export runs before it writes anything, on a track
11587 // that deserves to pass it.
11588 let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip), 2);
11589 assert!(
11590 fidelity >= OPUS_MIN_FIDELITY,
11591 "{kbps} kbps scored {fidelity:.4} on its own round trip"
11592 );
11593 }
11594
11595 // Mono, the shape `opus-rs 0.1.26` mis-encoded at every rate and the
11596 // reason a mono mix kept the AAC path: straight through the same seat,
11597 // including at the rate where the old encoder was already writing
11598 // stereo noise, let alone mono.
11599 let mono = mono_tones(3);
11600 for kbps in [96, 256] {
11601 let (packets, pre_skip) = encode_opus(&mono, kbps, 1)
11602 .expect("the encoder opens")
11603 .expect("and mono passes its own round trip");
11604 assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16);
11605 let decoded = ec_decode_mono(&packets);
11606 let (c, lag) = align(&mono, &decoded, 1);
11607 assert!(
11608 c >= 0.98,
11609 "mono at {kbps} kbps came back at correlation {c:.4}"
11610 );
11611 let (settled, _) = align(&mono[OPUS_FRAME..], &decoded[OPUS_FRAME..], 1);
11612 assert!(
11613 settled >= 0.999,
11614 "mono at {kbps} kbps past the first frame: correlation {settled:.4}"
11615 );
11616 assert_eq!(
11617 lag,
11618 usize::from(pre_skip),
11619 "mono at {kbps} kbps: the declared pre-skip is not where the sound starts"
11620 );
11621 assert!(
11622 decoded.len() - usize::from(pre_skip) >= mono.len(),
11623 "mono at {kbps} kbps: the track ends {} samples short of the timeline",
11624 mono.len() + usize::from(pre_skip) - decoded.len()
11625 );
11626 let fidelity = opus_fidelity(&packets, &mono, usize::from(pre_skip), 1);
11627 assert!(
11628 fidelity >= OPUS_MIN_FIDELITY,
11629 "mono at {kbps} kbps scored {fidelity:.4} on its own round trip"
11630 );
11631 }
11632 }
11633
11634 /// The gate on a track too long to listen to whole: it samples, and the
11635 /// middle of what it hears is the answer. A track whose sound is *not* what
11636 /// was encoded fails it; one bad five-second window does not, which is
11637 /// deliberate and measured ([`opus_fidelity`] carries the distribution:
11638 /// five windows of a good film's mix score under 0.95, the lowest 0.803).
11639 /// A silent track is not a failure either, which is what it used to be
11640 /// scored as -- 0.0 against a denominator of nothing, and an all-quiet
11641 /// timeline fell back to AAC for it.
11642 ///
11643 /// 61 s of sound: one second past the minute the gate stops listening whole,
11644 /// which is what puts this on the sampled path at all.
11645 #[test]
11646 fn a_long_track_is_judged_by_the_middle_of_what_it_samples() {
11647 let pcm = two_tones(61);
11648 let (packets, pre_skip) = encode_opus(&pcm, 96, 2)
11649 .expect("the encoder opens")
11650 .expect("and passes its own round trip");
11651 assert!(
11652 packets.len() > FIDELITY_WINDOW * FIDELITY_WINDOWS,
11653 "{} packets is not the sampled path",
11654 packets.len()
11655 );
11656 let pre_skip = usize::from(pre_skip);
11657 let whole = opus_fidelity(&packets, &pcm, pre_skip, 2);
11658 assert!(whole >= OPUS_MIN_FIDELITY, "a good track scored {whole:.4}");
11659
11660 // One window's worth of the *mix* replaced by its own phase inverse:
11661 // the packets still decode, they are simply no longer this sound. Placed
11662 // on a window the gate samples -- window 6 of the twelve, by the same
11663 // arithmetic the gate spreads them with. The track still passes, and
11664 // that is the measured decision, not an oversight: this codec really
11665 // does score 0.80 on five seconds of film it otherwise handles at 0.998.
11666 let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1);
11667 let from = (6 * step * OPUS_FRAME).saturating_sub(pre_skip) * 2;
11668 let mut one_bad = pcm.clone();
11669 for sample in &mut one_bad[from..(from + FIDELITY_WINDOW * OPUS_FRAME * 2).min(pcm.len())] {
11670 *sample = -*sample;
11671 }
11672 let dip = opus_fidelity(&packets, &one_bad, pre_skip, 2);
11673 assert!(
11674 dip >= OPUS_MIN_FIDELITY,
11675 "one ruined window sank the whole track ({dip:.4})"
11676 );
11677
11678 // ...and the shape the gate is actually for, which is what a rate the
11679 // encoder cannot hold does: the track is not the mix any more, not one
11680 // window of it. The middle of the list moves with it.
11681 let mut ruined = pcm.clone();
11682 for sample in &mut ruined[pcm.len() / 4..] {
11683 *sample = -*sample;
11684 }
11685 let ruined = opus_fidelity(&packets, &ruined, pre_skip, 2);
11686 assert!(
11687 ruined < OPUS_MIN_FIDELITY,
11688 "a track that is no longer the mix scored {ruined:.4}"
11689 );
11690
11691 // ...and silence is silence: nothing to correlate is not a round trip
11692 // that failed. Short, because the floor is the same on either path.
11693 let quiet = vec![0f32; OPUS_RATE as usize * 2 * 2];
11694 let (packets, pre_skip) = encode_opus(&quiet, 96, 2)
11695 .expect("the encoder opens")
11696 .expect("silence is written as Opus, not sent to AAC");
11697 let fidelity = opus_fidelity(&packets, &quiet, usize::from(pre_skip), 2);
11698 assert!(
11699 fidelity >= OPUS_MIN_FIDELITY,
11700 "a silent track scored {fidelity:.4} and would fall back to AAC"
11701 );
11702 }
11703
11704 /// The one rule that keeps a picture from being converted twice: a frame the
11705 /// tone map has already brought to BT.709 is never handed the 2020 matrix as
11706 /// well, on either canvas -- and everything else about the remap is
11707 /// unchanged by the tone map existing.
11708 #[test]
11709 fn a_tone_mapped_span_is_never_matrix_remapped_too() {
11710 let hdr = ColorDescription {
11711 matrix: Matrix::Bt2020Ncl,
11712 transfer: Transfer::Pq,
11713 full_range: false,
11714 };
11715 let sdr = ColorDescription::default(); // BT.601
11716 // The (from, to) pair of a remap, which is all these cases are about.
11717 let pair = |remap: Option<Remap>| remap.map(|r| (r.from, r.to));
11718 for out in [Matrix::Bt709, Matrix::Bt601] {
11719 let toned = pair(remap_into(Some(hdr), true, out));
11720 assert!(
11721 toned.is_none_or(|(from, _)| from == Matrix::Bt709),
11722 "tone-mapped onto a {out:?} canvas asked for {toned:?}"
11723 );
11724 // Untouched by any of this: the 2020 clip that was *not* tone-mapped
11725 // (an unreachable state today, and still the matrix answer), the
11726 // ordinary 601-on-709 reconcile, and a gap.
11727 assert_eq!(
11728 pair(remap_into(Some(hdr), false, out)),
11729 (out != Matrix::Bt2020Ncl).then_some((Matrix::Bt2020Ncl, out))
11730 );
11731 assert_eq!(
11732 pair(remap_into(Some(sdr), false, out)),
11733 (out != Matrix::Bt601).then_some((Matrix::Bt601, out))
11734 );
11735 assert_eq!(remap_into(None, false, out), None);
11736 }
11737 assert_eq!(
11738 pair(remap_into(Some(hdr), true, Matrix::Bt601)),
11739 Some((Matrix::Bt709, Matrix::Bt601)),
11740 "a tone-mapped clip below 720 lines still takes its 709 -> 601 step"
11741 );
11742 }
11743
11744 /// A full-range source is scaled into the limited span before it is matrix
11745 /// converted, and only an untouched one: a tone-mapped picture is already
11746 /// limited, and a limited source has nothing to scale.
11747 #[test]
11748 fn a_full_range_source_is_limited_before_it_is_remapped() {
11749 let full = ColorDescription {
11750 matrix: Matrix::Bt709,
11751 transfer: Transfer::Sdr,
11752 full_range: true,
11753 };
11754 let limited = ColorDescription {
11755 full_range: false,
11756 ..full
11757 };
11758 assert_eq!(
11759 remap_into(Some(full), false, Matrix::Bt709),
11760 Some(Remap {
11761 from: Matrix::Bt709,
11762 to: Matrix::Bt709,
11763 limit: true,
11764 }),
11765 "same matrix, but the range still has to come down"
11766 );
11767 assert_eq!(remap_into(Some(limited), false, Matrix::Bt709), None);
11768 assert_eq!(remap_into(Some(full), true, Matrix::Bt709), None);
11769 }
11770
11771 /// The picture as [`place_picture`] hands it to the encoder: a full-range
11772 /// source on a canvas of its own size, so the placement is the identity and
11773 /// what comes out is exactly the range change.
11774 #[test]
11775 fn a_full_range_picture_is_placed_as_limited_codes() {
11776 let (w, h) = (4u32, 2u32);
11777 let y = [0u8, 255, 130, 130, 0, 255, 130, 130];
11778 let (u, v) = ([0u8, 255], [255u8, 0]);
11779 let mut canvas = Composer::new(w, h, crate::scale::FitPolicy::default());
11780 let (mut turned, mut stretched, mut graded, mut transformed) = (
11781 (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()),
11782 (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()),
11783 (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()),
11784 (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()),
11785 );
11786 let remap = Some(Remap {
11787 from: Matrix::Bt709,
11788 to: Matrix::Bt709,
11789 limit: true,
11790 });
11791 let (py, pu, pv, _, _) = place_picture(
11792 &y,
11793 &u,
11794 &v,
11795 w,
11796 h,
11797 Rotation::default(),
11798 crate::demux::PixelAspect::SQUARE,
11799 None,
11800 TransformParams::default(),
11801 remap,
11802 None,
11803 &mut turned,
11804 &mut stretched,
11805 &mut graded,
11806 &mut transformed,
11807 &mut canvas,
11808 );
11809 assert_eq!(py, [16, 235, 128, 128, 16, 235, 128, 128]);
11810 assert_eq!(pu, [16, 240]);
11811 assert_eq!(pv, [240, 16]);
11812 }
11813
11814 /// A track of three cues, in whichever clock `track` says: `Some(n)` is a
11815 /// track of the media file, `None` a `.srt` beside it.
11816 fn subtitles(path: &str, track: Option<u64>) -> SubtitleTrack {
11817 SubtitleTrack {
11818 path: path.into(),
11819 track,
11820 language: "eng".into(),
11821 name: String::new(),
11822 label: "eng".into(),
11823 bitmap: false,
11824 cues: vec![
11825 Cue {
11826 start_us: 500_000,
11827 end_us: 1_500_000,
11828 text: "first".into(),
11829 image: None,
11830 words: Vec::new(),
11831 karaoke: Vec::new(),
11832 },
11833 Cue {
11834 start_us: 2_000_000,
11835 end_us: 3_250_000,
11836 text: "second".into(),
11837 image: None,
11838 words: Vec::new(),
11839 karaoke: Vec::new(),
11840 },
11841 Cue {
11842 start_us: 4_000_000,
11843 end_us: 4_750_000,
11844 text: "third".into(),
11845 image: None,
11846 words: Vec::new(),
11847 karaoke: Vec::new(),
11848 },
11849 ],
11850 refused: None,
11851 }
11852 }
11853
11854 /// A standalone subtitle file is timed against the timeline itself -- there
11855 /// is no clip to hang it on -- so a cut moves the pictures and not it. What
11856 /// it does get is the exported length: a cue past the end of the file would
11857 /// otherwise be a block after the last picture.
11858 ///
11859 /// The pair of this, the embedded clock, is measured against a real exported
11860 /// file in `tests/export_subs.rs`; both live in one function and this is the
11861 /// half that needs no encoder.
11862 #[test]
11863 fn a_subtitle_file_beside_the_media_keeps_the_timelines_own_clock() {
11864 // 5 seconds at 30, with `[0.5s, 2.5s)` cut out of it: 3 seconds left.
11865 let mut project = Project::single("/nonexistent/film.mp4", 150);
11866 let track = subtitles("/nonexistent/film.srt", None);
11867 assert!(project.ripple_delete(15, 60));
11868 assert_eq!(project.timeline_frames(), 90);
11869 let cues = timeline_cues(&project, &track, 30.0);
11870 assert_eq!(
11871 cues,
11872 vec![
11873 Cue {
11874 start_us: 500_000,
11875 end_us: 1_500_000,
11876 text: "first".into(),
11877 image: None,
11878 words: Vec::new(),
11879 karaoke: Vec::new(),
11880 },
11881 // Clipped to the three seconds the export writes...
11882 Cue {
11883 start_us: 2_000_000,
11884 end_us: 3_000_000,
11885 text: "second".into(),
11886 image: None,
11887 words: Vec::new(),
11888 karaoke: Vec::new(),
11889 },
11890 // ...and the one wholly past the end is not written at all.
11891 ]
11892 );
11893 // A track *of a file* the project no longer plays has no span to be
11894 // carried through either, so it falls back to the same clock rather
11895 // than exporting nothing.
11896 let orphan = subtitles("/nonexistent/other.mkv", Some(2));
11897 assert_eq!(timeline_cues(&project, &orphan, 30.0).len(), 2);
11898 }
11899
11900 /// The embedded clock, without an encoder in it: the cut moves the cues with
11901 /// the pictures, and a cue nothing clipped keeps its own microseconds.
11902 #[test]
11903 fn a_track_of_the_media_is_carried_through_the_cut() {
11904 let mut project = Project::single("/nonexistent/film.mkv", 150);
11905 let track = subtitles("/nonexistent/film.mkv", Some(2));
11906 assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out");
11907 let cues = timeline_cues(&project, &track, 30.0);
11908 assert_eq!(
11909 cues,
11910 vec![
11911 // The first cue was wholly inside the cut. The second straddled
11912 // its far edge and kept the 0.75s that is still there...
11913 Cue {
11914 start_us: 500_000,
11915 end_us: 1_250_000,
11916 text: "second".into(),
11917 image: None,
11918 words: Vec::new(),
11919 karaoke: Vec::new(),
11920 },
11921 // ...and the third simply moves back the two seconds that went.
11922 Cue {
11923 start_us: 2_000_000,
11924 end_us: 2_750_000,
11925 text: "third".into(),
11926 image: None,
11927 words: Vec::new(),
11928 karaoke: Vec::new(),
11929 },
11930 ]
11931 );
11932 }
11933
11934 #[test]
11935 fn export_spans_clips_to_the_marked_range_keeping_absolute_start() {
11936 let project = Project::single("/nonexistent/film.mkv", 150);
11937 // The whole timeline, unmarked: one span, the source's own length.
11938 let whole = export_spans(&project, None);
11939 assert_eq!(whole.len(), 1);
11940 assert_eq!((whole[0].start, whole[0].len), (0, 150));
11941 // A range wholly inside the span: `start` stays the timeline's own
11942 // coordinate ([`composite_color_at`] needs that), and the length is
11943 // exactly what the mark asked for.
11944 let clipped = export_spans(&project, Some((30, 100)));
11945 assert_eq!(clipped.len(), 1);
11946 assert_eq!((clipped[0].start, clipped[0].len), (30, 70));
11947 // A range past the end of the media clamps to it rather than reading
11948 // short on the wrong side.
11949 let past_end = export_spans(&project, Some((100, 500)));
11950 assert_eq!((past_end[0].start, past_end[0].len), (100, 50));
11951 }
11952
11953 #[test]
11954 fn bitrate_clamps_at_both_ends() {
11955 let meta = |width, height, frame_rate| VideoMeta {
11956 width,
11957 height,
11958 frame_rate,
11959 frame_count: 1,
11960 codec: crate::demux::Codec::H264,
11961 color: Default::default(),
11962 matrix_assumed: false,
11963 rotation: Rotation::None,
11964 // Square pixels, coded where they are declared: a meta no container
11965 // wrote, so nothing was read to disagree with it.
11966 coded_width: width,
11967 coded_height: height,
11968 pixel_aspect: crate::demux::PixelAspect::SQUARE,
11969 };
11970 // 1280 * 720 * 30 * 0.1
11971 assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800);
11972 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), 230_400, "tiny");
11973 assert_eq!(
11974 bitrate_for(&meta(160, 120, 15.0)),
11975 MIN_BITRATE,
11976 "tinier floors"
11977 );
11978 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
11979 // A rate somebody typed goes through untouched to its own ceiling, which
11980 // is above where the derived one stops: the card offers 50 Mbps, and a
11981 // second clamp here would write a file at a bitrate nobody picked.
11982 let asked = |bps| {
11983 bitrate_of(
11984 &meta(1920, 1080, 30.0),
11985 &ExportSettings {
11986 bitrate: Some(bps),
11987 ..Default::default()
11988 },
11989 )
11990 };
11991 assert_eq!(asked(50_000_000), 50_000_000, "the card's ceiling travels");
11992 assert_eq!(asked(21_000_000), 21_000_000, "past the derived range");
11993 assert_eq!(asked(600_000), 600_000, "a sub-Mbps ask travels");
11994 assert_eq!(asked(999_000_000), MAX_EXPLICIT_BITRATE, "still bounded");
11995 assert_eq!(asked(1), MIN_BITRATE, "and floored");
11996 }
11997
11998 /// A clip's fade takes the copy path away, exactly as an equalizer does:
11999 /// a copied AAC packet cannot carry gain math nobody put in the file. The
12000 /// bug this guards is [`forces_encode`] gating on `equalized`/`mastered`
12001 /// but never checking a clip's own `fade_in`/`fade_out` at all -- the
12002 /// default Web MP4 export then labelled and took the "AAC copy" path for
12003 /// a project whose picture showed a fade, and the fade never reached the
12004 /// file.
12005 #[test]
12006 fn a_fade_forces_the_audio_to_be_re_encoded() {
12007 let mut project = Project::single("/nonexistent/film.mp4", 90);
12008 assert!(!forces_encode(&project, false), "flat, so a copy is fine");
12009 assert!(project.set_fade_in(
12010 crate::project::Lane::new(crate::project::LaneKind::Audio, 0),
12011 0,
12012 15
12013 ));
12014 assert!(
12015 forces_encode(&project, false),
12016 "a fade-in on the only clip must force a re-encode"
12017 );
12018 }
12019
12020 fn meta(width: u32, height: u32) -> VideoMeta {
12021 VideoMeta {
12022 width,
12023 height,
12024 frame_rate: 30.0,
12025 frame_count: 1,
12026 codec: crate::demux::Codec::H264,
12027 color: Default::default(),
12028 matrix_assumed: false,
12029 rotation: Rotation::None,
12030 // Square pixels, coded where they are declared: a meta no
12031 // container wrote, so nothing was read to disagree with it.
12032 coded_width: width,
12033 coded_height: height,
12034 pixel_aspect: crate::demux::PixelAspect::SQUARE,
12035 }
12036 }
12037
12038 /// The bitrate row a user picked, read as the quality tier it is: a higher
12039 /// row is a lower QP, the band is honoured at both ends, and the same
12040 /// picture at the same rate gets the same number whatever its size (the
12041 /// mapping is bits per *pixel*, which is what makes 720p and 1080p one
12042 /// table).
12043 #[test]
12044 fn the_quality_rows_map_onto_quantisers_that_only_go_one_way() {
12045 let at = |width, height, mbps: Option<u64>| {
12046 hevc_qp(
12047 &meta(width, height),
12048 &ExportSettings {
12049 bitrate: mbps.map(|m| m * 1_000_000),
12050 ..Default::default()
12051 },
12052 )
12053 };
12054 // 20 Mbps at 1080p30 is 0.32 bits a pixel against the 0.6 measured at
12055 // QP 27, which is just over half: five QP up, and QP is not an
12056 // arithmetic scale, so this is the number the formula gives.
12057 assert_eq!(at(1920, 1080, Some(20)), 32);
12058 // Every step down the card is a step up in QP, never sideways.
12059 let rows: Vec<i32> = [20, 12, 8, 4, 2, 1]
12060 .into_iter()
12061 .map(|mbps| at(1920, 1080, Some(mbps)))
12062 .collect();
12063 assert!(
12064 rows.windows(2).all(|w| w[0] <= w[1]),
12065 "a lower bitrate row must never code at a lower QP: {rows:?}"
12066 );
12067 assert_eq!(*rows.last().unwrap(), HEVC_QP_MAX, "the floor is clamped");
12068 // ...and the top of the range is the clamp, not an unbounded number: 20
12069 // Mbps at 320x240 is 8.7 bits a pixel, which no picture needs.
12070 assert_eq!(at(320, 240, Some(20)), HEVC_QP_MIN);
12071 // The same bits per pixel is the same quantiser at any size: 1080p at
12072 // 20 Mbps and 720p at 8.9 Mbps are one picture quality.
12073 assert_eq!(at(1920, 1080, Some(20)), at(1280, 720, Some(9)));
12074 // The automatic bitrate is 0.1 bpp at every size, so it is one QP
12075 // everywhere -- the honest end of "intra-only, large files": the file
12076 // will be bigger than the row says, and the row buys quality.
12077 assert_eq!(at(1920, 1080, None), at(1280, 720, None));
12078 }
12079
12080 /// An odd picture cannot be cropped back to itself in 4:2:0 -- the
12081 /// conformance window is stated in chroma samples -- so it is refused by
12082 /// name rather than written a column wider than the timeline.
12083 #[test]
12084 fn an_odd_picture_is_refused_an_hevc_export_by_name() {
12085 let settings = ExportSettings {
12086 format: Format::Hevc,
12087 ..Default::default()
12088 };
12089 let refused = Enc::open(&meta(1919, 1080), &settings, false, ColorDescription::default())
12090 .err()
12091 .expect("an odd width has no chroma plane")
12092 .to_string();
12093 assert!(refused.contains("1919x1080"), "{refused}");
12094 assert!(refused.contains("even"), "{refused}");
12095 // ...and the even one it neighbours opens.
12096 assert!(Enc::open(&meta(1920, 1080), &settings, false, ColorDescription::default()).is_ok());
12097 }
12098
12099 /// H.264 codes 16x16 macroblocks and ec-h264's floor is the macroblock
12100 /// itself -- the old encoder took any positive even size -- so a
12101 /// sub-macroblock picture is refused by name, like every other seat
12102 /// refusal, rather than surfaced from inside a running export.
12103 #[test]
12104 fn a_sub_macroblock_picture_is_refused_an_h264_export_by_name() {
12105 let settings = ExportSettings {
12106 format: Format::Mp4,
12107 seat: EncoderSeat::Software,
12108 ..Default::default()
12109 };
12110 let refused = Enc::open(&meta(8, 8), &settings, false, ColorDescription::default())
12111 .err()
12112 .expect("8x8 is smaller than one macroblock")
12113 .to_string();
12114 assert!(refused.contains("8x8"), "{refused}");
12115 assert!(refused.contains("16x16"), "{refused}");
12116 }
12117
12118 /// Weights ramp from just above 0 to just below 1 and never touch either
12119 /// end -- the frame *after* the window is where a viewer would see plain
12120 /// B, and the window itself never quite repeats a hard cut's own instant.
12121 #[test]
12122 fn dissolve_weight_ramps_strictly_between_zero_and_one() {
12123 assert_eq!(
12124 dissolve_weight(0, 1),
12125 0.5,
12126 "a one-frame window is the midpoint"
12127 );
12128 assert_eq!(dissolve_weight(0, 4), 0.2);
12129 assert_eq!(dissolve_weight(1, 4), 0.4);
12130 assert_eq!(dissolve_weight(2, 4), 0.6);
12131 assert_eq!(dissolve_weight(3, 4), 0.8);
12132 }
12133
12134 /// [`dissolve_window`] reads [`crate::project::Clip::transition_out`] back
12135 /// only once adjacency is re-checked at render time: two clips a split
12136 /// just made, still touching, still name B by its own source and its own
12137 /// timeline start.
12138 #[test]
12139 fn dissolve_window_names_bs_source_in_frame_window_and_start() {
12140 use crate::project::{Lane, Project};
12141 let mut p = Project::single("/nonexistent/film.mkv", 20);
12142 assert!(p.split(15));
12143 assert!(p.set_transition_out(Lane::V1, 0, 5));
12144 let spans = export_spans(&p, None);
12145 let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span");
12146 assert_eq!(
12147 dissolve_window(&p, a_span),
12148 Some((0, 15, 5, 15)),
12149 "b's source, b's in_frame, the window, b's timeline start"
12150 );
12151 }
12152
12153 /// A `transition_out` set while two clips touched, then made stale by a
12154 /// trim that opens a gap between them: the number is still in storage,
12155 /// [`dissolve_window`] reads `None` from it, and the span renders as the
12156 /// hard cut two clips that no longer touch actually are.
12157 #[test]
12158 fn a_stale_transition_out_after_a_trim_renders_as_a_hard_cut() {
12159 use crate::project::{Edge, Lane, Project};
12160 let mut p = Project::single("/nonexistent/film.mkv", 20);
12161 assert!(p.split(15));
12162 assert!(p.set_transition_out(Lane::V1, 0, 5));
12163 assert!(p.trim(Lane::V1, 1, Edge::Start, 18, &[100]), "opens a gap");
12164 let spans = export_spans(&p, None);
12165 let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span");
12166 assert!(
12167 dissolve_window(&p, a_span).is_none(),
12168 "b no longer abuts a; hard cut"
12169 );
12170 }
12171}
12172
12173#[cfg(test)]
12174mod audio_language_tests {
12175 use super::*;
12176
12177 fn asset(name: &str) -> PathBuf {
12178 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
12179 }
12180
12181 /// `test_multilang.mp4` has an `und` track 0 and a `fra` track 1.
12182 #[test]
12183 fn a_stream_states_its_language_or_none() {
12184 let path = asset("test_multilang.mp4");
12185 assert_eq!(stream_language(&path, 0), None, "und is no language");
12186 assert_eq!(stream_language(&path, 1).as_deref(), Some("fra"));
12187 assert_eq!(stream_language(&path, 9), None, "a track the file does not have");
12188 }
12189
12190 /// The tag is the one language every clip shares; any disagreement or any `und` leaves it out.
12191 #[test]
12192 fn the_mix_takes_a_language_only_when_every_clip_shares_it() {
12193 let s = |l: &str| Some(l.to_string());
12194 assert_eq!(shared_language([s("fra"), s("fra")]), s("fra"));
12195 assert_eq!(shared_language([s("fra"), s("eng")]), None, "two languages");
12196 assert_eq!(shared_language([s("fra"), None]), None, "one clip states none");
12197 assert_eq!(shared_language(Vec::<Option<String>>::new()), None, "no sound at all");
12198 }
12199
12200 /// The clips on the audio lanes name the streams the sound comes from: a `und` clip beside
12201 /// a `fra` one leaves the tag out.
12202 #[test]
12203 fn a_mix_of_und_and_french_clips_has_no_tag() {
12204 let path = asset("test_multilang.mp4");
12205 let mut p = Project::single(&path, 30);
12206 assert_eq!(audio_language(&p), None, "the first track is und");
12207 let fra = p.import(&path, 1);
12208 assert!(p.append_clip(fra, 30));
12209 assert_eq!(audio_language(&p), None, "the und clip is still on A1");
12210 }
12211}
12212
12213#[cfg(test)]
12214mod burn_stack_tests {
12215 #[test]
12216 fn two_overlapping_cues_are_both_drawn_stacked() {
12217 use super::{Burn, Cue, cues_on_screen};
12218 use crate::text::TextStyle;
12219 let cue = |text: &str| Cue {
12220 start_us: 0,
12221 end_us: 5_000_000,
12222 text: text.to_string(),
12223 image: None,
12224 words: Vec::new(),
12225 karaoke: Vec::new(),
12226 };
12227 let (w, h) = (640u32, 360u32);
12228 let paint = |cues: Vec<Cue>| {
12229 let mut burn = Burn {
12230 cues,
12231 style: TextStyle {
12232 boxed: false,
12233 ..TextStyle::default()
12234 },
12235 fps: 30.0,
12236 full_range: false,
12237 last: None,
12238 titles: Vec::new(),
12239 title_last: Vec::new(),
12240 native: None,
12241 spare: None,
12242 narrow: Default::default(),
12243 merged: Default::default(),
12244 };
12245 let y = vec![40u8; (w * h) as usize];
12246 let u = vec![128u8; (w / 2 * (h / 2)) as usize];
12247 let v = u.clone();
12248 burn.paint(30, w, h, (&y, &u, &v))
12249 .expect("a caption is drawn")
12250 };
12251 // The rows that carry a lit (white) pixel in the luma plane.
12252 let lit_rows = |planes: &(Vec<u8>, Vec<u8>, Vec<u8>)| -> Vec<u32> {
12253 (0..h)
12254 .filter(|&r| {
12255 let row = &planes.0[(r * w) as usize..((r + 1) * w) as usize];
12256 row.iter().any(|&l| l > 40)
12257 })
12258 .collect()
12259 };
12260 let cues = vec![cue("First cue"), cue("Second cue")];
12261 assert_eq!(cues_on_screen(&cues, 30, 30.0), vec![0, 1], "both are on screen");
12262 let one = lit_rows(&paint(vec![cue("First cue")]));
12263 let both = lit_rows(&paint(cues));
12264 assert!(
12265 both.len() >= 2 * one.len() - 1,
12266 "second cue not drawn: {} lit rows against {} for the first alone",
12267 both.len(),
12268 one.len()
12269 );
12270 // The first cue keeps its place on the bottom edge; the second stacks above.
12271 assert_eq!(both.last(), one.last(), "the first cue moved");
12272 }
12273}
12274
12275#[cfg(test)]
12276mod chroma_420_tests {
12277 use super::*;
12278
12279 fn asset(name: &str) -> PathBuf {
12280 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
12281 }
12282
12283 /// The layout a chroma plane's sample count names, for each subsampling.
12284 #[test]
12285 fn a_chroma_count_names_its_layout() {
12286 assert_eq!(chroma_shape(64 * 64, 64, 64), Some((64, 64)), "4:4:4");
12287 assert_eq!(chroma_shape(32 * 64, 64, 64), Some((32, 64)), "4:2:2");
12288 assert_eq!(chroma_shape(32 * 32, 64, 64), Some((32, 32)), "4:2:0");
12289 assert_eq!(chroma_shape(3 * 3, 5, 3), Some((3, 3)), "odd 4:4:4 keeps its width");
12290 assert_eq!(chroma_shape(3 * 2, 5, 3), Some((3, 2)), "odd 4:2:2");
12291 assert_eq!(chroma_shape(7, 5, 3), None, "no layout has seven samples");
12292 }
12293
12294 /// A 2x2 block of 4:4:4 chroma becomes its rounded mean.
12295 #[test]
12296 fn a_444_block_averages_to_its_rounded_mean() {
12297 let src: Vec<u16> = vec![1, 2, 3, 4];
12298 assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![3], "(10 + 2) / 4");
12299 let src: Vec<u16> = vec![0, 0, 0, 1];
12300 assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![0], "a quarter rounds down");
12301 let src: Vec<u16> = vec![0, 0, 1, 1];
12302 assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![1], "a half rounds up");
12303 }
12304
12305 /// 4:2:2 has full height, so only the rows pair up.
12306 #[test]
12307 fn a_422_plane_pairs_rows_only() {
12308 // Two columns, four rows: rows (0,1) and (2,3) average, columns stay apart.
12309 let src: Vec<u8> = vec![10, 100, 20, 200, 30, 0, 40, 0];
12310 assert_eq!(chroma_420(&src, 2, 4, 2, 2), vec![15, 150, 35, 0]);
12311 }
12312
12313 /// An odd edge averages the samples there are, and 10-bit samples stay in 10 bits.
12314 #[test]
12315 fn an_odd_edge_and_ten_bit_samples_are_handled() {
12316 // 3x3 chroma down to 2x2: the last column and row are a single sample each,
12317 // so the corner is the 8 alone and the edge pairs are (2, 5) and (6, 7).
12318 let src: Vec<u16> = (0..9).collect();
12319 assert_eq!(chroma_420(&src, 3, 3, 2, 2), vec![2, 4, 7, 8]);
12320 // A 10-bit mean is still a 10-bit value, not a truncated 8-bit one.
12321 let src: Vec<u16> = vec![1023, 1023, 1022, 1023];
12322 assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![1023]);
12323 }
12324
12325 /// The AV1 seat hands the composer 4:2:0 planes for every layout edith decodes
12326 /// (4:2:0, 4:2:2, 4:4:4 and gray), at the size a 4:2:0 picture would have.
12327 #[test]
12328 fn every_av1_fixture_arrives_as_420() {
12329 for name in ["test_av1_444.mp4", "test_av1_422.mp4", "test_av1_12bit.mp4"] {
12330 let mut pictures = Pictures::software(&asset(name), 0, false, Deinterlace::Frame).expect(name);
12331 let Ok(Some(Yuv::Pixels { u, v, width, height, .. })) = pictures.next(None) else {
12332 panic!("{name}: no picture");
12333 };
12334 let (cw, ch) = (width.div_ceil(2) as usize, height.div_ceil(2) as usize);
12335 assert_eq!((u.len(), v.len()), (cw * ch, cw * ch), "{name}: chroma is 4:2:0");
12336 }
12337 for name in ["test_av1_gray.mp4", "test_av1_420.mp4"] {
12338 let mut pictures = Pictures::software(&asset(name), 0, false, Deinterlace::Frame).expect(name);
12339 let Ok(Some(Yuv::Pixels { y, u, v, width, height })) = pictures.next(None) else {
12340 panic!("{name}: no picture");
12341 };
12342 let (cw, ch) = (width.div_ceil(2) as usize, height.div_ceil(2) as usize);
12343 assert_eq!(y.len(), (width * height) as usize, "{name}: luma");
12344 assert_eq!((u.len(), v.len()), (cw * ch, cw * ch), "{name}: chroma is 4:2:0");
12345 if name.contains("gray") {
12346 assert!(u.iter().chain(&v).all(|&s| s == 128), "{name}: grey chroma is 128");
12347 }
12348 }
12349 }
12350}
12351
12352#[cfg(test)]
12353mod planned_sound_tests {
12354 use super::*;
12355
12356 fn asset(name: &str) -> PathBuf {
12357 Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name)
12358 }
12359
12360 /// The sound [`planned_seats`] predicts for `timeline` in an mp4, with the
12361 /// picture's meta taken from `picture`.
12362 fn predicted_sound(timeline: &str, picture: &str) -> &'static str {
12363 let project = Project::single(asset(timeline), 30);
12364 let (meta, _) = Demuxer::open(&asset(picture)).expect("the picture's file opens");
12365 let settings = ExportSettings { format: Format::Mp4, ..Default::default() };
12366 planned_seats(&project, &meta, &settings).1
12367 }
12368
12369 /// A DTS track is decoded by `ec-dts`, so the export predicts an encode of its
12370 /// sound (as it does for an mp3), not the "can't be decoded" card.
12371 #[test]
12372 fn a_dts_source_is_predicted_as_an_encode() {
12373 assert_eq!(
12374 predicted_sound("test_dts.mkv", "test_dts.mkv"),
12375 "AAC · SW encode (ec-aac)"
12376 );
12377 }
12378
12379 /// An mp3 on the timeline has no sample table to copy from: the sound is
12380 /// decoded and encoded as AAC, not copied.
12381 #[test]
12382 fn a_standalone_mp3_source_is_predicted_as_an_encode() {
12383 assert_eq!(
12384 predicted_sound("test_tone.mp3", "test_av.mp4"),
12385 "AAC · SW encode (ec-aac)"
12386 );
12387 }
12388
12389 /// The untouched AAC of an mp4 is still the copy it was.
12390 #[test]
12391 fn an_untouched_aac_mp4_is_still_predicted_as_a_copy() {
12392 assert_eq!(predicted_sound("test_av.mp4", "test_av.mp4"), "AAC copy");
12393 }
12394
12395 /// The HDR meta and picture size of a fixture, as the export reads them.
12396 fn meta_of(name: &str) -> VideoMeta {
12397 Demuxer::open(&asset(name)).expect("the fixture opens").0
12398 }
12399
12400 /// A PQ source is tone-mapped to SDR in every picture export, and the plan says so.
12401 #[test]
12402 fn a_pq_source_is_predicted_as_tone_mapped() {
12403 let project = Project::single(asset("test_pq.mp4"), 30);
12404 let meta = meta_of("test_pq.mp4");
12405 let settings = ExportSettings { format: Format::Mp4, ..Default::default() };
12406 let expected = match ColorDescription::output_sized(meta.width, meta.height).matrix {
12407 Matrix::Bt601 => "HDR (PQ) source tone-mapped to SDR BT.601",
12408 _ => "HDR (PQ) source tone-mapped to SDR BT.709",
12409 };
12410 assert_eq!(planned_tone(&project, &meta, &settings).as_deref(), Some(expected));
12411 }
12412
12413 /// The matrix the words name is the one the file is tagged with: a standard-definition
12414 /// canvas is BT.601 and an HD one BT.709, whatever the source's own size, and a
12415 /// `size` setting moves the canvas the rule is applied to.
12416 #[test]
12417 fn the_tone_map_names_the_matrix_of_the_size_it_is_written_at() {
12418 let project = Project::single(asset("test_pq.mp4"), 30);
12419 let mut hd = meta_of("test_pq.mp4");
12420 hd.width = 1920;
12421 hd.height = 1080;
12422 let mut sd = hd;
12423 sd.width = 720;
12424 sd.height = 576;
12425 let mp4 = ExportSettings { format: Format::Mp4, ..Default::default() };
12426 assert_eq!(
12427 planned_tone(&project, &hd, &mp4).as_deref(),
12428 Some("HDR (PQ) source tone-mapped to SDR BT.709")
12429 );
12430 assert_eq!(
12431 planned_tone(&project, &sd, &mp4).as_deref(),
12432 Some("HDR (PQ) source tone-mapped to SDR BT.601"),
12433 "720x576 is SD, and is tagged BT.601"
12434 );
12435 let small = ExportSettings { size: Some((640, 360)), ..mp4.clone() };
12436 assert_eq!(
12437 planned_tone(&project, &hd, &small).as_deref(),
12438 Some("HDR (PQ) source tone-mapped to SDR BT.601"),
12439 "a 640x360 export is SD though the project is HD"
12440 );
12441 let hd_again = ExportSettings { size: Some((1280, 720)), ..mp4.clone() };
12442 assert_eq!(
12443 planned_tone(&project, &sd, &hd_again).as_deref(),
12444 Some("HDR (PQ) source tone-mapped to SDR BT.709"),
12445 "a 1280x720 export of an SD canvas is HD"
12446 );
12447 }
12448
12449 /// A preview that keeps its source's curve is not tone-mapped, and an SDR timeline or a
12450 /// sound-only format has nothing to say.
12451 #[test]
12452 fn only_a_tone_mapped_picture_is_predicted_as_one() {
12453 let pq = Project::single(asset("test_hdr_sei.mkv"), 30);
12454 let meta = meta_of("test_hdr_sei.mkv");
12455 let keep = ExportSettings {
12456 format: Format::Mp4,
12457 keep_source_colour: true,
12458 ..Default::default()
12459 };
12460 assert_eq!(planned_tone(&pq, &meta, &keep), None, "a preview keeps the curve");
12461 let mp4 = ExportSettings { format: Format::Mp4, ..Default::default() };
12462 assert!(planned_tone(&pq, &meta, &mp4).is_some(), "the mkv's PQ too");
12463 let sdr = Project::single(asset("test_av.mp4"), 30);
12464 assert_eq!(planned_tone(&sdr, &meta, &mp4), None, "an SDR timeline");
12465 let wav = ExportSettings { format: Format::Wav, ..Default::default() };
12466 assert_eq!(planned_tone(&pq, &meta, &wav), None, "no picture to tone-map");
12467 }
12468
12469 /// A size setting draws the export at that size, coded size included, and leaves every
12470 /// other fact of the project's canvas as it is; no size is the project's canvas.
12471 #[test]
12472 fn a_size_setting_moves_the_canvas_and_only_the_canvas() {
12473 let meta = meta_of("test_av.mp4");
12474 let none = ExportSettings::default();
12475 assert_eq!(output_meta(&meta, &none), meta);
12476 let small = ExportSettings { size: Some((640, 360)), ..Default::default() };
12477 let out = output_meta(&meta, &small);
12478 assert_eq!((out.width, out.height), (640, 360));
12479 assert_eq!((out.coded_width, out.coded_height), (640, 360));
12480 assert_eq!(out.frame_rate, meta.frame_rate);
12481 assert_eq!(out.frame_count, meta.frame_count);
12482 assert_eq!(out.pixel_aspect, meta.pixel_aspect);
12483 }
12484
12485 /// An mkv export that is encoded names the codec its mix will get: Opus when the sources
12486 /// put it at 48 kHz mono or stereo, AAC otherwise. `test_av1.mkv` is 44.1 kHz stereo AAC,
12487 /// so its export is AAC, as its done line says; `test_seek_chirp.mkv` is 48 kHz mono Opus.
12488 #[test]
12489 fn a_matroska_export_names_the_codec_its_mix_will_get() {
12490 let settings = ExportSettings { format: Format::Av1, ..Default::default() };
12491 let aac = Project::single(asset("test_av1.mkv"), 30);
12492 let meta = meta_of("test_av1.mkv");
12493 let (_, sound) = planned_seats(&aac, &meta, &settings);
12494 assert_eq!(sound, "AAC · SW encode (ec-aac)");
12495 let opus = Project::single(asset("test_seek_chirp.mkv"), 30);
12496 let meta = meta_of("test_seek_chirp.mkv");
12497 let (_, sound) = planned_seats(&opus, &meta, &settings);
12498 assert_eq!(sound, "Opus · SW encode (ec-opus)");
12499 }
12500}
12501
12502#[cfg(test)]
12503mod vp9_444_tests {
12504 use super::*;
12505
12506 #[test]
12507 fn a_422_or_444_source_names_its_reduction_on_a_video_export() {
12508 let mut settings = ExportSettings { format: Format::Mp4, ..Default::default() };
12509 assert_eq!(
12510 chroma_reduction_words(Codec::Vp9, Chroma::C444, &settings).as_deref(),
12511 Some("VP9 4:4:4 source: chroma reduced to 4:2:0 for export"),
12512 );
12513 assert_eq!(
12514 chroma_reduction_words(Codec::Vp9, Chroma::C422, &settings).as_deref(),
12515 Some("VP9 4:2:2 source: chroma reduced to 4:2:0 for export"),
12516 );
12517 assert_eq!(
12518 chroma_reduction_words(Codec::H264, Chroma::C444, &settings).as_deref(),
12519 Some("H.264 4:4:4 source: chroma reduced to 4:2:0 for export"),
12520 );
12521 assert!(chroma_reduction_words(Codec::Vp9, Chroma::C420, &settings).is_none());
12522 assert!(chroma_reduction_words(Codec::Vp9, Chroma::Gray, &settings).is_none());
12523 for format in [Format::Wav, Format::Flac, Format::Mp3, Format::Ogg, Format::M4a, Format::Opus] {
12524 settings.format = format;
12525 assert!(
12526 chroma_reduction_words(Codec::Vp9, Chroma::C444, &settings).is_none(),
12527 "{format:?} has no picture to reduce",
12528 );
12529 }
12530 }
12531
12532 /// A VP9 profile 1 4:4:4 file is never offered to the GPU on an export: the decode
12533 /// door's gate refuses it before the plugin is asked, so the plugin's refusal never
12534 /// reaches stderr. Stderr is not read in-process; the seam is the plugin's attempt count.
12535 #[test]
12536 fn a_vp9_444_export_never_offers_the_file_to_the_gpu() {
12537 let path = std::env::temp_dir().join(format!("edith-vp9-444-{}.webm", std::process::id()));
12538 let generated = std::process::Command::new("ffmpeg")
12539 .args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=64x64:rate=5:duration=1"])
12540 .args(["-c:v", "libvpx-vp9", "-pix_fmt", "yuv444p", "-f", "webm"])
12541 .arg(&path)
12542 .status()
12543 .map(|status| status.success() && path.exists())
12544 .unwrap_or(false);
12545 if !generated {
12546 eprintln!("no ffmpeg with libvpx-vp9: the 4:4:4 fixture cannot be generated, skipping");
12547 return;
12548 }
12549 let chroma = Demuxer::open(&path).ok().and_then(|(_, demuxer)| demuxer.chroma());
12550 assert_eq!(chroma, Some(Chroma::C444), "the fixture is a 4:4:4 stream");
12551 let (tx, rx) = sync_channel(64);
12552 let before = crate::hw::OPEN_ATTEMPTS.with(|n| n.get());
12553 let _ = decode_stream(&path, 0, None, &tx, None, false, Deinterlace::Frame, u32::MAX);
12554 let after = crate::hw::OPEN_ATTEMPTS.with(|n| n.get());
12555 drop(rx);
12556 let _ = std::fs::remove_file(&path);
12557 assert_eq!(after, before, "the GPU was asked for a decoder for a 4:4:4 VP9 file");
12558 }
12559}