edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching0 forksRust18.3 MiBc439c14Tahinli25 days ago1006 commits
| 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. The hardware HEVC seat codes intra only. |
| 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 | |
| 57 | use std::collections::VecDeque; |
| 58 | use std::fs::File; |
| 59 | use std::io::{BufWriter, Write}; |
| 60 | use std::path::{Path, PathBuf}; |
| 61 | use std::sync::atomic::{AtomicBool, AtomicU32, Ordering}; |
| 62 | use std::sync::mpsc::{Receiver, SyncSender, sync_channel}; |
| 63 | use std::sync::{Arc, Mutex}; |
| 64 | use std::thread; |
| 65 | |
| 66 | use ec_av1::encode::Picture as Av1Picture; |
| 67 | use ec_av1::stream::decode_stream_with; |
| 68 | use ec_core::frame::VideoFrame; |
| 69 | use ec_core::registry::Decoder as _; |
| 70 | use ec_core::registry::{AudioParameters, CodecId, CodecParameters, MediaParameters, StreamInfo}; |
| 71 | use ec_core::{Buf, ChannelLayout, Error as Av1Error, Muxer as _, Packet, TimeBase}; |
| 72 | use ec_h264::{Encoder, EncoderConfig, H264Decoder, PictureView, Preset}; |
| 73 | use ec_h265::encoder::{Encoder as HevcEncoder, EncoderConfig as HevcEncoderConfig, RateControl}; |
| 74 | use ec_h265_syntax::vui::{ |
| 75 | ColourDescription as HevcColourDescription, VideoSignalType as HevcVideoSignalType, |
| 76 | }; |
| 77 | |
| 78 | use crate::audio::{AudioMeta, AudioSession}; |
| 79 | use crate::colorspace::{Chroma, ColorDescription, Matrix, Tags, Transfer}; |
| 80 | use crate::decode::{I420, Pulled, Wide}; |
| 81 | use crate::demux::{Codec, Demuxer, MkvDemuxer, Rotation, VideoMeta}; |
| 82 | use crate::hw::{DmaFrame, DmaWant, HwEncoder, HwPicture, HwSession}; |
| 83 | use crate::mux::{ |
| 84 | AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, |
| 85 | }; |
| 86 | use crate::project::{Deinterlace, Lane, LaneKind, Project, Rate, Speed, Title}; |
| 87 | use crate::scale::{Composer, FitPolicy, Sample}; |
| 88 | use crate::subtitle::{Cue, SubtitleTrack}; |
| 89 | use crate::text::{Overlay, Place, TextStyle, overlay, overlay_blocks}; |
| 90 | use crate::titleanim::Motion; |
| 91 | use crate::tonemap::{self, ToneMapper}; |
| 92 | use crate::transform::TransformParams; |
| 93 | |
| 94 | /// Progress is reported in permille: an atomic integer the render loop can read |
| 95 | /// without a lock, fine enough for any progress bar. |
| 96 | pub(crate) const PROGRESS_SCALE: u32 = 1_000; |
| 97 | |
| 98 | /// The head of the bar the *sound* owns, before a picture is written at all. |
| 99 | /// The mix is decoded, encoded and measured before the muxer exists ([`run`] |
| 100 | /// says why), and on a feature film that is a minute or two in which a bar |
| 101 | /// pinned at zero is the only thing on screen -- which reads as an export that |
| 102 | /// has hung. Small, because the picture is still nearly all of the work. |
| 103 | pub(crate) const AUDIO_BAND: u32 = PROGRESS_SCALE / 20; |
| 104 | |
| 105 | /// Where the bar stands with `done` of `total` pictures written: the sound's |
| 106 | /// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is |
| 107 | /// left rather than starting again from zero. |
| 108 | fn picture_progress(done: u32, total: u32) -> u32 { |
| 109 | // In `u64`: this is a picture count times a permille, and a film past |
| 110 | // ~4.5 M pictures (42 hours at 30 fps) overflowed the `u32` this used to be |
| 111 | // computed in -- a panic in debug inside the export thread, which a caller |
| 112 | // reads as `export worker panicked` on a file that was never written, and a |
| 113 | // bar that thrashed in release. The result is under the scale by |
| 114 | // construction, so the narrowing back is exact. |
| 115 | let band = u64::from(PROGRESS_SCALE - AUDIO_BAND); |
| 116 | let done = u64::from(done.min(total)); |
| 117 | AUDIO_BAND + (done * band / u64::from(total.max(1))) as u32 |
| 118 | } |
| 119 | |
| 120 | /// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands |
| 121 | /// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%. |
| 122 | const BITS_PER_PIXEL: f64 = 0.1; |
| 123 | /// The floor under a rate somebody *asked* for, and under the derived one: 100 |
| 124 | /// kbps, so a sub-Mbps budget -- a lo-fi delivery, a tiny picture, a |
| 125 | /// phone-rate master -- is a rate this export is written at. A megabit was the |
| 126 | /// old floor, and it silently rewrote every such ask. Nothing below this is |
| 127 | /// worth a container: the sound's own row starts at 128 kbps. |
| 128 | const MIN_BITRATE: u64 = 100_000; |
| 129 | const MAX_BITRATE: u64 = 20_000_000; |
| 130 | |
| 131 | /// The ceiling on a bitrate somebody *asked* for, which is a different question |
| 132 | /// from where the derived one stops: [`MAX_BITRATE`] is the top of the automatic |
| 133 | /// figure's sane range, and a rate a person typed is not that program's guess to |
| 134 | /// bound. Nothing in either encoder objects to it -- the VA-API seat takes a |
| 135 | /// `u64` and the software ones a `u32`/`i32`, all of which hold this with room |
| 136 | /// -- so the old shared ceiling was only ever the auto range wearing two hats. |
| 137 | const MAX_EXPLICIT_BITRATE: u64 = 50_000_000; |
| 138 | |
| 139 | /// The rates the sound may be coded at, smallest first -- what a front-end |
| 140 | /// offers and what [`ExportSettings::audio_kbps`] is clamped into. Every one of |
| 141 | /// them is a legal MPEG-1 Layer III value, so the MP3 path writes the figure it |
| 142 | /// was given rather than the nearest one `ec-mp3` snaps to. |
| 143 | pub const AUDIO_KBPS: [u32; 4] = [128, 192, 256, 320]; |
| 144 | |
| 145 | /// What the sound is coded at when nobody picked: the rate this project wrote |
| 146 | /// before the choice existed. 256 and not the encoders' own 128, because an |
| 147 | /// export is a master a person edits from again and this is a second lossy |
| 148 | /// generation over sources that may already have been one -- measured on the |
| 149 | /// suite's fixtures, an untouched clip re-encoded moves 0.15 dB here against |
| 150 | /// 0.46 dB at 128, and 32 KB/s beside a 2.76 Mbps picture is not a size anyone |
| 151 | /// is counting. |
| 152 | pub const DEFAULT_AUDIO_KBPS: u32 = 256; |
| 153 | |
| 154 | /// `rav1e`'s fastest preset. Anything slower is minutes per second of timeline |
| 155 | /// on a build with no assembly, which is what this one is. |
| 156 | const AV1_SPEED: u8 = 10; |
| 157 | |
| 158 | /// Tiles per software AV1 frame, the knob that spreads one picture over the |
| 159 | /// cores (see `Enc::open_av1`). A power of two; `rav1e` rounds it to a legal |
| 160 | /// layout for the frame size. |
| 161 | const AV1_TILES: usize = 32; |
| 162 | |
| 163 | /// How many lane encoders the intra HEVC seat spreads frames across. Twelve |
| 164 | /// is where the 2026-08-11 bench stopped scaling on this box; more lanes |
| 165 | /// only holds more decoded frames in memory. The cores the lanes leave over |
| 166 | /// go to the wavefront inside each lane's encoder. |
| 167 | const HEVC_LANES: usize = 12; |
| 168 | /// Bits per pixel an intra HEVC encoder spends at QP 27: 0.607 at 720p and |
| 169 | /// 0.586 at 1080p on the old seat's bench, and `ec-h265` lands on the same |
| 170 | /// 0.6 anchor. What [`hevc_qp`] maps a bitrate row through. |
| 171 | const HEVC_BPP_AT_27: f64 = 0.6; |
| 172 | /// The band [`hevc_qp`] is clamped into, for the reason stated there. |
| 173 | const HEVC_QP_MIN: i32 = 22; |
| 174 | const HEVC_QP_MAX: i32 = 40; |
| 175 | /// The quantiser the I+P GOP seat codes at when no bitrate is given: its |
| 176 | /// automatic quality, a constant-quality default in its own right. It is not |
| 177 | /// [`hevc_qp`]: that maps the automatic *bitrate* through the intra anchor |
| 178 | /// ([`HEVC_BPP_AT_27`]), which is measured on intra pictures. P pictures cost |
| 179 | /// far fewer bits, so the same mapping pushed a 1080p30 GOP export to the clamp |
| 180 | /// at QP 40 (652 kb/s at 31.8 dB mean PSNR on a 33 s timeline). |
| 181 | /// |
| 182 | /// 28 is chosen so that a default is never visibly worse than the H.264 default |
| 183 | /// on any source, and it matches x265's CRF 28 convention. Measured on 1080p30 |
| 184 | /// 10 s sources (kbps, PSNR dB against the source): |
| 185 | /// |
| 186 | /// | source | H.264 default | QP 28 | QP 31 | |
| 187 | /// |----------|---------------|----------------|----------------| |
| 188 | /// | testsrc2 | 6298, 44.08 | 6390, 41.84 | 4080, 39.50 | |
| 189 | /// | mandel | 6246, 35.98 | 11365, 38.37 | 6742, 36.21 | |
| 190 | /// |
| 191 | /// At QP 28 the GOP default is 2.2 dB under H.264 on testsrc2 at equal size |
| 192 | /// (+1.5%), and 2.4 dB above it on mandel at +82% bytes. QP 31 is 4.6 dB under |
| 193 | /// on testsrc2, which is visibly worse on synthetic content, so it is not the |
| 194 | /// default. File size is traded for never being far below H.264 quality: on |
| 195 | /// natural content the GOP default is larger than the H.264 file. |
| 196 | const HEVC_GOP_QP: i32 = 28; |
| 197 | |
| 198 | /// What an export writes. H.264-in-mp4, AV1 and HEVC -- each of the last two in |
| 199 | /// Matroska or in mp4, the user's pick of container -- are the *video* pairs |
| 200 | /// with both an encoder and a decoder under this project's no-install rule, and |
| 201 | /// pure-Rust encoder: `ec-riff`, `ec-flac`, `ec-mp3` and `ec-vorbis`. Opus |
| 202 | /// still has none as a *file* -- the Matroska seat is `ec-opus`, but a standalone |
| 203 | /// `.opus` row this project does not offer. |
| 204 | /// (AAC has one too -- `ec-aac`, which is what a re-encoded video track's |
| 205 | /// sound leaves through -- but AAC is a container's own audio, never a file of |
| 206 | /// its own here.) VP9 and VP8 are the |
| 207 | /// codecs that come in through the plugin and stop there, HEVC having |
| 208 | /// gained an encoder (an intra-only one, which the rows say). A front-end says |
| 209 | /// so rather than hiding the row. |
| 210 | /// |
| 211 | /// **Every video format carries sound.** Which way it carries it is the only |
| 212 | /// difference: copied packet for packet where a copy can say what the timeline |
| 213 | /// says, decoded and encoded again ([`encode_audio`]) where it cannot. |
| 214 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 215 | pub enum Format { |
| 216 | /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too, |
| 217 | /// where a copy could not carry the edit (a second audio lane to mix in, a |
| 218 | /// speeded clip, an equalized one, a source no mp4 sample table holds). |
| 219 | #[default] |
| 220 | Mp4, |
| 221 | /// AV1 in Matroska, with the timeline's AAC beside it: this engine's |
| 222 | /// Matroska writer carries an audio track ([`crate::mux::MkvMuxer`]) and its |
| 223 | /// reader reads one back, symphonia's `mkv` reader being what |
| 224 | /// `audio::Track::open` opens it with. |
| 225 | Av1, |
| 226 | /// The same AV1 stream in an mp4, for everything that plays mp4 and not |
| 227 | /// Matroska. The sample entry `mp4 0.14` cannot write is written by hand |
| 228 | /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own, |
| 229 | /// unchanged. |
| 230 | Av1Mp4, |
| 231 | /// HEVC in Matroska: I+P GOPs from `ec-h265` ([`Enc::open_hevc`]), or with |
| 232 | /// [`ExportSettings::intra_only`] an intraframe master, every frame an IDR. |
| 233 | Hevc, |
| 234 | /// The same HEVC stream in an mp4 (`hvc1`), for everything that plays mp4 |
| 235 | /// and not Matroska -- the AV1 pair's split, for the same reason. |
| 236 | HevcMp4, |
| 237 | /// AV1 in WebM, with Opus beside it: the open web's container. The same |
| 238 | /// AV1 encoder as [`Format::Av1`]; the sound is always Opus, mixed at 48 kHz |
| 239 | /// ([`start`]) because WebM carries no other audio, and the file carries no |
| 240 | /// subtitles ([`planned_subtitles`] says so). No copy path: a source's own |
| 241 | /// packets are not AV1 or Opus in general. |
| 242 | Webm, |
| 243 | /// The audio lanes alone, 16-bit PCM. |
| 244 | Wav, |
| 245 | /// The audio lanes alone, losslessly compressed. |
| 246 | Flac, |
| 247 | /// The audio lanes alone, MPEG-1 Layer III CBR (`ec-mp3`) at the rate |
| 248 | /// [`ExportSettings::audio_kbps`] asks for. |
| 249 | Mp3, |
| 250 | /// The audio lanes alone, Vorbis I in an Ogg container -- `ec-vorbis` |
| 251 | /// encoding, `ec-ogg` paging. Quality-coded and not rate-coded, which |
| 252 | /// is why [`audio_rate_refusal`] takes the Sound row away here: see |
| 253 | /// [`VORBIS_QUALITY`] for the operating point and how it was measured. |
| 254 | Ogg, |
| 255 | /// The audio lanes alone as AAC in an mp4 box with the `M4A ` brand -- the |
| 256 | /// file a player picks an audio parser for. The same track an mp4 of a |
| 257 | /// timeline with no picture carries ([`run_aac`]), which is an [`Format::Mp4`] |
| 258 | /// and not this one: the difference is the brand alone. |
| 259 | M4a, |
| 260 | /// The audio lanes alone as Opus in Ogg (RFC 7845), mixed at 48 kHz and |
| 261 | /// coded by `ec-opus` at [`ExportSettings::audio_kbps`] |
| 262 | /// ([`crate::opus_write`]). |
| 263 | Opus, |
| 264 | /// Apple ProRes in a QuickTime `.mov`, the profile in |
| 265 | /// [`ExportSettings::prores_profile`]: always 10-bit, software (`ec-prores`), |
| 266 | /// every frame a key frame, progressive, no alpha. The sound is 16-bit |
| 267 | /// little-endian PCM (`sowt`) at the timeline's rate, not AAC. See |
| 268 | /// [`crate::prores_out`] for the chroma upsampling the 4:2:0 compositor needs. |
| 269 | ProRes, |
| 270 | /// A numbered run of PNG pictures, one per timeline frame of the range (or the |
| 271 | /// whole timeline): `<folder name>_00001.png` onward, written into the folder the |
| 272 | /// export names. No sound. Each picture is the project's own size, with titles and |
| 273 | /// burnt captions as the export draws them ([`compose_at_with`]). |
| 274 | PngSequence, |
| 275 | /// One PNG picture: the frame at the start of the range (frame 0 without one), at |
| 276 | /// the project's own size. The poster frame. No sound. |
| 277 | Still, |
| 278 | /// An animated GIF of the range, at [`ExportSettings::gif`]. Not written yet: the |
| 279 | /// GIF encoder is still to come, so this format refuses by name ([`GifWriter`]). |
| 280 | Gif, |
| 281 | } |
| 282 | |
| 283 | impl Format { |
| 284 | /// The extension a file of this format is named with -- a front-end builds |
| 285 | /// the destination path from it, so the name never disagrees with the bytes. |
| 286 | pub fn ext(self) -> &'static str { |
| 287 | match self { |
| 288 | Self::Mp4 | Self::Av1Mp4 | Self::HevcMp4 => "mp4", |
| 289 | Self::Av1 | Self::Hevc => "mkv", |
| 290 | Self::Webm => "webm", |
| 291 | Self::Wav => "wav", |
| 292 | Self::Flac => "flac", |
| 293 | Self::Mp3 => "mp3", |
| 294 | Self::Ogg => "ogg", |
| 295 | Self::M4a => "m4a", |
| 296 | Self::Opus => "opus", |
| 297 | Self::ProRes => "mov", |
| 298 | Self::PngSequence | Self::Still => "png", |
| 299 | Self::Gif => "gif", |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | /// Whether this format carries the picture. The bitrate settings are video |
| 304 | /// settings and mean nothing to the audio-only ones. |
| 305 | pub fn has_video(self) -> bool { |
| 306 | matches!( |
| 307 | self, |
| 308 | Self::Mp4 | Self::Av1 | Self::Av1Mp4 | Self::Hevc | Self::HevcMp4 | Self::Webm | Self::ProRes |
| 309 | ) |
| 310 | } |
| 311 | |
| 312 | /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs |
| 313 | /// and which of the two AV1 containers is being written are separate |
| 314 | /// questions, and this is the first. |
| 315 | pub fn is_av1(self) -> bool { |
| 316 | matches!(self, Self::Av1 | Self::Av1Mp4 | Self::Webm) |
| 317 | } |
| 318 | |
| 319 | /// The same question for HEVC, and the same answer for both its containers: |
| 320 | /// one encoder, two boxes to put its stream in. |
| 321 | pub fn is_hevc(self) -> bool { |
| 322 | matches!(self, Self::Hevc | Self::HevcMp4) |
| 323 | } |
| 324 | |
| 325 | /// Whether the picture is ProRes in a QuickTime file ([`Format::ProRes`]). |
| 326 | pub fn is_prores(self) -> bool { |
| 327 | self == Self::ProRes |
| 328 | } |
| 329 | |
| 330 | /// Whether the file is a Matroska one. Only that container carries this |
| 331 | /// project's Opus track ([`encode_opus`]): an mp4 may hold Opus by spec, but |
| 332 | /// the crate that writes the mp4s here has no sample entry for it, so the |
| 333 | /// mp4 formats stay on AAC and say so. |
| 334 | fn is_mkv(self) -> bool { |
| 335 | matches!(self, Self::Av1 | Self::Hevc | Self::Webm) |
| 336 | } |
| 337 | |
| 338 | /// What the format is called where a refusal names it. |
| 339 | pub fn name(self) -> &'static str { |
| 340 | match self { |
| 341 | Self::Mp4 => "an mp4", |
| 342 | Self::Webm => "a WebM", |
| 343 | Self::Av1 => "an AV1 Matroska", |
| 344 | Self::Av1Mp4 => "an AV1 mp4", |
| 345 | Self::Hevc => "an HEVC Matroska", |
| 346 | Self::HevcMp4 => "an HEVC mp4", |
| 347 | Self::Wav => "a WAV", |
| 348 | Self::Flac => "a FLAC", |
| 349 | Self::Mp3 => "an MP3", |
| 350 | Self::Ogg => "an Ogg Vorbis", |
| 351 | Self::M4a => "an M4A", |
| 352 | Self::Opus => "an Ogg Opus", |
| 353 | Self::ProRes => "a ProRes QuickTime", |
| 354 | Self::PngSequence => "a PNG sequence", |
| 355 | Self::Still => "a PNG still", |
| 356 | Self::Gif => "an animated GIF", |
| 357 | } |
| 358 | } |
| 359 | } |
| 360 | |
| 361 | /// Which encoder writes the picture, as a person picks it on a card. Three |
| 362 | /// discrete choices and not a switch, because "whatever is best" and "the GPU, |
| 363 | /// and say so if there is none" are different answers: a driver that encodes |
| 364 | /// badly wants [`Software`](Self::Software), and a person who *needs* the GPU |
| 365 | /// (a long delivery, a machine whose CPU is doing something else) wants to be |
| 366 | /// told when it is not there rather than to wait out a silent fallback. |
| 367 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 368 | pub enum EncoderSeat { |
| 369 | /// Hardware where this machine has a seat for the picked codec, software |
| 370 | /// everywhere else -- what every export did before there was a choice, and |
| 371 | /// still what an unpicked project does. |
| 372 | #[default] |
| 373 | Auto, |
| 374 | /// The GPU or nothing: no silent fallback, and [`Enc::open`] refuses in |
| 375 | /// words before a byte is written. The only way to the plugin's AV1 seat, |
| 376 | /// which [`Auto`](Self::Auto) will not enter (see [`Enc::open_av1`]). |
| 377 | Hardware, |
| 378 | /// The software encoder even where a seat exists -- for a driver that |
| 379 | /// encodes badly, and for the AV1 pair, where it is what `Auto` picks too. |
| 380 | Software, |
| 381 | } |
| 382 | |
| 383 | impl EncoderSeat { |
| 384 | pub const ALL: [EncoderSeat; 3] = [Self::Auto, Self::Hardware, Self::Software]; |
| 385 | |
| 386 | /// What a card row and a project file call it. The file's keyword too, so |
| 387 | /// the two can never drift ([`crate::edith`]). |
| 388 | pub fn name(self) -> &'static str { |
| 389 | match self { |
| 390 | Self::Auto => "auto", |
| 391 | Self::Hardware => "hardware", |
| 392 | Self::Software => "software", |
| 393 | } |
| 394 | } |
| 395 | |
| 396 | /// Reads one back. `None` for anything else, which a project file refuses |
| 397 | /// by name rather than silently exporting on another seat. |
| 398 | pub fn from_name(name: &[u8]) -> Option<Self> { |
| 399 | Self::ALL.into_iter().find(|s| s.name().as_bytes() == name) |
| 400 | } |
| 401 | } |
| 402 | |
| 403 | /// The six ProRes profiles ([`Format::ProRes`]). The first four code 4:2:2, the |
| 404 | /// last two 4:4:4; the encoder's rate is Apple's nominal one for the profile and |
| 405 | /// the picture size, so a profile *is* the quality row ([`ExportSettings::bitrate`] |
| 406 | /// means nothing to ProRes). |
| 407 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 408 | pub enum ProResProfile { |
| 409 | Proxy, |
| 410 | Lt, |
| 411 | Standard, |
| 412 | #[default] |
| 413 | Hq, |
| 414 | P4444, |
| 415 | P4444Xq, |
| 416 | } |
| 417 | |
| 418 | impl ProResProfile { |
| 419 | pub const ALL: [ProResProfile; 6] = |
| 420 | [Self::Proxy, Self::Lt, Self::Standard, Self::Hq, Self::P4444, Self::P4444Xq]; |
| 421 | |
| 422 | /// What a card row calls it. |
| 423 | pub fn name(self) -> &'static str { |
| 424 | match self { |
| 425 | Self::Proxy => "ProRes 422 Proxy", |
| 426 | Self::Lt => "ProRes 422 LT", |
| 427 | Self::Standard => "ProRes 422", |
| 428 | Self::Hq => "ProRes 422 HQ", |
| 429 | Self::P4444 => "ProRes 4444", |
| 430 | Self::P4444Xq => "ProRes 4444 XQ", |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | /// Whether the profile codes full-resolution chroma (4:4:4). |
| 435 | pub fn is_444(self) -> bool { |
| 436 | matches!(self, Self::P4444 | Self::P4444Xq) |
| 437 | } |
| 438 | |
| 439 | fn codec(self) -> ec_prores::Profile { |
| 440 | match self { |
| 441 | Self::Proxy => ec_prores::Profile::Proxy, |
| 442 | Self::Lt => ec_prores::Profile::Lt, |
| 443 | Self::Standard => ec_prores::Profile::Standard, |
| 444 | Self::Hq => ec_prores::Profile::Hq, |
| 445 | Self::P4444 => ec_prores::Profile::P4444, |
| 446 | Self::P4444Xq => ec_prores::Profile::P4444Xq, |
| 447 | } |
| 448 | } |
| 449 | } |
| 450 | |
| 451 | /// The HDR transfer an HEVC export is written on ([`HdrOutput::transfer`]). |
| 452 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 453 | pub enum HdrTransfer { |
| 454 | /// No HDR: the export is SDR as it always was (tone-mapped from HDR sources). |
| 455 | #[default] |
| 456 | Sdr, |
| 457 | /// SMPTE ST 2084 (HDR10): BT.2020 primaries and matrix, limited range, 10-bit. |
| 458 | Pq, |
| 459 | /// ARIB STD-B67 (HLG): BT.2020 primaries and matrix, limited range, 10-bit. |
| 460 | Hlg, |
| 461 | } |
| 462 | |
| 463 | impl HdrTransfer { |
| 464 | pub const ALL: [HdrTransfer; 3] = [Self::Sdr, Self::Pq, Self::Hlg]; |
| 465 | |
| 466 | pub fn name(self) -> &'static str { |
| 467 | match self { |
| 468 | Self::Sdr => "SDR", |
| 469 | Self::Pq => "PQ (HDR10)", |
| 470 | Self::Hlg => "HLG", |
| 471 | } |
| 472 | } |
| 473 | |
| 474 | fn colour(self) -> Option<ColorDescription> { |
| 475 | let transfer = match self { |
| 476 | Self::Sdr => return None, |
| 477 | Self::Pq => Transfer::Pq, |
| 478 | Self::Hlg => Transfer::Hlg, |
| 479 | }; |
| 480 | Some(ColorDescription { matrix: Matrix::Bt2020Ncl, transfer, full_range: false }) |
| 481 | } |
| 482 | } |
| 483 | |
| 484 | /// A SMPTE ST 2086 mastering display, in the units the SEI states: chromaticities |
| 485 | /// in 0.00002 steps, luminance in 0.0001 cd/m2. |
| 486 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 487 | pub struct MasteringDisplay { |
| 488 | /// Green, blue, red `(x, y)`, in that order (the SEI's). |
| 489 | pub primaries: [(u16, u16); 3], |
| 490 | pub white_point: (u16, u16), |
| 491 | /// Peak luminance, 0.0001 cd/m2 (1000 nits = 10_000_000). |
| 492 | pub max_luminance: u32, |
| 493 | /// Black level, 0.0001 cd/m2 (0.005 nits = 50). |
| 494 | pub min_luminance: u32, |
| 495 | } |
| 496 | |
| 497 | impl MasteringDisplay { |
| 498 | /// A BT.2020-primaries, D65 display with the given peak and black, in nits. |
| 499 | pub fn bt2020(max_nits: f32, min_nits: f32) -> Self { |
| 500 | Self { |
| 501 | primaries: [(8500, 39850), (6550, 2300), (35400, 14600)], |
| 502 | white_point: (15635, 16450), |
| 503 | max_luminance: (max_nits * 10_000.0).round() as u32, |
| 504 | min_luminance: (min_nits * 10_000.0).round() as u32, |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | /// A DCI-P3 (D65) display, the usual HDR10 grading monitor, with the given |
| 509 | /// peak and black in nits. |
| 510 | pub fn p3_d65(max_nits: f32, min_nits: f32) -> Self { |
| 511 | Self { |
| 512 | primaries: [(13250, 34500), (7500, 3000), (34000, 16000)], |
| 513 | white_point: (15635, 16450), |
| 514 | max_luminance: (max_nits * 10_000.0).round() as u32, |
| 515 | min_luminance: (min_nits * 10_000.0).round() as u32, |
| 516 | } |
| 517 | } |
| 518 | } |
| 519 | |
| 520 | /// HDR output of an HEVC export ([`ExportSettings::hdr`]). The default is none: |
| 521 | /// every export that does not set it is the SDR file it always was. |
| 522 | /// |
| 523 | /// With a transfer set the file is 10-bit (an explicit |
| 524 | /// [`ExportSettings::video_bit_depth`] of 8 is refused), tagged BT.2020 primaries |
| 525 | /// and matrix with that transfer in the bitstream VUI, the mp4 `colr` box or the |
| 526 | /// Matroska `Colour` element, and the HDR sources are *not* tone-mapped. |
| 527 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 528 | pub struct HdrOutput { |
| 529 | pub transfer: HdrTransfer, |
| 530 | /// Written as a mastering display colour volume SEI (in the bitstream). |
| 531 | pub mastering_display: Option<MasteringDisplay>, |
| 532 | /// MaxCLL in cd/m2, with `max_fall`, written as a content light level SEI. |
| 533 | pub max_cll: Option<u16>, |
| 534 | /// MaxFALL in cd/m2. |
| 535 | pub max_fall: Option<u16>, |
| 536 | } |
| 537 | |
| 538 | /// What the caller gets to decide about the output. The codec is not among it: |
| 539 | /// [`Format`] names a container *and* what goes in it, because every pair we |
| 540 | /// can write is a pair we can also read back. |
| 541 | #[derive(Debug, Clone, Default, PartialEq, Eq)] |
| 542 | pub struct ExportSettings { |
| 543 | /// Bits per second, clamped to the same sane range the automatic value uses. |
| 544 | /// `None` picks it from the picture size and frame rate. Video only. |
| 545 | pub bitrate: Option<u64>, |
| 546 | /// Which encoder writes the picture ([`EncoderSeat`]). Was a `force_sw` |
| 547 | /// flag, which could say "not the GPU" and never "the GPU or say so". |
| 548 | /// [`EncoderSeat::Software`] is what the `VE_SW_ENC` env pin still forces |
| 549 | /// on every export of a run. |
| 550 | pub seat: EncoderSeat, |
| 551 | /// The file to write. Defaults to [`Format::Mp4`], which is what every |
| 552 | /// caller wrote before there was a choice. |
| 553 | pub format: Format, |
| 554 | /// The sample depth an AV1 software export is written at: `Some(8)` or |
| 555 | /// `Some(10)`, and `None` follows the source -- 10 where any video source of |
| 556 | /// the timeline is 10-bit. AV1 and software HEVC (H.264 stays 8-bit, and so do |
| 557 | /// the hardware AV1 and HEVC seats, which the 10-bit seats do not take). An HDR |
| 558 | /// transfer ([`ExportSettings::hdr`]) and ProRes are always 10-bit. |
| 559 | /// |
| 560 | /// A 10-bit export is decoded at 10 bits and encoded from its 16-bit planes |
| 561 | /// ([`Enc::encode_wide`]) wherever the span passes its picture through |
| 562 | /// untouched. A picture composed on the way (a grade, a transform, a fade, a |
| 563 | /// dissolve, a caption, a tone map, a layer) is composed at 8 bits as it always |
| 564 | /// was and shifted up to the file's depth, so the file is 10-bit either way. |
| 565 | pub video_bit_depth: Option<u8>, |
| 566 | /// What the *sound* is coded at, in kbps, wherever an encoder writes it -- |
| 567 | /// the AAC of a video export as much as an MP3. `None` is |
| 568 | /// [`DEFAULT_AUDIO_KBPS`], which is what every caller wrote before there |
| 569 | /// was a choice, so a settings value nobody touched writes the same bytes |
| 570 | /// it used to. Means nothing to WAV and FLAC, which code no rate, and |
| 571 | /// nothing to a *copied* AAC track, which carries its source's. |
| 572 | pub audio_kbps: Option<u32>, |
| 573 | /// Bits per sample of the PCM sound in a ProRes `.mov`: 16 or 24. `None` (and |
| 574 | /// anything else) is 24. No other format reads it. |
| 575 | pub audio_bit_depth: Option<u8>, |
| 576 | /// Which of the project's subtitle tracks travel with the file: indices into |
| 577 | /// [`Project::subtitles`], which is the same list a front-end picks rows of. |
| 578 | /// As many as the timeline holds, in the order given -- the file declares |
| 579 | /// them in that order and a player's subtitle menu lists them in it. Empty |
| 580 | /// writes none -- what every caller wrote before there was a choice, so an |
| 581 | /// export of a timeline without subtitles is the file it always was, byte |
| 582 | /// for byte. |
| 583 | /// |
| 584 | /// Every container that carries picture carries them: Matroska as |
| 585 | /// `S_TEXT/UTF8` blocks, an mp4 as a `tx3g` timed-text track |
| 586 | /// ([`crate::mux::Mp4Muxer::write_subtitles`]). A Matroska block names its |
| 587 | /// track in one byte, so a Matroska file carries at most |
| 588 | /// [`crate::mux::MAX_SUB_TRACKS`] of them and asking for more is refused by |
| 589 | /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has |
| 590 | /// no such ceiling. |
| 591 | pub subtitles: Vec<usize>, |
| 592 | /// Writes no soft subtitle track at all -- not the lanes, not the picks. The |
| 593 | /// captions a file carries are then only the ones [`burn_subtitles`] drew |
| 594 | /// into its picture. `false` is what every caller wrote before there was a |
| 595 | /// choice, so the lanes and the picks decide as they always did. |
| 596 | /// |
| 597 | /// [`burn_subtitles`]: ExportSettings::burn_subtitles |
| 598 | pub no_soft_subtitles: bool, |
| 599 | /// Code every picture as a key frame a decoder may be started from: no |
| 600 | /// frame references another, the file is an intraframe master in the shape |
| 601 | /// of ProRes, and a seek to any frame at all is one decode. |
| 602 | /// |
| 603 | /// Bigger files for that, so it is off for delivery and on for the |
| 604 | /// stand-ins [`crate::proxy`] makes, which exist precisely to be seeked |
| 605 | /// through. This is the switch of the H.264 and HEVC pairs; on HEVC the |
| 606 | /// software seat then codes every picture an IDR ([`Enc::open_hevc`]) and |
| 607 | /// the hardware seat is already intra. AV1 has no such switch. |
| 608 | pub intra_only: bool, |
| 609 | /// Captions drawn into the picture: the track at this index in |
| 610 | /// [`Project::subtitles`] (the index [`ExportSettings::subtitles`] and |
| 611 | /// [`crate::PlaybackSession::timeline_cues`] take), its cue on screen at |
| 612 | /// each timeline frame, drawn in this style ([`crate::text`]). `None` writes |
| 613 | /// the picture as it is -- what every caller wrote before there was a |
| 614 | /// choice. |
| 615 | /// |
| 616 | /// A burned-in picture is never copied out of its source: it is decoded, |
| 617 | /// drawn and encoded, so [`exact_refusal`] names the copy it gives up. The |
| 618 | /// cues are the ones the timeline plays, so a rippled edit captions what it |
| 619 | /// shows, the way the soft track does. |
| 620 | pub burn_subtitles: Option<(usize, TextStyle)>, |
| 621 | /// Write the picture in the space its **source** declares -- no tone map to |
| 622 | /// SDR, no matrix conversion -- and tag the file with it, instead of |
| 623 | /// converting everything into the space the output height implies. |
| 624 | /// |
| 625 | /// For a preview file and nothing else ([`crate::proxy`]): it makes the |
| 626 | /// stand-in a smaller copy of the film rather than a rendition of it, so |
| 627 | /// the screen tone-maps it live with whatever preset the project is set to |
| 628 | /// -- and it takes the per-frame conversion off the *source's* full |
| 629 | /// resolution, which on a 4K HDR film was 48 ms a frame and the whole of a |
| 630 | /// proxy's cost (measured 2026-08-13). |
| 631 | /// |
| 632 | /// A delivery export must leave it off: an mp4 in BT.2020 PQ is a file for |
| 633 | /// this editor to read back, not one to hand anybody. |
| 634 | pub keep_source_colour: bool, |
| 635 | /// Half-open `[start, end)` in timeline frames, or `None` for the whole |
| 636 | /// timeline -- what every caller wrote before there was a choice, so an |
| 637 | /// export nobody has marked in or out on writes the same bytes it always |
| 638 | /// did. Session state, like the mark itself: never saved to a `.edith`. |
| 639 | pub range: Option<(u32, u32)>, |
| 640 | /// The Exact quality row: this file must be the source's own coded |
| 641 | /// picture, copied wherever [`CopyPlan`] already says a copy is exactly |
| 642 | /// what the timeline says. `bitrate` and `seat` mean nothing to a copied |
| 643 | /// track, but a fallback re-encode (a cut off a sync point, a grade, a |
| 644 | /// speed, a transform) still honours them, so a copy-minded caller sends |
| 645 | /// `bitrate: None` beside this and gets the automatic figure rather than |
| 646 | /// a preset's. |
| 647 | /// |
| 648 | /// [`exact_refusal`] is the gate a front-end asks before the button is |
| 649 | /// pressed; [`run`] asks it again, which is what makes this a setting a |
| 650 | /// worker can trust rather than one only the card checked. |
| 651 | pub exact: bool, |
| 652 | /// The picture's size in pixels for this export alone, `(width, height)`: |
| 653 | /// the canvas the file is drawn and encoded at, in place of the project's |
| 654 | /// resolution. The project itself is not touched -- [`start`] applies it to |
| 655 | /// the export's own copy of the settings, and every clip refits on that |
| 656 | /// canvas by its fit mode, as it does when the project's resolution changes. |
| 657 | /// `None` is the project's own size, as every caller wrote before there was |
| 658 | /// a choice. Each side must be a picture size ([`crate::is_resolution`]) and |
| 659 | /// even, which the caller checks: a size here is trusted as given. |
| 660 | pub size: Option<(u32, u32)>, |
| 661 | /// Chapter marks the file carries, `(start in ns, title)` each, sorted by start. An mp4 gets |
| 662 | /// them as a Nero `chpl` and a QuickTime chapter track, a Matroska file as a `Chapters` |
| 663 | /// element. Empty writes none, which is what every caller wrote before there was a choice. |
| 664 | pub chapters: Vec<(u64, String)>, |
| 665 | /// Level the mixed sound to this integrated loudness under this true-peak ceiling before it |
| 666 | /// is coded ([`LoudnessTarget`]). `None` writes the mix at the level it was heard at, which |
| 667 | /// is what every caller wrote before there was a choice. A track is never *copied* when this |
| 668 | /// is set: a packet copy carries no gain. |
| 669 | pub loudness: Option<LoudnessTarget>, |
| 670 | /// The ProRes profile of a [`Format::ProRes`] export; means nothing to any |
| 671 | /// other format. Defaults to [`ProResProfile::Hq`]. |
| 672 | pub prores_profile: ProResProfile, |
| 673 | /// HDR output of an HEVC export ([`Format::Hevc`], [`Format::HevcMp4`]); see |
| 674 | /// [`HdrOutput`]. Refused for every other format. The default is none. |
| 675 | pub hdr: HdrOutput, |
| 676 | /// Speed preset of the software HEVC encoder ([`Format::Hevc`], [`Format::HevcMp4`]); means |
| 677 | /// nothing to any other format. `None` is [`HevcSpeed::Default`], the encoder's own search, |
| 678 | /// bit-identical to every export written before there was a choice. |
| 679 | pub hevc_speed: Option<HevcSpeed>, |
| 680 | /// What a GIF asks for beyond the picture ([`Format::Gif`]); means nothing to any other format. |
| 681 | pub gif: GifSettings, |
| 682 | } |
| 683 | |
| 684 | /// The settings of an animated GIF ([`Format::Gif`]): its width in pixels (the height follows |
| 685 | /// the project's aspect), its frame rate, and whether it loops. The default is the size and rate |
| 686 | /// a GIF is usually shared at: 480 pixels wide, 15 frames a second, looping forever. |
| 687 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 688 | pub struct GifSettings { |
| 689 | pub width: u32, |
| 690 | pub fps: u32, |
| 691 | pub loop_forever: bool, |
| 692 | } |
| 693 | |
| 694 | impl Default for GifSettings { |
| 695 | fn default() -> Self { |
| 696 | Self { width: 480, fps: 15, loop_forever: true } |
| 697 | } |
| 698 | } |
| 699 | |
| 700 | /// Speed preset of the software HEVC encoder (`ec-h265`'s `Preset`). `Fast` costs about 0-3% |
| 701 | /// BD-rate for 1.2-1.6x speed, `Faster` up to 27% for about 1.5-2x. |
| 702 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 703 | pub enum HevcSpeed { |
| 704 | #[default] |
| 705 | Default, |
| 706 | Fast, |
| 707 | Faster, |
| 708 | } |
| 709 | |
| 710 | impl HevcSpeed { |
| 711 | fn preset(self) -> ec_h265::encoder::Preset { |
| 712 | match self { |
| 713 | Self::Default => ec_h265::encoder::Preset::Default, |
| 714 | Self::Fast => ec_h265::encoder::Preset::Fast, |
| 715 | Self::Faster => ec_h265::encoder::Preset::Faster, |
| 716 | } |
| 717 | } |
| 718 | } |
| 719 | |
| 720 | /// An export-time loudness normalisation: one gain over the whole mix, from |
| 721 | /// [`crate::loudness::gain_to_target`], so the integrated loudness lands on `lufs` and the true |
| 722 | /// peak is held at or under `true_peak_dbtp` (the gain is cut back, never a limiter). |
| 723 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 724 | pub struct LoudnessTarget { |
| 725 | pub lufs: f64, |
| 726 | pub true_peak_dbtp: f64, |
| 727 | } |
| 728 | |
| 729 | // Plain finite figures, never NaN: the settings that hold one are `Eq`. |
| 730 | impl Eq for LoudnessTarget {} |
| 731 | |
| 732 | /// Measures `samples` (interleaved) and scales them by the gain that reaches `target`. |
| 733 | fn level_to_target(samples: &mut [f32], rate: u32, channels: u16, target: LoudnessTarget) { |
| 734 | let mut meter = crate::loudness::Meter::new(rate, channels); |
| 735 | meter.push(samples); |
| 736 | let gain = crate::loudness::gain_to_target(&meter.finish(), target.lufs, target.true_peak_dbtp); |
| 737 | if gain != 0.0 { |
| 738 | let g = 10f32.powf(gain as f32 / 20.0); |
| 739 | for s in samples.iter_mut() { |
| 740 | *s *= g; |
| 741 | } |
| 742 | } |
| 743 | } |
| 744 | |
| 745 | /// The export's picture size: the project's canvas, or the [`ExportSettings::size`] |
| 746 | /// this export is asked to draw at. Everything that decides what the file's picture |
| 747 | /// is (the encoder's seat, the copy's gate, the colour matrix) asks it through here, |
| 748 | /// so the answer each gives is the one the file has. |
| 749 | pub fn output_meta(meta: &VideoMeta, settings: &ExportSettings) -> VideoMeta { |
| 750 | match settings.size { |
| 751 | // The coded size goes with the drawn one: a copy's gate compares the coded pair with its |
| 752 | // source's, and a picture drawn at another size is not a copy of anything. |
| 753 | Some((width, height)) => VideoMeta { |
| 754 | width, |
| 755 | height, |
| 756 | coded_width: width, |
| 757 | coded_height: height, |
| 758 | ..*meta |
| 759 | }, |
| 760 | None => *meta, |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | /// What [`fit_picture_clips`] did: the full-frame clips it put on the policy, per lane (a lane |
| 765 | /// with none is left out), and how many transformed overlays it left on their own fit. |
| 766 | #[derive(Debug, Clone, PartialEq, Eq, Default)] |
| 767 | pub struct FitOutcome { |
| 768 | pub lanes: Vec<(Lane, usize)>, |
| 769 | pub overlays: usize, |
| 770 | } |
| 771 | |
| 772 | /// Puts every full-frame picture clip of `project` on `fit`, in place. Meant for the export's own |
| 773 | /// copy of the timeline ([`start`] takes it by value), so the project a user edits keeps its |
| 774 | /// clips' fit modes. A clip refits on the export's canvas by its fit mode, so this is how an |
| 775 | /// export asks for `fit` on the pictures that fill the frame. |
| 776 | /// |
| 777 | /// A clip placed by a transform (moved, scaled, cropped, faded or animated) is an overlay and |
| 778 | /// keeps its own fit: `fill` would crop it to the canvas's shape, so a logo would lose its |
| 779 | /// aspect on a vertical canvas. Its size stays relative to the canvas width, as in the project. |
| 780 | /// The whole change is one undo step on the copy, which nothing reads. |
| 781 | pub fn fit_picture_clips(project: &mut Project, fit: FitPolicy) -> FitOutcome { |
| 782 | let videos: Vec<Lane> = project.lanes().into_iter().filter(|l| l.kind == LaneKind::Video).collect(); |
| 783 | project.begin_batch(); |
| 784 | let mut outcome = FitOutcome::default(); |
| 785 | for lane in videos { |
| 786 | let mut count = 0; |
| 787 | for idx in 0..project.lane(lane).len() { |
| 788 | if is_placed(project, lane, idx) { |
| 789 | outcome.overlays += 1; |
| 790 | } else { |
| 791 | project.set_fit(lane, idx, fit); |
| 792 | count += 1; |
| 793 | } |
| 794 | } |
| 795 | if count > 0 { |
| 796 | outcome.lanes.push((lane, count)); |
| 797 | } |
| 798 | } |
| 799 | project.end_batch(); |
| 800 | outcome |
| 801 | } |
| 802 | |
| 803 | /// Whether the clip at `idx` of `lane` is placed by a transform that is not the identity, or has |
| 804 | /// a placement animation: the overlays [`fit_picture_clips`] leaves alone. |
| 805 | fn is_placed(project: &Project, lane: Lane, idx: usize) -> bool { |
| 806 | project.transform_of(lane, idx).is_some_and(|t| !t.is_identity()) |
| 807 | || !project.transform_keys_of(lane, idx).is_empty() |
| 808 | } |
| 809 | |
| 810 | /// The first moment a burned caption and a title show together in the same place. `cues` are the |
| 811 | /// burn's cues ([`burn_cues`]) and `place` the burn's own place; a title sits where its |
| 812 | /// `style.place` says, so a clash is a caption and a title with the same place on screen at once. |
| 813 | /// Returns the moment in seconds and the index into `titles` of the title, the earliest such |
| 814 | /// moment; `None` when no caption and title clash. |
| 815 | pub fn caption_title_clash(cues: &[Cue], titles: &[Title], place: Place, fps: f64) -> Option<(f64, usize)> { |
| 816 | let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64; |
| 817 | let mut first: Option<(i64, usize)> = None; |
| 818 | for (i, t) in titles.iter().enumerate().filter(|(_, t)| t.style.place == place) { |
| 819 | let (start, end) = (us(t.start), us(t.end())); |
| 820 | for c in cues.iter().filter(|c| c.image.is_none() && !c.text.trim().is_empty()) { |
| 821 | let lo = c.start_us.max(start); |
| 822 | if lo < c.end_us.min(end) && first.is_none_or(|(f, _)| lo < f) { |
| 823 | first = Some((lo, i)); |
| 824 | } |
| 825 | } |
| 826 | } |
| 827 | first.map(|(lo, i)| (lo as f64 / 1e6, i)) |
| 828 | } |
| 829 | |
| 830 | /// The lowest H.264 level (Table A-1) whose frame size and macroblock rate |
| 831 | /// hold `width`x`height` at `fps_num/fps_den`, as the `level_idc` byte; 62 |
| 832 | /// past the table. One table for both seats: the software encoder writes it |
| 833 | /// into its SPS (its default is 3.0, which is out of spec above 720p30) and |
| 834 | /// the plugin hands it to the driver. |
| 835 | pub fn h264_level_idc(width: u32, height: u32, fps_num: u32, fps_den: u32) -> u8 { |
| 836 | const LEVELS: [(u8, u64, u64); 17] = [ |
| 837 | (10, 1485, 99), |
| 838 | (11, 3000, 396), |
| 839 | (12, 6000, 396), |
| 840 | (13, 11880, 396), |
| 841 | (20, 11880, 396), |
| 842 | (21, 19800, 792), |
| 843 | (22, 20250, 1620), |
| 844 | (30, 40500, 1620), |
| 845 | (31, 108000, 3600), |
| 846 | (32, 216000, 5120), |
| 847 | (40, 245760, 8192), |
| 848 | (41, 245760, 8192), |
| 849 | (42, 522240, 8704), |
| 850 | (50, 589824, 22080), |
| 851 | (51, 983040, 36864), |
| 852 | (52, 2073600, 36864), |
| 853 | (60, 4177920, 139264), |
| 854 | ]; |
| 855 | let frame_mbs = u64::from(width.div_ceil(16)) * u64::from(height.div_ceil(16)); |
| 856 | let fps = f64::from(fps_num.max(1)) / f64::from(fps_den.max(1)); |
| 857 | let mbps = (frame_mbs as f64 * fps).ceil() as u64; |
| 858 | LEVELS |
| 859 | .iter() |
| 860 | .find(|&&(_, max_mbps, max_fs)| mbps <= max_mbps && frame_mbs <= max_fs) |
| 861 | .map_or(62, |&(idc, ..)| idc) |
| 862 | } |
| 863 | |
| 864 | struct Shared { |
| 865 | /// Fraction of the job done, in [`PROGRESS_SCALE`]ths. |
| 866 | /// |
| 867 | /// **Every stage that can run beside another writes this with `fetch_max`, |
| 868 | /// never `store`.** The sound and the picture are two threads publishing |
| 869 | /// two bands of one bar ([`AUDIO_BAND`]): a `store` from the lower band |
| 870 | /// pulls the bar backwards every time the other thread has already moved |
| 871 | /// it on, which is what a person sees as a progress bar that stutters |
| 872 | /// backwards -- 5,458 backward steps over one film export before this rule |
| 873 | /// was written down. A `store` is only correct where nothing else can be |
| 874 | /// publishing at all, which now means the terminal [`PROGRESS_SCALE`] and |
| 875 | /// the audio-only export ([`run_audio`]) that has no second thread. The |
| 876 | /// rule outlives one attempt at the file: an export rerun in software |
| 877 | /// because the hardware seat died writes this same atomic, and the bar |
| 878 | /// holds where the dead seat left it rather than starting again. |
| 879 | progress: AtomicU32, |
| 880 | cancel: AtomicBool, |
| 881 | finished: AtomicBool, |
| 882 | outcome: Mutex<Option<crate::Result<()>>>, |
| 883 | /// The encoders this job really opened, published the moment they are |
| 884 | /// chosen and never changed after -- one seat for the whole file, which is |
| 885 | /// what [`Enc`] states. `None` until then. The one thing that joins it |
| 886 | /// afterwards is how much of the edit never got a picture |
| 887 | /// ([`Shared::truncated`]), and [`ExportHandle::encoders`] does that |
| 888 | /// joining, so a notice cannot land on the line twice. |
| 889 | encoders: Mutex<Option<String>>, |
| 890 | /// Timeline frames of the edit the walk could not write because a file ran |
| 891 | /// out before its clip did ([`run`]'s break). The bar reaches its end |
| 892 | /// whatever happens, so without this a truncated file reads as a whole one. |
| 893 | /// Published the moment the walk gives up and read by |
| 894 | /// [`ExportHandle::encoders`] beside the seat line. |
| 895 | truncated: AtomicU32, |
| 896 | /// A stage that runs before a span can encode -- a stabilised clip's shake |
| 897 | /// being measured ([`crate::stabilise::ensure`]) -- as `1 +` its thousandths |
| 898 | /// done, `0` while none runs. Its own fraction, beside [`Shared::progress`] |
| 899 | /// rather than in it, which holds still meanwhile ([`ExportHandle::stage`]). |
| 900 | measuring: AtomicU32, |
| 901 | /// [`ExportSettings::loudness`], for the audio stages that only see `Shared`. |
| 902 | loudness: Option<LoudnessTarget>, |
| 903 | } |
| 904 | |
| 905 | /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per |
| 906 | /// rendered frame and take the [`result`](ExportHandle::result) when it flips; |
| 907 | /// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel) |
| 908 | /// does. |
| 909 | pub struct ExportHandle { |
| 910 | shared: Arc<Shared>, |
| 911 | /// The length of the file this export writes, in seconds: the range's, or the |
| 912 | /// picture and sound's end for a whole-timeline export. Known before the first frame. |
| 913 | length_secs: f64, |
| 914 | } |
| 915 | |
| 916 | impl ExportHandle { |
| 917 | /// Fraction of the timeline written, `0.0..=1.0`. |
| 918 | pub fn progress(&self) -> f32 { |
| 919 | self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32 |
| 920 | } |
| 921 | |
| 922 | /// The length of the file this export writes, in seconds: the frames it holds at the |
| 923 | /// canvas's frame rate, which is the file's duration as a player shows it (a range is |
| 924 | /// cut to the picture's end the same way the encoder cuts it). |
| 925 | pub fn length_secs(&self) -> f64 { |
| 926 | self.length_secs |
| 927 | } |
| 928 | |
| 929 | /// Asks the worker to stop at its next checkpoint and delete the partial |
| 930 | /// file. The outcome then reports the cancellation as an error. Checkpoints |
| 931 | /// run to the last instant before the rename, so even a cancel at full |
| 932 | /// progress leaves no output. |
| 933 | pub fn cancel(&self) { |
| 934 | self.shared.cancel.store(true, Ordering::Relaxed); |
| 935 | } |
| 936 | |
| 937 | /// Whether [`cancel`](Self::cancel) was asked: the worker has not yet reached its |
| 938 | /// next checkpoint, so the export is still running though it is going to stop. |
| 939 | pub fn is_cancelling(&self) -> bool { |
| 940 | self.shared.cancel.load(Ordering::Relaxed) |
| 941 | } |
| 942 | |
| 943 | pub fn is_finished(&self) -> bool { |
| 944 | self.shared.finished.load(Ordering::Acquire) |
| 945 | } |
| 946 | |
| 947 | /// What this export is encoding with -- the video seat and what the sound |
| 948 | /// is doing -- as the worker chose them, hardware fallback included. |
| 949 | /// `None` for the first instants of a job, before the encoder is open. |
| 950 | /// |
| 951 | /// ...and, where a file ran out under its clip, how much of the edit never |
| 952 | /// got a picture. Composed here rather than written into the stored line, |
| 953 | /// because that line is published more than once on a rerun (a hardware |
| 954 | /// seat that died) and a notice appended at the write site lands twice. |
| 955 | pub fn encoders(&self) -> Option<String> { |
| 956 | let line = self.shared.encoders.lock().unwrap().clone()?; |
| 957 | Some(match self.shared.truncated.load(Ordering::Relaxed) { |
| 958 | 0 => line, |
| 959 | past => format!("{line} · {past} frames of the edit past the last picture"), |
| 960 | }) |
| 961 | } |
| 962 | |
| 963 | /// The stage the export is in when it is not encoding: its name and its own |
| 964 | /// fraction done, `0.0..=1.0` -- `("Measuring shake", 0.4)` while a stabilised |
| 965 | /// clip with no finished analysis is measured. `None` while it encodes, when |
| 966 | /// [`progress`](Self::progress) is the one to show. |
| 967 | pub fn stage(&self) -> Option<(&'static str, f32)> { |
| 968 | match self.shared.measuring.load(Ordering::Relaxed) { |
| 969 | 0 => None, |
| 970 | n => Some((MEASURING_SHAKE, ((n - 1) as f32 / 1000.0).clamp(0.0, 1.0))), |
| 971 | } |
| 972 | } |
| 973 | |
| 974 | /// The outcome, once — taken out of the handle, so a caller that already |
| 975 | /// reported it sees `None` afterwards. `None` while the export is running. |
| 976 | pub fn result(&self) -> Option<crate::Result<()>> { |
| 977 | self.shared.outcome.lock().unwrap().take() |
| 978 | } |
| 979 | } |
| 980 | |
| 981 | /// Starts the worker. Failures are reported through the handle rather than |
| 982 | /// returned, so a caller has exactly one place to look. The files to read are |
| 983 | /// the project's own [`sources`](Project::sources) -- every clip names one -- |
| 984 | /// so nothing but the edit list decides what is decoded. |
| 985 | pub fn start( |
| 986 | project: Project, |
| 987 | meta: VideoMeta, |
| 988 | out: &Path, |
| 989 | settings: &ExportSettings, |
| 990 | sample_rate: Option<u32>, |
| 991 | ) -> ExportHandle { |
| 992 | let settings = settings.clone(); |
| 993 | // The canvas this export draws at: the project's, unless the settings name another. |
| 994 | let meta = output_meta(&meta, &settings); |
| 995 | let media = project.media_frames(); |
| 996 | let frames = match settings.range { |
| 997 | Some((from, to)) => to.min(media).saturating_sub(from), |
| 998 | None => media, |
| 999 | }; |
| 1000 | let length_secs = f64::from(frames) / meta.frame_rate; |
| 1001 | let shared = Arc::new(Shared { |
| 1002 | progress: AtomicU32::new(0), |
| 1003 | cancel: AtomicBool::new(false), |
| 1004 | finished: AtomicBool::new(false), |
| 1005 | outcome: Mutex::new(None), |
| 1006 | encoders: Mutex::new(None), |
| 1007 | truncated: AtomicU32::new(0), |
| 1008 | measuring: AtomicU32::new(0), |
| 1009 | loudness: settings.loudness, |
| 1010 | }); |
| 1011 | let worker = Arc::clone(&shared); |
| 1012 | // A second handle to the same slot, held outside the caught body below -- |
| 1013 | // what settles it if that body never gets to its own [`settle`] call at |
| 1014 | // all, because a codec parser deep inside `run` panicked instead of |
| 1015 | // returning the parse error it should have. Without this a panic there |
| 1016 | // strands the slot: [`ExportHandle::is_finished`] never flips, and a |
| 1017 | // proxy or export that hit a malformed frame sits in "Making" forever. |
| 1018 | let panic_worker = Arc::clone(&worker); |
| 1019 | let out = out.to_path_buf(); |
| 1020 | // `<out>.part`, appended rather than substituted: the temporary of |
| 1021 | // `a.export.mp4` is `a.export.mp4.part`, which no other export claims. |
| 1022 | let mut part = out.clone().into_os_string(); |
| 1023 | part.push(".part"); |
| 1024 | let part = PathBuf::from(part); |
| 1025 | let spawned = thread::Builder::new().name("export".into()).spawn(move || { |
| 1026 | let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 1027 | // Every file this export will read, named before a byte of one is. |
| 1028 | // These are the project's own sources and can be nothing else: a |
| 1029 | // stand-in ([`crate::proxy`]) is a substitution playback makes when it |
| 1030 | // opens a span, and nothing here knows such a thing exists. Printed so |
| 1031 | // that "the delivery came off the film itself" is a grep rather than a |
| 1032 | // belief. |
| 1033 | for source in project.sources() { |
| 1034 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export source: {}", source.path.display()); } |
| 1035 | } |
| 1036 | // The rename is the last step and the only one that publishes a file |
| 1037 | // under the name the caller asked for; it stays on the same directory, |
| 1038 | // so it is atomic. |
| 1039 | // |
| 1040 | // An emptied timeline is a legal project and an illegal file: no |
| 1041 | // picture, no sound, and a muxer that is never created because no coded |
| 1042 | // frame arrives. Refused by name here -- before the format is even |
| 1043 | // looked at, so an mp4 and a WAV refuse in the same words -- rather than |
| 1044 | // left to write a file of no frames that nothing opens. Every caller of |
| 1045 | // `start` comes through this, the app's own door |
| 1046 | // (`PlaybackSession::is_empty`) being only the first fence. |
| 1047 | // |
| 1048 | // An audio-only timeline has no picture to give a file, and an mp4 of |
| 1049 | // it would be black picture over the sound -- minutes of encoding for a |
| 1050 | // video of nothing. So an mp4 of it is written as the sound alone, the |
| 1051 | // same AAC track in an mp4 with no picture entry ([`run_aac`]); the |
| 1052 | // Matroska and WebM containers, which have no such form, are refused by |
| 1053 | // name. The app says the same on the format row before a destination |
| 1054 | // is even picked (`mp4_refusal`). |
| 1055 | let written = match settings.format { |
| 1056 | _ if project.timeline_frames() == 0 => { |
| 1057 | Err("the timeline is empty: there is nothing to export".into()) |
| 1058 | } |
| 1059 | Format::PngSequence | Format::Still | Format::Gif if !has_picture(&project) => Err(format!( |
| 1060 | "the timeline has no picture: {} would be black. Export an mp4, an \ |
| 1061 | M4A, WAV, FLAC, MP3, Ogg or Opus, which are the sound itself", |
| 1062 | settings.format.name() |
| 1063 | ) |
| 1064 | .into()), |
| 1065 | // The pictures are composed one timeline frame at a time, with no sound. |
| 1066 | Format::PngSequence => run_png_sequence(&project, &meta, &out, &worker, &settings), |
| 1067 | Format::Still => run_still(&project, &meta, &part, &settings), |
| 1068 | Format::Gif => run_gif(&project, &meta, &part, &worker, &settings), |
| 1069 | format if format.ext() == "mp4" && !has_picture(&project) => { |
| 1070 | run_aac(&project, &meta, &part, &worker, &settings, sample_rate) |
| 1071 | } |
| 1072 | format if format.has_video() && !has_picture(&project) => Err(format!( |
| 1073 | "the timeline has no picture: {} would be black. Export an mp4, an \ |
| 1074 | M4A, WAV, FLAC, MP3, Ogg or Opus, which are the sound itself", |
| 1075 | format.name() |
| 1076 | ) |
| 1077 | .into()), |
| 1078 | format if format.has_video() => { |
| 1079 | let first = run(&project, &meta, &part, &worker, &settings, sample_rate); |
| 1080 | match first { |
| 1081 | // The hardware encoder's *process* died under the driver |
| 1082 | // ([`crate::hwproc`]) -- the editor is still here, and the |
| 1083 | // file is still owed. Written again by the software encoder |
| 1084 | // for this codec, from the first frame: the pictures the |
| 1085 | // dead seat coded are not ones this one may continue from. |
| 1086 | // |
| 1087 | // Not where a person picked the GPU by name: that export |
| 1088 | // refuses in words, the same answer [`hw_seat`] already |
| 1089 | // gives a machine with no seat at all, rather than quietly |
| 1090 | // spending an hour in an encoder nobody chose. |
| 1091 | Err(e) |
| 1092 | if crate::hwproc::is_lost(&e) |
| 1093 | && settings.seat != EncoderSeat::Hardware => |
| 1094 | { |
| 1095 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export video: {e}; writing it again in software"); } |
| 1096 | let _ = std::fs::remove_file(&part); |
| 1097 | // The bar is *not* put back to zero: the rerun writes |
| 1098 | // it with `fetch_max` like everything else |
| 1099 | // ([`Shared::progress`]), so it holds where the dead |
| 1100 | // seat left it and moves again once the software |
| 1101 | // encoder passes that mark. A person whose GPU has just |
| 1102 | // died is the last one who should also watch the bar |
| 1103 | // run backwards. |
| 1104 | let mut software = settings.clone(); |
| 1105 | software.seat = EncoderSeat::Software; |
| 1106 | run(&project, &meta, &part, &worker, &software, sample_rate) |
| 1107 | } |
| 1108 | other => other, |
| 1109 | } |
| 1110 | } |
| 1111 | Format::M4a => run_aac(&project, &meta, &part, &worker, &settings, sample_rate), |
| 1112 | // Opus codes at 48 kHz and nothing else, so the mix is made there. |
| 1113 | Format::Opus => run_audio(&project, &meta, &part, &worker, &settings, Some(OPUS_RATE)), |
| 1114 | _ => run_audio(&project, &meta, &part, &worker, &settings, sample_rate), |
| 1115 | }; |
| 1116 | let result = match settings.format { |
| 1117 | // A run of pictures is written into the folder it was asked for, which has no |
| 1118 | // temporary of its own to publish. |
| 1119 | Format::PngSequence => written, |
| 1120 | _ => written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)), |
| 1121 | }; |
| 1122 | if result.is_err() { |
| 1123 | // The muxer -- and with it the file handle -- died with `run`. |
| 1124 | let _ = std::fs::remove_file(&part); |
| 1125 | } |
| 1126 | settle(&worker, result); |
| 1127 | })); |
| 1128 | if let Err(payload) = caught { |
| 1129 | // The body above panicked before it could settle its own slot -- |
| 1130 | // the panic message becomes the outcome, so a caller sees a |
| 1131 | // failure and a notice rather than a bar that never moves again. |
| 1132 | let message = payload |
| 1133 | .downcast_ref::<&str>() |
| 1134 | .map(ToString::to_string) |
| 1135 | .or_else(|| payload.downcast_ref::<String>().cloned()) |
| 1136 | .unwrap_or_else(|| "unknown panic".to_string()); |
| 1137 | if !panic_worker.finished.load(Ordering::Acquire) { |
| 1138 | // ...and the `.part` the body left behind is deleted here: the |
| 1139 | // module promises every failure path removes it, and the only |
| 1140 | // path that did was the body's own `result.is_err()` arm, which |
| 1141 | // a panic never reaches. Done inside this branch only -- a body |
| 1142 | // that *did* settle has already renamed or deleted the file. |
| 1143 | let _ = std::fs::remove_file(&part); |
| 1144 | settle( |
| 1145 | &panic_worker, |
| 1146 | Err(format!("export worker panicked: {message}").into()), |
| 1147 | ); |
| 1148 | } |
| 1149 | } |
| 1150 | }); |
| 1151 | if let Err(e) = spawned { |
| 1152 | settle(&shared, Err(e.into())); |
| 1153 | } |
| 1154 | ExportHandle { shared, length_secs } |
| 1155 | } |
| 1156 | |
| 1157 | /// Whether any video lane holds anything at all -- what tells an audio-only |
| 1158 | /// timeline from one that merely opens on a gap. Asked of the *lanes* rather |
| 1159 | /// than of the sources, because a project may name a video file no clip plays |
| 1160 | /// from any more. |
| 1161 | fn has_picture(project: &Project) -> bool { |
| 1162 | // A title is a picture of its own: a timeline of nothing but a title card |
| 1163 | // over black is a picture, not a black one. |
| 1164 | !project.titles().is_empty() |
| 1165 | || project |
| 1166 | .lanes() |
| 1167 | .into_iter() |
| 1168 | .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty()) |
| 1169 | } |
| 1170 | |
| 1171 | /// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a |
| 1172 | /// timeline whose export will carry sound from one whose file has none. |
| 1173 | fn has_sound(project: &Project) -> bool { |
| 1174 | project |
| 1175 | .lanes() |
| 1176 | .into_iter() |
| 1177 | .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty()) |
| 1178 | } |
| 1179 | |
| 1180 | /// Whether any equalizer on the sound is doing something -- the one edit a |
| 1181 | /// packet copy cannot carry, so an mp4 whose lane has one is decoded and |
| 1182 | /// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane: |
| 1183 | /// the copy path has exactly one by the time it asks, and [`planned_audio`] is |
| 1184 | /// asked before that is settled. |
| 1185 | fn equalized(project: &Project) -> bool { |
| 1186 | project.audio_lanes().into_iter().any(|lane| { |
| 1187 | (0..project.lane(lane).len()) |
| 1188 | .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity())) |
| 1189 | }) |
| 1190 | } |
| 1191 | |
| 1192 | /// How many timeline frames before a ranged export's start the mix is opened, so the voice |
| 1193 | /// chain's envelopes and the noise reduction's overlap are warm when the range begins |
| 1194 | /// instead of starting from silence ([`voice`](crate::voice)). Half a second, as far back as |
| 1195 | /// the timeline goes; none when no lane has a processor on. [`warm_up_samples`] is how much |
| 1196 | /// of the mix's front that is, taken off again. |
| 1197 | fn warm_up(project: &Project, offset: u32, fps: f64) -> u32 { |
| 1198 | if offset == 0 || !project.audio_voices().iter().any(crate::voice::VoiceFx::is_active) { |
| 1199 | return 0; |
| 1200 | } |
| 1201 | offset.min((fps * 0.5).ceil() as u32) |
| 1202 | } |
| 1203 | |
| 1204 | /// How many interleaved samples the `pre` frames of [`warm_up`] before `range_start` are: |
| 1205 | /// the samples the timeline's mix puts between the two frames, counted with the mixer's own |
| 1206 | /// rounding ([`timeline_sample`](crate::audio::timeline_sample)), so the range starts on the |
| 1207 | /// same sample a full export has there. Rounding the pre-roll's own length instead can miss |
| 1208 | /// by one at 29.97 or 23.976 fps. |
| 1209 | fn warm_up_samples(range_start: u32, pre: u32, fps: f64, rate: u32, channels: usize) -> usize { |
| 1210 | let at = |frame: u32| crate::audio::timeline_sample(f64::from(frame) / fps, rate); |
| 1211 | (at(range_start) - at(range_start - pre)) as usize * channels |
| 1212 | } |
| 1213 | |
| 1214 | /// Whether the *mix* is doing something -- a lane turned off unity, a lane |
| 1215 | /// ducked under another, or a limiter in circuit. [`equalized`]'s pair, and a |
| 1216 | /// copy cannot carry any of them: all live where the lanes are summed |
| 1217 | /// ([`AudioSession::open_mixed_streams_master`]), and a copied packet was never |
| 1218 | /// summed at all. An mp4 whose timeline is mixed is decoded and re-encoded. |
| 1219 | fn mastered(project: &Project) -> bool { |
| 1220 | project.limiter().is_active() |
| 1221 | || project.audio_gains().iter().any(|&g| g != 1.0) |
| 1222 | || project.audio_ducks().iter().any(|lane| !lane.is_empty()) |
| 1223 | || project.audio_voices().iter().any(crate::voice::VoiceFx::is_active) |
| 1224 | } |
| 1225 | |
| 1226 | /// Whether any audio clip has a fade -- [`equalized`]'s pair again: a fade is |
| 1227 | /// gain math on decoded samples ([`crate::project::Fade::apply`]), and a |
| 1228 | /// packet copy carries neither an equalizer nor a fade. An mp4 whose timeline |
| 1229 | /// has one is decoded and re-encoded so the fade actually reaches the file. |
| 1230 | fn faded(project: &Project) -> bool { |
| 1231 | project.audio_lanes().into_iter().any(|lane| { |
| 1232 | project |
| 1233 | .lane(lane) |
| 1234 | .iter() |
| 1235 | .any(|c| c.fade_in > 0 || c.fade_out > 0) |
| 1236 | }) |
| 1237 | } |
| 1238 | |
| 1239 | /// The bitrate an export codes at: the caller's number clamped into what an |
| 1240 | /// asked-for rate may be ([`MIN_BITRATE`]..[`MAX_EXPLICIT_BITRATE`]), the |
| 1241 | /// derived one where there was none. Clamped rather than refused, for the |
| 1242 | /// reason [`Enc::open`] states. |
| 1243 | fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 { |
| 1244 | settings.bitrate.map_or_else( |
| 1245 | || bitrate_for(meta), |
| 1246 | |b| b.clamp(MIN_BITRATE, MAX_EXPLICIT_BITRATE), |
| 1247 | ) |
| 1248 | } |
| 1249 | |
| 1250 | /// The rate the sound codes at: the caller's pick clamped into the offered |
| 1251 | /// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused, |
| 1252 | /// for [`bitrate_of`]'s reason -- a number out of range is a caller's slip and |
| 1253 | /// not a file worth failing. |
| 1254 | fn audio_kbps_of(settings: &ExportSettings) -> u32 { |
| 1255 | // 384 is above the offered rows, which a preset asks for (YouTube's AAC); MP3 has no such rate. |
| 1256 | let ceiling = if settings.format == Format::Mp3 { AUDIO_KBPS[3] } else { 384 }; |
| 1257 | settings.audio_kbps.map_or(DEFAULT_AUDIO_KBPS, |k| k.clamp(AUDIO_KBPS[0], ceiling)) |
| 1258 | } |
| 1259 | |
| 1260 | /// The hardware seat for these settings, opened exactly as the export opens it |
| 1261 | /// -- the same pins, the same dimensions a driver may refuse -- or `None` where |
| 1262 | /// the software encoder takes the file. The single place that choice is made, |
| 1263 | /// which is what lets [`planned_video`] *measure* it instead of promising it. |
| 1264 | /// |
| 1265 | /// `Err` is the one answer the software encoder does **not** take over from: |
| 1266 | /// [`EncoderSeat::Hardware`] asked for the GPU by name and this machine has no |
| 1267 | /// seat for the codec, so the export refuses in words rather than falling back |
| 1268 | /// to an encoder nobody picked. Every caller is before a file exists |
| 1269 | /// ([`Enc::open`] runs ahead of the muxer), which is what makes the refusal |
| 1270 | /// free. |
| 1271 | fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Option<HwEncoder>> { |
| 1272 | if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") { |
| 1273 | return Ok(None); |
| 1274 | } |
| 1275 | // The plugin's HEVC seat codes intra pictures only ([`open_hw_seat`]), so a |
| 1276 | // GOP export cannot be had from the GPU. Said here rather than written as an |
| 1277 | // intra file under a card that promised I+P. |
| 1278 | if settings.seat == EncoderSeat::Hardware && settings.format.is_hevc() && !settings.intra_only { |
| 1279 | return Err("hardware HEVC codes intra pictures only and this export is I+P: pick Auto or Software on the export card, or an intra-only export for the GPU".into()); |
| 1280 | } |
| 1281 | let opened = open_hw_seat(meta, settings); |
| 1282 | if opened.is_none() && settings.seat == EncoderSeat::Hardware { |
| 1283 | return Err(format!( |
| 1284 | "hardware encoding was asked for and this machine has no VA-API seat for {}: \ |
| 1285 | pick Auto or Software on the export card", |
| 1286 | settings.format.name() |
| 1287 | ) |
| 1288 | .into()); |
| 1289 | } |
| 1290 | Ok(opened) |
| 1291 | } |
| 1292 | |
| 1293 | /// The plugin half of [`hw_seat`]: what the driver gives for this codec and |
| 1294 | /// this picture, with no policy in it but the AV1 one. |
| 1295 | fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> { |
| 1296 | let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?; |
| 1297 | let bitrate = bitrate_of(meta, settings); |
| 1298 | match settings.format { |
| 1299 | // Both HEVC formats sit on the plugin's HEVC seat, and it is the |
| 1300 | // default again: what it codes is intra-only, the very file the |
| 1301 | // software seat writes, so preferring the GPU changes how long an |
| 1302 | // export takes and not what comes out of it. What made that untrue for |
| 1303 | // one day was the vendored encoder's parameter sets promising coding |
| 1304 | // tools the driver was not using; the pictures are now measured against |
| 1305 | // their sources rather than counted |
| 1306 | // (`hevc_export::a_1080p_hardware_export_leaves_a_decoder_with_nothing_to_say`). |
| 1307 | // `None` here is the plugin's own "no" -- no entrypoint, or a picture |
| 1308 | // under the driver's 384x384 floor -- and the software seat takes it. |
| 1309 | // The colour goes in at the open, from the same [`ColorDescription::output`] |
| 1310 | // rule the software seat's VUI and both containers' tags come from, so |
| 1311 | // the file cannot say one thing in its bitstream and another in its |
| 1312 | // header. |
| 1313 | // The GOP default is software: Auto takes `ec-h265` for an I+P file |
| 1314 | // rather than the GPU's intra one, which is what the card says it is. |
| 1315 | format if format.is_hevc() && !settings.intra_only => None, |
| 1316 | format if format.is_hevc() => HwEncoder::open_hevc( |
| 1317 | meta.width, |
| 1318 | meta.height, |
| 1319 | fps_num, |
| 1320 | fps_den, |
| 1321 | bitrate, |
| 1322 | ColorDescription::output_sized(meta.width, meta.height), |
| 1323 | ), |
| 1324 | // Asked for by name only, for the reason [`Enc::open_av1`] states in |
| 1325 | // full: `Auto` takes the software encoder here and nowhere else. Both |
| 1326 | // AV1 formats sit on it: the container is not the encoder's business. |
| 1327 | format if format.is_av1() && settings.seat != EncoderSeat::Hardware => None, |
| 1328 | format if format.is_av1() => { |
| 1329 | HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, bitrate) |
| 1330 | } |
| 1331 | // An intra-only H.264 file is a *different seat*, not the same seat with |
| 1332 | // a flag on the pictures: asking this one for a key frame every time |
| 1333 | // gets I slices that are not IDRs and carry no parameter sets, which is |
| 1334 | // a file with one starting point in it however many I pictures it holds |
| 1335 | // (measured: a 60-frame hardware proxy, 1 sync point of 60). `None` |
| 1336 | // where the plugin is older than that seat, and then the software |
| 1337 | // encoder takes the file -- its `gop_size = 1` writes what was asked |
| 1338 | // for, slowly, which is the only honest fallback here. |
| 1339 | // |
| 1340 | // Only H.264 reaches this arm: the two arms above take every HEVC and |
| 1341 | // AV1 format, and the HEVC seat is intra-only already. |
| 1342 | _ if settings.intra_only => { |
| 1343 | HwEncoder::open_intra(meta.width, meta.height, fps_num, fps_den, bitrate) |
| 1344 | } |
| 1345 | _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, bitrate), |
| 1346 | } |
| 1347 | } |
| 1348 | |
| 1349 | /// What a hardware encode is called wherever one is named -- the card's line |
| 1350 | /// before the export and the progress line during it. |
| 1351 | const HW_LABEL: &str = "HW encode (VA-API)"; |
| 1352 | |
| 1353 | /// ...and what a card says instead where [`EncoderSeat::Hardware`] was picked |
| 1354 | /// and there is no seat: the export's own refusal in the width of a card row, |
| 1355 | /// shown *before* the button is pressed rather than a minute into a file. |
| 1356 | pub const NO_HW_SEAT: &str = "no HW seat here — pick Auto or Software"; |
| 1357 | |
| 1358 | /// How a front-end names a video seat: which of the two encoders has the file, |
| 1359 | /// and which library that is. Not the codec -- a caller shows this beside the |
| 1360 | /// format it picked, and `rav1e` names AV1 as `ec-h264` names H.264. One |
| 1361 | /// place, so what a card says before an export and what its progress line says |
| 1362 | /// during one cannot drift apart. |
| 1363 | fn video_label(format: Format, hw: bool, intra: bool) -> &'static str { |
| 1364 | match (format, hw) { |
| 1365 | (_, true) => HW_LABEL, |
| 1366 | (Format::Hevc | Format::HevcMp4, false) if intra => "SW encode (ec-h265 intra)", |
| 1367 | (Format::Hevc | Format::HevcMp4, false) => "SW encode (ec-h265 GOP)", |
| 1368 | (Format::Av1 | Format::Av1Mp4 | Format::Webm, false) => "SW encode (rav1e)", |
| 1369 | (Format::ProRes, false) => "SW encode (ec-prores)", |
| 1370 | (_, false) => "SW encode (ec-h264)", |
| 1371 | } |
| 1372 | } |
| 1373 | |
| 1374 | /// Whether the *edit* has touched the samples a copy would carry out: the one |
| 1375 | /// predicate both copy-or-encode decisions ask, with `lanes` the sound's own |
| 1376 | /// list as the caller has it -- every audio lane for the question a card asks |
| 1377 | /// before the button ([`forces_encode`]), and the single lane the segments have |
| 1378 | /// already narrowed a copy to ([`copy_audio`]). |
| 1379 | /// |
| 1380 | /// One function and not two lists of the same conditions, which is what they |
| 1381 | /// were: `faded` reached [`forces_encode`] and not [`copy_audio`]'s gate, so an |
| 1382 | /// mp4 whose lane carried a fade wrote the source's own packets with the fade |
| 1383 | /// nowhere, while the card had promised a re-encode -- and the WAV, FLAC and |
| 1384 | /// MP3 exports of the same project applied it. Two gates that cannot be given |
| 1385 | /// two answers is the fix; the drift was the defect. |
| 1386 | fn sample_altered(project: &Project, lanes: &[Lane]) -> bool { |
| 1387 | // Two lanes are a mix and a mix is not a copy; a speeded lane is resampled; |
| 1388 | // an equalizer, a fade and the mix itself are gain math on decoded samples |
| 1389 | // ([`equalized`], [`faded`], [`mastered`]). None of them is inside a packet. |
| 1390 | lanes.len() > 1 |
| 1391 | || lanes |
| 1392 | .iter() |
| 1393 | .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal() || !c.speed_keys.is_empty() || c.reversed)) |
| 1394 | || equalized(project) |
| 1395 | || mastered(project) |
| 1396 | || faded(project) |
| 1397 | } |
| 1398 | |
| 1399 | /// The cheap half of "does this timeline's sound have to be re-encoded": what |
| 1400 | /// the *edit* says, with no file opened ([`sample_altered`], asked of every |
| 1401 | /// audio lane). The other half -- whether the sources can be copied out of at |
| 1402 | /// all -- costs a file open each and belongs to [`copy_audio`], which may |
| 1403 | /// re-encode where this says copy. |
| 1404 | fn forces_encode(project: &Project, ranged: bool) -> bool { |
| 1405 | // A ranged export needs an exact offset and an exact length, which a copy |
| 1406 | // of the source's own packets cannot give it ([`copy_audio`]) -- so a |
| 1407 | // range marked at all always encodes, whatever the lanes look like. |
| 1408 | ranged || sample_altered(project, &project.audio_lanes()) |
| 1409 | } |
| 1410 | |
| 1411 | /// What the sound is written by. Every audio encoder here is software -- there |
| 1412 | /// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and |
| 1413 | /// whether a container escapes encoding altogether by copying the packets it was |
| 1414 | /// given. Both AV1 formats are in it like the mp4: an AV1 export carries the |
| 1415 | /// timeline's sound too, so leaving it unnamed would be the old lie. |
| 1416 | /// |
| 1417 | /// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a |
| 1418 | /// card asking before the export has no way to know (a source that cannot be |
| 1419 | /// copied out of is only found by opening it). `None` predicts from the edit |
| 1420 | /// alone. |
| 1421 | fn audio_label( |
| 1422 | project: &Project, |
| 1423 | format: Format, |
| 1424 | sound: bool, |
| 1425 | copied: Option<bool>, |
| 1426 | ranged: bool, |
| 1427 | ) -> &'static str { |
| 1428 | if !sound { |
| 1429 | return "no sound to write"; |
| 1430 | } |
| 1431 | match format { |
| 1432 | Format::Wav => "PCM · SW (ec-riff)", |
| 1433 | Format::Flac => "FLAC · SW (ec-flac)", |
| 1434 | Format::Mp3 => "MP3 · SW (ec-mp3)", |
| 1435 | Format::Ogg => "Vorbis · SW (ec-vorbis)", |
| 1436 | Format::Opus => "Opus · SW (ec-opus)", |
| 1437 | Format::ProRes => "PCM · SW (16-bit, mov)", |
| 1438 | // Never a copy: WebM carries Opus, and the sound is mixed and encoded |
| 1439 | // for it at 48 kHz ([`start`], [`encode_audio`]). |
| 1440 | Format::Webm => "Opus · SW encode (ec-opus)", |
| 1441 | _ => match copied.unwrap_or(!forces_encode(project, ranged)) { |
| 1442 | true => "AAC copy", |
| 1443 | // A Matroska file gets Opus where the mix allows it -- 48 kHz and |
| 1444 | // stereo, which is every Opus source and most of everything else -- |
| 1445 | // and AAC where it does not ([`encode_audio`]). Which of the two it |
| 1446 | // will be cannot be known here: both answers need a source opened, |
| 1447 | // and this function may be asked per repaint. So the card names the |
| 1448 | // codec it will nearly always be, as a prediction like the copy above |
| 1449 | // it, and the line the export publishes while it runs is the measured |
| 1450 | // one ([`run`]) -- it says AAC when the fallback took it, so the |
| 1451 | // fallback is visible rather than silent. |
| 1452 | // |
| 1453 | // It is one line and 76 characters wide (`summary_head` in the app |
| 1454 | // has the test), which is why the condition is in this comment |
| 1455 | // instead of in the string. |
| 1456 | false if format.is_mkv() => "Opus · SW encode (ec-opus)", |
| 1457 | false => "AAC · SW encode (ec-aac)", |
| 1458 | }, |
| 1459 | } |
| 1460 | } |
| 1461 | |
| 1462 | /// What the export *did* to the sound, for the line it publishes while it runs: |
| 1463 | /// [`audio_label`]'s words with the one thing no prediction can know filled in |
| 1464 | /// -- whether the Opus seat took the track or handed it back |
| 1465 | /// ([`encode_opus`]'s gate). |
| 1466 | /// |
| 1467 | /// `sound` is `Some(copied)` for a track and `None` for a file with no sound. |
| 1468 | /// Naming Opus for *every* Matroska encode is what made that fallback |
| 1469 | /// invisible: a track the gate refused was written as AAC and the line still |
| 1470 | /// said Opus, on the one path where the difference is audible. |
| 1471 | fn measured_audio_label( |
| 1472 | project: &Project, |
| 1473 | format: Format, |
| 1474 | sound: Option<bool>, |
| 1475 | opus: bool, |
| 1476 | ) -> &'static str { |
| 1477 | match (sound, opus) { |
| 1478 | (_, true) => "Opus · SW encode (ec-opus)", |
| 1479 | // Encoded, into a container that would have carried Opus, and it is not |
| 1480 | // Opus: the fidelity gate sent it to AAC ([`OPUS_MIN_FIDELITY`]), or |
| 1481 | // the mix was not 48 kHz at a width the seat is measured in. |
| 1482 | (Some(false), false) if format.is_mkv() => "AAC · SW encode (ec-aac)", |
| 1483 | // `sound` is already what happened, not a prediction, so `copied` is |
| 1484 | // filled in and `ranged` never reaches the branch that reads it. |
| 1485 | _ => audio_label(project, format, sound.is_some(), sound, false), |
| 1486 | } |
| 1487 | } |
| 1488 | |
| 1489 | /// What [`start`] would write this timeline's sound with, before one is |
| 1490 | /// started. Pure: no probe and no file opened, so a card may ask it per |
| 1491 | /// repaint. `ranged` is whether the export a card is describing is bounded to |
| 1492 | /// a marked range -- a copy needs the source's own packets to *be* the file, |
| 1493 | /// which a range's exact offset and length rule out ([`copy_audio`]). |
| 1494 | pub fn planned_audio(project: &Project, format: Format, ranged: bool) -> &'static str { |
| 1495 | audio_label(project, format, has_sound(project), None, ranged) |
| 1496 | } |
| 1497 | |
| 1498 | /// Why the sound's rate is nothing this timeline can be asked about in this |
| 1499 | /// format, or `None` where it is a real choice: there is no sound to write, the |
| 1500 | /// format codes the samples themselves, or the packets are the source's own and |
| 1501 | /// carry the rate *it* was coded at. Pure, like [`planned_audio`], and a |
| 1502 | /// prediction in the same way -- a copy that turns out impossible (a source no |
| 1503 | /// mp4 sample table holds) falls through to [`encode_audio`], which codes at |
| 1504 | /// [`ExportSettings::audio_kbps`] like every other encode. So the value travels |
| 1505 | /// even where this refuses; what it cannot do is silently write a rate nobody |
| 1506 | /// picked. |
| 1507 | pub fn audio_rate_refusal(project: &Project, format: Format, ranged: bool) -> Option<&'static str> { |
| 1508 | match format { |
| 1509 | _ if !has_sound(project) => Some("no sound to write"), |
| 1510 | Format::Wav | Format::Flac | Format::ProRes => Some("lossless — the samples themselves, at no rate"), |
| 1511 | // Vorbis is written at one measured operating point ([`VORBIS_QUALITY`] |
| 1512 | // + [`VORBIS_TARGET_BPS`]), not at a rate a user may pick: its actual |
| 1513 | // landing moves with the content around that target (124-134 kbps |
| 1514 | // across this suite's bench inputs), so a live rate row would print a |
| 1515 | // figure the file does not hold -- the one thing this card is built |
| 1516 | // not to do. |
| 1517 | Format::Ogg => Some("quality-coded — Vorbis holds no rate to pick"), |
| 1518 | // The bitrate is the one choice WebM leaves: Opus at the rate picked. |
| 1519 | Format::Mp3 | Format::Webm | Format::Opus => None, |
| 1520 | _ if forces_encode(project, ranged) => None, |
| 1521 | _ => Some("the source's own packets are copied — at the rate they hold"), |
| 1522 | } |
| 1523 | } |
| 1524 | |
| 1525 | /// The soft subtitle tracks an export carries: the lanes the timeline places, each |
| 1526 | /// as its placement (the lanes a pick reaches), then every picked track no lane |
| 1527 | /// places, whole. Empty where it carries none: no pick and no placement, a pick |
| 1528 | /// nothing answers, a track that could not be read, one with no cue left on the |
| 1529 | /// exported timeline -- and every format that is the sound alone, which has |
| 1530 | /// nowhere to put them. Filtered *per track*, so one unusable pick costs its own |
| 1531 | /// row and not the others. |
| 1532 | /// |
| 1533 | /// Both containers, since the mp4 muxer gained its `tx3g` track: what the two |
| 1534 | /// do with the very same [`SubParams`] is theirs to say |
| 1535 | /// ([`crate::mux::Mp4Muxer::write_subtitles`], [`MkvMuxer`]), and nothing here |
| 1536 | /// asks which one is being written. |
| 1537 | fn export_subtitles( |
| 1538 | project: &Project, |
| 1539 | meta: &VideoMeta, |
| 1540 | settings: &ExportSettings, |
| 1541 | ) -> Vec<SubParams> { |
| 1542 | // WebM has no subtitle track this writer can state: [`planned_subtitles`] |
| 1543 | // says so on the card, and nothing is written. |
| 1544 | if !settings.format.has_video() || matches!(settings.format, Format::Webm | Format::ProRes) || !has_picture(project) { |
| 1545 | return Vec::new(); |
| 1546 | } |
| 1547 | // Burned captions are the only ones this file carries: a soft track of the |
| 1548 | // same words would show them twice. |
| 1549 | if settings.no_soft_subtitles { |
| 1550 | return Vec::new(); |
| 1551 | } |
| 1552 | // Words placed on a lane are written through the lanes, at their placement |
| 1553 | // (`lane_subtitle`; none when nothing is placed). A picked track that no lane |
| 1554 | // places is written whole beside them, as it always was: the palette's pick |
| 1555 | // is the only say it has in the file, so it must not be dropped for a lane |
| 1556 | // elsewhere. A placed track is never written twice. The tracks go in the |
| 1557 | // order the caller gave them ([`soft_order`]), placed or not. |
| 1558 | let lanes = placed_lanes(project); |
| 1559 | let mut subs = Vec::new(); |
| 1560 | for entry in soft_order(project, &lanes, &settings.subtitles) { |
| 1561 | match entry { |
| 1562 | SoftEntry::Lane(lane) => subs.extend(lane_subtitle( |
| 1563 | project, |
| 1564 | lane, |
| 1565 | meta.frame_rate, |
| 1566 | settings.range, |
| 1567 | &settings.subtitles, |
| 1568 | )), |
| 1569 | SoftEntry::Track(pick) => subs.extend(whole_track(project, meta, settings, pick)), |
| 1570 | } |
| 1571 | } |
| 1572 | subs |
| 1573 | } |
| 1574 | |
| 1575 | /// Whether a track has a cue the file would carry: any cue at all on the whole timeline, or one |
| 1576 | /// left inside `range` (on the clock the range is cut to, as [`written_cues`] cuts it). |
| 1577 | fn track_has_cues(project: &Project, track: &SubtitleTrack, range: Option<(u32, u32)>, fps: f64) -> bool { |
| 1578 | match range { |
| 1579 | None => !track.cues.is_empty(), |
| 1580 | Some(_) => !written_cues(timeline_cues(project, track, fps), range, fps, project.media_frames()).is_empty(), |
| 1581 | } |
| 1582 | } |
| 1583 | |
| 1584 | /// The reason a track with nothing to carry is dropped, in the card's words. |
| 1585 | fn no_cues_word(range: Option<(u32, u32)>) -> &'static str { |
| 1586 | if range.is_some() { "no cues in range" } else { "no cues" } |
| 1587 | } |
| 1588 | |
| 1589 | /// The labels of the written soft tracks whose styling the file drops: a standalone ASS or SSA |
| 1590 | /// script whose lines carry override blocks (`{\i1}`, `{\an8}`), which a cue's plain text does not |
| 1591 | /// keep. An embedded ASS track is not read here, so it is not named. Empty when none is. |
| 1592 | pub fn stripped_styling(project: &Project, picks: &[usize]) -> Vec<String> { |
| 1593 | let lanes = placed_lanes(project); |
| 1594 | let placed = placed_tracks(project); |
| 1595 | let mut used: std::collections::BTreeSet<usize> = picks.iter().copied().filter(|p| !placed.contains(p)).collect(); |
| 1596 | for &lane in &lanes { |
| 1597 | let on_lane = project.sub_lane(lane); |
| 1598 | if picked(on_lane, picks) { |
| 1599 | used.extend(on_lane.iter().map(|s| s.track)); |
| 1600 | } |
| 1601 | } |
| 1602 | used.into_iter() |
| 1603 | .filter_map(|i| project.subtitles().get(i)) |
| 1604 | .filter(|t| t.refused.is_none() && !t.is_bitmap() && t.track.is_none() && has_override_blocks(&t.path)) |
| 1605 | .map(|t| t.label.clone()) |
| 1606 | .collect() |
| 1607 | } |
| 1608 | |
| 1609 | /// Whether `path` is an ASS or SSA script with an override block in it. |
| 1610 | fn has_override_blocks(path: &Path) -> bool { |
| 1611 | let ass = path |
| 1612 | .extension() |
| 1613 | .and_then(|e| e.to_str()) |
| 1614 | .is_some_and(|e| e.eq_ignore_ascii_case("ass") || e.eq_ignore_ascii_case("ssa")); |
| 1615 | ass && std::fs::read_to_string(path).is_ok_and(|text| text.contains("{\\")) |
| 1616 | } |
| 1617 | |
| 1618 | /// One soft track of the file: a subtitle lane (written through its placements) or a picked |
| 1619 | /// track no lane places (written whole). |
| 1620 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 1621 | enum SoftEntry { |
| 1622 | Lane(Lane), |
| 1623 | Track(usize), |
| 1624 | } |
| 1625 | |
| 1626 | /// The soft tracks the file writes, in the order the file declares them. With picks, that is |
| 1627 | /// the order the caller gave them: a lane goes where the first pick that reaches it sits, and a |
| 1628 | /// pick no lane places goes whole in its own place. Without picks, every placed lane in lane |
| 1629 | /// order and no whole track. |
| 1630 | fn soft_order(project: &Project, lanes: &[Lane], picks: &[usize]) -> Vec<SoftEntry> { |
| 1631 | if picks.is_empty() { |
| 1632 | return lanes.iter().map(|&l| SoftEntry::Lane(l)).collect(); |
| 1633 | } |
| 1634 | let placed = placed_tracks(project); |
| 1635 | let mut out: Vec<SoftEntry> = Vec::new(); |
| 1636 | for &pick in picks { |
| 1637 | let entry = if placed.contains(&pick) { |
| 1638 | match lanes.iter().find(|&&l| project.sub_lane(l).iter().any(|s| s.track == pick)) { |
| 1639 | Some(&lane) => SoftEntry::Lane(lane), |
| 1640 | None => continue, |
| 1641 | } |
| 1642 | } else { |
| 1643 | SoftEntry::Track(pick) |
| 1644 | }; |
| 1645 | if !out.contains(&entry) { |
| 1646 | out.push(entry); |
| 1647 | } |
| 1648 | } |
| 1649 | out |
| 1650 | } |
| 1651 | |
| 1652 | /// One picked track written whole, on the timeline's clock and clipped to the range |
| 1653 | /// and the picture. `None` for a track that writes nothing: no row for the pick, a |
| 1654 | /// track that could not be read, a picture track (the muxer writes words), or no cue |
| 1655 | /// left in the file. |
| 1656 | fn whole_track( |
| 1657 | project: &Project, |
| 1658 | meta: &VideoMeta, |
| 1659 | settings: &ExportSettings, |
| 1660 | pick: usize, |
| 1661 | ) -> Option<SubParams> { |
| 1662 | let track = project.subtitles().get(pick)?; |
| 1663 | // A picture is not a line: the muxer writes an `S_TEXT/UTF8` track and a PGS cue |
| 1664 | // has no words to put in one. `planned_subtitles` says so before the button is |
| 1665 | // pressed rather than the file coming out short. |
| 1666 | if track.refused.is_some() || track.is_bitmap() { |
| 1667 | return None; |
| 1668 | } |
| 1669 | let cues = written_cues( |
| 1670 | timeline_cues(project, track, meta.frame_rate), |
| 1671 | settings.range, |
| 1672 | meta.frame_rate, |
| 1673 | project.media_frames(), |
| 1674 | ); |
| 1675 | // The container's own two fields, carried as two |
| 1676 | // ([`SubtitleTrack::language`]): a `TrackEntry` with no `Language` means `eng` |
| 1677 | // by spec, so a French track that arrives here as one flattened string leaves |
| 1678 | // as an English one. |
| 1679 | (!cues.is_empty()).then(|| SubParams { |
| 1680 | language: track.language.clone(), |
| 1681 | name: subtitle_title(track), |
| 1682 | cues, |
| 1683 | }) |
| 1684 | } |
| 1685 | |
| 1686 | /// The title a soft subtitle track is written under. An embedded track keeps the |
| 1687 | /// title its container gave it; a standalone file has none of its own, so it is |
| 1688 | /// titled with its language's name (`French`) or left untitled -- never with its |
| 1689 | /// file name. |
| 1690 | fn subtitle_title(track: &SubtitleTrack) -> String { |
| 1691 | match track.track { |
| 1692 | Some(_) => track.name.clone(), |
| 1693 | None => crate::subtitle::language_name(&track.language).unwrap_or_default().to_string(), |
| 1694 | } |
| 1695 | } |
| 1696 | |
| 1697 | /// The indices of the tracks some placement on a subtitle lane names. Those tracks |
| 1698 | /// are written through their lanes, so a pick of one of them is not written whole. |
| 1699 | fn placed_tracks(project: &Project) -> std::collections::BTreeSet<usize> { |
| 1700 | project |
| 1701 | .subtitle_lanes() |
| 1702 | .into_iter() |
| 1703 | .flat_map(|lane| project.sub_lane(lane).iter().map(|s| s.track)) |
| 1704 | .collect() |
| 1705 | } |
| 1706 | |
| 1707 | /// The labels of the soft subtitle tracks this export writes whose cues overlap. An mp4 |
| 1708 | /// writes an overlap as one stretch with both lines in it (`mux`'s `timed_text`), so the |
| 1709 | /// cue times the timeline holds are not the file's; an mkv keeps every cue. Empty when |
| 1710 | /// nothing is written or no two cues of a written track overlap. |
| 1711 | pub fn overlapping_subtitles(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Vec<String> { |
| 1712 | export_subtitles(project, meta, settings) |
| 1713 | .into_iter() |
| 1714 | .filter(|t| { |
| 1715 | let mut spans: Vec<(i64, i64)> = t.cues.iter().map(|c| (c.start_us, c.end_us)).collect(); |
| 1716 | spans.sort_unstable(); |
| 1717 | let mut reach = i64::MIN; |
| 1718 | spans.iter().any(|&(start, end)| { |
| 1719 | let overlap = start < reach; |
| 1720 | reach = reach.max(end); |
| 1721 | overlap |
| 1722 | }) |
| 1723 | }) |
| 1724 | .map(|t| match (t.name.is_empty(), t.language.is_empty()) { |
| 1725 | (false, _) => t.name, |
| 1726 | (true, false) => t.language, |
| 1727 | (true, true) => "an unnamed track".to_string(), |
| 1728 | }) |
| 1729 | .collect() |
| 1730 | } |
| 1731 | |
| 1732 | /// Whether a lane with these placements is in the file: an empty pick list is |
| 1733 | /// every lane, otherwise the lane must hold at least one placement of a picked |
| 1734 | /// track ([`Project::subtitles`] index, as [`ExportSettings::subtitles`] gives). |
| 1735 | fn picked(placed: &[crate::project::SubClip], picks: &[usize]) -> bool { |
| 1736 | picks.is_empty() || placed.iter().any(|s| picks.contains(&s.track)) |
| 1737 | } |
| 1738 | |
| 1739 | /// The project's subtitle lanes in display order, and empty where **nothing is |
| 1740 | /// placed on any of them** -- an empty list is what the export and the card both |
| 1741 | /// read as "this project does not use lanes yet", so a project holding a bare |
| 1742 | /// `S1` nobody dropped a caption on still exports by the pick list. |
| 1743 | fn placed_lanes(project: &Project) -> Vec<Lane> { |
| 1744 | let lanes = project.subtitle_lanes(); |
| 1745 | match lanes.iter().any(|&l| !project.sub_lane(l).is_empty()) { |
| 1746 | true => lanes, |
| 1747 | false => Vec::new(), |
| 1748 | } |
| 1749 | } |
| 1750 | |
| 1751 | /// One track per subtitle *lane*, in lane order -- so the file declares them |
| 1752 | /// top-down as the timeline shows them and a player's subtitle menu lists them |
| 1753 | /// in that order. |
| 1754 | /// |
| 1755 | /// The cues are [`Project::sub_lane_cues`]: each placement's window of its |
| 1756 | /// palette track, on the timeline's own clock. Clipped again here to what the |
| 1757 | /// export *writes*, which ends with the last picture or sound |
| 1758 | /// ([`Project::media_frames`]) -- a caption hanging past both holds the |
| 1759 | /// timeline open ([`Project::timeline_frames`]) but there is no picture under |
| 1760 | /// it to write, so a cue out there is dropped and one straddling the end keeps |
| 1761 | /// the half that is inside. [`planned_subtitles`] says so before the button is |
| 1762 | /// pressed. |
| 1763 | /// |
| 1764 | /// A lane is dropped whole -- no track at all in the file -- where any |
| 1765 | /// placement on it is a picture ([`SubtitleTrack::is_bitmap`]), a track that |
| 1766 | /// could not be read, or a palette row that has since gone: the muxers write |
| 1767 | /// words, and half a lane's cues under the other half's name would be worse |
| 1768 | /// than none. Its language and title are the lane's *first* placement's track, |
| 1769 | /// which is the one thing the whole lane is named by. |
| 1770 | /// |
| 1771 | /// `picks` narrows the lanes the same way [`ExportSettings::subtitles`] does: a |
| 1772 | /// lane is kept when it holds a placement of a picked track ([`picked`]), and an |
| 1773 | /// empty list keeps every lane. |
| 1774 | #[cfg(test)] |
| 1775 | fn lane_subtitles( |
| 1776 | project: &Project, |
| 1777 | fps: f64, |
| 1778 | range: Option<(u32, u32)>, |
| 1779 | picks: &[usize], |
| 1780 | ) -> Vec<SubParams> { |
| 1781 | placed_lanes(project) |
| 1782 | .into_iter() |
| 1783 | .filter_map(|lane| lane_subtitle(project, lane, fps, range, picks)) |
| 1784 | .collect() |
| 1785 | } |
| 1786 | |
| 1787 | /// One lane written as its track ([`lane_subtitles`] for a single lane); `None` where the |
| 1788 | /// lane is not in the file (see there for the reasons). |
| 1789 | fn lane_subtitle( |
| 1790 | project: &Project, |
| 1791 | lane: Lane, |
| 1792 | fps: f64, |
| 1793 | range: Option<(u32, u32)>, |
| 1794 | picks: &[usize], |
| 1795 | ) -> Option<SubParams> { |
| 1796 | let end = (f64::from(project.media_frames()) / fps * 1e6).round() as i64; |
| 1797 | let placed = project.sub_lane(lane); |
| 1798 | if !picked(placed, picks) { |
| 1799 | return None; |
| 1800 | } |
| 1801 | let first = placed.first()?; |
| 1802 | let writable = |track: usize| { |
| 1803 | project |
| 1804 | .subtitles() |
| 1805 | .get(track) |
| 1806 | .filter(|t| t.refused.is_none() && !t.is_bitmap()) |
| 1807 | }; |
| 1808 | let named = writable(first.track)?; |
| 1809 | if placed.iter().any(|s| writable(s.track).is_none()) { |
| 1810 | return None; |
| 1811 | } |
| 1812 | let cues: Vec<Cue> = written_cues( |
| 1813 | project |
| 1814 | .sub_lane_cues(lane, fps) |
| 1815 | .into_iter() |
| 1816 | .filter_map(|cue| { |
| 1817 | let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end)); |
| 1818 | (end_us > start_us).then_some(Cue { |
| 1819 | start_us, |
| 1820 | end_us, |
| 1821 | text: cue.text, |
| 1822 | image: cue.image, |
| 1823 | words: Vec::new(), |
| 1824 | karaoke: Vec::new(), |
| 1825 | }) |
| 1826 | }) |
| 1827 | .collect(), |
| 1828 | range, |
| 1829 | fps, |
| 1830 | project.media_frames(), |
| 1831 | ); |
| 1832 | (!cues.is_empty()).then(|| SubParams { |
| 1833 | language: named.language.clone(), |
| 1834 | name: subtitle_title(named), |
| 1835 | cues, |
| 1836 | }) |
| 1837 | } |
| 1838 | |
| 1839 | /// `cues` on the clock the export *writes*, for a range-relative file. |
| 1840 | /// |
| 1841 | /// A cue is timed on the timeline; a ranged export's file starts its own clock |
| 1842 | /// at zero where the range starts, so every cue moves back by the range's start. |
| 1843 | /// What falls before the range is dropped, what falls after it is dropped, and a |
| 1844 | /// cue straddling either edge keeps the half inside. The window is the range |
| 1845 | /// clamped to the media, the same clamp [`export_spans`] makes, so the cues stop |
| 1846 | /// where the pictures do. Both ends are whole microseconds of the same |
| 1847 | /// frame-to-time mapping the cues were timed with, so the only rounding left is |
| 1848 | /// the container's own tick. |
| 1849 | /// |
| 1850 | /// Unranged, the cues come back as they were. |
| 1851 | fn written_cues( |
| 1852 | cues: Vec<Cue>, |
| 1853 | range: Option<(u32, u32)>, |
| 1854 | fps: f64, |
| 1855 | media_frames: u32, |
| 1856 | ) -> Vec<Cue> { |
| 1857 | let Some((r_start, r_end)) = range else { |
| 1858 | return cues; |
| 1859 | }; |
| 1860 | let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64; |
| 1861 | let from = us(r_start); |
| 1862 | let to = us(r_end.min(media_frames).max(r_start)); |
| 1863 | cues.into_iter() |
| 1864 | .filter_map(|cue| { |
| 1865 | let start_us = cue.start_us.max(from); |
| 1866 | let end_us = cue.end_us.min(to); |
| 1867 | (end_us > start_us).then_some(Cue { |
| 1868 | start_us: start_us - from, |
| 1869 | end_us: end_us - from, |
| 1870 | text: cue.text, |
| 1871 | image: cue.image, |
| 1872 | words: Vec::new(), |
| 1873 | karaoke: Vec::new(), |
| 1874 | }) |
| 1875 | }) |
| 1876 | .collect() |
| 1877 | } |
| 1878 | |
| 1879 | /// The composite spans an export *writes*: [`Project::composite_spans_from`] |
| 1880 | /// cut to where the media runs out ([`Project::media_frames`]), and, with |
| 1881 | /// `range` set, to that window too. |
| 1882 | /// |
| 1883 | /// The walk itself is the timeline's ([`Project::timeline_frames`]), because a |
| 1884 | /// caption placed past the last picture holds the timeline open under it and |
| 1885 | /// playback parks on that tail -- but there is nothing to *write* out there, so |
| 1886 | /// an unbounded walk encoded and muxed black frames past the end of the media |
| 1887 | /// and padded the sound to match. This is the one place that end is decided: |
| 1888 | /// the frame count [`run`] publishes, the cues [`lane_subtitles`] clips and the |
| 1889 | /// blocks [`CopyPlan`] copies are then the same number by construction, which |
| 1890 | /// is what makes [`planned_lanes`]' "cut off there" true of the file. |
| 1891 | /// |
| 1892 | /// `span.start` stays the *project's* own timeline coordinate throughout -- |
| 1893 | /// what [`Project::composite_color_at`] and its fit sibling are keyed on -- so |
| 1894 | /// a caller writing a range-relative output shifts it at the one place that |
| 1895 | /// actually emits a position (`CopyPlan`'s own region, since the encode loop |
| 1896 | /// counts pictures rather than reading `span.start` for its output clock). |
| 1897 | /// Trimming the left edge mid-span moves `from`'s source frame by |
| 1898 | /// [`Speed::source_at`], the same mapping a legal cut is placed by. |
| 1899 | fn export_spans(project: &Project, range: Option<(u32, u32)>) -> Vec<crate::project::Span> { |
| 1900 | let end = project.media_frames(); |
| 1901 | let mut spans = stack_spans_from(project, 0); |
| 1902 | spans.retain(|span| span.start < end); |
| 1903 | for span in &mut spans { |
| 1904 | span.len = span.len.min(end - span.start); |
| 1905 | } |
| 1906 | // A title past the last clip is picture: the frames up to its end are black |
| 1907 | // under it, a gap like any other. Only titles extend the picture here; a |
| 1908 | // sound that runs on still does not, as it never did. |
| 1909 | let title_end = project |
| 1910 | .titles() |
| 1911 | .iter() |
| 1912 | .map(Title::end) |
| 1913 | .max() |
| 1914 | .unwrap_or(0) |
| 1915 | .min(end); |
| 1916 | let covered = spans.last().map_or(0, crate::project::Span::end); |
| 1917 | if covered < title_end { |
| 1918 | spans.push(crate::project::Span { |
| 1919 | ramp: None, |
| 1920 | start: covered, |
| 1921 | len: title_end - covered, |
| 1922 | from: None, |
| 1923 | speed: Speed::NORMAL, |
| 1924 | reverse: false, |
| 1925 | pitch: 0, |
| 1926 | }); |
| 1927 | } |
| 1928 | let Some((r_start, r_end)) = range else { |
| 1929 | return spans; |
| 1930 | }; |
| 1931 | let r_end = r_end.min(end).max(r_start); |
| 1932 | spans.retain(|span| span.start < r_end && span.start + span.len > r_start); |
| 1933 | for span in &mut spans { |
| 1934 | if span.start < r_start { |
| 1935 | let cut = r_start - span.start; |
| 1936 | if let Some((source, in_frame)) = span.from { |
| 1937 | span.from = Some((source, span.source_at(in_frame, cut))); |
| 1938 | } |
| 1939 | // A ramp's offsets are counted from the span's start, which has moved. |
| 1940 | span.ramp = span.ramp.map(|r| r.advanced(cut)); |
| 1941 | span.len -= cut; |
| 1942 | span.start = r_start; |
| 1943 | } |
| 1944 | span.len = span.len.min(r_end - span.start); |
| 1945 | } |
| 1946 | spans |
| 1947 | } |
| 1948 | |
| 1949 | /// The visible video lanes, bottom first: the last one is the topmost, the order |
| 1950 | /// [`Project::composite_clip_at`] counts in. |
| 1951 | fn visible_video_lanes(project: &Project) -> Vec<Lane> { |
| 1952 | project |
| 1953 | .lanes() |
| 1954 | .into_iter() |
| 1955 | .filter(|lane| lane.kind == LaneKind::Video && !project.lane_hidden(*lane)) |
| 1956 | .collect() |
| 1957 | } |
| 1958 | |
| 1959 | /// Every visible video clip covering `frame`, bottom first: the stack the |
| 1960 | /// picture is composed from. One entry is the single-clip picture every path |
| 1961 | /// has always drawn; two or more are a layered picture ([`layered_at`]), where |
| 1962 | /// each clip is drawn over the ones beneath it. |
| 1963 | pub(crate) fn stack_at(project: &Project, frame: u32) -> Vec<(Lane, usize)> { |
| 1964 | visible_video_lanes(project) |
| 1965 | .into_iter() |
| 1966 | .filter_map(|lane| Some((lane, project.lane_clip_at(lane, frame)?))) |
| 1967 | .collect() |
| 1968 | } |
| 1969 | |
| 1970 | /// Whether `frame` is a layered picture: more than one visible clip covers it. |
| 1971 | pub(crate) fn layered_at(project: &Project, frame: u32) -> bool { |
| 1972 | let stack = stack_at(project, frame); |
| 1973 | stack.len() >= 2 || animated_at(project, frame) || generated_at(project, &stack) |
| 1974 | } |
| 1975 | |
| 1976 | /// Whether a clip covering `frame` is an adjustment layer or an animated generator |
| 1977 | /// ([`crate::generate`]): neither is a picture the single-clip path draws. |
| 1978 | fn generated_at(project: &Project, stack: &[(Lane, usize)]) -> bool { |
| 1979 | stack.iter().any(|&(lane, idx)| { |
| 1980 | let src = project.sources().get(project.lane(lane)[idx].source); |
| 1981 | src.and_then(|s| crate::generate::Gen::parse(&s.path)).is_some_and(|g| g.animated() || g.is_adjust() || g.has_alpha()) |
| 1982 | }) |
| 1983 | } |
| 1984 | |
| 1985 | /// The one clip covering `frame` when its only animation is colour keys or an |
| 1986 | /// effects stack and nothing dissolves out of it: a 10-bit export keeps such a |
| 1987 | /// clip on the single-clip path, grading each picture by [`clip_color_at`] and |
| 1988 | /// drawing its effects at 10 bits ([`crate::effects`]), rather than composing it |
| 1989 | /// layered at 8 bits. |
| 1990 | fn color_keyed_alone_at(project: &Project, frame: u32) -> Option<&crate::project::Clip> { |
| 1991 | let [(lane, idx)] = stack_at(project, frame)[..] else { |
| 1992 | return None; |
| 1993 | }; |
| 1994 | let clip = &project.lane(lane)[idx]; |
| 1995 | ((!clip.color_keys.is_empty() || crate::effects::active(&clip.effects)) |
| 1996 | && clip.transform_keys.is_empty() |
| 1997 | && clip.opacity_keys.is_empty() |
| 1998 | && cross_window(project, lane, idx).is_none()) |
| 1999 | .then_some(clip) |
| 2000 | } |
| 2001 | |
| 2002 | /// Whether the picture at `frame` is one a single clip cannot show: the clip on |
| 2003 | /// top has placement keys, or its dissolve partner does. A keyed picture is |
| 2004 | /// composed as a layered one, which places each frame's own placement |
| 2005 | /// ([`LayerFeed::advance`]), so a single clip's span-long transform never has |
| 2006 | /// to stand in for a moving one. |
| 2007 | fn animated_at(project: &Project, frame: u32) -> bool { |
| 2008 | visible_video_lanes(project).into_iter().any(|lane| { |
| 2009 | let Some(idx) = project.lane_clip_at(lane, frame) else { |
| 2010 | return false; |
| 2011 | }; |
| 2012 | if crate::project::clip_animated(&project.lane(lane)[idx]) { |
| 2013 | return true; |
| 2014 | } |
| 2015 | matches!( |
| 2016 | cross_window(project, lane, idx), |
| 2017 | Some((window, start)) if frame >= start && frame - start < window |
| 2018 | ) && project.lane(lane).get(idx + 1).is_some_and(crate::project::clip_animated) |
| 2019 | }) |
| 2020 | } |
| 2021 | |
| 2022 | /// [`Project::composite_span_at`] over the stack. The topmost covering clip |
| 2023 | /// supplies `from` and `speed`, and the span runs until any visible video lane |
| 2024 | /// changes what covers the frame -- a clip there starts or ends. With one |
| 2025 | /// covering clip that is exactly the composite's own span; across a stack it |
| 2026 | /// also cuts where a lower lane changes beneath the picture on top, since the |
| 2027 | /// picture under it is then a different one. |
| 2028 | pub(crate) fn stack_span_at(project: &Project, frame: u32) -> Option<crate::project::Span> { |
| 2029 | let total = project.timeline_frames(); |
| 2030 | if frame >= total { |
| 2031 | return None; |
| 2032 | } |
| 2033 | let mut until = total; |
| 2034 | for lane in visible_video_lanes(project) { |
| 2035 | let clips = project.lane(lane); |
| 2036 | match project.lane_clip_at(lane, frame) { |
| 2037 | Some(idx) => until = until.min(clips[idx].end()), |
| 2038 | None => { |
| 2039 | if let Some(next) = clips.iter().find(|c| c.start > frame) { |
| 2040 | until = until.min(next.start); |
| 2041 | } |
| 2042 | } |
| 2043 | } |
| 2044 | } |
| 2045 | let (from, speed, ramp, reverse) = match stack_at(project, frame).pop() { |
| 2046 | Some((lane, idx)) => { |
| 2047 | let clip = &project.lane(lane)[idx]; |
| 2048 | let (speed, ramp) = crate::project::span_speed_of(clip, frame); |
| 2049 | ( |
| 2050 | Some((clip.source, clip_source_frame(clip, frame))), |
| 2051 | speed, |
| 2052 | ramp, |
| 2053 | clip.reversed, |
| 2054 | ) |
| 2055 | } |
| 2056 | None => (None, Speed::NORMAL, None, false), |
| 2057 | }; |
| 2058 | Some(crate::project::Span { |
| 2059 | start: frame, |
| 2060 | len: until - frame, |
| 2061 | from, |
| 2062 | speed, |
| 2063 | ramp, |
| 2064 | reverse, |
| 2065 | pitch: 0, |
| 2066 | }) |
| 2067 | } |
| 2068 | |
| 2069 | /// [`Project::composite_spans_from`] over the stack: every span from `frame` on. |
| 2070 | pub(crate) fn stack_spans_from(project: &Project, frame: u32) -> Vec<crate::project::Span> { |
| 2071 | let mut out = Vec::new(); |
| 2072 | let mut t = frame; |
| 2073 | while let Some(span) = stack_span_at(project, t) { |
| 2074 | t = span.end(); |
| 2075 | out.push(span); |
| 2076 | } |
| 2077 | out |
| 2078 | } |
| 2079 | |
| 2080 | /// Which source frame a clip plays at timeline `frame` -- the project's own |
| 2081 | /// rule, clamped inside the clip's range. |
| 2082 | fn clip_source_frame(clip: &crate::project::Clip, frame: u32) -> u32 { |
| 2083 | (crate::project::source_pos(clip, frame - clip.start).floor() as u32).min(clip.out_frame - 1) |
| 2084 | } |
| 2085 | |
| 2086 | /// One clip of a layered picture, open for the span: its decoder, read forward |
| 2087 | /// as the picture advances, and the canvas its picture lands on -- the same |
| 2088 | /// placement a single clip gets ([`place_picture`]). |
| 2089 | struct LayerFeed { |
| 2090 | clip: crate::project::Clip, |
| 2091 | info: Placed, |
| 2092 | meta: VideoMeta, |
| 2093 | grade: Option<crate::color::ColorParams>, |
| 2094 | /// The grade the current picture was graded with, so a colour-keyed clip is |
| 2095 | /// graded again the frame its grade moves, even on the same source frame. |
| 2096 | graded_with: Option<crate::color::ColorParams>, |
| 2097 | /// The clip's base placement ([`Clip::transform`] resolved); its keys, when |
| 2098 | /// it has any, are read from `clip` at each frame ([`clip_transform_at`]). |
| 2099 | transform: TransformParams, |
| 2100 | /// The placement the current picture was placed with, so a keyed clip is |
| 2101 | /// placed again the frame its placement moves, even on the same source frame. |
| 2102 | placed_with: TransformParams, |
| 2103 | /// The clip's own opacity ([`TransformParams::opacity`]), applied as its |
| 2104 | /// coverage over the layers beneath rather than in its placement. |
| 2105 | opacity: f32, |
| 2106 | fit_canvas: Composer, |
| 2107 | rotated: Planes, |
| 2108 | stretched: Planes, |
| 2109 | graded: Planes, |
| 2110 | transformed: Planes, |
| 2111 | /// The decoder, and the file frame its next picture is. |
| 2112 | decoder: Option<(ClipDecoder, u32)>, |
| 2113 | /// The placed picture, and the file frame it is of. |
| 2114 | current: Option<(u32, Planes)>, |
| 2115 | /// The same picture composed at 10 bits ([`LayerStack::picture16`]), and the |
| 2116 | /// scratch only that path uses. |
| 2117 | current16: Option<(u32, Planes16)>, |
| 2118 | scratch16: Scratch16, |
| 2119 | widened: Planes16, |
| 2120 | steadied16: Planes16, |
| 2121 | adjusted16: Planes16, |
| 2122 | fx16: crate::effects::Scratch<u16>, |
| 2123 | /// Luma-sized coverage of the placed picture on the canvas: 255 where the |
| 2124 | /// clip's own pixels are, 0 in the letterbox bars and off the canvas. A |
| 2125 | /// layer above lets the one beneath show wherever this is 0. |
| 2126 | cover: Option<Vec<u8>>, |
| 2127 | matrix: Matrix, |
| 2128 | /// The dissolve this clip's tail owes the clip after it on its lane, when |
| 2129 | /// one is set and adjacent ([`cross_window`]). |
| 2130 | cross: Option<Box<LayerCross>>, |
| 2131 | /// The effects stack's scratch, and what it made of the current picture: its |
| 2132 | /// coverage (the placed footprint times the keys and masks) where it has any, |
| 2133 | /// and the mode it is laid down in ([`crate::effects`]). |
| 2134 | fx: crate::effects::Scratch<u8>, |
| 2135 | fx_cover: Option<Vec<u8>>, |
| 2136 | fx_mode: crate::effects::BlendMode, |
| 2137 | /// The clip's stabilisation, once its analysis is cached |
| 2138 | /// ([`crate::stabilise::correction`]): applied to the decoded picture, by its |
| 2139 | /// file frame, before anything else is. |
| 2140 | steady: Option<std::sync::Arc<crate::stabilise::Correction>>, |
| 2141 | steadied: Planes, |
| 2142 | /// The clip's deinterlace setting as it applies to its file. `Field` makes |
| 2143 | /// `info.rate` count fields; stabilisation is measured per file frame, so a |
| 2144 | /// field takes its frame's correction. |
| 2145 | deint: Deinterlace, |
| 2146 | /// An adjustment layer ([`crate::generate`]): no picture, its grade and effects act on the |
| 2147 | /// layers beneath ([`LayerFeed::adjust_over`]). |
| 2148 | adjust: bool, |
| 2149 | /// An adjustment layer's scratch, kept between frames like `steadied`: the placed and |
| 2150 | /// effected copy of the layers beneath, and its coverage. |
| 2151 | adjusted: Planes, |
| 2152 | adjust_cover: Vec<u8>, |
| 2153 | /// A generator with a transparent background ([`crate::generate::Gen::has_alpha`]) and its |
| 2154 | /// alpha at the size last asked for, kept so the mask is drawn once, not per coverage. |
| 2155 | alpha_gen: Option<crate::generate::Gen>, |
| 2156 | alpha_mask: Option<(u32, u32, Vec<u8>)>, |
| 2157 | } |
| 2158 | |
| 2159 | /// The clip a layer's tail dissolves into: its own feed, and the window of |
| 2160 | /// timeline frames the blend runs over, from `start` for `window` frames. |
| 2161 | struct LayerCross { |
| 2162 | next: LayerFeed, |
| 2163 | window: u32, |
| 2164 | start: u32, |
| 2165 | } |
| 2166 | |
| 2167 | /// The dissolve window a clip's tail owes its successor, as [`dissolve_window`] |
| 2168 | /// reads it -- without the span rules, which a layered picture does not have: |
| 2169 | /// it blends wherever its lane is on the clip, whatever is above it. `None` for |
| 2170 | /// a hard cut, a stale transition out (the clips are no longer adjacent), or an |
| 2171 | /// empty window. `(window, start)` in timeline frames. |
| 2172 | fn cross_window(project: &Project, lane: Lane, idx: usize) -> Option<(u32, u32)> { |
| 2173 | let clips = project.lane(lane); |
| 2174 | let a = clips.get(idx)?; |
| 2175 | if a.transition_out == 0 { |
| 2176 | return None; |
| 2177 | } |
| 2178 | let b = clips.get(idx + 1)?; |
| 2179 | if a.end() != b.start { |
| 2180 | return None; |
| 2181 | } |
| 2182 | let window = a.transition_out.min(a.frames()).min(b.frames()); |
| 2183 | (window > 0).then_some((window, a.end() - window)) |
| 2184 | } |
| 2185 | |
| 2186 | impl LayerFeed { |
| 2187 | /// The feed for clip `idx` of `lane`, with the dissolve it owes its |
| 2188 | /// successor opened beside it. `paths`, when given, is the file each source |
| 2189 | /// is decoded from in place of its own (a proxy stand-in), by source index. |
| 2190 | /// `measure`, when given, is the cancel flag a stabilised clip's missing |
| 2191 | /// analysis is run under before this returns ([`crate::stabilise::ensure`]) |
| 2192 | /// and the stage it reports to ([`Shared::measuring`]); `None` takes only a |
| 2193 | /// finished one (the viewer, which shows the analysis's progress and redraws |
| 2194 | /// when it lands). |
| 2195 | fn open( |
| 2196 | project: &Project, |
| 2197 | meta: &VideoMeta, |
| 2198 | lane: Lane, |
| 2199 | idx: usize, |
| 2200 | matrix: Matrix, |
| 2201 | paths: Option<&[PathBuf]>, |
| 2202 | measure: Option<Measure<'_>>, |
| 2203 | ) -> crate::Result<Self> { |
| 2204 | let mut feed = Self::plain(project, meta, lane, idx, matrix, paths, measure)?; |
| 2205 | if let Some((window, start)) = cross_window(project, lane, idx) { |
| 2206 | let next = Self::plain(project, meta, lane, idx + 1, matrix, paths, measure)?; |
| 2207 | feed.cross = Some(Box::new(LayerCross { |
| 2208 | next, |
| 2209 | window, |
| 2210 | start, |
| 2211 | })); |
| 2212 | } |
| 2213 | Ok(feed) |
| 2214 | } |
| 2215 | |
| 2216 | fn plain( |
| 2217 | project: &Project, |
| 2218 | meta: &VideoMeta, |
| 2219 | lane: Lane, |
| 2220 | idx: usize, |
| 2221 | matrix: Matrix, |
| 2222 | paths: Option<&[PathBuf]>, |
| 2223 | measure: Option<Measure<'_>>, |
| 2224 | ) -> crate::Result<Self> { |
| 2225 | let Some(clip) = project.lane(lane).get(idx).cloned() else { |
| 2226 | return Err("a layer names a clip that is not there".into()); |
| 2227 | }; |
| 2228 | let mut info = placed_info(project, meta, clip.source)?; |
| 2229 | if let Some(path) = paths.and_then(|paths| paths.get(clip.source)) { |
| 2230 | info.path = path.clone(); |
| 2231 | } |
| 2232 | // Smoothed at the timeline's rate, as the viewer smooths it, over every |
| 2233 | // file frame the clip plays: an export measures what is missing rather |
| 2234 | // than write the clip unstabilised. |
| 2235 | let steady = match (clip.stabilise, project.sources().get(clip.source)) { |
| 2236 | (Some(st), Some(source)) => { |
| 2237 | let (lo, hi) = crate::stabilise::file_range(&clip, info.rate); |
| 2238 | match measure { |
| 2239 | Some((cancel, stage)) => { |
| 2240 | let mut tell = |f: f32| stage.store(1 + (f.clamp(0.0, 1.0) * 1000.0) as u32, Ordering::Relaxed); |
| 2241 | let c = crate::stabilise::ensure(&source.path, lo, hi, st, meta.frame_rate, &mut tell, cancel); |
| 2242 | stage.store(0, Ordering::Relaxed); |
| 2243 | Some(c?) |
| 2244 | } |
| 2245 | None => crate::stabilise::correction_or_start(&source.path, lo, hi, st, meta.frame_rate), |
| 2246 | } |
| 2247 | } |
| 2248 | _ => None, |
| 2249 | }; |
| 2250 | let deint = crate::deinterlace::effective(clip.deinterlace, &info.path); |
| 2251 | info.rate = crate::deinterlace::counted_rate(deint, info.rate); |
| 2252 | Ok(Self { |
| 2253 | steady, |
| 2254 | steadied: Default::default(), |
| 2255 | deint, |
| 2256 | adjust: crate::generate::is_adjust(&info.path), |
| 2257 | adjusted: Default::default(), |
| 2258 | adjust_cover: Vec::new(), |
| 2259 | alpha_gen: crate::generate::Gen::parse(&info.path).filter(|g| g.has_alpha()), |
| 2260 | alpha_mask: None, |
| 2261 | info, |
| 2262 | meta: *meta, |
| 2263 | grade: project.color_of(lane, idx).copied(), |
| 2264 | graded_with: None, |
| 2265 | // The layer's opacity is its coverage in [`LayerStack::picture`], so |
| 2266 | // the placement below runs at opacity 1: a placed mask at opacity |
| 2267 | // below 1 would fade the coverage it is read for. |
| 2268 | transform: { |
| 2269 | let whole = project.transform_of(lane, idx).copied().unwrap_or_default(); |
| 2270 | TransformParams { |
| 2271 | opacity: 1.0, |
| 2272 | ..whole |
| 2273 | } |
| 2274 | }, |
| 2275 | opacity: project |
| 2276 | .transform_of(lane, idx) |
| 2277 | .map_or(1.0, |t| t.opacity), |
| 2278 | fit_canvas: Composer::new(meta.width, meta.height, project.fit_of(lane, idx)), |
| 2279 | clip, |
| 2280 | rotated: Default::default(), |
| 2281 | stretched: Default::default(), |
| 2282 | graded: Default::default(), |
| 2283 | transformed: Default::default(), |
| 2284 | decoder: None, |
| 2285 | current: None, |
| 2286 | current16: None, |
| 2287 | scratch16: Default::default(), |
| 2288 | widened: Default::default(), |
| 2289 | steadied16: Default::default(), |
| 2290 | adjusted16: Default::default(), |
| 2291 | fx16: Default::default(), |
| 2292 | cover: None, |
| 2293 | placed_with: TransformParams::default(), |
| 2294 | matrix, |
| 2295 | cross: None, |
| 2296 | fx: Default::default(), |
| 2297 | fx_cover: None, |
| 2298 | fx_mode: Default::default(), |
| 2299 | }) |
| 2300 | } |
| 2301 | |
| 2302 | /// The dissolve picture this clip shows at timeline `frame` while its tail |
| 2303 | /// blends into the next clip on its lane: the two placed pictures mixed by |
| 2304 | /// [`dissolve_weight`], and the coverage between the two clips' footprints |
| 2305 | /// mixed the same way. `None` outside the window, and where the next clip's |
| 2306 | /// file ends first -- then this clip's own picture stands, as a single |
| 2307 | /// clip's does. The next clip is read forward as this one is. |
| 2308 | fn cross_at(&mut self, frame: u32) -> crate::Result<Option<(Planes, Vec<u8>)>> { |
| 2309 | let Some(cross) = self.cross.as_mut() else { |
| 2310 | return Ok(None); |
| 2311 | }; |
| 2312 | if frame < cross.start || frame - cross.start >= cross.window { |
| 2313 | return Ok(None); |
| 2314 | } |
| 2315 | // The next clip shows its own picture from its first frame on, as the |
| 2316 | // single clip's dissolve reads it ([`compose_at_with`]): window frame k |
| 2317 | // is its frame k, not the timeline frame, which is before its start. |
| 2318 | let k = frame - cross.start; |
| 2319 | if !cross.next.advance(cross.next.clip.start + k)? { |
| 2320 | return Ok(None); |
| 2321 | } |
| 2322 | let t = dissolve_weight(k, cross.window); |
| 2323 | let a_cover = self.fx_cover.as_deref().or(self.cover.as_deref()); |
| 2324 | let (Some((_, a)), Some(a_cover)) = (self.current.as_ref(), a_cover) else { |
| 2325 | return Ok(None); |
| 2326 | }; |
| 2327 | let b_cover = cross.next.fx_cover.as_deref().or(cross.next.cover.as_deref()); |
| 2328 | let (Some((_, b)), Some(b_cover)) = (cross.next.current.as_ref(), b_cover) |
| 2329 | else { |
| 2330 | return Ok(None); |
| 2331 | }; |
| 2332 | let planes = crate::transitions::blend_planes( |
| 2333 | self.clip.transition_kind, |
| 2334 | (&a.0, &a.1, &a.2), |
| 2335 | (&b.0, &b.1, &b.2), |
| 2336 | t, |
| 2337 | self.meta.width as usize, |
| 2338 | self.meta.height as usize, |
| 2339 | ); |
| 2340 | let cover = a_cover |
| 2341 | .iter() |
| 2342 | .zip(b_cover) |
| 2343 | .map(|(&x, &y)| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8) |
| 2344 | .collect(); |
| 2345 | Ok(Some((planes, cover))) |
| 2346 | } |
| 2347 | |
| 2348 | /// [`LayerFeed::cross_at`] at 10 bits. |
| 2349 | fn cross_at16(&mut self, frame: u32) -> crate::Result<Option<(Planes16, Vec<u8>)>> { |
| 2350 | let Some(cross) = self.cross.as_mut() else { |
| 2351 | return Ok(None); |
| 2352 | }; |
| 2353 | if frame < cross.start || frame - cross.start >= cross.window { |
| 2354 | return Ok(None); |
| 2355 | } |
| 2356 | let k = frame - cross.start; |
| 2357 | if !cross.next.advance16(cross.next.clip.start + k)? { |
| 2358 | return Ok(None); |
| 2359 | } |
| 2360 | let t = dissolve_weight(k, cross.window); |
| 2361 | let a_cover = self.fx_cover.as_deref().or(self.cover.as_deref()); |
| 2362 | let (Some((_, a)), Some(a_cover)) = (self.current16.as_ref(), a_cover) else { |
| 2363 | return Ok(None); |
| 2364 | }; |
| 2365 | let b_cover = cross.next.fx_cover.as_deref().or(cross.next.cover.as_deref()); |
| 2366 | let (Some((_, b)), Some(b_cover)) = (cross.next.current16.as_ref(), b_cover) else { |
| 2367 | return Ok(None); |
| 2368 | }; |
| 2369 | let planes = crate::transitions::blend_planes( |
| 2370 | self.clip.transition_kind, |
| 2371 | (&a.0, &a.1, &a.2), |
| 2372 | (&b.0, &b.1, &b.2), |
| 2373 | t, |
| 2374 | self.meta.width as usize, |
| 2375 | self.meta.height as usize, |
| 2376 | ); |
| 2377 | let cover = a_cover |
| 2378 | .iter() |
| 2379 | .zip(b_cover) |
| 2380 | .map(|(&x, &y)| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8) |
| 2381 | .collect(); |
| 2382 | Ok(Some((planes, cover))) |
| 2383 | } |
| 2384 | |
| 2385 | /// Makes the placed picture for timeline `frame` the current one, reading |
| 2386 | /// the decoder forward to it. `false` when the file ends first. |
| 2387 | fn advance(&mut self, frame: u32) -> crate::Result<bool> { |
| 2388 | self.advance_as(frame, false) |
| 2389 | } |
| 2390 | |
| 2391 | /// [`LayerFeed::advance`] at 10 bits: the placed picture lands in `current16`. |
| 2392 | fn advance16(&mut self, frame: u32) -> crate::Result<bool> { |
| 2393 | self.advance_as(frame, true) |
| 2394 | } |
| 2395 | |
| 2396 | fn advance_as(&mut self, frame: u32, wide: bool) -> crate::Result<bool> { |
| 2397 | let want = self.info.rate.source_at(clip_source_frame(&self.clip, frame)); |
| 2398 | // Coverage is the layer's own (see `LayerFeed::picture`), so the placement |
| 2399 | // runs at opacity 1 whatever the keys say. |
| 2400 | let tf = TransformParams { |
| 2401 | opacity: 1.0, |
| 2402 | ..crate::project::clip_transform_at(&self.clip, self.transform, frame) |
| 2403 | }; |
| 2404 | // A colour-keyed clip's grade moves with the frame ([`clip_color_at`]). |
| 2405 | let grade = match self.clip.color_keys.is_empty() { |
| 2406 | true => self.grade, |
| 2407 | false => Some(crate::project::clip_color_at( |
| 2408 | &self.clip, |
| 2409 | self.grade.unwrap_or_default(), |
| 2410 | frame, |
| 2411 | )), |
| 2412 | }; |
| 2413 | let have = match wide { |
| 2414 | true => self.current16.as_ref().map(|(at, _)| *at), |
| 2415 | false => self.current.as_ref().map(|(at, _)| *at), |
| 2416 | }; |
| 2417 | if have == Some(want) |
| 2418 | && self.placed_with == tf |
| 2419 | && self.graded_with == grade |
| 2420 | && !crate::effects::animated(&self.clip.effects) |
| 2421 | { |
| 2422 | return Ok(true); |
| 2423 | } |
| 2424 | // A decoder that has read past the picture wanted is reopened at it; |
| 2425 | // playback and export only ever move forward through a span -- down it, |
| 2426 | // for a reversed clip, whose decoder counts the file frame it is on |
| 2427 | // downwards. |
| 2428 | let backwards = self.clip.reversed; |
| 2429 | let behind = matches!(&self.decoder, Some((_, pos)) if match backwards { |
| 2430 | true => *pos < want, |
| 2431 | false => *pos > want, |
| 2432 | }); |
| 2433 | if self.decoder.is_none() || behind { |
| 2434 | let path = self.info.path.clone(); |
| 2435 | let flags = self.clip.visualizer; |
| 2436 | let decoder = if crate::is_audio(&path) || flags & 1 != 0 { |
| 2437 | ClipDecoder::visualizer( |
| 2438 | &path, |
| 2439 | self.info.stream, |
| 2440 | want, |
| 2441 | (self.meta.width, self.meta.height), |
| 2442 | self.meta.frame_rate, |
| 2443 | flags, |
| 2444 | self.clip.viz_paint, |
| 2445 | )? |
| 2446 | } else if backwards && !crate::is_image(&path) { |
| 2447 | ClipDecoder::reversed(&path, want, self.info.rate.source_at(self.clip.in_frame), self.deint) |
| 2448 | } else { |
| 2449 | ClipDecoder::open_with(&path, want, None, None, wide, self.deint)? |
| 2450 | }; |
| 2451 | self.decoder = Some((decoder, want)); |
| 2452 | } |
| 2453 | let (decoder, pos) = self.decoder.as_mut().expect("opened above"); |
| 2454 | while match backwards { |
| 2455 | true => *pos > want, |
| 2456 | false => *pos < want, |
| 2457 | } { |
| 2458 | if decoder.next()?.is_none() { |
| 2459 | return Ok(false); |
| 2460 | } |
| 2461 | *pos = if backwards { *pos - 1 } else { *pos + 1 }; |
| 2462 | } |
| 2463 | let Some(picture) = decoder.next()? else { |
| 2464 | return Ok(false); |
| 2465 | }; |
| 2466 | *pos = if backwards { pos.saturating_sub(1) } else { *pos + 1 }; |
| 2467 | if wide { |
| 2468 | let (y, u, v, w, h): (&[u16], &[u16], &[u16], u32, u32) = match picture { |
| 2469 | Frame::Wide(y, u, v, w, h) => (y, u, v, w, h), |
| 2470 | Frame::Pixels(y, u, v, w, h) => { |
| 2471 | widen_into(y, &mut self.widened.0); |
| 2472 | widen_into(u, &mut self.widened.1); |
| 2473 | widen_into(v, &mut self.widened.2); |
| 2474 | (&self.widened.0[..], &self.widened.1[..], &self.widened.2[..], w, h) |
| 2475 | } |
| 2476 | Frame::Dma(_) => return Err("a layer's decoder produced no pixels".into()), |
| 2477 | }; |
| 2478 | let (y, u, v) = match &self.steady { |
| 2479 | Some(c) => { |
| 2480 | let m = c.at(crate::deinterlace::file_frame(self.deint, &self.info.path, want), w).ok_or_else(|| -> crate::Error { |
| 2481 | format!("stabilise: file frame {want} lies before the measured range").into() |
| 2482 | })?; |
| 2483 | crate::stabilise::warp_i420(y, u, v, w, h, m, &mut self.steadied16); |
| 2484 | (&self.steadied16.0[..], &self.steadied16.1[..], &self.steadied16.2[..]) |
| 2485 | } |
| 2486 | None => (y, u, v), |
| 2487 | }; |
| 2488 | let remap = remap_into(Some(self.info.color), self.info.mapper.is_some(), self.matrix); |
| 2489 | let (py, pu, pv, pw, ph) = place_picture16( |
| 2490 | y, |
| 2491 | u, |
| 2492 | v, |
| 2493 | w, |
| 2494 | h, |
| 2495 | self.info.rotation, |
| 2496 | self.info.pixel_aspect, |
| 2497 | grade, |
| 2498 | tf, |
| 2499 | remap, |
| 2500 | self.info.mapper.as_ref(), |
| 2501 | &mut self.scratch16, |
| 2502 | &mut self.fit_canvas, |
| 2503 | ); |
| 2504 | let mut planes = (py.to_vec(), pu.to_vec(), pv.to_vec()); |
| 2505 | if self.cover.is_none() || self.placed_with != tf { |
| 2506 | self.cover = Some(self.coverage(w, h, tf)); |
| 2507 | } |
| 2508 | debug_assert_eq!((pw, ph), (self.meta.width, self.meta.height), "a placed layer is canvas-sized"); |
| 2509 | let secs = f64::from(frame) / self.meta.frame_rate; |
| 2510 | let src = crate::project::key_sample_pos(&self.clip, frame); |
| 2511 | let (mode, fx_cover) = layer_effects( |
| 2512 | &self.clip.effects, |
| 2513 | &mut planes, |
| 2514 | (pw, ph), |
| 2515 | secs, |
| 2516 | src, |
| 2517 | self.matrix, |
| 2518 | &mut self.fx16, |
| 2519 | self.cover.as_deref().expect("set above"), |
| 2520 | ); |
| 2521 | self.fx_mode = mode; |
| 2522 | self.fx_cover = fx_cover; |
| 2523 | self.placed_with = tf; |
| 2524 | self.graded_with = grade; |
| 2525 | self.current16 = Some((want, planes)); |
| 2526 | return Ok(true); |
| 2527 | } |
| 2528 | let Frame::Pixels(y, u, v, w, h) = picture else { |
| 2529 | return Err("a layer's decoder produced no pixels".into()); |
| 2530 | }; |
| 2531 | let (y, u, v) = match &self.steady { |
| 2532 | Some(c) => { |
| 2533 | let m = c.at(crate::deinterlace::file_frame(self.deint, &self.info.path, want), w).ok_or_else(|| -> crate::Error { |
| 2534 | format!("stabilise: file frame {want} lies before the measured range").into() |
| 2535 | })?; |
| 2536 | crate::stabilise::warp_i420(y, u, v, w, h, m, &mut self.steadied); |
| 2537 | (&self.steadied.0[..], &self.steadied.1[..], &self.steadied.2[..]) |
| 2538 | } |
| 2539 | None => (y, u, v), |
| 2540 | }; |
| 2541 | let remap = remap_into( |
| 2542 | Some(self.info.color), |
| 2543 | self.info.mapper.is_some(), |
| 2544 | self.matrix, |
| 2545 | ); |
| 2546 | let (py, pu, pv, pw, ph) = place_picture( |
| 2547 | y, |
| 2548 | u, |
| 2549 | v, |
| 2550 | w, |
| 2551 | h, |
| 2552 | self.info.rotation, |
| 2553 | self.info.pixel_aspect, |
| 2554 | grade, |
| 2555 | tf, |
| 2556 | remap, |
| 2557 | self.info.mapper.as_ref(), |
| 2558 | &mut self.rotated, |
| 2559 | &mut self.stretched, |
| 2560 | &mut self.graded, |
| 2561 | &mut self.transformed, |
| 2562 | &mut self.fit_canvas, |
| 2563 | ); |
| 2564 | let mut planes = (py.to_vec(), pu.to_vec(), pv.to_vec()); |
| 2565 | if self.cover.is_none() || self.placed_with != tf { |
| 2566 | self.cover = Some(self.coverage(w, h, tf)); |
| 2567 | } |
| 2568 | // The effects stack, on the placed picture: its filters rewrite the |
| 2569 | // samples, and its keys and masks narrow the footprint it lands with. |
| 2570 | debug_assert_eq!((pw, ph), (self.meta.width, self.meta.height), "a placed layer is canvas-sized"); |
| 2571 | let secs = f64::from(frame) / self.meta.frame_rate; |
| 2572 | let src = crate::project::key_sample_pos(&self.clip, frame); |
| 2573 | let (mode, fx_cover) = layer_effects( |
| 2574 | &self.clip.effects, |
| 2575 | &mut planes, |
| 2576 | (pw, ph), |
| 2577 | secs, |
| 2578 | src, |
| 2579 | self.matrix, |
| 2580 | &mut self.fx, |
| 2581 | self.cover.as_deref().expect("set above"), |
| 2582 | ); |
| 2583 | self.fx_mode = mode; |
| 2584 | self.fx_cover = fx_cover; |
| 2585 | self.placed_with = tf; |
| 2586 | self.graded_with = grade; |
| 2587 | self.current = Some((want, planes)); |
| 2588 | Ok(true) |
| 2589 | } |
| 2590 | |
| 2591 | /// The layers composed so far, `base`, with this adjustment layer's grade, placement and |
| 2592 | /// effects applied to them, at strength `k` (its fade times its opacity). |
| 2593 | /// |
| 2594 | /// The clip's transform moves the composite below it (as Motion on an adjustment layer does |
| 2595 | /// in Premiere), so what the placement uncovers -- a shrunk, shifted or rotated composite -- |
| 2596 | /// goes black. Crop is different: the layer only reaches where its crop footprint |
| 2597 | /// ([`LayerFeed::coverage`], placement left out) is, so a cropped-away region keeps the base. |
| 2598 | fn adjust_over(&mut self, base: Planes, k: f32, frame: u32) -> Planes { |
| 2599 | let (w, h) = (self.meta.width, self.meta.height); |
| 2600 | let grade = match self.clip.color_keys.is_empty() { |
| 2601 | true => self.grade, |
| 2602 | false => Some(crate::project::clip_color_at(&self.clip, self.grade.unwrap_or_default(), frame)), |
| 2603 | }; |
| 2604 | let tf = TransformParams { opacity: 1.0, ..crate::project::clip_transform_at(&self.clip, self.transform, frame) }; |
| 2605 | let (py, pu, pv, _, _) = place_picture( |
| 2606 | &base.0, &base.1, &base.2, w, h, Rotation::None, crate::demux::PixelAspect::SQUARE, grade, tf, None, None, |
| 2607 | &mut self.rotated, &mut self.stretched, &mut self.graded, &mut self.transformed, &mut self.fit_canvas, |
| 2608 | ); |
| 2609 | let mut adjusted = std::mem::take(&mut self.adjusted); |
| 2610 | for (dst, src) in [(&mut adjusted.0, py), (&mut adjusted.1, pu), (&mut adjusted.2, pv)] { |
| 2611 | dst.clear(); |
| 2612 | dst.extend_from_slice(src); |
| 2613 | } |
| 2614 | let mut cover = std::mem::take(&mut self.adjust_cover); |
| 2615 | cover.clear(); |
| 2616 | // Only the crop limits the layer: the placement moved the composite itself, and |
| 2617 | // what it uncovers is the black of its own fit bars. |
| 2618 | // With crop and a transform together the crop footprint stays at the identity |
| 2619 | // position while the picture moves: the crop limits where the layer acts, not what moves. |
| 2620 | 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() }; |
| 2621 | match crop == TransformParams::default() { |
| 2622 | true => cover.resize(w as usize * h as usize, 255), |
| 2623 | false => cover.extend(self.coverage(w, h, crop)), |
| 2624 | } |
| 2625 | if crate::effects::active(&self.clip.effects) { |
| 2626 | let out = crate::effects::apply( |
| 2627 | &self.clip.effects, |
| 2628 | (&mut adjusted.0, &mut adjusted.1, &mut adjusted.2), |
| 2629 | w as usize, |
| 2630 | h as usize, |
| 2631 | f64::from(frame) / self.meta.frame_rate, |
| 2632 | crate::project::key_sample_pos(&self.clip, frame), |
| 2633 | self.matrix, |
| 2634 | &mut self.fx, |
| 2635 | ); |
| 2636 | if let Some(alpha) = out.alpha { |
| 2637 | for (c, a) in cover.iter_mut().zip(alpha) { |
| 2638 | *c = ((u32::from(*c) * u32::from(a) + 127) / 255) as u8; |
| 2639 | } |
| 2640 | } |
| 2641 | } |
| 2642 | let mut result = base; |
| 2643 | layer_over(&mut result, &adjusted, &cover, k, w as usize, h as usize); |
| 2644 | self.adjusted = adjusted; |
| 2645 | self.adjust_cover = cover; |
| 2646 | result |
| 2647 | } |
| 2648 | |
| 2649 | /// [`LayerFeed::adjust_over`] at 10 bits. |
| 2650 | fn adjust_over16(&mut self, base: Planes16, k: f32, frame: u32) -> Planes16 { |
| 2651 | let (w, h) = (self.meta.width, self.meta.height); |
| 2652 | let grade = match self.clip.color_keys.is_empty() { |
| 2653 | true => self.grade, |
| 2654 | false => Some(crate::project::clip_color_at(&self.clip, self.grade.unwrap_or_default(), frame)), |
| 2655 | }; |
| 2656 | let tf = TransformParams { opacity: 1.0, ..crate::project::clip_transform_at(&self.clip, self.transform, frame) }; |
| 2657 | let (py, pu, pv, _, _) = place_picture16( |
| 2658 | &base.0, &base.1, &base.2, w, h, Rotation::None, crate::demux::PixelAspect::SQUARE, grade, tf, None, None, |
| 2659 | &mut self.scratch16, &mut self.fit_canvas, |
| 2660 | ); |
| 2661 | let mut adjusted = std::mem::take(&mut self.adjusted16); |
| 2662 | for (dst, src) in [(&mut adjusted.0, py), (&mut adjusted.1, pu), (&mut adjusted.2, pv)] { |
| 2663 | dst.clear(); |
| 2664 | dst.extend_from_slice(src); |
| 2665 | } |
| 2666 | let mut cover = std::mem::take(&mut self.adjust_cover); |
| 2667 | cover.clear(); |
| 2668 | 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() }; |
| 2669 | match crop == TransformParams::default() { |
| 2670 | true => cover.resize(w as usize * h as usize, 255), |
| 2671 | false => cover.extend(self.coverage(w, h, crop)), |
| 2672 | } |
| 2673 | if crate::effects::active(&self.clip.effects) { |
| 2674 | let out = crate::effects::apply( |
| 2675 | &self.clip.effects, |
| 2676 | (&mut adjusted.0, &mut adjusted.1, &mut adjusted.2), |
| 2677 | w as usize, |
| 2678 | h as usize, |
| 2679 | f64::from(frame) / self.meta.frame_rate, |
| 2680 | crate::project::key_sample_pos(&self.clip, frame), |
| 2681 | self.matrix, |
| 2682 | &mut self.fx16, |
| 2683 | ); |
| 2684 | if let Some(alpha) = out.alpha { |
| 2685 | for (c, a) in cover.iter_mut().zip(alpha) { |
| 2686 | *c = ((u32::from(*c) * u32::from(a) + 127) / 255) as u8; |
| 2687 | } |
| 2688 | } |
| 2689 | } |
| 2690 | let mut result = base; |
| 2691 | layer_over(&mut result, &adjusted, &cover, k, w as usize, h as usize); |
| 2692 | self.adjusted16 = adjusted; |
| 2693 | self.adjust_cover = cover; |
| 2694 | result |
| 2695 | } |
| 2696 | |
| 2697 | /// Where a `w` x `h` picture of this clip lands on the canvas, as luma: the |
| 2698 | /// same placement, run on a picture that is white everywhere, so the cover |
| 2699 | /// is exactly the placed picture's footprint -- transform, crop, fit bars |
| 2700 | /// and all -- without a second copy of that geometry to keep in step. |
| 2701 | fn coverage(&mut self, w: u32, h: u32, transform: TransformParams) -> Vec<u8> { |
| 2702 | // A generator with a transparent background ([`crate::generate::Gen::has_alpha`]) places |
| 2703 | // its alpha as the luma (limited range, so the fit bars are 0) and is covered by degree. |
| 2704 | // The mask is drawn at the picture's own size, so a canvas that is not the generator's |
| 2705 | // still gets a shape, not the full frame. It reaches `place_picture` as plain luma with |
| 2706 | // no grade, remap or tonemap (all `None` below): only geometry and resampling touch it. |
| 2707 | if let Some(g) = self.alpha_gen |
| 2708 | && !matches!(&self.alpha_mask, Some((mw, mh, _)) if (*mw, *mh) == (w, h)) |
| 2709 | { |
| 2710 | let mask = crate::generate::Gen::new(g.kind, w, h).alpha().expect("an alpha generator has a mask"); |
| 2711 | self.alpha_mask = Some((w, h, mask)); |
| 2712 | } |
| 2713 | let alpha = self.alpha_gen.and(self.alpha_mask.as_ref()).map(|(_, _, m)| m); |
| 2714 | let ones: Vec<u8> = match alpha { |
| 2715 | Some(a) => a.iter().map(|&v| 16 + (u32::from(v) * 219 / 255) as u8).collect(), |
| 2716 | None => vec![255u8; w as usize * h as usize], |
| 2717 | }; |
| 2718 | let chroma = vec![128u8; w.div_ceil(2) as usize * h.div_ceil(2) as usize]; |
| 2719 | let (cy, _, _, _, _) = place_picture( |
| 2720 | &ones, |
| 2721 | &chroma, |
| 2722 | &chroma, |
| 2723 | w, |
| 2724 | h, |
| 2725 | self.info.rotation, |
| 2726 | self.info.pixel_aspect, |
| 2727 | None, |
| 2728 | transform, |
| 2729 | None, |
| 2730 | None, |
| 2731 | &mut self.rotated, |
| 2732 | &mut self.stretched, |
| 2733 | &mut self.graded, |
| 2734 | &mut self.transformed, |
| 2735 | &mut self.fit_canvas, |
| 2736 | ); |
| 2737 | match alpha.is_some() { |
| 2738 | true => cy.iter().map(|&p| ((u32::from(p.clamp(16, 235)) - 16) * 255 / 219) as u8).collect(), |
| 2739 | false => cy.iter().map(|&p| if p >= 128 { 255 } else { 0 }).collect(), |
| 2740 | } |
| 2741 | } |
| 2742 | } |
| 2743 | |
| 2744 | /// A layer's effects stack drawn on its placed picture `planes` (a canvas of `size`): the |
| 2745 | /// blend mode it lands in and the coverage its keys and masks leave of `cover`, `None` where |
| 2746 | /// it has no effects (or none that cut the footprint). Generic over the sample so the 8-bit |
| 2747 | /// and the 10-bit layer paths draw one stack the same way. |
| 2748 | #[allow(clippy::too_many_arguments)] |
| 2749 | fn layer_effects<T: crate::scale::Sample>( |
| 2750 | effects: &[crate::effects::Effect], |
| 2751 | planes: &mut Planes<T>, |
| 2752 | size: (u32, u32), |
| 2753 | secs: f64, |
| 2754 | src: f64, |
| 2755 | matrix: Matrix, |
| 2756 | scratch: &mut crate::effects::Scratch<T>, |
| 2757 | cover: &[u8], |
| 2758 | ) -> (crate::effects::BlendMode, Option<Vec<u8>>) { |
| 2759 | if !crate::effects::active(effects) { |
| 2760 | return (Default::default(), None); |
| 2761 | } |
| 2762 | let out = crate::effects::apply( |
| 2763 | effects, |
| 2764 | (&mut planes.0, &mut planes.1, &mut planes.2), |
| 2765 | size.0 as usize, |
| 2766 | size.1 as usize, |
| 2767 | secs, |
| 2768 | src, |
| 2769 | matrix, |
| 2770 | scratch, |
| 2771 | ); |
| 2772 | let fx_cover = out.alpha.map(|alpha| { |
| 2773 | debug_assert_eq!(cover.len(), alpha.len(), "the cover and the effects' alpha are one size"); |
| 2774 | cover |
| 2775 | .iter() |
| 2776 | .zip(alpha) |
| 2777 | .map(|(&c, a)| ((u32::from(c) * u32::from(a) + 127) / 255) as u8) |
| 2778 | .collect() |
| 2779 | }); |
| 2780 | (out.mode, fx_cover) |
| 2781 | } |
| 2782 | |
| 2783 | /// A layered picture's clips, open together: read forward by timeline frame and |
| 2784 | /// composed bottom to top ([`LayerStack::picture`]). |
| 2785 | pub(crate) struct LayerStack { |
| 2786 | feeds: Vec<LayerFeed>, |
| 2787 | width: usize, |
| 2788 | height: usize, |
| 2789 | } |
| 2790 | |
| 2791 | impl LayerStack { |
| 2792 | /// The clips of `stack` ([`stack_at`]) on a `meta`-sized canvas, colour |
| 2793 | /// converted with `matrix`, decoded from `paths` where given (see |
| 2794 | /// [`LayerFeed::open`]). Nothing is decoded until a frame is asked for. |
| 2795 | pub(crate) fn open( |
| 2796 | project: &Project, |
| 2797 | meta: &VideoMeta, |
| 2798 | stack: &[(Lane, usize)], |
| 2799 | matrix: Matrix, |
| 2800 | paths: Option<&[PathBuf]>, |
| 2801 | measure: Option<Measure<'_>>, |
| 2802 | ) -> crate::Result<Self> { |
| 2803 | let feeds = stack |
| 2804 | .iter() |
| 2805 | .map(|&(lane, idx)| LayerFeed::open(project, meta, lane, idx, matrix, paths, measure)) |
| 2806 | .collect::<crate::Result<Vec<_>>>()?; |
| 2807 | Ok(Self { |
| 2808 | feeds, |
| 2809 | width: meta.width as usize, |
| 2810 | height: meta.height as usize, |
| 2811 | }) |
| 2812 | } |
| 2813 | |
| 2814 | /// The composed I420 picture at timeline `frame`, or `None` once a clip's |
| 2815 | /// file ends before it. The bottom clip is drawn exactly as a single clip |
| 2816 | /// is (its bars black); each clip above lands on it where its own picture |
| 2817 | /// covers, at its own fade -- so a fade on a picture on top shows the one |
| 2818 | /// beneath through it, rather than fading the whole frame. A clip whose |
| 2819 | /// tail is dissolving into the next clip on its lane shows the blend of the |
| 2820 | /// two over the window ([`LayerFeed::cross_at`]), and the layers above |
| 2821 | /// composite over that -- so a dissolve under a picture-in-picture blends |
| 2822 | /// the same as one without it. |
| 2823 | pub(crate) fn picture(&mut self, frame: u32) -> crate::Result<Option<Planes>> { |
| 2824 | let (w, h) = (self.width, self.height); |
| 2825 | let mut out: Option<Planes> = None; |
| 2826 | for feed in &mut self.feeds { |
| 2827 | if !feed.adjust && !feed.advance(frame)? { |
| 2828 | return Ok(None); |
| 2829 | } |
| 2830 | // The fade and the opacity both scale this layer's coverage. |
| 2831 | let opacity = crate::project::clip_transform_at( |
| 2832 | &feed.clip, |
| 2833 | TransformParams { |
| 2834 | opacity: feed.opacity, |
| 2835 | ..TransformParams::default() |
| 2836 | }, |
| 2837 | frame, |
| 2838 | ) |
| 2839 | .opacity; |
| 2840 | let opacity = crate::project::clip_opacity_at(&feed.clip, opacity, frame); |
| 2841 | let k = clip_fade(&feed.clip, frame).unwrap_or(1.0) * opacity; |
| 2842 | // An adjustment layer with nothing beneath it is a no-op. Adjacent adjustment clips |
| 2843 | // hard-cut: `cross_at` is skipped for them, so a dissolve between two does nothing. |
| 2844 | if feed.adjust { |
| 2845 | out = out.take().map(|base| feed.adjust_over(base, k, frame)); |
| 2846 | continue; |
| 2847 | } |
| 2848 | let blended = feed.cross_at(frame)?; |
| 2849 | let (planes, cover): (&Planes, &[u8]) = match blended.as_ref() { |
| 2850 | Some((planes, cover)) => (planes, cover.as_slice()), |
| 2851 | None => { |
| 2852 | let Some((_, planes)) = feed.current.as_ref() else { |
| 2853 | return Ok(None); |
| 2854 | }; |
| 2855 | let cover = feed.fx_cover.as_deref().or(feed.cover.as_deref()); |
| 2856 | (planes, cover.expect("set with the picture")) |
| 2857 | } |
| 2858 | }; |
| 2859 | // A clip whose effects key, mask or blend it is laid over what is |
| 2860 | // beneath -- black, at the bottom -- by [`crate::effects::blend_over`]. |
| 2861 | let mode = feed.fx_mode; |
| 2862 | if feed.fx_cover.is_some() || mode != crate::effects::BlendMode::Normal { |
| 2863 | let base = out.get_or_insert_with(|| crate::scale::black_i420(w, h)); |
| 2864 | crate::effects::blend_over( |
| 2865 | (&mut base.0, &mut base.1, &mut base.2), |
| 2866 | borrow_planes(planes), |
| 2867 | cover, |
| 2868 | k, |
| 2869 | mode, |
| 2870 | feed.matrix, |
| 2871 | w, |
| 2872 | h, |
| 2873 | ); |
| 2874 | continue; |
| 2875 | } |
| 2876 | // A picture with a transparent background lands on black, as the bottom layer does. |
| 2877 | if out.is_none() && feed.alpha_gen.is_some() { |
| 2878 | out = Some(crate::scale::black_i420(w, h)); |
| 2879 | } |
| 2880 | match out.as_mut() { |
| 2881 | // The bottom layer sits on black, as a single clip does. |
| 2882 | None => { |
| 2883 | out = Some(match k < 1.0 { |
| 2884 | true => fade_planes(borrow_planes(planes), k), |
| 2885 | false => planes.clone(), |
| 2886 | }); |
| 2887 | } |
| 2888 | Some(base) => layer_over(base, planes, cover, k, w, h), |
| 2889 | } |
| 2890 | } |
| 2891 | // Nothing drew (a stack of adjustment layers alone) is a gap: black. |
| 2892 | Ok(Some(out.unwrap_or_else(|| crate::scale::black_i420(w, h)))) |
| 2893 | } |
| 2894 | |
| 2895 | /// [`LayerStack::picture`] at 10 bits: 10-bit layers keep every sample, 8-bit ones are |
| 2896 | /// widened where they meet, and the grade, the placement, the blends and the effects all |
| 2897 | /// run on 10-bit codes. |
| 2898 | pub(crate) fn picture16(&mut self, frame: u32) -> crate::Result<Option<Planes16>> { |
| 2899 | let (w, h) = (self.width, self.height); |
| 2900 | let mut out: Option<Planes16> = None; |
| 2901 | for feed in &mut self.feeds { |
| 2902 | if !feed.adjust && !feed.advance16(frame)? { |
| 2903 | return Ok(None); |
| 2904 | } |
| 2905 | let opacity = crate::project::clip_transform_at( |
| 2906 | &feed.clip, |
| 2907 | TransformParams { |
| 2908 | opacity: feed.opacity, |
| 2909 | ..TransformParams::default() |
| 2910 | }, |
| 2911 | frame, |
| 2912 | ) |
| 2913 | .opacity; |
| 2914 | let opacity = crate::project::clip_opacity_at(&feed.clip, opacity, frame); |
| 2915 | let k = clip_fade(&feed.clip, frame).unwrap_or(1.0) * opacity; |
| 2916 | if feed.adjust { |
| 2917 | out = out.take().map(|base| feed.adjust_over16(base, k, frame)); |
| 2918 | continue; |
| 2919 | } |
| 2920 | let blended = feed.cross_at16(frame)?; |
| 2921 | let (planes, cover): (&Planes16, &[u8]) = match blended.as_ref() { |
| 2922 | Some((planes, cover)) => (planes, cover.as_slice()), |
| 2923 | None => { |
| 2924 | let Some((_, planes)) = feed.current16.as_ref() else { |
| 2925 | return Ok(None); |
| 2926 | }; |
| 2927 | let cover = feed.fx_cover.as_deref().or(feed.cover.as_deref()); |
| 2928 | (planes, cover.expect("set with the picture")) |
| 2929 | } |
| 2930 | }; |
| 2931 | let mode = feed.fx_mode; |
| 2932 | if feed.fx_cover.is_some() || mode != crate::effects::BlendMode::Normal { |
| 2933 | let base = out.get_or_insert_with(|| crate::scale::black_i420_wide(w, h)); |
| 2934 | crate::effects::blend_over( |
| 2935 | (&mut base.0, &mut base.1, &mut base.2), |
| 2936 | borrow_planes(planes), |
| 2937 | cover, |
| 2938 | k, |
| 2939 | mode, |
| 2940 | feed.matrix, |
| 2941 | w, |
| 2942 | h, |
| 2943 | ); |
| 2944 | continue; |
| 2945 | } |
| 2946 | if out.is_none() && feed.alpha_gen.is_some() { |
| 2947 | out = Some(crate::scale::black_i420_wide(w, h)); |
| 2948 | } |
| 2949 | match out.as_mut() { |
| 2950 | None => { |
| 2951 | out = Some(match k < 1.0 { |
| 2952 | true => fade_planes(borrow_planes(planes), k), |
| 2953 | false => planes.clone(), |
| 2954 | }); |
| 2955 | } |
| 2956 | Some(base) => layer_over(base, planes, cover, k, w, h), |
| 2957 | } |
| 2958 | } |
| 2959 | Ok(Some(out.unwrap_or_else(|| crate::scale::black_i420_wide(w, h)))) |
| 2960 | } |
| 2961 | } |
| 2962 | |
| 2963 | /// `top` laid over `base` where `cover` says the picture is, at strength `k` |
| 2964 | /// (its fade times 1). Luma takes each sample's own coverage; chroma takes the |
| 2965 | /// coverage of the luma sample at its block's top left. |
| 2966 | fn layer_over<T: crate::scale::Sample>(base: &mut Planes<T>, top: &Planes<T>, cover: &[u8], k: f32, w: usize, h: usize) { |
| 2967 | let mix = |b: T, t: T, a: f32| { |
| 2968 | let (b, t) = (b.code() as f32, t.code() as f32); |
| 2969 | T::from_f32(b + (t - b) * a) |
| 2970 | }; |
| 2971 | for (i, (b, &t)) in base.0.iter_mut().zip(&top.0).enumerate() { |
| 2972 | let a = f32::from(cover[i]) / 255.0 * k; |
| 2973 | if a > 0.0 { |
| 2974 | *b = mix(*b, t, a); |
| 2975 | } |
| 2976 | } |
| 2977 | let cw = w.div_ceil(2); |
| 2978 | for i in 0..cw * h.div_ceil(2) { |
| 2979 | let (cx, cy) = (i % cw, i / cw); |
| 2980 | let a = f32::from(cover[2 * cy * w + 2 * cx]) / 255.0 * k; |
| 2981 | if a > 0.0 { |
| 2982 | base.1[i] = mix(base.1[i], top.1[i], a); |
| 2983 | base.2[i] = mix(base.2[i], top.2[i], a); |
| 2984 | } |
| 2985 | } |
| 2986 | } |
| 2987 | |
| 2988 | /// A layered span as a playback stream: its composed frames, one per picture |
| 2989 | /// change, decoded on a thread of their own. Each is `view`-sized and numbered |
| 2990 | /// the way a decoder numbers its pictures -- the span's first source frame plus |
| 2991 | /// the speed's step -- so the playback clock maps it like any other clip. |
| 2992 | pub(crate) fn layered_stream( |
| 2993 | project: Project, |
| 2994 | view: VideoMeta, |
| 2995 | out_color: ColorDescription, |
| 2996 | span: crate::project::Span, |
| 2997 | paths: Option<Vec<PathBuf>>, |
| 2998 | ) -> crate::decode::FrameStream { |
| 2999 | let stack = stack_at(&project, span.start); |
| 3000 | let base = span.from.map_or(0, |(_, in_frame)| in_frame); |
| 3001 | crate::decode::DecodeSession::spawn_stream( |
| 3002 | "layers", |
| 3003 | crate::decode::Backend::Software, |
| 3004 | move |tx, cancel| { |
| 3005 | let Ok(mut layers) = |
| 3006 | LayerStack::open(&project, &view, &stack, out_color.matrix, paths.as_deref(), None) |
| 3007 | else { |
| 3008 | return; |
| 3009 | }; |
| 3010 | let mut last = None; |
| 3011 | for offset in 0..span.len { |
| 3012 | if cancel.load(Ordering::Relaxed) { |
| 3013 | return; |
| 3014 | } |
| 3015 | // One picture per source step, as a decoder yields one per frame: |
| 3016 | // a slowed clip's repeats are held by the clock, not decoded again. |
| 3017 | let step = span.source_offset(offset); |
| 3018 | if last == Some(step) { |
| 3019 | continue; |
| 3020 | } |
| 3021 | last = Some(step); |
| 3022 | let Ok(Some((y, u, v))) = layers.picture(span.start + offset) else { |
| 3023 | return; |
| 3024 | }; |
| 3025 | let bgra = crate::convert::i420_to_bgra( |
| 3026 | &out_color, |
| 3027 | &y, |
| 3028 | &u, |
| 3029 | &v, |
| 3030 | view.width as usize, |
| 3031 | view.height as usize, |
| 3032 | ); |
| 3033 | let frame = crate::decode::Frame { |
| 3034 | index: base + step, |
| 3035 | width: view.width, |
| 3036 | height: view.height, |
| 3037 | bgra, |
| 3038 | }; |
| 3039 | if tx.send(frame).is_err() { |
| 3040 | return; |
| 3041 | } |
| 3042 | } |
| 3043 | }, |
| 3044 | ) |
| 3045 | } |
| 3046 | |
| 3047 | /// The cross-dissolve this span's tail owes its successor, or `None` for a |
| 3048 | /// hard cut. `(b_source, b_in_frame, window, b_start)`: which source and |
| 3049 | /// source frame the dissolve's B side starts reading, how many *output* |
| 3050 | /// frames the blend ramps across, and where B sits on the timeline (which is |
| 3051 | /// what its own grade and fit are keyed on, [`Project::composite_color_at`] |
| 3052 | /// and [`Project::composite_fit_at`]). |
| 3053 | /// |
| 3054 | /// [`Clip::transition_out`] is trusted only after adjacency is checked again |
| 3055 | /// here: a trim or a split since it was set leaves the stored number in |
| 3056 | /// place but not its meaning, so a stale one plays as the hard cut it now |
| 3057 | /// is rather than as a dissolve into a clip that no longer follows. |
| 3058 | pub(crate) fn dissolve_window( |
| 3059 | project: &Project, |
| 3060 | span: &crate::project::Span, |
| 3061 | ) -> Option<(usize, u32, u32, u32)> { |
| 3062 | // A layered picture is composed beneath its top clip, and a dissolve of that |
| 3063 | // clip would blend a picture of one clip alone -- the layers are not blended. |
| 3064 | if layered_at(project, span.start) { |
| 3065 | return None; |
| 3066 | } |
| 3067 | let (source, _) = span.from?; |
| 3068 | let (lane, idx) = project.composite_clip_at(span.start)?; |
| 3069 | let clips = project.lane(lane); |
| 3070 | let a = clips.get(idx)?; |
| 3071 | if a.source != source || a.transition_out == 0 { |
| 3072 | return None; |
| 3073 | } |
| 3074 | let b = clips.get(idx + 1)?; |
| 3075 | if a.end() != b.start { |
| 3076 | return None; // trimmed or split apart since the dissolve was set |
| 3077 | } |
| 3078 | // The span must run uninterrupted all the way to A's own end: a higher |
| 3079 | // video lane taking over before that means there is no tail of A left |
| 3080 | // here to blend into anything. |
| 3081 | if span.start + span.len != a.end() { |
| 3082 | return None; |
| 3083 | } |
| 3084 | let window = a |
| 3085 | .transition_out |
| 3086 | .min(a.frames()) |
| 3087 | .min(b.frames()) |
| 3088 | .min(span.len); |
| 3089 | (window > 0).then_some((b.source, b.in_frame, window, b.start)) |
| 3090 | } |
| 3091 | |
| 3092 | /// `B`'s weight in [`crate::scale::blend_i420`] at output frame `idx_in_window` of `window` |
| 3093 | /// (`idx_in_window < window`): a ramp from just above 0 to just below 1 that |
| 3094 | /// never actually reaches either end, so the first blended frame still shows |
| 3095 | /// a trace of A and the last still a trace of B -- the cut a hard transition |
| 3096 | /// would have made lands one frame *after* the window, at full B, rather than |
| 3097 | /// inside it. |
| 3098 | pub(crate) fn dissolve_weight(idx_in_window: u32, window: u32) -> f32 { |
| 3099 | (idx_in_window + 1) as f32 / (window + 1) as f32 |
| 3100 | } |
| 3101 | |
| 3102 | /// The picture's black fade at timeline `frame`: the share of the picture that |
| 3103 | /// survives, `None` where no fade reaches it. The clip on screen |
| 3104 | /// ([`Project::composite_clip_at`]) owns its own fades -- [`Clip::fade_in`] ramps |
| 3105 | /// from black on its first frame to the whole picture at `fade_in`, and |
| 3106 | /// [`Clip::fade_out`] ramps back to black over its last `fade_out` frames, the |
| 3107 | /// same edges [`crate::project::Fade`] ramps the sound on. A linear ramp: the |
| 3108 | /// first frame of a fade-in is pure black and the frame a fade-out ends on is |
| 3109 | /// one step short of it, so nothing shows the picture at full strength while |
| 3110 | /// the ramp is still running. |
| 3111 | pub(crate) fn picture_fade_at(project: &Project, frame: u32) -> Option<f32> { |
| 3112 | let (lane, idx) = project.composite_clip_at(frame)?; |
| 3113 | clip_fade(project.lane(lane).get(idx)?, frame) |
| 3114 | } |
| 3115 | |
| 3116 | /// [`picture_fade_at`] for one clip: the share of its picture that survives at |
| 3117 | /// `frame`. A layered picture asks it of each clip, so a fade belongs to the |
| 3118 | /// clip it is on. |
| 3119 | fn clip_fade(clip: &crate::project::Clip, frame: u32) -> Option<f32> { |
| 3120 | if clip.fade_in == 0 && clip.fade_out == 0 { |
| 3121 | return None; |
| 3122 | } |
| 3123 | let pos = frame.checked_sub(clip.start)?; |
| 3124 | let total = clip.frames(); |
| 3125 | let mut k = 1.0f32; |
| 3126 | if clip.fade_in > 0 && pos < clip.fade_in { |
| 3127 | k = pos as f32 / clip.fade_in as f32; |
| 3128 | } |
| 3129 | if clip.fade_out > 0 && pos >= total.saturating_sub(clip.fade_out) { |
| 3130 | k = k.min((total - pos) as f32 / clip.fade_out as f32); |
| 3131 | } |
| 3132 | (k < 1.0).then_some(k) |
| 3133 | } |
| 3134 | |
| 3135 | /// Whether any frame of `span` is inside a picture fade ([`picture_fade_at`]): |
| 3136 | /// the span's pixels then have to be touched, which a zero-copy span never is. |
| 3137 | fn picture_faded_in(project: &Project, span: &crate::project::Span) -> bool { |
| 3138 | (span.start..span.start.saturating_add(span.len)) |
| 3139 | .any(|frame| picture_fade_at(project, frame).is_some()) |
| 3140 | } |
| 3141 | |
| 3142 | /// Whether any video clip on the timeline has a picture fade -- the |
| 3143 | /// picture-side twin of [`faded`], which asks the same of sound: a fade is |
| 3144 | /// pixel math, so a stream copy cannot carry one. |
| 3145 | fn picture_faded(project: &Project) -> bool { |
| 3146 | project |
| 3147 | .lanes() |
| 3148 | .into_iter() |
| 3149 | .filter(|lane| lane.kind == LaneKind::Video) |
| 3150 | .any(|lane| { |
| 3151 | project |
| 3152 | .lane(lane) |
| 3153 | .iter() |
| 3154 | .any(|c| c.fade_in > 0 || c.fade_out > 0) |
| 3155 | }) |
| 3156 | } |
| 3157 | |
| 3158 | /// `planes` drawn toward black by `k` ([`picture_fade_at`]): luma moves toward |
| 3159 | /// 16 and chroma toward 128, the black a gap is composed as, so a faded frame |
| 3160 | /// and a gap agree on what black is. |
| 3161 | fn fade_planes<T: Sample>(planes: (&[T], &[T], &[T]), k: f32) -> Planes<T> { |
| 3162 | let toward = |s: &[T], black: T| -> Vec<T> { |
| 3163 | s.iter() |
| 3164 | .map(|&p| { |
| 3165 | let (black, p) = (black.code() as f32, p.code() as f32); |
| 3166 | T::from_f32(black + (p - black) * k) |
| 3167 | }) |
| 3168 | .collect() |
| 3169 | }; |
| 3170 | ( |
| 3171 | toward(planes.0, T::BLACK), |
| 3172 | toward(planes.1, T::NEUTRAL), |
| 3173 | toward(planes.2, T::NEUTRAL), |
| 3174 | ) |
| 3175 | } |
| 3176 | |
| 3177 | /// A dissolve's B side, open beside A's own decoder for this span's tail: |
| 3178 | /// its own decoder, and everything [`place_picture`] needs to put its frames |
| 3179 | /// on the same canvas, in the same space, graded the way B is graded rather |
| 3180 | /// than the way A is -- [`Project::composite_color_at`]/`composite_fit_at` |
| 3181 | /// asked at B's own start, not at the timeline position the blend writes to, |
| 3182 | /// which is still inside A's span. |
| 3183 | struct Dissolve<'a> { |
| 3184 | /// How many output frames the blend ramps across. |
| 3185 | window: u32, |
| 3186 | kind: crate::transitions::TransitionKind, |
| 3187 | /// The first output frame of this span's tail that is inside the window. |
| 3188 | tail_start: u32, |
| 3189 | decoder: ClipDecoder, |
| 3190 | mapper: Option<&'a ToneMapper>, |
| 3191 | remap: Option<Remap>, |
| 3192 | grade: Option<crate::color::ColorParams>, |
| 3193 | transform: TransformParams, |
| 3194 | /// B's own file's display-matrix turn, [`place_picture`]'s first stage; |
| 3195 | /// B is a different file and may be turned differently from A. |
| 3196 | rotation: Rotation, |
| 3197 | /// B's own file's sample aspect, [`place_picture`]'s second stage, for |
| 3198 | /// the same reason the turn is per file. |
| 3199 | pixel_aspect: crate::demux::PixelAspect, |
| 3200 | canvas: Composer, |
| 3201 | /// The turn's, the grade's and the transform's scratch, exactly as A's |
| 3202 | /// span keeps them: refilled per picture, allocated once. |
| 3203 | rotated: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3204 | /// The stretch's own scratch, [`place_picture`]'s second stage -- the |
| 3205 | /// pixel aspect's, beside the turn's. |
| 3206 | stretched: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3207 | graded: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3208 | transformed: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3209 | /// The 10-bit scratch of B's placement, for a 10-bit export. |
| 3210 | scratch16: Scratch16, |
| 3211 | } |
| 3212 | |
| 3213 | /// The Videos folder a default export lands in: the user's own (`XDG_VIDEOS_DIR`, |
| 3214 | /// else the one `~/.config/user-dirs.dirs` names, else `~/Videos`), then the |
| 3215 | /// project's folder, never the media's own folder by default. |
| 3216 | pub fn default_export_folder(project: &Path) -> PathBuf { |
| 3217 | let home = std::env::var_os("HOME").map(PathBuf::from); |
| 3218 | let xdg = std::env::var_os("XDG_VIDEOS_DIR").map(PathBuf::from).or_else(|| { |
| 3219 | let home = home.as_ref()?; |
| 3220 | let text = std::fs::read_to_string(home.join(".config/user-dirs.dirs")).ok()?; |
| 3221 | let line = text.lines().find_map(|l| l.trim().strip_prefix("XDG_VIDEOS_DIR="))?; |
| 3222 | let value = line.trim().trim_matches('"'); |
| 3223 | Some(PathBuf::from(value.replace("$HOME", &home.to_string_lossy()))) |
| 3224 | }); |
| 3225 | let videos = xdg.filter(|d| d.is_dir()).or_else(|| home.map(|h| h.join("Videos")).filter(|d| d.is_dir())); |
| 3226 | videos |
| 3227 | .or_else(|| project.parent().filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf)) |
| 3228 | .unwrap_or_else(|| PathBuf::from(".")) |
| 3229 | } |
| 3230 | |
| 3231 | /// The track's cues where the *exported* timeline puts them, which is the only |
| 3232 | /// clock the file has: the export writes timeline frame 0 onwards and nothing |
| 3233 | /// else, exactly as the sound is mixed from frame 0 and resized to the |
| 3234 | /// timeline's own length ([`encode_audio`]). |
| 3235 | /// |
| 3236 | /// Which clock the cues arrive in is what the track itself says: |
| 3237 | /// |
| 3238 | /// * a track out of a *file* (`SubtitleTrack::track`) is timed against that |
| 3239 | /// file, so each cue is carried through the spans that play it -- a cue over |
| 3240 | /// a stretch that was cut out is gone, one straddling a cut keeps the half |
| 3241 | /// that is still there, and one after a rippled delete moves back with the |
| 3242 | /// picture it belongs to. The *edges* a cut clips to are frames -- that is |
| 3243 | /// what a cut is -- but a cue nothing clipped keeps its own microseconds, so |
| 3244 | /// an untouched timeline exports the times the source states. |
| 3245 | /// * a *standalone* file (`subs.srt`) is timed against nothing else -- there is |
| 3246 | /// no clip to hang it on and no offset in the project to shift it by -- so it |
| 3247 | /// is the timeline's own clock, which is where it was drawn while editing |
| 3248 | /// (`Player::subtitle_overlay`). Clipped to the exported length and no more. |
| 3249 | /// |
| 3250 | /// This is also what the *preview* draws: the plate over the picture and the |
| 3251 | /// timeline strip both ask it through |
| 3252 | /// [`PlaybackSession::timeline_cues`](crate::PlaybackSession::timeline_cues), so |
| 3253 | /// what a rippled timeline shows and what its export writes are one answer by |
| 3254 | /// construction rather than two maps kept in step by hand. |
| 3255 | /// |
| 3256 | /// Pure and cheap enough to ask per repaint (a walk of the spans and of the |
| 3257 | /// cues, no file opened), which is how a front-end asks it. |
| 3258 | pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<Cue> { |
| 3259 | let frames = project.timeline_frames(); |
| 3260 | let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64; |
| 3261 | let end = us(frames); |
| 3262 | // The file the cues are timed against, when there is one on this timeline. |
| 3263 | // A track whose media has since been dropped from the project has no span |
| 3264 | // to be carried through and falls back to the timeline's clock, which is |
| 3265 | // what it was drawn on. |
| 3266 | // |
| 3267 | // Through the same `canonical` a source is indexed by, or the two spellings |
| 3268 | // of one file (an argv `../assets/film.mkv`, a symlinked folder) would read |
| 3269 | // as two files and the cues would quietly fall back to the timeline's clock. |
| 3270 | let source = track.track.and_then(|_| { |
| 3271 | let path = crate::project::canonical(&track.path); |
| 3272 | project.sources().iter().position(|s| s.path == path) |
| 3273 | }); |
| 3274 | let Some(source) = source else { |
| 3275 | return track |
| 3276 | .cues |
| 3277 | .iter() |
| 3278 | .filter_map(|cue| { |
| 3279 | let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end)); |
| 3280 | (end_us > start_us).then_some(Cue { |
| 3281 | start_us, |
| 3282 | end_us, |
| 3283 | text: cue.text.clone(), |
| 3284 | image: cue.image.clone(), |
| 3285 | words: crate::subtitle::map_words(&cue.words, (start_us, end_us), (start_us, end_us)), |
| 3286 | karaoke: crate::subtitle::map_karaoke(&cue.karaoke, (start_us, end_us), (start_us, end_us)), |
| 3287 | }) |
| 3288 | }) |
| 3289 | .collect(); |
| 3290 | }; |
| 3291 | let mut out = Vec::new(); |
| 3292 | for span in stack_spans_from(project, 0) { |
| 3293 | let Some((_, in_frame)) = span.from.filter(|&(from, _)| from == source) else { |
| 3294 | continue; |
| 3295 | }; |
| 3296 | // What of the file this span plays, as *time in the file*: a clip counts |
| 3297 | // the timeline's frames whatever its file was shot at ([`Rate`]), which |
| 3298 | // is what makes those frames the same seconds a cue is timed in. |
| 3299 | let (first, last) = match span.source_window() { |
| 3300 | Some((_, lo, hi)) => (us(lo), us(hi)), |
| 3301 | None => (us(in_frame), us(in_frame + span.source_len())), |
| 3302 | }; |
| 3303 | // Where that lands, and how fast: a cue is carried by the same factor |
| 3304 | // the pictures under it are, so a slowed clip stretches its subtitles |
| 3305 | // with it instead of leaving them behind. |
| 3306 | let start = us(span.start); |
| 3307 | // `rel` is the time since the span's head in the file's own direction of play: |
| 3308 | // forwards from `first`, and for a reversed clip back from `last` (the cue |
| 3309 | // [s, e] is mirrored to [last - e, last - s]). |
| 3310 | let onto = |rel: i64| { |
| 3311 | let Some(_) = span.ramp else { |
| 3312 | return start + (rel as f64 / span.speed.as_f64()).round() as i64; |
| 3313 | }; |
| 3314 | // A ramp has no one factor: carry the cue through the ramp's own |
| 3315 | // inverse (`Span::timeline_at`), interpolating between whole frames. |
| 3316 | let f = (rel as f64 / 1e6 * fps).max(0.0); |
| 3317 | let (lo, hi) = (f.floor() as u32, f.ceil() as u32); |
| 3318 | let at = |s: u32| f64::from(span.timeline_at(in_frame + s).min(span.start + span.len) - span.start); |
| 3319 | let (a, b) = (at(lo), at(hi)); |
| 3320 | let frames = if hi == lo { b } else { a + (b - a) * (f - f64::from(lo)) }; |
| 3321 | start + (frames / fps * 1e6).round() as i64 |
| 3322 | }; |
| 3323 | for cue in &track.cues { |
| 3324 | let (a, b) = (cue.start_us.max(first), cue.end_us.min(last)); |
| 3325 | if b <= a { |
| 3326 | continue; // wholly outside what this span kept |
| 3327 | } |
| 3328 | let (from, to) = if span.reverse { (last - b, last - a) } else { (a - first, b - first) }; |
| 3329 | out.push(Cue { |
| 3330 | start_us: onto(from), |
| 3331 | end_us: onto(to).min(end), |
| 3332 | text: cue.text.clone(), |
| 3333 | image: cue.image.clone(), |
| 3334 | // Each word through the same mapping as the cue, so a ramp places it where |
| 3335 | // its own sound plays; a reversed clip keeps none, its cue shown whole. |
| 3336 | words: if span.reverse { |
| 3337 | Vec::new() |
| 3338 | } else { |
| 3339 | cue.words |
| 3340 | .iter() |
| 3341 | .filter(|(s, _, _)| *s < b) |
| 3342 | .map(|(s, e, w)| { |
| 3343 | let at = |t: i64| onto(t.clamp(a, b) - first).min(end); |
| 3344 | (at(*s), at(*e), w.clone()) |
| 3345 | }) |
| 3346 | .collect() |
| 3347 | }, |
| 3348 | karaoke: if span.reverse { |
| 3349 | Vec::new() |
| 3350 | } else { |
| 3351 | cue.karaoke |
| 3352 | .iter() |
| 3353 | .filter(|k| k.start_us < b) |
| 3354 | .map(|k| { |
| 3355 | let at = |t: i64| onto(t.clamp(a, b) - first).min(end); |
| 3356 | crate::subtitle::Syllable { start_us: at(k.start_us), end_us: at(k.end_us), ..k.clone() } |
| 3357 | }) |
| 3358 | .collect() |
| 3359 | }, |
| 3360 | }); |
| 3361 | } |
| 3362 | } |
| 3363 | // The spans come in timeline order but a cue's *own* order across them does |
| 3364 | // not: a Matroska muxer writes blocks as they come up. |
| 3365 | out.sort_by_key(|cue| cue.start_us); |
| 3366 | out |
| 3367 | } |
| 3368 | |
| 3369 | /// What [`start`] would do about the subtitles, in the words a card shows: what |
| 3370 | /// travels, and the reason beside every pick that does not. Pure, like |
| 3371 | /// [`planned_audio`]: no file is opened, so it may be asked per repaint. |
| 3372 | /// |
| 3373 | /// `picks` is any run of indices into [`Project::subtitles`] -- an |
| 3374 | /// [`ExportSettings::subtitles`] list (`picks.iter().copied()`) as much as a |
| 3375 | /// single `Some(row)`, which is what a front-end holding one row still hands it. |
| 3376 | pub fn planned_subtitles( |
| 3377 | project: &Project, |
| 3378 | format: Format, |
| 3379 | picks: impl IntoIterator<Item = usize>, |
| 3380 | ) -> String { |
| 3381 | planned_subtitles_in(project, format, picks, None, 0.0) |
| 3382 | } |
| 3383 | |
| 3384 | /// [`planned_subtitles`] for an export of `range` (the frames a ranged file keeps) at `fps`: a |
| 3385 | /// track or lane with no cue left in the range is named as dropped for that reason, since the |
| 3386 | /// file would carry it empty. `None` is the whole timeline, and `fps` is then not read. |
| 3387 | pub fn planned_subtitles_in( |
| 3388 | project: &Project, |
| 3389 | format: Format, |
| 3390 | picks: impl IntoIterator<Item = usize>, |
| 3391 | range: Option<(u32, u32)>, |
| 3392 | fps: f64, |
| 3393 | ) -> String { |
| 3394 | let picks: Vec<usize> = picks.into_iter().collect(); |
| 3395 | let lanes = placed_lanes(project); |
| 3396 | // WebM is the one container that names no subtitle track here, placed or |
| 3397 | // picked: said first and once, as the reason nothing travels. |
| 3398 | if format == Format::Webm && (!picks.is_empty() || !lanes.is_empty()) { |
| 3399 | return "none — a WebM file carries no subtitles".into(); |
| 3400 | } |
| 3401 | if format == Format::ProRes && (!picks.is_empty() || !lanes.is_empty()) { |
| 3402 | return "none — a ProRes QuickTime file carries no subtitles".into(); |
| 3403 | } |
| 3404 | // An mp4 of a timeline with no picture is the sound alone too: no track of |
| 3405 | // either kind is written, placed or picked ([`export_subtitles`]). |
| 3406 | if format.ext() == "mp4" && !has_picture(project) { |
| 3407 | return "none — a timeline with no picture is the sound alone".into(); |
| 3408 | } |
| 3409 | // One statement about the *file*, said before any about a track: a format |
| 3410 | // that is the sound alone has nowhere to put a single one of them, and the |
| 3411 | // reason a pick would not have travelled anyway (a picture track, no cues) |
| 3412 | // is not the reason it does not travel here. Nothing picked is "none" -- |
| 3413 | // there is nothing to say a container cannot carry. |
| 3414 | if !format.has_video() && (!picks.is_empty() || !lanes.is_empty()) { |
| 3415 | return "none — this format is the sound alone".into(); |
| 3416 | } |
| 3417 | // The lanes are the words placed on the timeline and go as they are placed |
| 3418 | // ([`export_subtitles`]); each picked track no lane places is written whole, |
| 3419 | // beside them. The clauses go in the order the file writes the tracks |
| 3420 | // ([`soft_order`]), which is the order the caller gave them. |
| 3421 | let (mut embedded, mut dropped) = (Vec::new(), Vec::new()); |
| 3422 | let (mut lane_count, mut trailing) = (0, false); |
| 3423 | for entry in soft_order(project, &lanes, &picks) { |
| 3424 | let pick = match entry { |
| 3425 | SoftEntry::Lane(lane) => { |
| 3426 | let (e, d, t) = planned_lanes(project, &[lane], &picks, range, fps); |
| 3427 | lane_count += e.len(); |
| 3428 | embedded.extend(e); |
| 3429 | dropped.extend(d); |
| 3430 | trailing |= t; |
| 3431 | continue; |
| 3432 | } |
| 3433 | SoftEntry::Track(pick) => pick, |
| 3434 | }; |
| 3435 | // A pick the project has no row for: a caller holding an index the list |
| 3436 | // no longer has (a removed row shifts every later one down). Every other |
| 3437 | // reason a pick does not travel is named on this card, so this one is |
| 3438 | // too -- a bug that says nothing is a bug found in the finished file. |
| 3439 | let Some(track) = project.subtitles().get(pick) else { |
| 3440 | dropped.push(format!("#{pick} — no such track")); |
| 3441 | continue; |
| 3442 | }; |
| 3443 | if let Some(why) = &track.refused { |
| 3444 | dropped.push(format!("{} — {why}", track.label)); |
| 3445 | } else if track.is_bitmap() { |
| 3446 | // Drawn over the picture, written into no file: the exported track |
| 3447 | // is text and these cues are bitmaps. Said whatever the format, |
| 3448 | // because it is the track and not the container that cannot be |
| 3449 | // carried. |
| 3450 | dropped.push(format!("{} — pictures; drawn, not written", track.label)); |
| 3451 | } else if !track_has_cues(project, track, range, fps) { |
| 3452 | dropped.push(format!("{} — {}", track.label, no_cues_word(range))); |
| 3453 | } else { |
| 3454 | // Whichever container: a Matroska carries the track as |
| 3455 | // `S_TEXT/UTF8` blocks and an mp4 as a `tx3g` timed-text track, and |
| 3456 | // a pick travels either way. There is no container refusal left on |
| 3457 | // this card -- the sound-alone one above is about the *file* and the |
| 3458 | // ones beside it about the *track*. |
| 3459 | embedded.push(track.label.clone()); |
| 3460 | } |
| 3461 | } |
| 3462 | // Lanes only are named as lanes; a picked track in the mix makes them tracks. |
| 3463 | let noun = if lane_count == embedded.len() { "lanes" } else { "tracks" }; |
| 3464 | // A Matroska block numbers its track in one byte, so a file carries at most |
| 3465 | // MAX_SUB_TRACKS of them, placed or picked; the muxer refuses more again. |
| 3466 | if format.is_mkv() && embedded.len() > crate::mux::MAX_SUB_TRACKS { |
| 3467 | return format!( |
| 3468 | "{} subtitle {noun}: a Matroska block writes its track number in one byte, so one file \ |
| 3469 | carries at most {}", |
| 3470 | embedded.len(), |
| 3471 | crate::mux::MAX_SUB_TRACKS |
| 3472 | ); |
| 3473 | } |
| 3474 | let mut parts = match embedded.len() { |
| 3475 | 0 => Vec::new(), |
| 3476 | 1 => vec![format!("{} → embedded", embedded[0])], |
| 3477 | n => vec![format!("{n} {noun} → embedded ({})", embedded.join(", "))], |
| 3478 | }; |
| 3479 | parts.extend(dropped); |
| 3480 | if trailing { |
| 3481 | parts.push("cues past the last picture are cut off there".into()); |
| 3482 | } |
| 3483 | match parts.is_empty() { |
| 3484 | true => "none".into(), |
| 3485 | false => parts.join("; "), |
| 3486 | } |
| 3487 | } |
| 3488 | |
| 3489 | /// [`planned_subtitles`] for a timeline that *places* its words: one clause per |
| 3490 | /// subtitle lane, named by the lane and by the palette row it shows, in the |
| 3491 | /// order the file will declare them ([`lane_subtitles`]). |
| 3492 | /// |
| 3493 | /// Every reason a lane does not travel is said here rather than found in the |
| 3494 | /// file: a picture track placed on it, a track that could not be read, a palette |
| 3495 | /// row that has since gone, a lane sitting entirely past the last picture, and |
| 3496 | /// -- before a byte is written -- more lanes than a Matroska block can number |
| 3497 | /// ([`crate::mux::MAX_SUB_TRACKS`], which the muxer refuses again). |
| 3498 | fn planned_lanes( |
| 3499 | project: &Project, |
| 3500 | lanes: &[Lane], |
| 3501 | picks: &[usize], |
| 3502 | range: Option<(u32, u32)>, |
| 3503 | fps: f64, |
| 3504 | ) -> (Vec<String>, Vec<String>, bool) { |
| 3505 | let end = project.media_frames(); |
| 3506 | let (mut embedded, mut dropped, mut trailing) = (Vec::new(), Vec::new(), false); |
| 3507 | for &lane in lanes { |
| 3508 | let placed = project.sub_lane(lane); |
| 3509 | // An empty lane is a lane nobody has used yet, not a refusal. A lane no |
| 3510 | // pick reaches is not in this file at all, so it is not named either. |
| 3511 | let Some(first) = placed.first() else { |
| 3512 | continue; |
| 3513 | }; |
| 3514 | if !picked(placed, picks) { |
| 3515 | continue; |
| 3516 | } |
| 3517 | let row = |s: &crate::project::SubClip| project.subtitles().get(s.track); |
| 3518 | let (label, head) = (lane.label(), row(first)); |
| 3519 | let name = head.map_or_else(String::new, |t| format!("{} ", t.label)); |
| 3520 | if let Some(gone) = placed.iter().find(|s| row(s).is_none()) { |
| 3521 | dropped.push(format!("{label} — #{} is no longer a track", gone.track)); |
| 3522 | } else if let Some((t, why)) = placed |
| 3523 | .iter() |
| 3524 | .find_map(|s| row(s).and_then(|t| t.refused.as_ref().map(|why| (t, why)))) |
| 3525 | { |
| 3526 | dropped.push(format!("{label} {} — {why}", t.label)); |
| 3527 | } else if let Some(t) = placed.iter().find_map(|s| row(s).filter(|t| t.is_bitmap())) { |
| 3528 | // Drawn over the picture, written into no file -- the same sentence |
| 3529 | // a picked track gets, because it is the track and not the lane that |
| 3530 | // cannot be carried. |
| 3531 | dropped.push(format!( |
| 3532 | "{label} {} — pictures; drawn, not written", |
| 3533 | t.label |
| 3534 | )); |
| 3535 | } else if first.start >= end { |
| 3536 | dropped.push(format!("{label} {name}— past the last picture")); |
| 3537 | } else if range.is_some() && lane_subtitle(project, lane, fps, range, picks).is_none() { |
| 3538 | dropped.push(format!("{label} {name}— {}", no_cues_word(range))); |
| 3539 | } else { |
| 3540 | embedded.push(format!("{label} {}", name.trim_end())); |
| 3541 | // Something on it hangs past the end of the media: the timeline is |
| 3542 | // held open under it ([`Project::timeline_frames`]) but the file |
| 3543 | // stops with the last picture, so those cues are cut off there. |
| 3544 | trailing |= placed.last().is_some_and(|s| s.end() > end); |
| 3545 | } |
| 3546 | } |
| 3547 | (embedded, dropped, trailing) |
| 3548 | } |
| 3549 | |
| 3550 | /// What [`start`] would encode the picture with, probed the way the export |
| 3551 | /// probes it -- the very encoder is opened and closed again -- so this is a |
| 3552 | /// measurement and not a promise. `None` for a format that carries no picture. |
| 3553 | /// |
| 3554 | /// Costs that open (~100 ms here): ask it off a render thread and keep the |
| 3555 | /// answer until the format, the resolution or the bitrate changes. |
| 3556 | pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> { |
| 3557 | settings |
| 3558 | .format |
| 3559 | .has_video() |
| 3560 | .then(|| match hw_seat(meta, settings) { |
| 3561 | Ok(hw) => video_label(settings.format, hw.is_some(), settings.intra_only), |
| 3562 | // The seat the settings demand and this machine has not: the very |
| 3563 | // refusal [`start`] would settle with, said on the card instead. |
| 3564 | Err(_) => NO_HW_SEAT, |
| 3565 | }) |
| 3566 | } |
| 3567 | |
| 3568 | /// What [`start`] would open for *this* timeline: the picture's seat -- or the |
| 3569 | /// copy that means there is no encoder at all -- and the sound's, asked of the |
| 3570 | /// very gates the export asks ([`CopyPlan::of`] and [`copy_audio`]'s) rather |
| 3571 | /// than of the format alone. |
| 3572 | /// |
| 3573 | /// This exists because the card and the running export used to disagree in both |
| 3574 | /// directions on the same file: the card named a software HEVC encode for a cut |
| 3575 | /// the engine copied, and named an AAC copy for a Matroska source whose sound |
| 3576 | /// no sample table holds and which therefore always re-encodes. A prediction |
| 3577 | /// that is not the decision is worse than no prediction, because a person plans |
| 3578 | /// their evening around it. |
| 3579 | /// |
| 3580 | /// Costs what [`planned_video`] costs (an encoder opened and closed) plus a |
| 3581 | /// header read per source and, once per file, its cluster walk: ask it off a |
| 3582 | /// render thread and keep the answer until the timeline or the settings change. |
| 3583 | pub fn planned_seats( |
| 3584 | project: &Project, |
| 3585 | meta: &VideoMeta, |
| 3586 | settings: &ExportSettings, |
| 3587 | ) -> (Option<&'static str>, &'static str) { |
| 3588 | // The canvas the file is drawn at, which is what the seat and the copy gate are about. |
| 3589 | let meta = &output_meta(meta, settings); |
| 3590 | let video = settings.format.has_video().then(|| { |
| 3591 | match CopyPlan::of(project, meta, settings).is_some() { |
| 3592 | true => "copy (source packets)", |
| 3593 | false => planned_video(meta, settings).unwrap_or(NO_HW_SEAT), |
| 3594 | } |
| 3595 | }); |
| 3596 | // The half [`audio_label`] cannot know from the format: a copy is a *sample |
| 3597 | // table's* packets ([`copy_audio`] hands them to `copy_multi_streams`), and |
| 3598 | // a Matroska file has none -- so every mkv source re-encodes, however |
| 3599 | // untouched its lane is. Extension only, which is what `is_matroska` |
| 3600 | // reads, so this costs nothing beyond what is already open. A standalone |
| 3601 | // audio file (mp3, wav, flac...) has no sample table either: its sound is |
| 3602 | // decoded and encoded again, as [`copy_multi_streams`] refusing it sends it. |
| 3603 | let copyable = !forces_encode(project, settings.range.is_some()) |
| 3604 | && !project.sources().iter().any(|source| |
| 3605 | { |
| 3606 | crate::demux::is_matroska(&source.path) |
| 3607 | || crate::demux::is_mpeg_system(&source.path) |
| 3608 | || crate::is_audio(&source.path) |
| 3609 | }); |
| 3610 | let sound = match undecodable_sound(project) { |
| 3611 | Some(label) if has_sound(project) => label, |
| 3612 | // A Matroska file that is encoded (not copied) takes Opus or AAC as the mix decides, so |
| 3613 | // the card names the one this mix will get, read from the sources' headers. |
| 3614 | None if has_sound(project) |
| 3615 | && !copyable |
| 3616 | && settings.format.is_mkv() |
| 3617 | && settings.format != Format::Webm => |
| 3618 | { |
| 3619 | match mkv_mix_is_opus(project, meta.frame_rate) { |
| 3620 | true => "Opus · SW encode (ec-opus)", |
| 3621 | false => "AAC · SW encode (ec-aac)", |
| 3622 | } |
| 3623 | } |
| 3624 | _ => audio_label( |
| 3625 | project, |
| 3626 | settings.format, |
| 3627 | has_sound(project), |
| 3628 | Some(copyable), |
| 3629 | settings.range.is_some(), |
| 3630 | ), |
| 3631 | }; |
| 3632 | (video, sound) |
| 3633 | } |
| 3634 | |
| 3635 | /// Whether the mix a Matroska export encodes would be written as Opus: the rule |
| 3636 | /// [`encode_audio`] applies after the mix is open -- 48 kHz, mono or stereo -- worked |
| 3637 | /// out from the lanes' sources' headers instead ([`AudioSession::probe`]), since no mix |
| 3638 | /// is opened to ask. The mix runs at the highest source rate, 48 kHz when every source |
| 3639 | /// is below 44.1 kHz ([`crate::audio`]'s `mix_rate`), and as wide as the widest source. |
| 3640 | /// The fidelity gate that can still hand the track back to AAC is measured only once |
| 3641 | /// the encode has run, so this is the prediction the export's own line corrects. |
| 3642 | fn mkv_mix_is_opus(project: &Project, fps: f64) -> bool { |
| 3643 | let sources = project.audio_sources(); |
| 3644 | let mut rates = Vec::new(); |
| 3645 | let mut channels = 0u16; |
| 3646 | for lane in project.audio_segments_from(0, fps) { |
| 3647 | for (source, ..) in lane { |
| 3648 | let Some((path, stream)) = source.and_then(|i| sources.get(i)) else { |
| 3649 | continue; |
| 3650 | }; |
| 3651 | if crate::is_image(path) { |
| 3652 | continue; |
| 3653 | } |
| 3654 | if let Ok(Some(probe)) = AudioSession::probe(path, *stream) { |
| 3655 | rates.push(probe.sample_rate); |
| 3656 | channels = channels.max(probe.channels); |
| 3657 | } |
| 3658 | } |
| 3659 | } |
| 3660 | let rate = rates.into_iter().max().map(|r| if r < 44_100 { OPUS_RATE } else { r }); |
| 3661 | rate == Some(OPUS_RATE) && (1..=2).contains(&channels) |
| 3662 | } |
| 3663 | |
| 3664 | /// The sound a timeline's sources cannot give: `Some(label)` when every source |
| 3665 | /// on the audio lanes is one [`AudioSession::unsupported`] names as undecodable, |
| 3666 | /// which is what the export's own open answers with no sound at all ("no audio |
| 3667 | /// to write"). `None` when any source decodes, or when a source has no sound |
| 3668 | /// this question can name. |
| 3669 | fn undecodable_sound(project: &Project) -> Option<&'static str> { |
| 3670 | let reasons: Vec<Option<String>> = project |
| 3671 | .audio_sources() |
| 3672 | .iter() |
| 3673 | .map(|(path, _)| AudioSession::unsupported(path).ok().flatten()) |
| 3674 | .collect(); |
| 3675 | if reasons.is_empty() || reasons.iter().any(Option::is_none) { |
| 3676 | return None; |
| 3677 | } |
| 3678 | // The reason's first words name the codec: a Matroska file by its codec id |
| 3679 | // ("the A_DTS track ..."), an mp4 by its media type ("the dts audio track |
| 3680 | // ..."). Only DTS is named by name; any other codec this engine cannot decode |
| 3681 | // gets the general words. |
| 3682 | let dts = reasons.iter().flatten().all(|reason| { |
| 3683 | let reason = reason.to_ascii_lowercase(); |
| 3684 | reason.starts_with("the a_dts ") || reason.starts_with("the dts ") |
| 3685 | }); |
| 3686 | Some(match dts { |
| 3687 | true => "none — DTS can't be decoded", |
| 3688 | false => "none — this codec can't be decoded", |
| 3689 | }) |
| 3690 | } |
| 3691 | |
| 3692 | /// The tone map a picture export puts on its HDR sources, as a sentence for the |
| 3693 | /// start line and the plan: the picture is written 8-bit BT.709 SDR, so a PQ or |
| 3694 | /// HLG source is tone-mapped down silently otherwise. `None` where no picture |
| 3695 | /// is tone-mapped -- a sound-only format, a preview that keeps its source's |
| 3696 | /// curve ([`ExportSettings::keep_source_colour`]), or no HDR source in the |
| 3697 | /// project. Asked of every source, as [`planned_seats`] asks its sound. |
| 3698 | /// |
| 3699 | /// Header reads only, one per source, the same colour the export's own tone map |
| 3700 | /// is built from ([`source_rate`]). |
| 3701 | pub fn planned_tone(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<String> { |
| 3702 | if !settings.format.has_video() || settings.keep_source_colour { |
| 3703 | return None; |
| 3704 | } |
| 3705 | // The matrix the file is tagged with: the one [`start`] writes for this canvas |
| 3706 | // ([`ColorDescription::output_sized`]), so the words name what the file says. |
| 3707 | let out = output_meta(meta, settings); |
| 3708 | let matrix = match ColorDescription::output_sized(out.width, out.height).matrix { |
| 3709 | Matrix::Bt601 => "BT.601", |
| 3710 | _ => "BT.709", |
| 3711 | }; |
| 3712 | let mut transfers = project.sources().iter().filter_map(|source| { |
| 3713 | if crate::is_image(&source.path) || crate::is_audio(&source.path) { |
| 3714 | return None; |
| 3715 | } |
| 3716 | Demuxer::open(&source.path).ok().map(|(meta, _)| meta.color.transfer) |
| 3717 | }); |
| 3718 | transfers.find_map(|transfer| match transfer { |
| 3719 | Transfer::Pq => Some(format!("HDR (PQ) source tone-mapped to SDR {matrix}")), |
| 3720 | Transfer::Hlg => Some(format!("HDR (HLG) source tone-mapped to SDR {matrix}")), |
| 3721 | Transfer::Sdr => None, |
| 3722 | }) |
| 3723 | } |
| 3724 | |
| 3725 | fn settle(shared: &Shared, result: crate::Result<()>) { |
| 3726 | *shared.outcome.lock().unwrap() = Some(result); |
| 3727 | // Published last: a caller that sees the flag is guaranteed the outcome. |
| 3728 | shared.finished.store(true, Ordering::Release); |
| 3729 | } |
| 3730 | |
| 3731 | /// The audio track an export writes, and how it was made -- a copy is the |
| 3732 | /// source's own packets, bit for bit, and anything else is this project's |
| 3733 | /// encoder over the decoded mix. [`run`] publishes which of the two really |
| 3734 | /// happened, so the encoder line a user reads is measured and not promised. |
| 3735 | pub(crate) struct ExportAudio { |
| 3736 | pub params: crate::AacTrackParams, |
| 3737 | pub packets: Vec<crate::AacPacket>, |
| 3738 | /// Whether those packets are the source's, untouched. |
| 3739 | pub copied: bool, |
| 3740 | /// The track's pre-skip in samples where those packets are **Opus** and not |
| 3741 | /// AAC ([`encode_opus`]), which is what the Matroska track entry states in |
| 3742 | /// its `OpusHead` and its `CodecDelay`. `None` is an AAC track, which is |
| 3743 | /// every copy and every mp4. |
| 3744 | pub opus_pre_skip: Option<u16>, |
| 3745 | /// The language the track is tagged with ([`audio_language`]), `None` for |
| 3746 | /// `und`. Set once where the track is made, from the project it came from. |
| 3747 | pub language: Option<String>, |
| 3748 | /// The sound's length in PCM frames per channel, where the packets were |
| 3749 | /// encoded from a mix of exactly that many: the count the encoder was fed, |
| 3750 | /// not the packets' sum, which runs on past it by the encoder's priming and |
| 3751 | /// the last frame's padding. `None` for a copy, whose length is the |
| 3752 | /// source's own packets. |
| 3753 | pub pcm_frames: Option<u64>, |
| 3754 | } |
| 3755 | |
| 3756 | /// The timeline's audio track for a file that carries picture: copied packet for |
| 3757 | /// packet where a copy says exactly what the timeline says, and decoded, mixed |
| 3758 | /// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane, |
| 3759 | /// a speeded clip, an equalizer, a source that is not AAC inside an mp4 sample |
| 3760 | /// table. Nothing is refused for being uncopyable any more; the only refusals |
| 3761 | /// left below the copy are about sound this engine cannot *decode* either, and |
| 3762 | /// those come out of the decode path by name. |
| 3763 | /// |
| 3764 | /// The copy is still the default and still bit-exact: a timeline nobody has |
| 3765 | /// touched leaves as the very packets its source holds. |
| 3766 | /// |
| 3767 | /// corner-cut: this holds the whole exported AAC track in memory (~3 kB per |
| 3768 | /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming |
| 3769 | /// `copy_segments` that yields packets instead of collecting them. |
| 3770 | #[allow(clippy::too_many_arguments)] |
| 3771 | fn copy_audio( |
| 3772 | project: &Project, |
| 3773 | meta: &VideoMeta, |
| 3774 | kbps: u32, |
| 3775 | mkv: bool, |
| 3776 | webm: bool, |
| 3777 | shared: &Shared, |
| 3778 | sample_rate: Option<u32>, |
| 3779 | range: Option<(u32, u32)>, |
| 3780 | ) -> crate::Result<Option<ExportAudio>> { |
| 3781 | // WebM's sound is Opus, which no source's packets are: always the mix. A loudness target is a |
| 3782 | // gain over the mix, which a copied packet cannot carry. |
| 3783 | if webm || shared.loudness.is_some() { |
| 3784 | return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, range); |
| 3785 | } |
| 3786 | // A ranged export needs an exact offset and an exact length, which a |
| 3787 | // packet copy cannot give -- it carries whole segments named by |
| 3788 | // `audio_segments_from(0, ..)`, not an arbitrary window into them. The |
| 3789 | // decoded path already resamples per segment, so it is the one that can |
| 3790 | // start and stop anywhere; this falls to it exactly as a speeded or |
| 3791 | // equalized lane already does. |
| 3792 | if range.is_some() { |
| 3793 | return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, range); |
| 3794 | } |
| 3795 | // The segments name their source, and the copy carries its packet-rounding |
| 3796 | // debt across a source join exactly as across a cut, so a timeline spanning |
| 3797 | // files stays in sync. A source whose AAC parameters disagree with the |
| 3798 | // first one is an `Err` from there -- import refuses those up front, this |
| 3799 | // is the backstop -- and the caller deletes the `.part`. |
| 3800 | // |
| 3801 | // The stream each source is copied from is the one it plays: `audio_sources` |
| 3802 | // is the same list `PlaybackSession::seek` hands the decoder, so an export |
| 3803 | // of a timeline playing a file's second audio track carries *that* track. |
| 3804 | // |
| 3805 | // One lane is the only shape a *copy* has: summing two means decoding both, |
| 3806 | // and a sum is not a copy. Two or more go to [`encode_audio`], which is the |
| 3807 | // very mix the WAV path writes -- it used to be a refusal, and a refusal is |
| 3808 | // what a file missing half its sound deserves, not what a mix does. |
| 3809 | // |
| 3810 | // *Which* lane is the same question `audio_segments_from` answers for |
| 3811 | // playback, and it is asked here rather than assumed: the lane that holds |
| 3812 | // the sound need not be `A1` (a project may leave `A1` empty and place |
| 3813 | // everything on `A2`), and copying `A1`'s list in that case would write a |
| 3814 | // file with no audio track at all -- silently, which is the failure this |
| 3815 | // whole comment is about. |
| 3816 | let mut lanes = project.audio_segments_from(0, meta.frame_rate); |
| 3817 | // ...cut to what the picture writes ([`export_spans`]). The play list is |
| 3818 | // the *timeline's* ([`Project::timeline_frames`]), so a caption hanging past |
| 3819 | // the last picture ends every audio lane with a trailing gap -- silence this |
| 3820 | // path would copy out past the last frame, three seconds of it on the film |
| 3821 | // this was found on. Only a gap can be out there (`media_frames` is the last |
| 3822 | // clip's own end), and the mixed paths already resize to the same length |
| 3823 | // ([`encode_audio`]); a copy carries source packets and has no resize. |
| 3824 | let over = f64::from(project.timeline_frames() - project.media_frames()) / meta.frame_rate; |
| 3825 | for lane in &mut lanes { |
| 3826 | match lane.last_mut() { |
| 3827 | Some((None, _, len)) if *len > over => *len -= over, |
| 3828 | Some((None, _, _)) if over > 0.0 => { |
| 3829 | lane.pop(); |
| 3830 | } |
| 3831 | _ => {} |
| 3832 | } |
| 3833 | } |
| 3834 | let [segments] = &lanes[..] else { |
| 3835 | return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None); |
| 3836 | }; |
| 3837 | // ...and the same list names *which* lane those clips sit on, which is the |
| 3838 | // only way to ask what has been done to them. |
| 3839 | let lane = project.audio_lanes()[0]; |
| 3840 | // ...and the same list decides whether any clip this would copy plays at a |
| 3841 | // rate other than the one it was recorded at. A copy hands the muxer the |
| 3842 | // very AAC packets the source holds and there is no rate inside a packet to |
| 3843 | // change: the picture would come out re-timed (the walk in [`run`] honours |
| 3844 | // it) over sound at 1.00x, which is the drift a person finds only after the |
| 3845 | // file has gone somewhere. Decoded and resampled instead, by the same worker |
| 3846 | // playback feeds from. |
| 3847 | // |
| 3848 | // ...and whether any clip on it carries an equalizer, which is sample math a |
| 3849 | // copy never reaches: copying such a lane would write the clip *flat*, |
| 3850 | // silently. |
| 3851 | // |
| 3852 | // A frame *rate* of its own is not one of those, and that is deliberate: do |
| 3853 | // not "fix" this into a re-encode. A clip counts the **timeline's** frames |
| 3854 | // whatever its file was shot at ([`crate::project::Rate`]), so the window |
| 3855 | // this copy trims a source's sound to is `start..end` in whole timeline |
| 3856 | // frames -- exactly the seconds the picture covers -- and the file is read |
| 3857 | // at the pitch it was recorded at, which is what playing at the rate it was |
| 3858 | // shot at means. There is no per-clip stretch to express, so the packets are |
| 3859 | // already the right sound in the right place; re-encoding a conformed lane |
| 3860 | // would buy nothing and cost a generation of loss on every mixed-rate export |
| 3861 | // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot` |
| 3862 | // measures the copied sound against the picture). A *speed* is different |
| 3863 | // because it resamples, which is why it leaves through the re-encode above. |
| 3864 | // |
| 3865 | // Only these: a timeline nobody has touched still leaves through the copy |
| 3866 | // below, packet for packet, so no passthrough quietly becomes a generation |
| 3867 | // of loss. |
| 3868 | // ...and whether the mix itself does anything a packet never went through: |
| 3869 | // a lane volume is applied at the sum and a limiter over it, so copying |
| 3870 | // such a lane would write it at unity and unlimited, silently. |
| 3871 | // ...asked as the very predicate [`forces_encode`] is, over the one lane |
| 3872 | // the segments came off, so what a card predicted and what this decides are |
| 3873 | // one answer. `lane` here is that lane, and not `A1` by assumption: |
| 3874 | // [`Project::audio_lanes`] is the list built for, and filtered by, these |
| 3875 | // very segments. |
| 3876 | if sample_altered(project, &[lane]) { |
| 3877 | return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None); |
| 3878 | } |
| 3879 | // What is left is a copy the *sources* may still not be able to give: AAC |
| 3880 | // inside a Matroska file (readable, but not out of a sample table this walks |
| 3881 | // -- there is none), an mp3 or a wav on the timeline, an AC-3 track, two |
| 3882 | // sources whose AAC parameters disagree. Every one of them decodes, and what |
| 3883 | // decodes can be encoded again, so the copy's refusal is now a route: the |
| 3884 | // error a *decode* cannot get past -- Opus or AC-3 inside a Matroska file, |
| 3885 | // which symphonia has no decoder for at any version -- is the one that comes |
| 3886 | // back, by name, from [`encode_audio`]. |
| 3887 | match AudioSession::copy_multi_streams(&project.audio_sources(), segments) { |
| 3888 | Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio { |
| 3889 | params, |
| 3890 | packets, |
| 3891 | copied: true, |
| 3892 | // A copy is the source's own AAC packets: there is no Opus copy |
| 3893 | // path here, since the packets an mkv source holds never reach this |
| 3894 | // (they are not in a sample table) and every one of them re-encodes. |
| 3895 | opus_pre_skip: None, |
| 3896 | language: None, |
| 3897 | pcm_frames: None, |
| 3898 | })), |
| 3899 | Err(_) => encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None), |
| 3900 | } |
| 3901 | } |
| 3902 | |
| 3903 | /// The picture's half of [`copy_audio`]: a Matroska export whose every span is |
| 3904 | /// its source's own coded blocks, written back out without a decoder or an |
| 3905 | /// encoder anywhere in the path. |
| 3906 | /// |
| 3907 | /// **When.** A copy is entered only where it says *exactly* what the timeline |
| 3908 | /// says, which is the audio gate's rule and not a looser one: the file this |
| 3909 | /// export writes is Matroska, the source's codec is the one that file would |
| 3910 | /// carry ([`Format::Hevc`] over HEVC, [`Format::Av1`] over AV1), and nothing on |
| 3911 | /// the way has touched a sample -- no grade, no speed, no rate conversion, no |
| 3912 | /// gap to fill with black, no source of another size to place on the canvas, |
| 3913 | /// no `ContentEncodings` packing to undo. Anything else re-encodes exactly as |
| 3914 | /// it always did; there is no half-copied file. |
| 3915 | /// |
| 3916 | /// **All or nothing, per export.** A copied span and an encoded one cannot |
| 3917 | /// share one track: this project's encoders write 8-bit SDR streams whose |
| 3918 | /// parameter sets are their own, so splicing them into (say) a Main 10 HDR |
| 3919 | /// source would change bit depth and colour mid-track, and a container states |
| 3920 | /// its configuration record once. So the head and tail fragments of a cut that |
| 3921 | /// lands mid-GOP are *not* re-encoded into the copy -- they are what makes the |
| 3922 | /// whole export fall back to the encoder. What a copy needs instead is that |
| 3923 | /// every span begins on a sync point and ends where the next one begins, which |
| 3924 | /// is what a cut placed on a keyframe gives it. |
| 3925 | /// |
| 3926 | /// **What a cut costs.** An open-GOP source (x265's default) writes leading |
| 3927 | /// pictures after a sync point that are shown *before* it and reference the |
| 3928 | /// group before it. At the start of a copied region those references are not in |
| 3929 | /// the file, so they are dropped -- the picture before the cut is held for those |
| 3930 | /// few frames (four at this film's B-depth, a sixth of a second) rather than |
| 3931 | /// being written as pictures that cannot decode. The region still starts at the |
| 3932 | /// timeline frame it owns, so the sound never drifts. |
| 3933 | /// |
| 3934 | /// corner-cut: mp4 is not copied (its `hvc1` sample entry forbids in-band |
| 3935 | /// parameter sets, and the mp4 muxer here writes its sample table from a frame |
| 3936 | /// counter), and neither is H.264, which this project only writes into mp4. The |
| 3937 | /// upgrade path for both is a sample-table writer that takes explicit |
| 3938 | /// timestamps, which is what [`MkvMuxer::write_block`] already is for Matroska. |
| 3939 | struct CopyPlan { |
| 3940 | /// Every source a region reads, by the index the project names it with; |
| 3941 | /// `None` for a source no clip plays from. |
| 3942 | sources: Vec<Option<MkvDemuxer>>, |
| 3943 | regions: Vec<CopyRegion>, |
| 3944 | codec_id: &'static [u8], |
| 3945 | /// The `CodecPrivate` every region's source agrees on -- a track is declared |
| 3946 | /// once, so two sources that disagree about their parameter sets are not one |
| 3947 | /// copy. |
| 3948 | private: Vec<u8>, |
| 3949 | /// The picture's language as the first source states it ([`video_language`]), which the |
| 3950 | /// copied track declares. |
| 3951 | language: Option<String>, |
| 3952 | /// The container's colour tags exactly as the source wrote them, which the |
| 3953 | /// copied track declares: a field the source left out stays left out, and |
| 3954 | /// nothing is resolved in its place ([`MkvDemuxer::colour_tags`]). |
| 3955 | colour: Tags, |
| 3956 | /// The coded shape the copied track declares: the samples under it are the |
| 3957 | /// source's own, so the header names what they are stored at -- not the |
| 3958 | /// shape they are drawn at. |
| 3959 | width: u32, |
| 3960 | height: u32, |
| 3961 | /// The aspect the copied samples are drawn at, written into the file as |
| 3962 | /// display metadata ([`CopyParams::pixel_aspect`]): square for every |
| 3963 | /// ordinary source, so the header gains nothing. |
| 3964 | pixel_aspect: crate::demux::PixelAspect, |
| 3965 | } |
| 3966 | |
| 3967 | /// A run of source blocks copied in one piece: what a cut leaves behind, and |
| 3968 | /// what two spans that continue each other in the same file merge back into. |
| 3969 | struct CopyRegion { |
| 3970 | source: usize, |
| 3971 | /// Blocks of that source, in the file's own decode order. |
| 3972 | blocks: std::ops::Range<usize>, |
| 3973 | /// The *output* frame the region's first picture is shown at -- the |
| 3974 | /// project's own timeline frame less the range's own start, since a |
| 3975 | /// ranged export's file starts a fresh clock at zero. |
| 3976 | start: u32, |
| 3977 | } |
| 3978 | |
| 3979 | /// Why [`ExportSettings::exact`] cannot be honoured for this project right |
| 3980 | /// now, or `None` where [`CopyPlan`] already carries the whole file. A state |
| 3981 | /// report, not an instruction: it says what the file *is* rather than what to |
| 3982 | /// pick instead. |
| 3983 | /// |
| 3984 | /// Two shapes of reason, told apart because only one of them is permanent. |
| 3985 | /// **The container cannot carry the source's own codec at all** -- Exact was |
| 3986 | /// asked of an mp4, or of a Matroska file whose codec is not the source's own |
| 3987 | /// -- which is [`CopyPlan`]'s own corner-cut (mp4 copies nothing yet) and |
| 3988 | /// [`CopyPlan::of`]'s codec check, so it is checked here the same way rather |
| 3989 | /// than duplicated with different words. **The edit is what stops it** -- a |
| 3990 | /// cut off a sync point, a grade, a speed, a dissolve, a moved or scaled |
| 3991 | /// clip -- which the same format would carry exactly if the edit let it, so |
| 3992 | /// those six [`CopyPlan::of`] gates are named together rather than picked |
| 3993 | /// apart into six different sentences. |
| 3994 | pub fn exact_refusal( |
| 3995 | project: &Project, |
| 3996 | meta: &VideoMeta, |
| 3997 | settings: &ExportSettings, |
| 3998 | ) -> Option<String> { |
| 3999 | if !settings.exact || CopyPlan::of(project, meta, settings).is_some() { |
| 4000 | return None; |
| 4001 | } |
| 4002 | // An anamorphic source asked of a format that cannot state the aspect: the |
| 4003 | // blocks would copy, but the sample entry this writer produces has no |
| 4004 | // `pasp` box to carry it in, and a header that declares the coded pair |
| 4005 | // while the pixels are drawn 4/3 wide is a file that lies about its own |
| 4006 | // shape. Refused by name -- the sentence a reader is owed -- before the |
| 4007 | // container's codec question, because this is the *nearer* reason: a |
| 4008 | // Matroska copy needs no refusal at all (its track carries the aspect |
| 4009 | // beside the blocks, [`CopyParams::pixel_aspect`], which is ffmpeg's own |
| 4010 | // copy behaviour), so an anamorphic source's Exact row only ever dies on |
| 4011 | // this for an mp4. |
| 4012 | if settings.burn_subtitles.is_some() { |
| 4013 | return Some( |
| 4014 | "captions are drawn into the picture, so it is decoded and encoded again rather \ |
| 4015 | than copied byte for byte" |
| 4016 | .to_string(), |
| 4017 | ); |
| 4018 | } |
| 4019 | if !project.titles().is_empty() { |
| 4020 | return Some( |
| 4021 | "titles are drawn into the picture, so it is decoded and encoded again rather \ |
| 4022 | than copied byte for byte" |
| 4023 | .to_string(), |
| 4024 | ); |
| 4025 | } |
| 4026 | if picture_faded(project) { |
| 4027 | return Some( |
| 4028 | "a picture fade is pixel math, so it is decoded and encoded again rather than \ |
| 4029 | copied byte for byte" |
| 4030 | .to_string(), |
| 4031 | ); |
| 4032 | } |
| 4033 | if !settings.format.is_mkv() { |
| 4034 | let anamorphic = project.sources().iter().any(|source| { |
| 4035 | Demuxer::open(&source.path) |
| 4036 | .ok() |
| 4037 | .is_some_and(|(source_meta, _)| !source_meta.pixel_aspect.is_square()) |
| 4038 | }); |
| 4039 | if anamorphic { |
| 4040 | return Some( |
| 4041 | "a copy would lose the pixel aspect — this format cannot state it beside the \ |
| 4042 | coded picture, so the export re-encodes it into the square pixels it is drawn at" |
| 4043 | .to_string(), |
| 4044 | ); |
| 4045 | } |
| 4046 | } |
| 4047 | let codec = match settings.format { |
| 4048 | Format::Hevc => Codec::Hevc, |
| 4049 | Format::Av1 => Codec::Av1, |
| 4050 | _ => { |
| 4051 | return Some(format!( |
| 4052 | "{} cannot carry a source's own coded picture byte for byte — pick an HEVC or AV1 Matroska to copy it exactly", |
| 4053 | settings.format.name() |
| 4054 | )); |
| 4055 | } |
| 4056 | }; |
| 4057 | // The turn-baking corner-cut (a copied packet is the source's own coded |
| 4058 | // picture; this export bakes a display-matrix turn into the pixels) and |
| 4059 | // the rest of the reasons a copy says something other than what the |
| 4060 | // timeline says are [`CopyPlan::of`]'s own gates, so the container and |
| 4061 | // edit sentences below are checked the same way rather than duplicated |
| 4062 | // with different words. |
| 4063 | let carries = project.sources().iter().all(|source| { |
| 4064 | crate::demux::is_matroska(&source.path) |
| 4065 | && Demuxer::open(&source.path) |
| 4066 | .ok() |
| 4067 | .is_some_and(|(source_meta, _)| source_meta.codec == codec) |
| 4068 | }); |
| 4069 | Some(match carries { |
| 4070 | false => format!( |
| 4071 | "{} cannot carry the source's own codec byte for byte", |
| 4072 | settings.format.name() |
| 4073 | ), |
| 4074 | true => "the edit does not let this file copy the source exactly — a cut off a sync \ |
| 4075 | point, a grade, a speed, a transform or a canvas the source is not forces a \ |
| 4076 | re-encode" |
| 4077 | .to_string(), |
| 4078 | }) |
| 4079 | } |
| 4080 | |
| 4081 | impl CopyPlan { |
| 4082 | /// The plan for this timeline, or `None` where anything at all makes a copy |
| 4083 | /// say something other than what the timeline says -- in which case the |
| 4084 | /// caller encodes, which is what it always did. |
| 4085 | fn of(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<Self> { |
| 4086 | // Burned-in captions and titles are drawn into pixels, which a copy |
| 4087 | // never has. |
| 4088 | if settings.burn_subtitles.is_some() |
| 4089 | || !project.titles().is_empty() |
| 4090 | || picture_faded(project) |
| 4091 | { |
| 4092 | return None; |
| 4093 | } |
| 4094 | // An explicit picture depth is a request for samples the source may not |
| 4095 | // have (8 bits from a 10-bit HEVC, say), which a copy would silently |
| 4096 | // keep: the picture is re-encoded at the depth asked for. |
| 4097 | if settings.video_bit_depth.is_some() { |
| 4098 | return None; |
| 4099 | } |
| 4100 | // An HDR transfer is a statement the encoder writes into its own stream |
| 4101 | // (VUI, SEIs); a copy carries the source's. |
| 4102 | if settings.hdr.transfer != HdrTransfer::Sdr { |
| 4103 | return None; |
| 4104 | } |
| 4105 | let (codec_id, codec): (&'static [u8], Codec) = match settings.format { |
| 4106 | Format::Hevc => (b"V_MPEGH/ISO/HEVC", Codec::Hevc), |
| 4107 | Format::Av1 => (b"V_AV1", Codec::Av1), |
| 4108 | _ => return None, |
| 4109 | }; |
| 4110 | let entries = project.sources(); |
| 4111 | let mut sources: Vec<Option<MkvDemuxer>> = (0..entries.len()).map(|_| None).collect(); |
| 4112 | // The DRAWN pair each source is displayed at, kept beside its demuxer: |
| 4113 | // the fit gate below asks what a clip's policy does with this source's |
| 4114 | // picture on this canvas, and the picture the encoder places is the |
| 4115 | // drawn one ([`VideoMeta::width`]/`height`] -- the coded one with the |
| 4116 | // file's turn and its pixel aspect already applied), not the pair the |
| 4117 | // samples are stored at. A non-square source at its own displayed size |
| 4118 | // is therefore the identity again, which is what a copy of one is: the |
| 4119 | // aspect travels beside the track in the `Display*` elements rather |
| 4120 | // than being resampled into it. |
| 4121 | let mut drawn: Vec<Option<(u32, u32)>> = (0..entries.len()).map(|_| None).collect(); |
| 4122 | let mut declared: Option<(Vec<u8>, Tags, crate::demux::PixelAspect)> = None; |
| 4123 | let mut regions: Vec<CopyRegion> = Vec::new(); |
| 4124 | let r_start = settings.range.map_or(0, |(s, _)| s); |
| 4125 | for span in export_spans(project, settings.range) { |
| 4126 | let out_start = span.start - r_start; |
| 4127 | // A gap is black frames, which only an encoder makes. |
| 4128 | let (source, in_frame) = span.from?; |
| 4129 | if !span.speed.is_normal() || span.ramp.is_some() || span.reverse { |
| 4130 | return None; |
| 4131 | } |
| 4132 | // A layered picture is composed from more than one clip; no packet |
| 4133 | // of one of them is the picture. |
| 4134 | if layered_at(project, span.start) { |
| 4135 | return None; |
| 4136 | } |
| 4137 | // A copied packet is the source's own picture, never a blend: a |
| 4138 | // live dissolve on this span's tail forces the whole video track |
| 4139 | // through the encoder, exactly as a grade or a speed does below. |
| 4140 | // |
| 4141 | // corner-cut: the whole file falls back rather than only the |
| 4142 | // clips either side of the dissolve -- [`CopyPlan`] is already |
| 4143 | // all-or-nothing per export ([`CopyPlan`]'s own doc comment |
| 4144 | // states why), so one dissolve on a two-hour film re-encodes all |
| 4145 | // of it. Upgrade path: splice a re-encoded region between two |
| 4146 | // copied ones, which needs the sample-table writer that doc |
| 4147 | // comment already names as the cost of a finer copy. |
| 4148 | if dissolve_window(project, &span).is_some() { |
| 4149 | return None; |
| 4150 | } |
| 4151 | // The grade playback shows, which a copied packet never went |
| 4152 | // through. `None` and the identity are the same untouched picture. |
| 4153 | if project |
| 4154 | .composite_color_at(span.start) |
| 4155 | .is_some_and(|params| !params.is_identity()) |
| 4156 | { |
| 4157 | return None; |
| 4158 | } |
| 4159 | // A moved, scaled, rotated or cropped clip is a different picture |
| 4160 | // than the source's own packets, exactly as a grade is. |
| 4161 | if project |
| 4162 | .composite_transform_at(span.start) |
| 4163 | .is_some_and(|params| !params.is_identity()) |
| 4164 | { |
| 4165 | return None; |
| 4166 | } |
| 4167 | let path = &entries.get(source)?.path; |
| 4168 | if sources.get(source)?.is_none() { |
| 4169 | if !crate::demux::is_matroska(path) { |
| 4170 | return None; |
| 4171 | } |
| 4172 | let (source_meta, demuxer) = Demuxer::open(path).ok()?; |
| 4173 | let Demuxer::Mkv(demuxer) = demuxer else { |
| 4174 | return None; |
| 4175 | }; |
| 4176 | // The stream this file would carry, at the size and the rate the |
| 4177 | // timeline is in: anything else is a picture that has to be |
| 4178 | // coded again to become this file's. |
| 4179 | // |
| 4180 | // A source whose display matrix asks for a turn is one of |
| 4181 | // those: a copied packet is the source's own coded picture, and |
| 4182 | // this export bakes the turn into the pixels -- so a copy would |
| 4183 | // ship the file sideways. Re-encoding is the only honest |
| 4184 | // answer here. |
| 4185 | // |
| 4186 | // The size the copy declares is the source's *coded* pair, so |
| 4187 | // that is what the comparison asks: coded to coded. A display |
| 4188 | // comparison would refuse every anamorphic source that happens |
| 4189 | // to sit at the project's displayed shape and then write a |
| 4190 | // track that lies about its own samples -- and a square |
| 4191 | // source's coded pair is its display pair, so this asks nothing |
| 4192 | // new of the ordinary file. |
| 4193 | // |
| 4194 | // A source whose samples are not square is the *other* kind of |
| 4195 | // picture a copy cannot carry here: the blocks are its own |
| 4196 | // coded pixels and this engine's Matroska writer can now state |
| 4197 | // the aspect beside them -- but only this engine's |
| 4198 | // ([`MkvMuxer::create_copy`] writes the `Display*` elements), |
| 4199 | // and the copy's declared shape must stay the coded one. The |
| 4200 | // aspect travels with the track instead of being baked in, |
| 4201 | // which is ffmpeg's own copy behaviour, so an anamorphic |
| 4202 | // source is copyable *into Matroska* and nowhere else. |
| 4203 | if !source_meta.rotation.is_none() |
| 4204 | || source_meta.codec != codec |
| 4205 | || source_meta.coded_width != meta.coded_width |
| 4206 | || source_meta.coded_height != meta.coded_height |
| 4207 | || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()? |
| 4208 | != Rate::REAL_TIME |
| 4209 | || !demuxer.plain_blocks() |
| 4210 | { |
| 4211 | return None; |
| 4212 | } |
| 4213 | // Two sources that disagree about their pixel aspect are two |
| 4214 | // displayed pictures under one track; the copy declares one |
| 4215 | // aspect or none. |
| 4216 | let declares = ( |
| 4217 | demuxer.codec_private().to_vec(), |
| 4218 | demuxer.colour_tags(), |
| 4219 | source_meta.pixel_aspect, |
| 4220 | ); |
| 4221 | if declared.get_or_insert(declares.clone()) != &declares { |
| 4222 | return None; |
| 4223 | } |
| 4224 | sources[source] = Some(*demuxer); |
| 4225 | drawn[source] = Some((source_meta.width, source_meta.height)); |
| 4226 | } |
| 4227 | let demuxer = sources.get_mut(source)?.as_mut()?; |
| 4228 | // **The canvas gate** -- the condition this path was missing, and |
| 4229 | // the one that decides whether a copy can state the project's size. |
| 4230 | // |
| 4231 | // A copied packet is the source's own coded picture; the file this |
| 4232 | // export writes has to be the size the *project* is, and those are |
| 4233 | // two different pairs held in two different fields: |
| 4234 | // |
| 4235 | // * `meta.coded_width`/`coded_height` is the pair a *copied* track |
| 4236 | // declares -- what the samples are stored at, and what the check |
| 4237 | // above compares every source against. Only a *source* ever moves |
| 4238 | // it. |
| 4239 | // * `meta.width`/`meta.height` is the canvas -- what a person chose |
| 4240 | // with [`crate::playback::PlaybackSession::set_resolution`], |
| 4241 | // which writes those two and leaves the coded pair exactly where |
| 4242 | // it was. The encode door sizes everything from it |
| 4243 | // ([`Composer`]), so this is the size the file must have. |
| 4244 | // |
| 4245 | // ...and the two meet in the *drawn* pair: what this span is |
| 4246 | // composed from is the source's picture as a decoder delivers it, |
| 4247 | // turn and pixel aspect already applied |
| 4248 | // ([`VideoMeta::width`]/`height`]), which is what the check below is |
| 4249 | // asked about. |
| 4250 | // |
| 4251 | // A canvas that differs from the source's drawn pair means every |
| 4252 | // span is a picture the export has to *place onto* that canvas, and |
| 4253 | // there is no resampler on this path at all -- so a copy would ship |
| 4254 | // the source's frame size under the project's name, with the seat |
| 4255 | // line reading "copy · …" all the way out. That is the defect: not |
| 4256 | // a wrong rate or a wrong codec but the wrong geometry, silently, |
| 4257 | // on the one door that is supposed to be exact. |
| 4258 | // |
| 4259 | // Asked as a *placement* rather than as two separate conditions -- |
| 4260 | // is this clip's policy the identity for this source on this canvas |
| 4261 | // -- because that is the one thing a condition has to mean here: |
| 4262 | // [`fit_is_identity`] computes it from [`scale::fit_rect`] itself, |
| 4263 | // so it holds for `Fill` on a canvas the size of the picture the |
| 4264 | // source draws at (there is nothing to crop there) and refuses a |
| 4265 | // canvas of another size under *every* policy, and a |
| 4266 | // [`crate::scale::FitPolicy`] added later is judged by what it |
| 4267 | // places rather than by being absent from a list here. |
| 4268 | if !fit_is_identity( |
| 4269 | drawn.get(source).copied().flatten()?, |
| 4270 | (meta.width, meta.height), |
| 4271 | project.composite_fit_at(span.start), |
| 4272 | ) { |
| 4273 | return None; |
| 4274 | } |
| 4275 | // The window this span reads, in the blocks the whole engine counts |
| 4276 | // a source's frames in. It has to *be* whole groups of pictures: a |
| 4277 | // copy that began between two sync points would hand a decoder |
| 4278 | // pictures whose references are not in the file, and one that ended |
| 4279 | // between them would drop a reference the pictures before it need. |
| 4280 | let (start, end) = (in_frame as usize, in_frame as usize + span.len as usize); |
| 4281 | if end > demuxer.block_count() |
| 4282 | || !demuxer.is_sync(start) |
| 4283 | || (end < demuxer.block_count() && !demuxer.is_sync(end)) |
| 4284 | { |
| 4285 | return None; |
| 4286 | } |
| 4287 | // Two spans that continue each other in one file are one region: |
| 4288 | // nothing was cut between them, so the leading pictures across that |
| 4289 | // boundary still have every reference they need. |
| 4290 | match regions.last_mut() { |
| 4291 | Some(last) |
| 4292 | if last.source == source |
| 4293 | && last.blocks.end == start |
| 4294 | && last.start + (last.blocks.end - last.blocks.start) as u32 |
| 4295 | == out_start => |
| 4296 | { |
| 4297 | last.blocks.end = end; |
| 4298 | } |
| 4299 | _ => regions.push(CopyRegion { |
| 4300 | source, |
| 4301 | blocks: start..end, |
| 4302 | start: out_start, |
| 4303 | }), |
| 4304 | } |
| 4305 | } |
| 4306 | let (private, colour, pixel_aspect) = declared?; |
| 4307 | Some(Self { |
| 4308 | sources, |
| 4309 | regions, |
| 4310 | codec_id, |
| 4311 | private, |
| 4312 | language: video_language(project), |
| 4313 | colour, |
| 4314 | // The track the copy declares is the source's coded shape -- the |
| 4315 | // samples under it are the source's own -- with the aspect beside |
| 4316 | // it as the display metadata ([`CopyParams::pixel_aspect`]). |
| 4317 | width: meta.coded_width, |
| 4318 | height: meta.coded_height, |
| 4319 | pixel_aspect, |
| 4320 | }) |
| 4321 | } |
| 4322 | |
| 4323 | /// The file itself: one Matroska muxer, every region's blocks through it in |
| 4324 | /// the order and at the timing their source states. |
| 4325 | #[allow( |
| 4326 | clippy::too_many_arguments, |
| 4327 | reason = "the copy's one run: its inputs are passed positionally at its one call site, and a struct would only rename them" |
| 4328 | )] |
| 4329 | fn run( |
| 4330 | mut self, |
| 4331 | out: &Path, |
| 4332 | meta: &VideoMeta, |
| 4333 | shared: &Shared, |
| 4334 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, |
| 4335 | subs: Vec<SubParams>, |
| 4336 | total: u32, |
| 4337 | chapters: &[(u64, String)], |
| 4338 | ) -> crate::Result<()> { |
| 4339 | let mut muxer = MkvMuxer::create_copy( |
| 4340 | out, |
| 4341 | &CopyParams { |
| 4342 | width: self.width, |
| 4343 | height: self.height, |
| 4344 | frame_rate: meta.frame_rate, |
| 4345 | codec_id: self.codec_id, |
| 4346 | codec_private: &self.private, |
| 4347 | colour: self.colour, |
| 4348 | pixel_aspect: self.pixel_aspect, |
| 4349 | language: self.language.clone(), |
| 4350 | }, |
| 4351 | audio, |
| 4352 | subs, |
| 4353 | )?; |
| 4354 | muxer.set_chapters(chapters)?; |
| 4355 | // Nanoseconds a timeline frame lasts, which is what a region's own |
| 4356 | // position on the timeline is measured in. |
| 4357 | let frame_ns = 1e9 / meta.frame_rate; |
| 4358 | let mut done = 0u32; |
| 4359 | for region in &self.regions { |
| 4360 | let demuxer = self.sources[region.source] |
| 4361 | .as_mut() |
| 4362 | .ok_or("a copied region names a source that was never opened")?; |
| 4363 | let base = (f64::from(region.start) * frame_ns).round() as i64; |
| 4364 | // When the region's first picture is shown on its source's clock; |
| 4365 | // everything after it is written that far along from `base`. |
| 4366 | let mut origin: Option<i64> = None; |
| 4367 | for index in region.blocks.clone() { |
| 4368 | cancelled(shared)?; |
| 4369 | let Some(block) = demuxer.coded_block(index)? else { |
| 4370 | break; |
| 4371 | }; |
| 4372 | let origin = *origin.get_or_insert(block.ts_ns); |
| 4373 | // The leading pictures of the group this region opens on: shown |
| 4374 | // before it, coded against the group before it, and that group |
| 4375 | // is not in this file. Dropped rather than written as pictures |
| 4376 | // no decoder can put back together. |
| 4377 | if block.ts_ns < origin { |
| 4378 | continue; |
| 4379 | } |
| 4380 | muxer.write_block(block.bytes, block.key, base + block.ts_ns - origin)?; |
| 4381 | done += 1; |
| 4382 | shared |
| 4383 | .progress |
| 4384 | .fetch_max(picture_progress(done, total), Ordering::Relaxed); |
| 4385 | } |
| 4386 | } |
| 4387 | // Everything up to here is still cancellable, exactly as the encoded |
| 4388 | // path is up to its own `finish`. |
| 4389 | cancelled(shared)?; |
| 4390 | muxer.finish()?; |
| 4391 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); |
| 4392 | Ok(()) |
| 4393 | } |
| 4394 | } |
| 4395 | |
| 4396 | /// Whether `policy` places the picture `source` is DRAWN at onto this `canvas` |
| 4397 | /// without touching a sample: the whole picture, at the whole canvas, 1:1. |
| 4398 | /// |
| 4399 | /// The 1:1 is the half the rects cannot state: a source scaled onto a canvas |
| 4400 | /// of another aspect is placed whole and cropped nowhere, which is a resize |
| 4401 | /// and not an identity -- so the pairs themselves are compared first. |
| 4402 | /// |
| 4403 | /// The pair asked about is the **drawn** one ([`VideoMeta::width`]/`height`]), |
| 4404 | /// never the coded one: what the fit is composed against is what a decoder |
| 4405 | /// hands the canvas after the file's turn and its pixel aspect have been |
| 4406 | /// applied, so a 1440x1080 file with a 4:3 sample aspect is a 1920x1080 |
| 4407 | /// picture, and a project at 1920x1080 is copying it exactly. The coded pair |
| 4408 | /// has its own question -- what a copied track *declares* -- and the coded-to- |
| 4409 | /// coded check in [`CopyPlan::of`] already asks that one; asking it twice, in |
| 4410 | /// the geometry's stead, refuses a copy main performs byte for byte. |
| 4411 | /// |
| 4412 | /// Asked from [`scale::fit_rect`] -- the one function that *is* a fit policy's |
| 4413 | /// meaning -- rather than from the policy itself, which is what makes this |
| 4414 | /// canvas-aware twice over: `Fill` on a canvas the size of the source's own |
| 4415 | /// samples is the identity (nothing is cropped, because there is nothing to |
| 4416 | /// crop), while `Fit` on a canvas of another aspect is not (it bars or crops). |
| 4417 | /// A policy added to [`FitPolicy`] later is judged by what it places, not by |
| 4418 | /// being absent from a list here. |
| 4419 | fn fit_is_identity( |
| 4420 | source: (u32, u32), |
| 4421 | canvas: (u32, u32), |
| 4422 | policy: crate::scale::FitPolicy, |
| 4423 | ) -> bool { |
| 4424 | // The pairs themselves: a picture is the canvas only when it *is* the |
| 4425 | // canvas, and the rects below cannot say so -- a source scaled onto a |
| 4426 | // canvas of another aspect is still placed whole and still cropped |
| 4427 | // nowhere, which is a resize, and a resize is exactly what a copied packet |
| 4428 | // cannot be. |
| 4429 | if source != canvas { |
| 4430 | return false; |
| 4431 | } |
| 4432 | let (placed, cropped) = crate::scale::fit_rect(source.0, source.1, canvas.0, canvas.1, policy); |
| 4433 | placed |
| 4434 | == crate::scale::Rect { |
| 4435 | x: 0, |
| 4436 | y: 0, |
| 4437 | w: canvas.0, |
| 4438 | h: canvas.1, |
| 4439 | } |
| 4440 | && cropped |
| 4441 | == crate::scale::Rect { |
| 4442 | x: 0, |
| 4443 | y: 0, |
| 4444 | w: source.0, |
| 4445 | h: source.1, |
| 4446 | } |
| 4447 | } |
| 4448 | |
| 4449 | /// The same lane, *decoded*: what a packet copy cannot carry comes out here as |
| 4450 | /// AAC written by this project's own encoder. |
| 4451 | /// |
| 4452 | /// The samples are the very ones [`run_audio`] would put in a WAV -- the same |
| 4453 | /// opener with the same equalizers, the same rates and the same resize onto the |
| 4454 | /// timeline's own length -- so an mp4 and a WAV of one timeline are one mix, |
| 4455 | /// not two that could disagree. |
| 4456 | /// |
| 4457 | /// AAC-LC's encoder delay is one 1024-frame block, which is exactly the priming |
| 4458 | /// a reader drops when the file carries no edit list (`audio::DEFAULT_PRIMING`, |
| 4459 | /// and [`crate::mux::Mp4Muxer`] writes none): the first packet is that delay, so |
| 4460 | /// the sound starts at timeline frame 0 as a copied track's does. |
| 4461 | /// |
| 4462 | /// corner-cut: the mix sits in memory as f32 before it is encoded (~46 MB a |
| 4463 | /// minute of 48 kHz stereo), for [`run_audio`]'s reason -- sizing the track |
| 4464 | /// against the timeline, publishing the mix third of the bar as it goes and |
| 4465 | /// answering a cancel before the encode are whole-mix concerns here. The |
| 4466 | /// upgrade path is a chunked push: `ec_aac`'s encoder itself streams. |
| 4467 | #[allow(clippy::too_many_arguments)] |
| 4468 | fn encode_audio( |
| 4469 | project: &Project, |
| 4470 | meta: &VideoMeta, |
| 4471 | kbps: u32, |
| 4472 | mkv: bool, |
| 4473 | webm: bool, |
| 4474 | shared: &Shared, |
| 4475 | sample_rate: Option<u32>, |
| 4476 | range: Option<(u32, u32)>, |
| 4477 | ) -> crate::Result<Option<ExportAudio>> { |
| 4478 | let sources = project.audio_sources(); |
| 4479 | let range_start = range.map_or(0, |(s, _)| s); |
| 4480 | let pre = warm_up(project, range_start, meta.frame_rate); |
| 4481 | let offset = range_start - pre; |
| 4482 | let segs = project.audio_segments_from(offset, meta.frame_rate); |
| 4483 | let eqs = project.audio_eqs_from(offset, meta.frame_rate); |
| 4484 | let speeds = project.audio_speeds_from(offset, meta.frame_rate); |
| 4485 | let fades = project.audio_fades_from(offset, meta.frame_rate); |
| 4486 | // Coarse stage timers, in the same voice as `export video: copy` below: an |
| 4487 | // export of a feature film spends minutes in here before a byte of picture |
| 4488 | // is written, and which minutes went where is the first question asked of a |
| 4489 | // slow export. Three lines an export, so they stay on. |
| 4490 | let mixed = std::time::Instant::now(); |
| 4491 | let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade( |
| 4492 | &sources, |
| 4493 | &segs, |
| 4494 | &eqs, |
| 4495 | &speeds, |
| 4496 | &fades, |
| 4497 | meta.frame_rate, |
| 4498 | &project.audio_gains(), |
| 4499 | &project.audio_ducks(), |
| 4500 | &project.audio_voices(), |
| 4501 | project.limiter(), |
| 4502 | sample_rate, |
| 4503 | )? |
| 4504 | else { |
| 4505 | return Ok(None); // no audio to write, exactly as a copy of nothing is |
| 4506 | }; |
| 4507 | let freq_index = ec_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| { |
| 4508 | format!( |
| 4509 | "{} Hz is not an AAC sample rate: export WAV, FLAC, MP3 or OGG, which write it as \ |
| 4510 | it is", |
| 4511 | audio.sample_rate |
| 4512 | ) |
| 4513 | })?; |
| 4514 | let channels = usize::from(audio.channels.max(1)); |
| 4515 | // The timeline's length, not the mix's: a segment resolves its window to |
| 4516 | // whole samples on its own, so the sum can miss by a sample or two and a |
| 4517 | // source that ran out early would leave the track short under a picture |
| 4518 | // that is not. One resize settles both, as [`run_audio`]'s does. |
| 4519 | let out_frames = range.map_or(project.media_frames(), |(s, e)| { |
| 4520 | e.min(project.media_frames()).saturating_sub(s) |
| 4521 | }); |
| 4522 | let total = (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() |
| 4523 | as usize |
| 4524 | * channels; |
| 4525 | let skip = warm_up_samples(range_start, pre, meta.frame_rate, audio.sample_rate, channels); |
| 4526 | let mut samples: Vec<f32> = Vec::with_capacity(total + skip); |
| 4527 | for chunk in chunks { |
| 4528 | // The only place a cancelled export can be answered before the whole |
| 4529 | // timeline has been mixed. This pass runs on a thread of its own now |
| 4530 | // ([`run`]), so without this a cancel left it mixing a feature film |
| 4531 | // for minutes behind a job nobody is waiting for any more, writing |
| 4532 | // into a `Shared` whose outcome was already settled. |
| 4533 | cancelled(shared)?; |
| 4534 | samples.extend(chunk.samples); |
| 4535 | // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of |
| 4536 | // the three stages and the only one that can be counted as it goes. |
| 4537 | // |
| 4538 | // `fetch_max` and not `store`, for the reason [`Shared::progress`] |
| 4539 | // states: this runs on the audio thread while the picture publishes |
| 4540 | // numbers above [`AUDIO_BAND`] from the other, and a `store` of this |
| 4541 | // small one pulled the bar backwards 5,458 times over one film export. |
| 4542 | shared.progress.fetch_max( |
| 4543 | (samples.len().saturating_sub(skip).min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32, |
| 4544 | Ordering::Relaxed, |
| 4545 | ); |
| 4546 | // The range is in: the mix past its end would only be cut off below. |
| 4547 | if samples.len() >= skip + total { |
| 4548 | break; |
| 4549 | } |
| 4550 | } |
| 4551 | samples.drain(..skip.min(samples.len())); |
| 4552 | samples.resize(total, 0.0); |
| 4553 | if let Some(target) = shared.loudness { |
| 4554 | level_to_target(&mut samples, audio.sample_rate, audio.channels.max(1), target); |
| 4555 | } |
| 4556 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!( |
| 4557 | "export audio: mixed {:.1} s of sound in {:.1} s", |
| 4558 | total as f64 / f64::from(audio.sample_rate.max(1)) / channels as f64, |
| 4559 | mixed.elapsed().as_secs_f64() |
| 4560 | ); } |
| 4561 | |
| 4562 | // Opus where the container carries it and the mix is inside the envelope |
| 4563 | // this encoder is *measured* correct in ([`encode_opus`]): a Matroska file, |
| 4564 | // 48 kHz, mono or stereo. An Opus source edited into an mkv export |
| 4565 | // therefore leaves as Opus instead of being turned into AAC on the way |
| 4566 | // out, which is the one generation of loss an all-Opus timeline used to |
| 4567 | // pay for being cut. |
| 4568 | // |
| 4569 | // Everything else falls through to the AAC below and is unchanged by this: |
| 4570 | // every mp4, a 44.1 kHz timeline. The rate is the mix's own -- there is no |
| 4571 | // resampler on this path, and inventing one to reach 48 kHz would resample |
| 4572 | // a whole timeline to satisfy a codec, which is a bigger change to the |
| 4573 | // sound than the codec is. |
| 4574 | // ...and again before either encoder is entered: both of them run to the |
| 4575 | // end of the mix without a checkpoint of their own, so this is the last |
| 4576 | // moment a cancel costs seconds rather than the whole encode. |
| 4577 | cancelled(shared)?; |
| 4578 | if mkv |
| 4579 | && audio.sample_rate == OPUS_RATE |
| 4580 | && (1..=2).contains(&channels) |
| 4581 | && let Some((packets, pre_skip)) = encode_opus(&samples, kbps, channels)? |
| 4582 | { |
| 4583 | return Ok(Some(ExportAudio { |
| 4584 | params: crate::AacTrackParams { |
| 4585 | freq_index, |
| 4586 | chan_conf: channels as u8, |
| 4587 | sample_rate: OPUS_RATE, |
| 4588 | }, |
| 4589 | packets, |
| 4590 | copied: false, |
| 4591 | opus_pre_skip: Some(pre_skip), |
| 4592 | language: None, |
| 4593 | pcm_frames: Some(samples.len() as u64 / channels as u64), |
| 4594 | })); |
| 4595 | } |
| 4596 | |
| 4597 | // A WebM file carries Opus or nothing: a track the gate handed back is named |
| 4598 | // here rather than written as AAC into a file no WebM reader will open. |
| 4599 | if webm { |
| 4600 | return Err( |
| 4601 | "the sound could not be coded as Opus, the only sound a WebM file \ |
| 4602 | carries: export a Matroska instead" |
| 4603 | .into(), |
| 4604 | ); |
| 4605 | } |
| 4606 | // The caller's rate, never the encoder's own 128 default -- see |
| 4607 | // [`DEFAULT_AUDIO_KBPS`] for why the untouched figure is 256. |
| 4608 | let mut encoder = ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig { |
| 4609 | bitrate_bps: kbps * 1_000, |
| 4610 | ..Default::default() |
| 4611 | }); |
| 4612 | encoder.push_pcm(&samples, audio.channels.max(1), audio.sample_rate)?; |
| 4613 | encoder.finish(); |
| 4614 | let mut packets = Vec::new(); |
| 4615 | // `next_packet` after `finish` yields packets until `Eof` and nothing else, |
| 4616 | // so the loop ends on the only error it can see. |
| 4617 | while let Ok(packet) = encoder.next_packet() { |
| 4618 | cancelled(shared)?; |
| 4619 | packets.push(crate::AacPacket { |
| 4620 | bytes: packet.data, |
| 4621 | samples: packet.duration, |
| 4622 | }); |
| 4623 | } |
| 4624 | Ok(Some(ExportAudio { |
| 4625 | params: crate::AacTrackParams { |
| 4626 | freq_index, |
| 4627 | // 1 and 2 are the ISO channel configurations for mono and stereo, |
| 4628 | // and what the opener hands the timeline is one of those whatever |
| 4629 | // the source carried ([`crate::audio::downmix`]). |
| 4630 | chan_conf: audio.channels.max(1) as u8, |
| 4631 | sample_rate: audio.sample_rate, |
| 4632 | }, |
| 4633 | packets, |
| 4634 | copied: false, |
| 4635 | opus_pre_skip: None, |
| 4636 | language: None, |
| 4637 | pcm_frames: Some(samples.len() as u64 / channels as u64), |
| 4638 | })) |
| 4639 | } |
| 4640 | |
| 4641 | /// The one rate Opus codes at. The container may state another one in its |
| 4642 | /// `OpusHead` and every decoder still runs at 48 kHz (RFC 7845 §5.1), so a |
| 4643 | /// timeline at any other rate is not "encoded at its own rate" here -- it is |
| 4644 | /// resampled or it is not Opus, and [`encode_audio`] picks the second. |
| 4645 | pub(crate) const OPUS_RATE: u32 = 48_000; |
| 4646 | |
| 4647 | /// 20 ms at [`OPUS_RATE`], the frame every Opus muxer in the wild writes: |
| 4648 | /// long enough that the per-packet overhead is nothing, short enough that a |
| 4649 | /// Matroska block timestamp in whole milliseconds is exact. |
| 4650 | const OPUS_FRAME: usize = 960; |
| 4651 | |
| 4652 | /// The most this project asks of the Opus encoder, in kbps, and why it is a cap |
| 4653 | /// rather than the four rates the Sound row offers. |
| 4654 | /// |
| 4655 | /// History, because the number moved once already and the reason it could is |
| 4656 | /// part of the record. Under `opus-rs 0.1.26` the ceiling was 128: that encoder |
| 4657 | /// fell off a cliff at a rate that depended on the *content*, and above it a |
| 4658 | /// conformant decoder got noise back. Measured on three one-second spans of a |
| 4659 | /// real 5.1 Opus film, encoded there and decoded with `ruopus` -- which was not |
| 4660 | /// the suspect, since it decoded ffmpeg's own libopus at 256 kbps to |
| 4661 | /// correlation 1.00000 on the same material: |
| 4662 | /// |
| 4663 | /// ```text |
| 4664 | /// kbps 120 128 136 144 152 160 |
| 4665 | /// span A 0.945 0.937 0.452 0.206 0.223 0.163 |
| 4666 | /// span B 0.986 0.989 0.697 0.153 0.114 0.149 |
| 4667 | /// span C 0.999 0.994 0.951 0.335 0.266 0.326 |
| 4668 | /// libopus 0.997 0.998 -- -- -- 0.996 (same spans, control) |
| 4669 | /// ``` |
| 4670 | /// |
| 4671 | /// So: usable to 128, ruined by 136 on real film sound -- and mono worse, at |
| 4672 | /// every rate, which is why a mono mix kept the AAC path entirely. `ec-opus` |
| 4673 | /// has no such cliff: its own suite holds every rate of the format's table to |
| 4674 | /// the reference decoders, mono, stereo and 5.1 alike, and this project |
| 4675 | /// re-measures the high band and the mono path where the old encoder failed |
| 4676 | /// (`the_opus_encoder_is_pinned_to_the_band_it_was_measured_in`). |
| 4677 | /// |
| 4678 | /// It is still not *trusted*: every track is decoded again and measured before |
| 4679 | /// it is written ([`opus_fidelity`]), because a rate nobody measured on *your* |
| 4680 | /// sound is not something a constant can be safe against on its own. |
| 4681 | /// The ceiling is the Sound row's ([`AUDIO_KBPS`]), not the format's 510 kbps: |
| 4682 | /// a rate nothing in the product can ask for is a rate nothing here measures. |
| 4683 | /// 320 covers the row honestly, including the 256 default |
| 4684 | /// ([`DEFAULT_AUDIO_KBPS`]) the old cap silently halved on a Matroska export. |
| 4685 | pub(crate) const OPUS_MAX_KBPS: u32 = 320; |
| 4686 | |
| 4687 | /// How well a track has to survive its own round trip to be written as Opus: |
| 4688 | /// the correlation between the mix and the decode of what was encoded from it. |
| 4689 | /// A good encoder scores 0.98-0.999 on this material (libopus, measured above); |
| 4690 | /// the failure mode is not subtle at all, scoring 0.1-0.7. 0.95 sits in the gap |
| 4691 | /// with room on both sides, and what fails it is written as AAC -- the export's |
| 4692 | /// own encoder line then says AAC, so the fallback is visible rather than |
| 4693 | /// silent. |
| 4694 | const OPUS_MIN_FIDELITY: f64 = 0.95; |
| 4695 | |
| 4696 | /// The encoder's lookahead at [`OPUS_RATE`] in the mode this envelope always |
| 4697 | /// selects (CELT-only: 2.5 ms). The pre-skip a file states is this *plus* the |
| 4698 | /// warm-up frame [`encode_opus`] throws away. Measured by |
| 4699 | /// cross-correlating the decode against the source, not taken from the crate -- |
| 4700 | /// it exposes no lookahead getter -- and asserted at both ends of the rate band |
| 4701 | /// in `tests/opus_export.rs`, which is what catches a version that changes it. |
| 4702 | const OPUS_PRE_SKIP: u16 = 120; |
| 4703 | |
| 4704 | /// The mix as Opus packets, one per [`OPUS_FRAME`], plus the pre-skip that has |
| 4705 | /// to be declared in front of them. Mono or stereo, at [`OPUS_RATE`] -- the |
| 4706 | /// caller checks all of it, because outside that envelope this encoder is not |
| 4707 | /// one this project is willing to write files with ([`OPUS_MAX_KBPS`]). |
| 4708 | /// |
| 4709 | /// The tail frame is padded with silence rather than dropped: Opus codes whole |
| 4710 | /// frames and a track a few milliseconds short under a picture that is not is |
| 4711 | /// the drift every other path here is written to avoid. The pre-skip trims the |
| 4712 | /// front; the container's duration trims the back. |
| 4713 | fn encode_opus( |
| 4714 | samples: &[f32], |
| 4715 | kbps: u32, |
| 4716 | channels: usize, |
| 4717 | ) -> crate::Result<Option<(Vec<crate::AacPacket>, u16)>> { |
| 4718 | let mut encoder = ec_opus::Encoder::new(OPUS_RATE, channels, ec_opus::Application::Audio) |
| 4719 | .map_err(|e| format!("the Opus encoder refused 48 kHz {channels}-channel sound: {e}"))?; |
| 4720 | // CBR, the crate's default: every packet exactly the rate's size. The old |
| 4721 | // seat ran opus-rs's VBR; the gate below measures either, and a fixed |
| 4722 | // packet size is the friendlier neighbour to a muxer's block budget. |
| 4723 | encoder.set_bitrate(kbps.min(OPUS_MAX_KBPS) * 1_000); |
| 4724 | // No complexity knob on this crate: the reference's default (9) is baked |
| 4725 | // into its rate arithmetic, one percent of equiv rate away from the 10 the |
| 4726 | // old encoder was asked for. |
| 4727 | let mut packets = Vec::new(); |
| 4728 | let mut frame = vec![0f32; OPUS_FRAME * channels]; |
| 4729 | // 1275 bytes is the most one Opus frame may weigh (RFC 6716 §3.2); this is |
| 4730 | // that with room for the TOC and a padded frame, so `encode_float` never |
| 4731 | // has to refuse for want of a buffer. |
| 4732 | let mut out = vec![0u8; 1500]; |
| 4733 | // The head, coded **twice**. An encoder's very first frame has no history |
| 4734 | // behind it and comes out ramped and out of phase -- measured on a 440 Hz |
| 4735 | // fixture, the first 20 ms of the export correlated 0.09 with the source |
| 4736 | // where every later window correlated 0.9997 -- and 20 ms of wrong sound at |
| 4737 | // the head of a file is the kind of thing nobody hears in a test and |
| 4738 | // everybody hears in the first frame of a cut. So the first frame is fed in |
| 4739 | // once to warm the encoder, and thrown away again by the pre-skip: exactly |
| 4740 | // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet. |
| 4741 | let coded = std::time::Instant::now(); |
| 4742 | let warm = samples.len().min(OPUS_FRAME * channels); |
| 4743 | // ...and one silent frame after the sound, for the same delay seen from the |
| 4744 | // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so |
| 4745 | // without a frame to push them out the last 2.5 ms of the timeline stay |
| 4746 | // inside it and the track ends short under a picture that does not. |
| 4747 | let blocks = std::iter::once(&samples[..warm]) |
| 4748 | .chain(samples.chunks(OPUS_FRAME * channels)) |
| 4749 | .chain(std::iter::once(&samples[..0])); |
| 4750 | for block in blocks { |
| 4751 | frame[..block.len()].copy_from_slice(block); |
| 4752 | frame[block.len()..].fill(0.0); |
| 4753 | let len = encoder |
| 4754 | .encode_float(&frame, OPUS_FRAME, &mut out) |
| 4755 | .map_err(|e| format!("Opus encode failed: {e}"))?; |
| 4756 | packets.push(crate::AacPacket { |
| 4757 | bytes: out[..len].to_vec(), |
| 4758 | samples: OPUS_FRAME as u32, |
| 4759 | }); |
| 4760 | } |
| 4761 | // ...and now the part that is not optimism: what was just written is |
| 4762 | // decoded again and measured against what went in, and a track that does |
| 4763 | // not come back is not written at all ([`OPUS_MIN_FIDELITY`]). The caller |
| 4764 | // falls through to AAC, which is exactly where it stood before this seat |
| 4765 | // existed -- a worse codec is a fair trade for a track that is the sound. |
| 4766 | // |
| 4767 | // corner-cut: this costs one Opus decode of the whole track (a minute of |
| 4768 | // sound in a few hundred milliseconds, against a video encode that is |
| 4769 | // minutes). Upgrade path is deleting it, the day this encoder can be |
| 4770 | // trusted at the rate it is asked for. |
| 4771 | let encoded = coded.elapsed().as_secs_f64(); |
| 4772 | let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16; |
| 4773 | let measured = std::time::Instant::now(); |
| 4774 | let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip), channels); |
| 4775 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!( |
| 4776 | "export audio: Opus encode {encoded:.1} s, fidelity {fidelity:.4} measured in {:.1} s", |
| 4777 | measured.elapsed().as_secs_f64() |
| 4778 | ); } |
| 4779 | Ok((fidelity >= OPUS_MIN_FIDELITY).then_some((packets, pre_skip))) |
| 4780 | } |
| 4781 | |
| 4782 | /// Packets one sampled window listens to: 5 s at [`OPUS_FRAME`]. |
| 4783 | const FIDELITY_WINDOW: usize = 250; |
| 4784 | |
| 4785 | /// How many of them a long track is judged on -- a minute of sound, wherever |
| 4786 | /// the track's length puts them, and a constant cost rather than one that grows |
| 4787 | /// with the film ([`opus_fidelity`]). |
| 4788 | const FIDELITY_WINDOWS: usize = 12; |
| 4789 | |
| 4790 | /// Packets decoded into a window and thrown away before it is measured. CELT |
| 4791 | /// predicts across frames, so a decoder started cold mid-stream is behind its |
| 4792 | /// own history for a few frames; 100 ms is far more than it needs and is not |
| 4793 | /// worth counting. |
| 4794 | const FIDELITY_WARMUP: usize = 5; |
| 4795 | |
| 4796 | /// How much sound a window must carry before its correlation means anything: |
| 4797 | /// mean square per sample. A window of digital silence -- the head of a film, |
| 4798 | /// the gap between a feature and its credits -- correlates with nothing, and |
| 4799 | /// failing a track for it would send perfectly good sound to AAC. |
| 4800 | const FIDELITY_FLOOR: f64 = 1e-9; |
| 4801 | |
| 4802 | /// The correlation between `samples` and the decode of `packets` with the first |
| 4803 | /// `pre_skip` frames dropped: 1.0 is the same waveform, and this codec's failure |
| 4804 | /// mode lands near 0.1. Streamed packet by packet -- the decode is never held, |
| 4805 | /// only three running sums -- because the mix behind it is already the biggest |
| 4806 | /// thing in an export ([`encode_audio`]'s corner-cut). |
| 4807 | /// |
| 4808 | /// A packet the decoder refuses is 0.0 and no argument: a track this project |
| 4809 | /// cannot read is exactly what this is here to catch. |
| 4810 | /// |
| 4811 | /// **Sampled above a minute of sound, and the median window is the answer.** |
| 4812 | /// This decode was the whole cost of exporting a feature film under the |
| 4813 | /// previous decoder: `ruopus` ran its inverse MDCT at 0.2x real time (measured, |
| 4814 | /// 24.2 s for 121.5 s of stereo; `ec-opus`, the decoder here now, is far |
| 4815 | /// quicker, and the sampling survives it because it costs almost nothing to |
| 4816 | /// keep), |
| 4817 | /// so judging every packet of a two-and-a-half-hour film costs half an hour |
| 4818 | /// before a byte of picture is written -- which is what it did, and what made a |
| 4819 | /// copy export that has no encoding to do at all sit at zero for twenty minutes. |
| 4820 | /// [`FIDELITY_WINDOWS`] windows spread evenly across the track cost the same |
| 4821 | /// minute of decode whatever the film's length, and what they are looking for |
| 4822 | /// survives sampling: [`OPUS_MAX_KBPS`]'s cliff is a *rate* the encoder falls |
| 4823 | /// off everywhere that rate is used, not a defect of one bar of music. |
| 4824 | /// |
| 4825 | /// The **median** and not the worst, and that is measured rather than cautious. |
| 4826 | /// Forty five-second windows of a real 5.1 film's mix, encoded here at 128 kbps |
| 4827 | /// and decoded back, in order: |
| 4828 | /// |
| 4829 | /// ```text |
| 4830 | /// 0.803 0.835 0.938 0.940 0.960 0.987 0.994 ... median 0.998 ... 0.999 |
| 4831 | /// ``` |
| 4832 | /// |
| 4833 | /// Five of the thirty-nine that carried sound sit under [`OPUS_MIN_FIDELITY`] on |
| 4834 | /// a track that is *good* -- which is the same thing the table in |
| 4835 | /// [`OPUS_MAX_KBPS`] shows, where a span scoring 0.937 at 128 kbps is inside the |
| 4836 | /// usable band. A worst-window rule at 0.95 therefore refuses films this encoder |
| 4837 | /// handles perfectly well, while the failure it exists for is the opposite |
| 4838 | /// shape: at 136 kbps the same three measured spans read 0.452, 0.697, 0.951, |
| 4839 | /// and at 256 kbps the whole track correlates 0.06. Half a track cannot be |
| 4840 | /// ruined without the middle of the list moving, so the median separates the two |
| 4841 | /// by a margin no single window can (0.998 against under 0.7) -- and a track |
| 4842 | /// under a minute is one window, where median and whole-track correlation are |
| 4843 | /// the same number the gate always used. |
| 4844 | fn opus_fidelity( |
| 4845 | packets: &[crate::AacPacket], |
| 4846 | samples: &[f32], |
| 4847 | pre_skip: usize, |
| 4848 | channels: usize, |
| 4849 | ) -> f64 { |
| 4850 | // Short enough to hear all of: every fixture, every unit test, and any |
| 4851 | // track under a minute. There is nothing to sample from. |
| 4852 | let all = FIDELITY_WINDOW * FIDELITY_WINDOWS; |
| 4853 | if packets.len() <= all { |
| 4854 | return window_fidelity(packets, samples, pre_skip, channels, 0, 0, packets.len()) |
| 4855 | .unwrap_or(1.0); |
| 4856 | } |
| 4857 | // Evenly spread, first window at the head: the head is where an encoder's |
| 4858 | // own warm-up would show, and the last starts a window short of the end so |
| 4859 | // no window runs past the packets. |
| 4860 | let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1); |
| 4861 | let mut scores: Vec<f64> = Vec::with_capacity(FIDELITY_WINDOWS); |
| 4862 | for w in 0..FIDELITY_WINDOWS { |
| 4863 | let at = w * step; |
| 4864 | let from = at.saturating_sub(FIDELITY_WARMUP); |
| 4865 | let Some(fidelity) = window_fidelity( |
| 4866 | packets, |
| 4867 | samples, |
| 4868 | pre_skip, |
| 4869 | channels, |
| 4870 | from, |
| 4871 | at, |
| 4872 | at + FIDELITY_WINDOW, |
| 4873 | ) else { |
| 4874 | continue; // silence: nothing to correlate, and not a failure |
| 4875 | }; |
| 4876 | scores.push(fidelity); |
| 4877 | } |
| 4878 | // Every window silent is a silent track, which this codec writes as silence. |
| 4879 | if scores.is_empty() { |
| 4880 | return 1.0; |
| 4881 | } |
| 4882 | scores.sort_by(f64::total_cmp); |
| 4883 | scores[scores.len() / 2] |
| 4884 | } |
| 4885 | |
| 4886 | /// [`opus_fidelity`] over `packets[measure..to]`, with `packets[from..measure]` |
| 4887 | /// -- the warm-up -- decoded for its state and thrown away. `None` where the |
| 4888 | /// source window carries no sound worth correlating ([`FIDELITY_FLOOR`]). |
| 4889 | fn window_fidelity( |
| 4890 | packets: &[crate::AacPacket], |
| 4891 | samples: &[f32], |
| 4892 | pre_skip: usize, |
| 4893 | channels: usize, |
| 4894 | from: usize, |
| 4895 | measure: usize, |
| 4896 | to: usize, |
| 4897 | ) -> Option<f64> { |
| 4898 | let (streams, coupled, mapping) = match channels { |
| 4899 | 1 => (1, 0, vec![0u8]), |
| 4900 | // One coupled stream: the stereo shape every fixture and every mix |
| 4901 | // here decodes back through. |
| 4902 | _ => (1, 1, vec![0, 1]), |
| 4903 | }; |
| 4904 | let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, streams, coupled, &mapping); |
| 4905 | let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); |
| 4906 | // Where in the mix this window's first decoded sample lands: every packet |
| 4907 | // is [`OPUS_FRAME`] long, and the pre-skip is what the front of the stream |
| 4908 | // owes before the first of them is the timeline's frame 0. |
| 4909 | let mut at = (from * OPUS_FRAME * channels).saturating_sub(pre_skip * channels); |
| 4910 | let mut drop = (pre_skip * channels).saturating_sub(from * OPUS_FRAME * channels); |
| 4911 | let mut counted = 0usize; |
| 4912 | for (index, packet) in packets.iter().enumerate().take(to).skip(from) { |
| 4913 | let Ok(pcm) = decoder.decode_packet(&packet.bytes) else { |
| 4914 | return Some(0.0); |
| 4915 | }; |
| 4916 | let pcm = &pcm[drop.min(pcm.len())..]; |
| 4917 | drop = drop.saturating_sub(packet.samples as usize * channels); |
| 4918 | // The warm-up is decoded for its state and not for its numbers. |
| 4919 | if index < measure { |
| 4920 | at += pcm.len(); |
| 4921 | continue; |
| 4922 | } |
| 4923 | for (want, got) in samples[at.min(samples.len())..].iter().zip(pcm) { |
| 4924 | let (x, y) = (f64::from(*want), f64::from(*got)); |
| 4925 | num += x * y; |
| 4926 | da += x * x; |
| 4927 | db += y * y; |
| 4928 | at += 1; |
| 4929 | counted += 1; |
| 4930 | } |
| 4931 | } |
| 4932 | (da / counted.max(1) as f64 > FIDELITY_FLOOR).then(|| num / (da.sqrt() * db.sqrt()).max(1e-12)) |
| 4933 | } |
| 4934 | |
| 4935 | /// The audio pass, running beside the picture: what [`run`] holds while it |
| 4936 | /// encodes and joins where the file it is writing needs the track. |
| 4937 | type AudioJob = thread::JoinHandle<crate::Result<Option<ExportAudio>>>; |
| 4938 | |
| 4939 | /// The pass while [`run`] holds it, joined however that function leaves -- |
| 4940 | /// including through a `?`. |
| 4941 | /// |
| 4942 | /// A [`JoinHandle`](thread::JoinHandle) that is merely dropped *detaches* its |
| 4943 | /// thread, and the one error that matters here is the hardware encoder's |
| 4944 | /// process dying ([`crate::hwproc`]): the whole export is then written again by |
| 4945 | /// [`start`], which starts an audio pass of its own. The abandoned one would go |
| 4946 | /// on mixing and encoding the same sound beside it -- two passes of a feature |
| 4947 | /// film's audio at once, on the machine that has just lost its GPU. Joined |
| 4948 | /// instead, so an export has one audio pass at a time and none outlives it. |
| 4949 | struct AudioPass(Option<AudioJob>); |
| 4950 | |
| 4951 | impl AudioPass { |
| 4952 | /// Whether the pass has landed, so the picture loop may collect it without |
| 4953 | /// waiting. |
| 4954 | fn is_finished(&self) -> bool { |
| 4955 | self.0.as_ref().is_some_and(thread::JoinHandle::is_finished) |
| 4956 | } |
| 4957 | |
| 4958 | /// Whether a pass is still to be collected -- which is what "the sound is |
| 4959 | /// still being worked out" means on the encoder line. |
| 4960 | fn running(&self) -> bool { |
| 4961 | self.0.is_some() |
| 4962 | } |
| 4963 | |
| 4964 | /// The handle, for the one caller that is about to join it itself. |
| 4965 | fn take(&mut self) -> Option<AudioJob> { |
| 4966 | self.0.take() |
| 4967 | } |
| 4968 | } |
| 4969 | |
| 4970 | impl Drop for AudioPass { |
| 4971 | fn drop(&mut self) { |
| 4972 | if let Some(job) = self.0.take() { |
| 4973 | let _ = job.join(); |
| 4974 | } |
| 4975 | } |
| 4976 | } |
| 4977 | |
| 4978 | /// The pass's answer, or the failure that is the export's failure. A panicked |
| 4979 | /// audio thread reads as an error rather than as silence: an export that wrote |
| 4980 | /// its picture and quietly no sound is the one outcome this must not have. |
| 4981 | fn join_audio(job: AudioJob) -> crate::Result<Option<ExportAudio>> { |
| 4982 | job.join() |
| 4983 | .map_err(|_| crate::Error::from("the audio pass stopped without a picture or a reason"))? |
| 4984 | } |
| 4985 | |
| 4986 | /// The encoder line a running export shows: the seat the picture is really |
| 4987 | /// being written by, and what the sound is -- or that the sound is still being |
| 4988 | /// worked out, which an overlapped audio pass is until it is collected. |
| 4989 | fn publish_seats( |
| 4990 | shared: &Shared, |
| 4991 | seat: &str, |
| 4992 | project: &Project, |
| 4993 | settings: &ExportSettings, |
| 4994 | sound: Option<bool>, |
| 4995 | opus: bool, |
| 4996 | waiting: bool, |
| 4997 | ) { |
| 4998 | let audio = match waiting { |
| 4999 | // Still mixing on the other thread. The same half-line the copied- |
| 5000 | // picture path has always shown, and for the same reason: what is |
| 5001 | // published is never a codec that did not run. |
| 5002 | true => "working out the sound…", |
| 5003 | false => measured_audio_label(project, settings.format, sound, opus), |
| 5004 | }; |
| 5005 | *shared.encoders.lock().unwrap() = Some(format!("{seat} · {audio}")); |
| 5006 | } |
| 5007 | |
| 5008 | /// Hands a mix that finished mixing early to the mp4 it belongs in, the |
| 5009 | /// moment both exist: `late` may land before the first coded picture has |
| 5010 | /// opened `muxer` at all, so this is tried both right where the mix lands |
| 5011 | /// and after every picture written afterwards, and does nothing once |
| 5012 | /// `*fed` says an earlier try already succeeded. Declaring the track and |
| 5013 | /// queuing its packets here is what lets [`crate::mux::Mp4Muxer`]'s own |
| 5014 | /// hold interleave them under the pictures still to come, rather than the |
| 5015 | /// track landing all at once after the picture is done. |
| 5016 | fn feed_late_audio( |
| 5017 | muxer: &mut Option<Muxer>, |
| 5018 | late: &Option<ExportAudio>, |
| 5019 | fed: &mut bool, |
| 5020 | ) -> crate::Result<()> { |
| 5021 | if *fed { |
| 5022 | return Ok(()); |
| 5023 | } |
| 5024 | let (Some(track), Some(Muxer::Mp4(mp4))) = (late.as_ref(), muxer.as_mut()) else { |
| 5025 | return Ok(()); |
| 5026 | }; |
| 5027 | mp4.add_audio_track(¶ms_of(track))?; |
| 5028 | for packet in &track.packets { |
| 5029 | mp4.write_audio_packet(&packet.bytes)?; |
| 5030 | } |
| 5031 | *fed = true; |
| 5032 | Ok(()) |
| 5033 | } |
| 5034 | |
| 5035 | /// The language the timeline's sound is in, for the export to tag its audio track with: the one |
| 5036 | /// language every audio clip's stream states. `None` when the clips disagree, when one of them |
| 5037 | /// states none (`und`), or when there are no audio clips, and the track stays `und`. |
| 5038 | pub(crate) fn audio_language(project: &Project) -> Option<String> { |
| 5039 | let sources = project.sources(); |
| 5040 | shared_language( |
| 5041 | project |
| 5042 | .audio_lanes() |
| 5043 | .into_iter() |
| 5044 | .flat_map(|lane| project.lane(lane).iter()) |
| 5045 | .map(|clip| sources.get(clip.source).and_then(|src| stream_language(&src.path, src.audio_stream))), |
| 5046 | ) |
| 5047 | } |
| 5048 | |
| 5049 | /// The one language every stream in `langs` states, or `None` when there are none, when one |
| 5050 | /// states none, or when they differ. |
| 5051 | fn shared_language(langs: impl IntoIterator<Item = Option<String>>) -> Option<String> { |
| 5052 | let mut shared: Option<String> = None; |
| 5053 | for lang in langs { |
| 5054 | let lang = lang?; |
| 5055 | match &shared { |
| 5056 | None => shared = Some(lang), |
| 5057 | Some(s) if *s == lang => {} |
| 5058 | Some(_) => return None, |
| 5059 | } |
| 5060 | } |
| 5061 | shared |
| 5062 | } |
| 5063 | |
| 5064 | /// The language audio stream `audio_stream` of `path` states in its header, with `und` (none |
| 5065 | /// stated) as `None`. Read from the header alone. |
| 5066 | fn stream_language(path: &Path, audio_stream: usize) -> Option<String> { |
| 5067 | crate::probe_media(path) |
| 5068 | .streams |
| 5069 | .into_iter() |
| 5070 | .find(|s| s.kind == crate::StreamKind::Audio && s.index == audio_stream)? |
| 5071 | .language |
| 5072 | .filter(|l| l != "und") |
| 5073 | } |
| 5074 | |
| 5075 | /// The language the picture is tagged with, for the Matroska video track to state: the first |
| 5076 | /// source's picture track, the one the export takes its picture from ([`source_colour_tags`]). |
| 5077 | /// `None` where that track states none (`und`), or no source can be read. |
| 5078 | fn video_language(project: &Project) -> Option<String> { |
| 5079 | let path = &project.sources().first()?.path; |
| 5080 | crate::probe_media(path) |
| 5081 | .streams |
| 5082 | .into_iter() |
| 5083 | .find(|s| s.kind == crate::StreamKind::Video && s.index == 0)? |
| 5084 | .language |
| 5085 | .filter(|l| l != "und") |
| 5086 | } |
| 5087 | |
| 5088 | /// The colour tags of the first source, exactly as its container states them: |
| 5089 | /// what a file that keeps its source's colour declares, unspecified fields left |
| 5090 | /// unspecified. Nothing when no source can be read, which declares nothing. |
| 5091 | fn source_colour_tags(project: &Project) -> Tags { |
| 5092 | project |
| 5093 | .sources() |
| 5094 | .first() |
| 5095 | .and_then(|source| crate::demux::Demuxer::open(&source.path).ok()) |
| 5096 | .map(|(_, demuxer)| demuxer.colour_tags()) |
| 5097 | .unwrap_or_default() |
| 5098 | } |
| 5099 | |
| 5100 | fn params_of(track: &ExportAudio) -> AudioParams { |
| 5101 | AudioParams { |
| 5102 | freq_index: track.params.freq_index, |
| 5103 | chan_conf: track.params.chan_conf, |
| 5104 | sample_rate: track.params.sample_rate, |
| 5105 | opus_pre_skip: track.opus_pre_skip, |
| 5106 | language: track.language.clone(), |
| 5107 | } |
| 5108 | } |
| 5109 | |
| 5110 | fn run( |
| 5111 | project: &Project, |
| 5112 | meta: &VideoMeta, |
| 5113 | out: &Path, |
| 5114 | shared: &Arc<Shared>, |
| 5115 | settings: &ExportSettings, |
| 5116 | sample_rate: Option<u32>, |
| 5117 | ) -> crate::Result<()> { |
| 5118 | // The media's length and not the timeline's: a caption placed past the last |
| 5119 | // picture holds the *timeline* open ([`Project::timeline_frames`]) and there |
| 5120 | // is nothing to write under it -- the picture loop walks the composite spans |
| 5121 | // and stops with them, so a file padded to the caption's end would be |
| 5122 | // trailing silence over a frozen last frame. The export ends with the last |
| 5123 | // picture or sound, the cues are cut off there ([`lane_subtitles`]), and |
| 5124 | // [`planned_subtitles`] says so before the button is pressed. |
| 5125 | // The range's own length where one is marked, the media's otherwise -- |
| 5126 | // `export_spans` walks the same window, so `done` ends on this `total` |
| 5127 | // exactly as it always did. |
| 5128 | let total = settings.range.map_or(project.media_frames(), |(s, e)| { |
| 5129 | e.min(project.media_frames()).saturating_sub(s) |
| 5130 | }); |
| 5131 | // The two preview switches are the H.264 mp4 pair's alone. Only that |
| 5132 | // container carries a colour of its own back out ([`write_video`] tags it |
| 5133 | // there), so asking any other for a source-space file would write pictures |
| 5134 | // in one space and a header in another; and only that codec's seats honour |
| 5135 | // `intra_only` -- the H.264 and HEVC pairs do, and an AV1 one would quietly |
| 5136 | // write the long-GOP file it always did. |
| 5137 | if settings.keep_source_colour && settings.format != Format::Mp4 { |
| 5138 | return Err(format!( |
| 5139 | "{} cannot be written in its source's colour space", |
| 5140 | settings.format.name() |
| 5141 | ) |
| 5142 | .into()); |
| 5143 | } |
| 5144 | if settings.intra_only && !matches!(settings.format, Format::Mp4 | Format::Hevc | Format::HevcMp4) { |
| 5145 | return Err(format!("{} cannot be written intra-only", settings.format.name()).into()); |
| 5146 | } |
| 5147 | if let Some(why) = exact_refusal(project, meta, settings) { |
| 5148 | return Err(why.into()); |
| 5149 | } |
| 5150 | let hdr_colour = hdr_colour_of(settings)?; |
| 5151 | let sources = project.sources(); |
| 5152 | // The picture's decision first, before a sample of sound is touched: it is |
| 5153 | // the answer that decides what the whole export *is*, it costs one header |
| 5154 | // read per source, and it is what the line on screen has been missing -- |
| 5155 | // an export that copies its picture used to say nothing at all for as long |
| 5156 | // as its sound took, which on a feature film was minutes. Half a line now, |
| 5157 | // completed by the measured codec once the sound is known below: what is |
| 5158 | // published is never a codec that did not run. |
| 5159 | let plan = CopyPlan::of(project, meta, settings); |
| 5160 | if plan.is_some() { |
| 5161 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export video: copy (source packets)"); } |
| 5162 | *shared.encoders.lock().unwrap() = Some("copy · working out the sound…".into()); |
| 5163 | } |
| 5164 | // ...then the audio, on a thread of its own, started before anything is |
| 5165 | // opened for the picture. |
| 5166 | // |
| 5167 | // Where it is *waited* for is the whole of this: a Matroska file interleaves |
| 5168 | // its audio into the clusters from the header on, so that path needs every |
| 5169 | // packet before the first coded picture and there is nothing to overlap. An |
| 5170 | // mp4 writes its audio track after the whole picture -- and now declares it |
| 5171 | // there too ([`MkvMuxer`]'s opposite, `Mp4Muxer::add_audio_track`) -- so the |
| 5172 | // picture's loop needs nothing at all from this until it has finished, and |
| 5173 | // the mix, its encode and the encode of every frame run at once. An export |
| 5174 | // used to cost the sound *plus* the picture; an mp4 one now costs the longer |
| 5175 | // of the two. On this project's own film that is 168 s of AC-3 that no |
| 5176 | // longer stands in front of 733 s of hardware H.264. |
| 5177 | // What a file keeping its source's colour declares, read once: the picture |
| 5178 | // is written in that space, so the tags are the source's own, not resolved. |
| 5179 | let source_colour = match settings.keep_source_colour { |
| 5180 | true => source_colour_tags(project), |
| 5181 | false => Tags::default(), |
| 5182 | }; |
| 5183 | // The picture's language, which the Matroska video track states (`und` where none). |
| 5184 | let source_language = video_language(project); |
| 5185 | // A ProRes file's sound is PCM (24-bit unless asked for 16) mixed on a thread of its own and written |
| 5186 | // after the picture ([`PcmPass`]); no AAC pass runs beside it. |
| 5187 | let bits = prores_audio_bits(settings); |
| 5188 | let pcm_job = match settings.format.is_prores() { |
| 5189 | true => { |
| 5190 | let (project, meta, settings, shared) = |
| 5191 | (project.clone(), *meta, settings.clone(), Arc::clone(shared)); |
| 5192 | PcmPass(Some( |
| 5193 | thread::Builder::new() |
| 5194 | .name("export-pcm".into()) |
| 5195 | .spawn(move || mix_pcm16(&project, &meta, &shared, &settings, sample_rate, bits))?, |
| 5196 | )) |
| 5197 | } |
| 5198 | false => PcmPass(None), |
| 5199 | }; |
| 5200 | let audio_job = if settings.format.is_prores() { None } else { Some({ |
| 5201 | let (project, meta, settings, shared) = |
| 5202 | (project.clone(), *meta, settings.clone(), Arc::clone(shared)); |
| 5203 | thread::Builder::new() |
| 5204 | .name("export-audio".into()) |
| 5205 | .spawn(move || { |
| 5206 | let track = copy_audio( |
| 5207 | &project, |
| 5208 | &meta, |
| 5209 | audio_kbps_of(&settings), |
| 5210 | settings.format.is_mkv(), |
| 5211 | settings.format == Format::Webm, |
| 5212 | &shared, |
| 5213 | // WebM's sound is mixed at the rate Opus codes at, so the |
| 5214 | // one encoder path it takes is the one that resamples. |
| 5215 | match settings.format { |
| 5216 | Format::Webm => Some(OPUS_RATE), |
| 5217 | _ => sample_rate, |
| 5218 | }, |
| 5219 | settings.range, |
| 5220 | )?; |
| 5221 | // The language the sound is in, on the copy and the mix alike: |
| 5222 | // the one tag the whole track carries. |
| 5223 | Ok(track.map(|track| ExportAudio { |
| 5224 | language: audio_language(&project), |
| 5225 | ..track |
| 5226 | })) |
| 5227 | })? |
| 5228 | }) }; |
| 5229 | // A Matroska file (and a copied one, whose muxer is the same) collects it |
| 5230 | // here; an mp4 leaves it running and collects it under the picture below. |
| 5231 | // Held in a guard from here on, so no way out of this function leaves the |
| 5232 | // pass running behind it ([`AudioPass`]). |
| 5233 | let mut audio_job = AudioPass(audio_job); |
| 5234 | // The condition is the *format*, and the copied-picture path below relies |
| 5235 | // on that covering it too: `plan` hands its packets straight to a Matroska |
| 5236 | // muxer, so it may only exist where this has already collected them -- |
| 5237 | // which holds because [`CopyPlan::of`] returns `None` for every format |
| 5238 | // that is not `Hevc` or `Av1`, both of which are `is_mkv`. Said out loud |
| 5239 | // because a copy plan for an mp4 would otherwise reach `plan.run` with the |
| 5240 | // sound still being mixed on the other thread. |
| 5241 | debug_assert!( |
| 5242 | settings.format.is_mkv() || plan.is_none(), |
| 5243 | "a copy plan outside Matroska would run before its sound is collected" |
| 5244 | ); |
| 5245 | let mut pcm_job = pcm_job; |
| 5246 | let audio = match settings.format.is_mkv() { |
| 5247 | true => join_audio(audio_job.take().expect("the job was just made"))?, |
| 5248 | false => None, |
| 5249 | }; |
| 5250 | let audio_params = audio.as_ref().map(params_of); |
| 5251 | // What the track *is*, kept before the packets are handed to a muxer: the |
| 5252 | // encoder line names a copy or an encode and only `copy_audio` knows which. |
| 5253 | // `None` on the mp4 path until the pass is collected -- the line says it is |
| 5254 | // still working the sound out, which is what it is doing. |
| 5255 | let mut sound = audio.as_ref().map(|track| track.copied); |
| 5256 | // ...and *which* encoder, for the same line: the card predicts Opus from the |
| 5257 | // format alone and cannot know the mix's rate or width ([`audio_label`]), |
| 5258 | // while this is after the mix was opened, so it is the measured answer. |
| 5259 | let mut opus = audio |
| 5260 | .as_ref() |
| 5261 | .is_some_and(|track| track.opus_pre_skip.is_some()); |
| 5262 | // Taken by the Matroska muxer at creation; the mp4 one writes its track |
| 5263 | // after the picture, so for that path this is filled in at the end. |
| 5264 | let mut packets = audio.map(|track| track.packets); |
| 5265 | // ...and the cues with them, for the same reason: the subtitle track is |
| 5266 | // declared in the header and its blocks are interleaved into the clusters, |
| 5267 | // so the muxer needs the lot before the first picture is written. |
| 5268 | let mut subs = export_subtitles(project, meta, settings); |
| 5269 | // Whatever the sound has reached, the picture's share starts here |
| 5270 | // ([`AUDIO_BAND`]) -- and the bar only ever moves forwards, which is what |
| 5271 | // `fetch_max` below keeps true while an audio pass is still publishing its |
| 5272 | // own third of that band from the other thread. |
| 5273 | shared.progress.fetch_max(AUDIO_BAND, Ordering::Relaxed); |
| 5274 | |
| 5275 | // Before an encoder is opened at all: a timeline nobody has touched, whose |
| 5276 | // sources this file can hold as they are, is written by copying their coded |
| 5277 | // blocks -- the picture's half of what `copy_audio` just did for the sound, |
| 5278 | // and the difference between an export bounded by the *edited* spans and one |
| 5279 | // that re-encodes a whole film to change a cut. [`CopyPlan`] states the |
| 5280 | // whole rule; anything at all outside it falls through to the walk below. |
| 5281 | if let Some(plan) = plan { |
| 5282 | *shared.encoders.lock().unwrap() = Some(format!( |
| 5283 | "copy · {}", |
| 5284 | // The measured codec, exactly as the encoder path below publishes |
| 5285 | // it: the mix has been opened by now, so a line that fell back to |
| 5286 | // AAC says AAC. Naming the prediction here would make the fallback |
| 5287 | // invisible on precisely the exports that are over in seconds. |
| 5288 | measured_audio_label(project, settings.format, sound, opus) |
| 5289 | )); |
| 5290 | return plan.run( |
| 5291 | out, |
| 5292 | meta, |
| 5293 | shared, |
| 5294 | audio_params.as_ref().zip(packets.take()), |
| 5295 | std::mem::take(&mut subs), |
| 5296 | total, |
| 5297 | &settings.chapters, |
| 5298 | ); |
| 5299 | } |
| 5300 | |
| 5301 | // One header parse per source, before any of them is decoded: what rate |
| 5302 | // each file was shot at against the timeline's ([`Rate`]), which is how the |
| 5303 | // clip's timeline frames below become frames of the file, and what its |
| 5304 | // samples *mean* ([`ColorDescription`]), which is what decides whether they |
| 5305 | // are remapped on the way in. Real time for a still, a song and a |
| 5306 | // single-rate project, where every conversion below is the identity. |
| 5307 | let rates: Vec<( |
| 5308 | Rate, |
| 5309 | ColorDescription, |
| 5310 | Option<f32>, |
| 5311 | Rotation, |
| 5312 | crate::demux::PixelAspect, |
| 5313 | )> = sources |
| 5314 | .iter() |
| 5315 | .map(|source| source_rate(&source.path, meta.frame_rate)) |
| 5316 | .collect(); |
| 5317 | // ...and, for a source on an HDR curve, the tone map that brings its samples |
| 5318 | // down to the SDR this file is written in ([`crate::tonemap`]). Once per |
| 5319 | // source stream: the table costs a couple of milliseconds to build and a |
| 5320 | // span reopens its file, so building it here rather than in the loop below |
| 5321 | // is the difference between paying that once and paying it per cut. An SDR |
| 5322 | // source -- the whole of an ordinary project -- builds no table at all. |
| 5323 | // |
| 5324 | // Through the project's own preset ([`tonemap::Preset`]) and each source's |
| 5325 | // own declared peak, which is the pair playback's decode funnel builds its |
| 5326 | // tables with: preview and export are the same rendition of the same film |
| 5327 | // because they are told the same two things, not because two numbers happen |
| 5328 | // to agree. |
| 5329 | let preset = project.tone(); |
| 5330 | let tone: Vec<Option<ToneMapper>> = rates |
| 5331 | .iter() |
| 5332 | .map(|(_, color, peak, _, _)| match color.transfer { |
| 5333 | // A preview file keeps the film's own curve and is tone-mapped when |
| 5334 | // it is *shown* ([`ExportSettings::keep_source_colour`]), which is |
| 5335 | // both cheaper and the only way the preset can still be changed |
| 5336 | // after the stand-in was made. |
| 5337 | _ if settings.keep_source_colour => None, |
| 5338 | // An HDR export keeps the HDR sources' own curve: no tone map to SDR |
| 5339 | // ([`ExportSettings::hdr`], [`hdr_colour_of`] refuses a curve change). |
| 5340 | _ if hdr_colour.is_some() => None, |
| 5341 | Transfer::Sdr => None, |
| 5342 | Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)), |
| 5343 | Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)), |
| 5344 | }) |
| 5345 | .collect(); |
| 5346 | // ...and the one space they are all written in, the same rule a reader with |
| 5347 | // no tags to read would apply to this file's height -- or, for a preview |
| 5348 | // file, the source's own, which is what makes every remap below the |
| 5349 | // identity and the file's `colr` box its film's. |
| 5350 | // The software seat's depth ([`wide_ten_bit`]): a 10-bit timeline is |
| 5351 | // decoded and encoded at 10 bits wherever its pictures pass through untouched. |
| 5352 | for (_, color, ..) in &rates { |
| 5353 | let clash = hdr_colour.is_some_and(|out| color.transfer != Transfer::Sdr && color.transfer != out.transfer); |
| 5354 | if clash { |
| 5355 | let out = hdr_colour.expect("a clash needs an HDR output"); |
| 5356 | return Err(format!( |
| 5357 | "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", |
| 5358 | transfer_name(color.transfer), |
| 5359 | transfer_name(out.transfer) |
| 5360 | ) |
| 5361 | .into()); |
| 5362 | } |
| 5363 | } |
| 5364 | let ten_bit = wide_ten_bit(settings, || { |
| 5365 | sources |
| 5366 | .iter() |
| 5367 | .any(|s| Demuxer::open(&s.path).is_ok_and(|(_, d)| d.bit_depth() >= 10)) |
| 5368 | })?; |
| 5369 | // The colour a 10-bit SDR export declares: its sources' own matrix, where every |
| 5370 | // clip is SDR in one matrix ([`source_sdr_colour`]). Every other export keeps the |
| 5371 | // output rule, and so does the encoder's declared colour when there is no such one. |
| 5372 | let source_sdr = match ten_bit && !settings.keep_source_colour { |
| 5373 | // An HDR export declares its own colour, whatever the sources are. |
| 5374 | true if hdr_colour.is_some() => hdr_colour, |
| 5375 | true => source_sdr_colour(&rates.iter().map(|(_, c, ..)| *c).collect::<Vec<_>>()), |
| 5376 | false => None, |
| 5377 | }; |
| 5378 | let rule = ColorDescription::output_sized(meta.width, meta.height); |
| 5379 | let out_color = match settings.keep_source_colour { |
| 5380 | true => meta.color, |
| 5381 | false => source_sdr.unwrap_or(rule), |
| 5382 | }; |
| 5383 | let container_colour = source_sdr.map_or(source_colour, Tags::of); |
| 5384 | |
| 5385 | // The captions drawn into each picture, if the export burns any in ([`Burn`]). |
| 5386 | let mut burn = Burn::new(project, settings, meta.frame_rate, out_color.full_range)?; |
| 5387 | let mut encoder = Enc::open(meta, settings, ten_bit, source_sdr.unwrap_or(rule))?; |
| 5388 | // What this file is really being written by, for a progress line to name. |
| 5389 | // Published *after* the seat is open, so a hardware encoder the driver |
| 5390 | // refused reads as the software one that took over rather than as the hope |
| 5391 | // it replaced -- and the sound says whether it was copied or encoded, which |
| 5392 | // only `copy_audio` knows and, on the overlapped path, does not know yet. |
| 5393 | let seat = encoder.label(); |
| 5394 | publish_seats( |
| 5395 | shared, |
| 5396 | seat, |
| 5397 | project, |
| 5398 | settings, |
| 5399 | sound, |
| 5400 | opus, |
| 5401 | audio_job.running(), |
| 5402 | ); |
| 5403 | // When the picture started, so the stage line below can say where under it |
| 5404 | // the sound landed -- the one number that says whether the two passes |
| 5405 | // really overlapped, in the same voice as `encode_audio`'s own timers. |
| 5406 | let picture_started = std::time::Instant::now(); |
| 5407 | // The sound, once the pass beside this one has finished with it: joined |
| 5408 | // here the moment it lands rather than only after the picture, so |
| 5409 | // `feed_late_audio` below can hand it to the muxer while pictures are |
| 5410 | // still being coded and let `Mp4Muxer`'s own hold interleave the two |
| 5411 | // ([`crate::mux::Mp4Muxer`]). |
| 5412 | let mut late: Option<ExportAudio> = None; |
| 5413 | // Set once `late`'s track has been handed to the muxer -- so the final |
| 5414 | // join below, which still exists for a mix that never lands mid-picture, |
| 5415 | // knows not to declare the track or write its packets a second time. |
| 5416 | let mut audio_fed = false; |
| 5417 | let mut muxer = None; |
| 5418 | // A ProRes file is declared up front: the encoder knows its own sample entry. |
| 5419 | if let Some(params) = encoder.prores_params() { |
| 5420 | muxer = Some(Muxer::Mov(crate::prores_out::MovWriter::create( |
| 5421 | out, |
| 5422 | params, |
| 5423 | crate::mux::frame_timing(meta.frame_rate)?, |
| 5424 | )?)); |
| 5425 | } |
| 5426 | let mut done = 0u32; |
| 5427 | // ...and how many of the edit's frames a file could not give, summed over |
| 5428 | // the spans that ran out under their clip ([`Shared::truncated`]). |
| 5429 | let mut skipped = 0u32; |
| 5430 | let black = Black::new(meta); |
| 5431 | // Software decoders that spans leave behind for the next span of the same |
| 5432 | // file to continue (see [`Parked`]). |
| 5433 | let parked = Arc::new(Parked::default()); |
| 5434 | // Spans, not clips: a gap in the video is part of the timeline and gets |
| 5435 | // encoded too, as black frames. The picture count is therefore |
| 5436 | // `media_frames` however the lanes are arranged -- [`export_spans`] is that |
| 5437 | // walk cut to it, so `done` ends on the `total` above instead of running |
| 5438 | // past it under a trailing caption -- and *which* lane a span comes from is |
| 5439 | // `composite_spans_from`'s answer, the same one playback shows, so an |
| 5440 | // export is what was watched. |
| 5441 | for span in export_spans(project, settings.range) { |
| 5442 | // Every clip reopens its own source file at its own in point; the |
| 5443 | // encoder is *not* reopened, so the export is one continuous stream |
| 5444 | // whose GOP boundaries need not line up with the cuts -- nor with the |
| 5445 | // file boundaries, which are just cuts that change the path. |
| 5446 | // Whether this span's tail dissolves into its successor -- decided |
| 5447 | // before A's own decoder is opened, because it is what decides |
| 5448 | // whether A may take the DMA fast path at all: the blend below needs |
| 5449 | // A's pixels on the CPU, so a dissolving span never asks for a GPU |
| 5450 | // buffer, not even outside its own window. |
| 5451 | // |
| 5452 | // A layered span (two or more clips on the stack, [`layered_at`]) takes |
| 5453 | // no decoder of its own: its pictures are composed by a [`LayerStack`] |
| 5454 | // opened beside it, placed and faded per clip, so it never dissolves, |
| 5455 | // never takes the DMA path and never runs the single-clip placement. |
| 5456 | let keyed_color = color_keyed_alone_at(project, span.start).filter(|_| ten_bit); |
| 5457 | let layered_here = layered_at(project, span.start) && keyed_color.is_none(); |
| 5458 | let dissolve = dissolve_window(project, &span); |
| 5459 | let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) = |
| 5460 | match span.from.filter(|_| !layered_here) { |
| 5461 | Some((source, in_frame)) => { |
| 5462 | let entry = sources |
| 5463 | .get(source) |
| 5464 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; |
| 5465 | let (rate, color, _peak, rotation, pixel_aspect) = rates[source]; |
| 5466 | // A field-mode clip of an interlaced file counts fields, two a frame. |
| 5467 | let deint = span_deint(project, span.start, &entry.path); |
| 5468 | let rate = crate::deinterlace::counted_rate(deint, rate); |
| 5469 | let mapper = tone[source].as_ref(); |
| 5470 | // Nothing on the way from this span's decoder to the encoder |
| 5471 | // touches a sample: no tone map, no matrix remap, no grade -- |
| 5472 | // which is what lets the *decoded buffer itself* be encoded, |
| 5473 | // never read back and never written out again. The canvas is |
| 5474 | // the fourth thing that would touch it, and the decoder answers |
| 5475 | // that one: a picture of another size than this file's is one |
| 5476 | // the plugin hands back as pixels ([`HwSession::next_frame_dma`]). |
| 5477 | let untouched = mapper.is_none() |
| 5478 | && keyed_color.is_none() |
| 5479 | && burn.is_none() |
| 5480 | && remap_into(Some(color), false, out_color.matrix).is_none() |
| 5481 | && project |
| 5482 | .composite_color_at(span.start) |
| 5483 | .is_none_or(|params| params.is_identity()) |
| 5484 | && project |
| 5485 | .composite_transform_at(span.start) |
| 5486 | .is_none_or(|params| params.is_identity()) |
| 5487 | // A file whose display matrix asks for a turn is *not* |
| 5488 | // untouched, whatever else the timeline says: its pictures |
| 5489 | // have to be turned, which is a read-back no GPU buffer |
| 5490 | // survives. The sample aspect is the same refusal one |
| 5491 | // stage later: its pictures have to be stretched to the |
| 5492 | // square-pixel raster before an encoder sees them, which |
| 5493 | // is the same kind of touch. |
| 5494 | && rotation.is_none() |
| 5495 | && pixel_aspect.is_square() |
| 5496 | && dissolve.is_none() |
| 5497 | && !picture_faded_in(project, &span); |
| 5498 | let want = untouched.then(|| encoder.dma_want(meta)).flatten(); |
| 5499 | // Opened at the file's own frame, which is the only place the |
| 5500 | // file's numbering is used -- the span's are the timeline's. |
| 5501 | let flags = project.composite_visualizer_at(span.start); |
| 5502 | let pictures = if crate::is_audio(&entry.path) || flags & 1 != 0 { |
| 5503 | ClipDecoder::visualizer( |
| 5504 | &entry.path, |
| 5505 | entry.audio_stream, |
| 5506 | rate.source_at(in_frame), |
| 5507 | (meta.width, meta.height), |
| 5508 | meta.frame_rate, |
| 5509 | flags, |
| 5510 | project.composite_viz_paint_at(span.start), |
| 5511 | )? |
| 5512 | } else if span.reverse && !crate::is_image(&entry.path) { |
| 5513 | // Played backwards: from the file frame the span starts on, down |
| 5514 | // to the lowest it reads. The loop below counts the pictures it |
| 5515 | // takes off the decoder, which is how it reads a forward one. |
| 5516 | let lo = span.source_window().map_or(0, |(_, lo, _)| rate.source_at(lo)); |
| 5517 | ClipDecoder::reversed(&entry.path, rate.source_at(in_frame), lo, deint) |
| 5518 | } else { |
| 5519 | ClipDecoder::open_with(&entry.path, rate.source_at(in_frame), want, Some(&parked), ten_bit, deint)? |
| 5520 | }; |
| 5521 | ( |
| 5522 | Some(pictures), |
| 5523 | rate, |
| 5524 | in_frame, |
| 5525 | Some(color), |
| 5526 | mapper, |
| 5527 | rotation, |
| 5528 | pixel_aspect, |
| 5529 | ) |
| 5530 | } |
| 5531 | // A gap's black is 16/128/128, which is black in every matrix here |
| 5532 | // and on every curve: nothing to remap and nothing to tone-map, |
| 5533 | // which is what `None` says. A gap is no file either, so nothing |
| 5534 | // turns it. |
| 5535 | None => ( |
| 5536 | None, |
| 5537 | Rate::REAL_TIME, |
| 5538 | 0, |
| 5539 | None, |
| 5540 | None, |
| 5541 | Rotation::None, |
| 5542 | crate::demux::PixelAspect::SQUARE, |
| 5543 | ), |
| 5544 | }; |
| 5545 | // Mixed spaces on one timeline: a clip coded against another matrix than |
| 5546 | // the one this file declares is rewritten into it, *after* the grade -- |
| 5547 | // playback grades in the source's own space and converts for the screen |
| 5548 | // ([`crate::decode`]), so a grade applied to remapped samples is a |
| 5549 | // different picture than the one the canvas showed. Same-space clips -- |
| 5550 | // the whole of an ordinary project -- take `None` and not a byte is |
| 5551 | // touched. |
| 5552 | // |
| 5553 | // ...and what the samples mean when that remap sees them is not always |
| 5554 | // what the file said, which is [`remap_into`]'s whole question. |
| 5555 | let remap = remap_into(color, mapper.is_some(), out_color.matrix); |
| 5556 | // What this span is graded by -- the same answer playback's decoder |
| 5557 | // carries, so the export is the picture that was watched. `None` for a |
| 5558 | // gap and for an ungraded clip, and that is the path where not a byte |
| 5559 | // is touched. Scratch outside the frame loop: it is refilled per frame |
| 5560 | // and its allocation survives the whole span. |
| 5561 | // A layered span's clips carry their own grades and transforms, in the |
| 5562 | // [`LayerStack`] that composes them; the top clip's do not apply here. |
| 5563 | let grade = match layered_here { |
| 5564 | true => None, |
| 5565 | false => project.composite_color_at(span.start).copied(), |
| 5566 | }; |
| 5567 | let transform = match layered_here { |
| 5568 | true => TransformParams::default(), |
| 5569 | false => project |
| 5570 | .composite_transform_at(span.start) |
| 5571 | .copied() |
| 5572 | .unwrap_or_default(), |
| 5573 | }; |
| 5574 | // The composing stack for a layered span, open for the whole span. |
| 5575 | let mut layers = match layered_here { |
| 5576 | true => Some(LayerStack::open( |
| 5577 | project, |
| 5578 | meta, |
| 5579 | &stack_at(project, span.start), |
| 5580 | out_color.matrix, |
| 5581 | None, |
| 5582 | Some((&shared.cancel, &shared.measuring)), |
| 5583 | )?), |
| 5584 | false => None, |
| 5585 | }; |
| 5586 | // A 10-bit export composes a layered picture at 10 bits too ([`LayerStack::picture16`]). |
| 5587 | let layered_wide = ten_bit && layers.is_some(); |
| 5588 | let mut graded = (Vec::new(), Vec::new(), Vec::new()); |
| 5589 | let mut transformed = (Vec::new(), Vec::new(), Vec::new()); |
| 5590 | // The 10-bit scratch of A's placement, and the 10-bit copies of an 8-bit |
| 5591 | // picture (or of B's) that composes at 10 bits ([`widen_into`]). |
| 5592 | let mut scratch16 = Scratch16::default(); |
| 5593 | let mut widened_a: Planes16 = Planes16::default(); |
| 5594 | let mut widened_b: Planes16 = Planes16::default(); |
| 5595 | // A lone clip's effects stack on this path draws on copies of its placed |
| 5596 | // picture, at whichever depth it was placed ([`color_keyed_alone_at`]). |
| 5597 | let fx_clip = keyed_color.filter(|clip| crate::effects::active(&clip.effects)); |
| 5598 | let (mut fx8, mut fx16): (Planes, Planes16) = Default::default(); |
| 5599 | let mut fx_scratch8 = crate::effects::Scratch::<u8>::default(); |
| 5600 | let mut fx_scratch16 = crate::effects::Scratch::<u16>::default(); |
| 5601 | // ...and one more for the file's own display-matrix turn, which happens |
| 5602 | // before all of those (see [`place_picture`]): empty for every source |
| 5603 | // that states no turn. `stretched` is its twin for the pixel aspect, |
| 5604 | // which happens right after it. |
| 5605 | let mut rotated = (Vec::new(), Vec::new(), Vec::new()); |
| 5606 | let mut stretched = (Vec::new(), Vec::new(), Vec::new()); |
| 5607 | // ...and the canvas it is placed on, which is where a source of another |
| 5608 | // resolution becomes a picture at the project's. The same `Composer` |
| 5609 | // playback composes with, given the same policy, so an export is what |
| 5610 | // was watched down to the letterbox; a clip already the project's size |
| 5611 | // passes through it untouched. |
| 5612 | let mut canvas = Composer::new( |
| 5613 | meta.width, |
| 5614 | meta.height, |
| 5615 | project.composite_fit_at(span.start), |
| 5616 | ); |
| 5617 | // The 10-bit canvas: its own composer, because the 8-bit placement above |
| 5618 | // borrows `canvas` in the same frame. It places the same fit. |
| 5619 | let mut canvas16 = Composer::new( |
| 5620 | meta.width, |
| 5621 | meta.height, |
| 5622 | project.composite_fit_at(span.start), |
| 5623 | ); |
| 5624 | // Scratch for the 8-bit composition of a 10-bit picture ([`narrowed`]), |
| 5625 | // one for A's picture and one for B's. |
| 5626 | let mut narrow_a: [Vec<u8>; 3] = Default::default(); |
| 5627 | let mut narrow_b: [Vec<u8>; 3] = Default::default(); |
| 5628 | // B's own decoder, opened beside A's: the two streams come off their |
| 5629 | // files together for exactly the frames the tail below blends, and |
| 5630 | // nothing else in this span ever touches it. |
| 5631 | let mut b = dissolve |
| 5632 | .map( |
| 5633 | |(b_source, b_in_frame, window, b_start)| -> crate::Result<_> { |
| 5634 | let entry = sources.get(b_source).ok_or_else(|| { |
| 5635 | format!("clip names source {b_source} of {}", sources.len()) |
| 5636 | })?; |
| 5637 | let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source]; |
| 5638 | // The blended tail of a dissolve takes one picture per timeline |
| 5639 | // frame, so it never counts fields: `Field` is its `Frame`. |
| 5640 | let b_deint = frame_counting(span_deint(project, b_start, &entry.path)); |
| 5641 | let b_rate = crate::deinterlace::counted_rate(b_deint, b_rate); |
| 5642 | let b_mapper = tone[b_source].as_ref(); |
| 5643 | let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); |
| 5644 | Ok(Dissolve { |
| 5645 | window, |
| 5646 | kind: crate::transitions::kind_at(project, span.start), |
| 5647 | tail_start: span.len - window, |
| 5648 | decoder: if crate::is_audio(&entry.path) |
| 5649 | || project.composite_visualizer_at(b_start) & 1 != 0 |
| 5650 | { |
| 5651 | ClipDecoder::visualizer( |
| 5652 | &entry.path, |
| 5653 | entry.audio_stream, |
| 5654 | b_rate.source_at(b_in_frame), |
| 5655 | (meta.width, meta.height), |
| 5656 | meta.frame_rate, |
| 5657 | project.composite_visualizer_at(b_start), |
| 5658 | project.composite_viz_paint_at(b_start), |
| 5659 | )? |
| 5660 | } else { |
| 5661 | ClipDecoder::open_with(&entry.path, b_rate.source_at(b_in_frame), None, Some(&parked), ten_bit, b_deint)? |
| 5662 | }, |
| 5663 | mapper: b_mapper, |
| 5664 | remap: b_remap, |
| 5665 | grade: project.composite_color_at(b_start).copied(), |
| 5666 | transform: project |
| 5667 | .composite_transform_at(b_start) |
| 5668 | .copied() |
| 5669 | .unwrap_or_default(), |
| 5670 | rotation: b_rotation, |
| 5671 | pixel_aspect: b_pixel_aspect, |
| 5672 | canvas: Composer::new( |
| 5673 | meta.width, |
| 5674 | meta.height, |
| 5675 | project.composite_fit_at(b_start), |
| 5676 | ), |
| 5677 | rotated: (Vec::new(), Vec::new(), Vec::new()), |
| 5678 | stretched: (Vec::new(), Vec::new(), Vec::new()), |
| 5679 | graded: (Vec::new(), Vec::new(), Vec::new()), |
| 5680 | transformed: (Vec::new(), Vec::new(), Vec::new()), |
| 5681 | scratch16: Scratch16::default(), |
| 5682 | }) |
| 5683 | }, |
| 5684 | ) |
| 5685 | .transpose()?; |
| 5686 | // Timeline frames, taken a *source* frame at a time: at a rate other |
| 5687 | // than real time the two are not the same count, and the span says which |
| 5688 | // source frame each timeline frame shows ([`Speed::source_at`]) -- the |
| 5689 | // very frame playback is holding there, because the two conversions are |
| 5690 | // one floor/ceil pair (`speed_maps_both_ways`). A speed-up decodes the |
| 5691 | // frames it skips and drops them, because the pictures after them |
| 5692 | // reference those; a slow-down encodes the picture it is holding again |
| 5693 | // rather than decoding it twice. At real time `repeats` is 1 and `want` |
| 5694 | // advances by one, which is the loop this always ran. |
| 5695 | let mut done_here = 0u32; |
| 5696 | // Source frames already taken out of this span's decoder. |
| 5697 | let mut taken = 0u32; |
| 5698 | // The whole of the mapping, in the order it composes: the speed says |
| 5699 | // which of the clip's (timeline-rate) frames a timeline frame shows, |
| 5700 | // and the rate says which frame of the *file* that is -- counted from |
| 5701 | // the one the decoder was opened at. At real time and at the timeline's |
| 5702 | // own rate this is `Speed::source_at` and nothing else, which is the |
| 5703 | // walk a single-rate project has always taken. |
| 5704 | let opened_at = rate.source_at(in_frame); |
| 5705 | let source_at = |
| 5706 | |offset: u32| rate.source_at(in_frame + span.source_offset(offset)) - opened_at; |
| 5707 | while done_here < span.len { |
| 5708 | cancelled(shared)?; |
| 5709 | // The sound's failure is the export's, and it is heard the moment |
| 5710 | // it happens rather than after the last frame: a mix this engine |
| 5711 | // cannot decode used to refuse in seconds, before any picture was |
| 5712 | // encoded, and an overlapped pass that reported only at the end |
| 5713 | // would spend the whole encode first. Also where its measured |
| 5714 | // codec reaches the line on screen. |
| 5715 | if audio_job.is_finished() { |
| 5716 | late = join_audio(audio_job.take().expect("just seen to be there"))?; |
| 5717 | sound = late.as_ref().map(|track| track.copied); |
| 5718 | opus = late |
| 5719 | .as_ref() |
| 5720 | .is_some_and(|track| track.opus_pre_skip.is_some()); |
| 5721 | publish_seats(shared, seat, project, settings, sound, opus, false); |
| 5722 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!( |
| 5723 | "export audio: done {:.1} s into the picture", |
| 5724 | picture_started.elapsed().as_secs_f64() |
| 5725 | ); } |
| 5726 | feed_late_audio(&mut muxer, &late, &mut audio_fed)?; |
| 5727 | } |
| 5728 | let want = source_at(done_here); |
| 5729 | // A colour-keyed clip on the 10-bit path: this picture's grade is the |
| 5730 | // keys' value at its first timeline frame (a slowed picture repeated |
| 5731 | // over several frames keeps it). |
| 5732 | let grade = match keyed_color { |
| 5733 | Some(clip) => Some(crate::project::clip_color_at( |
| 5734 | clip, |
| 5735 | grade.unwrap_or_default(), |
| 5736 | span.start + done_here, |
| 5737 | )), |
| 5738 | None => grade, |
| 5739 | }; |
| 5740 | // How many timeline frames from here show that same picture: one at |
| 5741 | // real time, more when the clip is slowed or its file is slower |
| 5742 | // than the timeline. Encoded again rather than decoded twice. |
| 5743 | // A layered span composes every timeline frame, so it never repeats one. |
| 5744 | // ...nor does a lone clip whose effects move from frame to frame (a |
| 5745 | // shake); a static stack is drawn once and its picture held like any other. |
| 5746 | let repeats = match layered_here || fx_clip.is_some_and(|c| crate::effects::animated(&c.effects)) { |
| 5747 | true => 1, |
| 5748 | false => (done_here..span.len) |
| 5749 | .take_while(|&offset| source_at(offset) == want) |
| 5750 | .count() as u32, |
| 5751 | }; |
| 5752 | // The composed picture of a layered span, owned for this frame. |
| 5753 | let mut composed: Option<Planes> = None; |
| 5754 | let mut composed16: Option<Planes16> = None; |
| 5755 | let picture = match (&mut layers, &mut pictures) { |
| 5756 | (Some(stack), _) if layered_wide => match stack.picture16(span.start + done_here)? { |
| 5757 | Some(planes) => { |
| 5758 | let planes = composed16.insert(planes); |
| 5759 | Some(Frame::Wide( |
| 5760 | &planes.0[..], |
| 5761 | &planes.1[..], |
| 5762 | &planes.2[..], |
| 5763 | meta.width, |
| 5764 | meta.height, |
| 5765 | )) |
| 5766 | } |
| 5767 | None => None, |
| 5768 | }, |
| 5769 | (Some(stack), _) => match stack.picture(span.start + done_here)? { |
| 5770 | Some(planes) => { |
| 5771 | let planes = composed.insert(planes); |
| 5772 | Some(Frame::Pixels( |
| 5773 | &planes.0[..], |
| 5774 | &planes.1[..], |
| 5775 | &planes.2[..], |
| 5776 | meta.width, |
| 5777 | meta.height, |
| 5778 | )) |
| 5779 | } |
| 5780 | None => None, |
| 5781 | }, |
| 5782 | (None, Some(pictures)) => { |
| 5783 | let mut ran_out = false; |
| 5784 | while taken < want && !ran_out { |
| 5785 | ran_out = pictures.next()?.is_none(); |
| 5786 | taken += 1; |
| 5787 | } |
| 5788 | match ran_out { |
| 5789 | true => None, |
| 5790 | false => { |
| 5791 | taken += 1; |
| 5792 | pictures.next()? |
| 5793 | } |
| 5794 | } |
| 5795 | } |
| 5796 | (None, None) => { |
| 5797 | let (y, u, v, width, height) = black.picture(); |
| 5798 | Some(Frame::Pixels(y, u, v, width, height)) |
| 5799 | } |
| 5800 | }; |
| 5801 | let Some(frame) = picture else { |
| 5802 | // The file ran out before its clip did: this span's tail never |
| 5803 | // gets a picture -- and *only* this span's tail, because the |
| 5804 | // span loop this break sits in carries on with the spans after |
| 5805 | // it and writes every picture they have. Counted, not |
| 5806 | // swallowed: the bar reaches its end whatever happens, so |
| 5807 | // without this a truncated file reads as a whole one. The same |
| 5808 | // sentence `planned_subtitles` gives cues that hang past the |
| 5809 | // last picture, said after the fact here because how many |
| 5810 | // pictures a *file* holds is only known by opening it. |
| 5811 | // |
| 5812 | // `span.len > done_here` holds by the loop's own condition, and |
| 5813 | // the sum over every break is exactly `total - done` at the end |
| 5814 | // of the walk: the spans are disjoint and cover the whole edit. |
| 5815 | skipped += span.len - done_here; |
| 5816 | break; // source ran out early; the clip list outlives the file |
| 5817 | }; |
| 5818 | // A picture still on the GPU has nothing waiting for it here: the |
| 5819 | // span was opened that way only where none of what follows would |
| 5820 | // have touched a sample of it, so it is placed by nobody and goes |
| 5821 | // into the encoder as the buffer the decoder wrote. |
| 5822 | // A 10-bit picture goes to the encoder whole only where nothing on the |
| 5823 | // way touches a sample: no layer, dissolve, tone map, remap, grade, |
| 5824 | // transform, turn, stretch, caption or fade. Anything else composes at |
| 5825 | // 8 bits as it always did, narrowed here. |
| 5826 | let untouched = ten_bit |
| 5827 | && !layered_here |
| 5828 | && b.is_none() |
| 5829 | && mapper.is_none() |
| 5830 | && remap.is_none() |
| 5831 | && grade.is_none() |
| 5832 | && transform == TransformParams::default() |
| 5833 | && matches!(rotation, Rotation::None) |
| 5834 | && pixel_aspect.is_square() |
| 5835 | && burn |
| 5836 | .as_ref() |
| 5837 | .is_none_or(|b| b.cues.is_empty() && b.titles.is_empty()) |
| 5838 | && (done_here..done_here + repeats) |
| 5839 | .all(|off| picture_fade_at(project, span.start + off).is_none()); |
| 5840 | // A 10-bit export composes at 10 bits wherever the picture is touched at |
| 5841 | // all. The exceptions stay at 8 bits: a tone map (HDR), a turn or a |
| 5842 | // stretch, and a layered picture (composed per clip). |
| 5843 | let wide16 = ten_bit |
| 5844 | && (layered_wide || !layered_here) |
| 5845 | && !untouched; |
| 5846 | let frame = match frame { |
| 5847 | Frame::Wide(_, _, _, width, height) |
| 5848 | if !wide16 && !(untouched && width == meta.width && height == meta.height) => |
| 5849 | { |
| 5850 | narrowed(frame, &mut narrow_a) |
| 5851 | } |
| 5852 | other => other, |
| 5853 | }; |
| 5854 | // The picture at 10 bits, composed: a 10-bit one as it is, an 8-bit one widened. |
| 5855 | let placed16 = match (wide16, &frame) { |
| 5856 | (true, Frame::Wide(y, u, v, width, height)) => Some(place_picture16( |
| 5857 | y, |
| 5858 | u, |
| 5859 | v, |
| 5860 | *width, |
| 5861 | *height, |
| 5862 | rotation, |
| 5863 | pixel_aspect, |
| 5864 | grade, |
| 5865 | transform, |
| 5866 | remap.filter(|_| !layered_here), |
| 5867 | mapper, |
| 5868 | &mut scratch16, |
| 5869 | &mut canvas16, |
| 5870 | )), |
| 5871 | (true, Frame::Pixels(y, u, v, width, height)) => { |
| 5872 | widen_into(y, &mut widened_a.0); |
| 5873 | widen_into(u, &mut widened_a.1); |
| 5874 | widen_into(v, &mut widened_a.2); |
| 5875 | Some(place_picture16( |
| 5876 | &widened_a.0[..], |
| 5877 | &widened_a.1[..], |
| 5878 | &widened_a.2[..], |
| 5879 | *width, |
| 5880 | *height, |
| 5881 | rotation, |
| 5882 | pixel_aspect, |
| 5883 | grade, |
| 5884 | transform, |
| 5885 | remap.filter(|_| !layered_here), |
| 5886 | mapper, |
| 5887 | &mut scratch16, |
| 5888 | &mut canvas16, |
| 5889 | )) |
| 5890 | } |
| 5891 | _ => None, |
| 5892 | }; |
| 5893 | let placed = match frame { |
| 5894 | Frame::Dma(_) => None, |
| 5895 | // Encoded whole below, at 10 bits. |
| 5896 | Frame::Wide(..) => None, |
| 5897 | // Composed at 10 bits above. |
| 5898 | Frame::Pixels(..) if wide16 => None, |
| 5899 | // A layered picture is composed already, per clip: nothing here |
| 5900 | // places it again. |
| 5901 | Frame::Pixels(y, u, v, width, height) if layered_here => { |
| 5902 | Some((y, u, v, width, height)) |
| 5903 | } |
| 5904 | Frame::Pixels(y, u, v, width, height) => Some(place_picture( |
| 5905 | y, |
| 5906 | u, |
| 5907 | v, |
| 5908 | width, |
| 5909 | height, |
| 5910 | rotation, |
| 5911 | pixel_aspect, |
| 5912 | grade, |
| 5913 | transform, |
| 5914 | remap, |
| 5915 | mapper, |
| 5916 | &mut rotated, |
| 5917 | &mut stretched, |
| 5918 | &mut graded, |
| 5919 | &mut transformed, |
| 5920 | &mut canvas, |
| 5921 | )), |
| 5922 | }; |
| 5923 | // A lone clip's effects, drawn on its placed picture and laid over black. |
| 5924 | let (placed16, placed) = match fx_clip { |
| 5925 | None => (placed16, placed), |
| 5926 | Some(clip) => { |
| 5927 | let secs = f64::from(span.start + done_here) / meta.frame_rate; |
| 5928 | let src = crate::project::key_sample_pos(clip, span.start + done_here); |
| 5929 | let placed16 = placed16.map(|(y, u, v, w, h)| { |
| 5930 | fx16 = (y.to_vec(), u.to_vec(), v.to_vec()); |
| 5931 | effected(&clip.effects, &mut fx16, w, h, secs, src, out_color.matrix, &mut fx_scratch16); |
| 5932 | (&fx16.0[..], &fx16.1[..], &fx16.2[..], w, h) |
| 5933 | }); |
| 5934 | let placed = placed.map(|(y, u, v, w, h)| { |
| 5935 | fx8 = (y.to_vec(), u.to_vec(), v.to_vec()); |
| 5936 | effected(&clip.effects, &mut fx8, w, h, secs, src, out_color.matrix, &mut fx_scratch8); |
| 5937 | (&fx8.0[..], &fx8.1[..], &fx8.2[..], w, h) |
| 5938 | }); |
| 5939 | (placed16, placed) |
| 5940 | } |
| 5941 | }; |
| 5942 | // Once per timeline frame this source frame covers: one at real time |
| 5943 | // and faster, more when the clip is slowed -- the picture is already |
| 5944 | // graded and placed, so a held frame costs an encode and no decode. |
| 5945 | for r in 0..repeats { |
| 5946 | // Inside the window every *output* frame gets its own B |
| 5947 | // picture -- decoded fresh here rather than once for the |
| 5948 | // whole held A frame -- which is what makes a slowed A's |
| 5949 | // tail still ramp one weight per frame shown rather than one |
| 5950 | // per source frame. |
| 5951 | let in_window = b.as_ref().is_some_and(|d| done_here + r >= d.tail_start); |
| 5952 | let coded = match (&mut b, in_window) { |
| 5953 | (Some(d), true) if placed16.is_some() => { |
| 5954 | let (ay, au, av, aw, ah) = placed16.expect("checked by the guard"); |
| 5955 | let t = dissolve_weight(done_here + r - d.tail_start, d.window); |
| 5956 | let blended: Option<Planes16> = match d.decoder.next()? { |
| 5957 | // B's file ran out inside the window: A's own picture carries the frame. |
| 5958 | None => None, |
| 5959 | Some(b) => { |
| 5960 | // B at 10 bits: a 10-bit picture as it is, an 8-bit one widened. |
| 5961 | let (by, bu, bv, bw, bh): (&[u16], &[u16], &[u16], u32, u32) = match b { |
| 5962 | Frame::Wide(y, u, v, w, h) => (y, u, v, w, h), |
| 5963 | Frame::Pixels(y, u, v, w, h) => { |
| 5964 | widen_into(y, &mut widened_b.0); |
| 5965 | widen_into(u, &mut widened_b.1); |
| 5966 | widen_into(v, &mut widened_b.2); |
| 5967 | (&widened_b.0[..], &widened_b.1[..], &widened_b.2[..], w, h) |
| 5968 | } |
| 5969 | Frame::Dma(_) => unreachable!("b's decoder is never a DMA buffer"), |
| 5970 | }; |
| 5971 | let (y, u, v, _, _) = place_picture16( |
| 5972 | by, |
| 5973 | bu, |
| 5974 | bv, |
| 5975 | bw, |
| 5976 | bh, |
| 5977 | d.rotation, |
| 5978 | d.pixel_aspect, |
| 5979 | d.grade, |
| 5980 | d.transform, |
| 5981 | d.remap, |
| 5982 | d.mapper, |
| 5983 | &mut d.scratch16, |
| 5984 | &mut d.canvas, |
| 5985 | ); |
| 5986 | Some(crate::transitions::blend_planes( |
| 5987 | d.kind, |
| 5988 | (ay, au, av), |
| 5989 | (y, u, v), |
| 5990 | t, |
| 5991 | aw as usize, |
| 5992 | ah as usize, |
| 5993 | )) |
| 5994 | } |
| 5995 | }; |
| 5996 | let frame_at = span.start + done_here + r; |
| 5997 | let (y, u, v) = match &blended { |
| 5998 | Some(p) => borrow_planes(p), |
| 5999 | None => (ay, au, av), |
| 6000 | }; |
| 6001 | let faded = picture_fade_at(project, frame_at).map(|k| fade_planes((y, u, v), k)); |
| 6002 | let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes); |
| 6003 | let painted = burned16(&mut burn, frame_at, aw, ah, (y, u, v)); |
| 6004 | let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes); |
| 6005 | encoder.encode_wide(y, u, v, aw, ah)? |
| 6006 | } |
| 6007 | (Some(d), true) => { |
| 6008 | let (ay, au, av, aw, ah) = |
| 6009 | placed.expect("a dissolving span always decodes to pixels"); |
| 6010 | match d.decoder.next()?.map(|f| narrowed(f, &mut narrow_b)) { |
| 6011 | // B's file ran out inside the window: A's own |
| 6012 | // picture carries the frame rather than the |
| 6013 | // export losing it. |
| 6014 | None => { |
| 6015 | let frame_at = span.start + done_here + r; |
| 6016 | let faded = picture_fade_at(project, frame_at) |
| 6017 | .map(|k| fade_planes((ay, au, av), k)); |
| 6018 | let (ay, au, av) = |
| 6019 | faded.as_ref().map_or((ay, au, av), borrow_planes); |
| 6020 | let painted = burned(&mut burn, frame_at, aw, ah, (ay, au, av)); |
| 6021 | let (ay, au, av) = painted.as_ref().map_or((ay, au, av), borrow_planes); |
| 6022 | encoder.encode(ay, au, av, aw, ah, settings.intra_only)? |
| 6023 | } |
| 6024 | Some(Frame::Dma(_) | Frame::Wide(..)) => { |
| 6025 | unreachable!("b's decoder was opened with no DMA want and is narrowed") |
| 6026 | } |
| 6027 | Some(Frame::Pixels(by, bu, bv, bw, bh)) => { |
| 6028 | let (by, bu, bv, _, _) = place_picture( |
| 6029 | by, |
| 6030 | bu, |
| 6031 | bv, |
| 6032 | bw, |
| 6033 | bh, |
| 6034 | d.rotation, |
| 6035 | d.pixel_aspect, |
| 6036 | d.grade, |
| 6037 | d.transform, |
| 6038 | d.remap, |
| 6039 | d.mapper, |
| 6040 | &mut d.rotated, |
| 6041 | &mut d.stretched, |
| 6042 | &mut d.graded, |
| 6043 | &mut d.transformed, |
| 6044 | &mut d.canvas, |
| 6045 | ); |
| 6046 | let idx_in_window = done_here + r - d.tail_start; |
| 6047 | let t = dissolve_weight(idx_in_window, d.window); |
| 6048 | let (y, u, v) = crate::transitions::blend_planes( |
| 6049 | d.kind, |
| 6050 | (ay, au, av), |
| 6051 | (by, bu, bv), |
| 6052 | t, |
| 6053 | aw as usize, |
| 6054 | ah as usize, |
| 6055 | ); |
| 6056 | let frame_at = span.start + done_here + r; |
| 6057 | let faded = picture_fade_at(project, frame_at) |
| 6058 | .map(|k| fade_planes((&y[..], &u[..], &v[..]), k)); |
| 6059 | let (y, u, v) = |
| 6060 | faded.as_ref().map_or((&y[..], &u[..], &v[..]), borrow_planes); |
| 6061 | let painted = |
| 6062 | burned(&mut burn, frame_at, aw, ah, (y, u, v)); |
| 6063 | let (y, u, v) = |
| 6064 | painted.as_ref().map_or((y, u, v), borrow_planes); |
| 6065 | encoder.encode(y, u, v, aw, ah, settings.intra_only)? |
| 6066 | } |
| 6067 | } |
| 6068 | } |
| 6069 | _ => match (&frame, placed16) { |
| 6070 | (_, Some((y, u, v, width, height))) => { |
| 6071 | let frame_at = span.start + done_here + r; |
| 6072 | // A layered picture's fades were applied per clip in its stack. |
| 6073 | let faded = picture_fade_at(project, frame_at) |
| 6074 | .filter(|_| !layered_here) |
| 6075 | .map(|k| fade_planes((y, u, v), k)); |
| 6076 | let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes); |
| 6077 | let painted = burned16(&mut burn, frame_at, width, height, (y, u, v)); |
| 6078 | let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes); |
| 6079 | encoder.encode_wide(y, u, v, width, height)? |
| 6080 | } |
| 6081 | (Frame::Dma(dma), None) => encoder.encode_dma(dma, settings.intra_only)?, |
| 6082 | (Frame::Wide(y, u, v, width, height), None) => { |
| 6083 | encoder.encode_wide(y, u, v, *width, *height)? |
| 6084 | } |
| 6085 | (Frame::Pixels(..), None) => { |
| 6086 | let (y, u, v, width, height) = |
| 6087 | placed.expect("a picture with pixels was placed"); |
| 6088 | let frame_at = span.start + done_here + r; |
| 6089 | // A layered picture's fades were applied per clip in |
| 6090 | // its stack; the top clip's does not fade the frame. |
| 6091 | let faded = picture_fade_at(project, frame_at) |
| 6092 | .filter(|_| !layered_here) |
| 6093 | .map(|k| fade_planes((y, u, v), k)); |
| 6094 | let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes); |
| 6095 | let painted = burned(&mut burn, frame_at, width, height, (y, u, v)); |
| 6096 | let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes); |
| 6097 | encoder.encode(y, u, v, width, height, settings.intra_only)? |
| 6098 | } |
| 6099 | }, |
| 6100 | }; |
| 6101 | if let Some((au, key)) = coded { |
| 6102 | write_video( |
| 6103 | &mut muxer, |
| 6104 | out, |
| 6105 | meta, |
| 6106 | settings, |
| 6107 | container_colour, |
| 6108 | source_language.as_deref(), |
| 6109 | audio_params.as_ref(), |
| 6110 | &mut packets, |
| 6111 | &mut subs, |
| 6112 | au, |
| 6113 | key, |
| 6114 | ten_bit, |
| 6115 | )?; |
| 6116 | // Retried here rather than only where the mix lands: the |
| 6117 | // very first coded picture is what creates `muxer`, and a |
| 6118 | // mix that lands before it (a short film, or a slow first |
| 6119 | // frame) has nothing to hand it to until now. |
| 6120 | feed_late_audio(&mut muxer, &late, &mut audio_fed)?; |
| 6121 | inject_export_test_panic(out); |
| 6122 | } |
| 6123 | done += 1; |
| 6124 | // Forwards only: an audio pass still running beside this one |
| 6125 | // publishes its own share of [`AUDIO_BAND`], and a bar that |
| 6126 | // went backwards every time it did would be worse than one |
| 6127 | // that stood still. |
| 6128 | shared |
| 6129 | .progress |
| 6130 | .fetch_max(picture_progress(done, total), Ordering::Relaxed); |
| 6131 | } |
| 6132 | done_here += repeats; |
| 6133 | } |
| 6134 | } |
| 6135 | // The whole walk is over, so what it could not write is known to the frame |
| 6136 | // and is published once. `fetch_max` and not `fetch_add`, because a |
| 6137 | // hardware seat that died has the *whole* walk run again from its first |
| 6138 | // frame ([`start`]): the same project and the same picture counts, so a |
| 6139 | // second run must not double a number that is already on the line. |
| 6140 | shared.truncated.fetch_max(skipped, Ordering::Relaxed); |
| 6141 | while let Some((au, key)) = encoder.drain()? { |
| 6142 | write_video( |
| 6143 | &mut muxer, |
| 6144 | out, |
| 6145 | meta, |
| 6146 | settings, |
| 6147 | container_colour, |
| 6148 | source_language.as_deref(), |
| 6149 | audio_params.as_ref(), |
| 6150 | &mut packets, |
| 6151 | &mut subs, |
| 6152 | au, |
| 6153 | key, |
| 6154 | ten_bit, |
| 6155 | )?; |
| 6156 | } |
| 6157 | // Progress reads 100% from here on, but nothing is published yet: draining, |
| 6158 | // the audio pass and `finish` are all still cancellable. |
| 6159 | cancelled(shared)?; |
| 6160 | |
| 6161 | let Some(muxer) = muxer else { |
| 6162 | return Err("export produced no coded pictures".into()); |
| 6163 | }; |
| 6164 | // The mp4's audio and subtitle tracks after its picture -- the Matroska one |
| 6165 | // interleaved its own as it went and left `packets` and `subs` empty behind |
| 6166 | // it. The text last, so its samples are written knowing how long the picture |
| 6167 | // turned out to be. |
| 6168 | let muxer = match muxer { |
| 6169 | Muxer::Mp4(mut mp4) => { |
| 6170 | // The sound, collected where this file first needs it: it has been |
| 6171 | // mixing and encoding under the whole picture, and an mp4 declares |
| 6172 | // its audio track here rather than at the open precisely so that |
| 6173 | // could happen ([`Mp4Muxer::add_audio_track`]). |
| 6174 | let track = match audio_job.take() { |
| 6175 | Some(job) => { |
| 6176 | let track = join_audio(job)?; |
| 6177 | // The picture finished first and this waited for the |
| 6178 | // sound: the pair of stage lines is what says which of the |
| 6179 | // two an export is really bounded by. |
| 6180 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!( |
| 6181 | "export audio: waited for after {:.1} s of picture", |
| 6182 | picture_started.elapsed().as_secs_f64() |
| 6183 | ); } |
| 6184 | // ...and the line on screen finished with it. The loop above |
| 6185 | // publishes the measured codec the moment the pass lands |
| 6186 | // under the picture, but a picture that outran the mix never |
| 6187 | // reaches that branch -- and "working out the sound…" would |
| 6188 | // then be the last thing the card ever said about a track it |
| 6189 | // had long since written. |
| 6190 | publish_seats( |
| 6191 | shared, |
| 6192 | seat, |
| 6193 | project, |
| 6194 | settings, |
| 6195 | track.as_ref().map(|track| track.copied), |
| 6196 | track |
| 6197 | .as_ref() |
| 6198 | .is_some_and(|track| track.opus_pre_skip.is_some()), |
| 6199 | false, |
| 6200 | ); |
| 6201 | track |
| 6202 | } |
| 6203 | // `late` was already handed to `mp4` inside the picture loop |
| 6204 | // ([`feed_late_audio`]) unless the mix never landed there, in |
| 6205 | // which case it is still `None` and there was nothing to feed. |
| 6206 | None if audio_fed => None, |
| 6207 | None => late, |
| 6208 | }; |
| 6209 | if let Some(track) = &track { |
| 6210 | mp4.add_audio_track(¶ms_of(track))?; |
| 6211 | } |
| 6212 | for packet in track.into_iter().flat_map(|track| track.packets) { |
| 6213 | mp4.write_audio_packet(&packet.bytes)?; |
| 6214 | } |
| 6215 | mp4.set_chapters(&settings.chapters)?; |
| 6216 | mp4.write_subtitles(&subs)?; |
| 6217 | Muxer::Mp4(mp4) |
| 6218 | } |
| 6219 | Muxer::Mov(mut mov) => { |
| 6220 | // The sound, PCM at the asked width, laid to the picture's length. |
| 6221 | if let Some(job) = pcm_job.take() |
| 6222 | && let Some((mut samples, rate, channels)) = join_pcm(job)? |
| 6223 | { |
| 6224 | let want = (f64::from(done) / meta.frame_rate * f64::from(rate)).round() as usize |
| 6225 | * usize::from(channels.max(1)); |
| 6226 | samples.resize(want, 0); |
| 6227 | mov.write_sound(&samples, rate, channels, prores_audio_bits(settings))?; |
| 6228 | } |
| 6229 | Muxer::Mov(mov) |
| 6230 | } |
| 6231 | muxer => muxer, |
| 6232 | }; |
| 6233 | cancelled(shared)?; |
| 6234 | muxer.finish()?; |
| 6235 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); |
| 6236 | Ok(()) |
| 6237 | } |
| 6238 | |
| 6239 | /// The cues a burn of track `pick` draws, on this timeline's clock: what the |
| 6240 | /// screen shows. Once a track is placed on a subtitle lane, its placements are |
| 6241 | /// the answer -- a cut sentence is gone, a trimmed or moved one sits where it |
| 6242 | /// was put, and a hidden lane draws nothing -- with each cue's words read from |
| 6243 | /// its palette track, so a retyped cue burns retyped. A track no lane places is |
| 6244 | /// drawn as the export writes it whole ([`timeline_cues`]), whatever else is |
| 6245 | /// placed, so a burn and a soft track of the same pick never disagree. |
| 6246 | /// |
| 6247 | /// `Err` for a pick that is not a track of the project. |
| 6248 | pub fn burn_cues(project: &Project, pick: usize, fps: f64) -> crate::Result<Vec<Cue>> { |
| 6249 | let track = project |
| 6250 | .subtitles() |
| 6251 | .get(pick) |
| 6252 | .ok_or_else(|| format!("burn_subtitles: no subtitle track {pick} in this project"))?; |
| 6253 | if !placed_tracks(project).contains(&pick) { |
| 6254 | return Ok(timeline_cues(project, track, fps)); |
| 6255 | } |
| 6256 | let mut cues: Vec<Cue> = project |
| 6257 | .subtitle_lanes() |
| 6258 | .into_iter() |
| 6259 | .flat_map(|lane| project.sub_lane_cue_spans(lane, fps)) |
| 6260 | .filter(|s| s.track == pick) |
| 6261 | .filter_map(|s| { |
| 6262 | let c = track.cues.get(s.cue)?; |
| 6263 | Some(Cue { |
| 6264 | start_us: s.start_us, |
| 6265 | end_us: s.end_us, |
| 6266 | text: c.text.clone(), |
| 6267 | image: c.image.clone(), |
| 6268 | words: crate::subtitle::map_words(&c.words, s.window, (s.start_us, s.end_us)), |
| 6269 | karaoke: crate::subtitle::map_karaoke(&c.karaoke, s.window, (s.start_us, s.end_us)), |
| 6270 | }) |
| 6271 | }) |
| 6272 | .collect(); |
| 6273 | cues.sort_by_key(|c| c.start_us); |
| 6274 | Ok(cues) |
| 6275 | } |
| 6276 | |
| 6277 | /// The index of the cue on screen at timeline frame `frame`, if one is: a cue |
| 6278 | /// is shown from the instant of its start up to, not including, its end, read |
| 6279 | /// off the frame's own start time the way [`timeline_cues`] times the frames. |
| 6280 | /// Cues with no text (a picture track's, or a blank line) show nothing. |
| 6281 | pub fn cue_on_screen(cues: &[Cue], frame: u32, fps: f64) -> Option<usize> { |
| 6282 | let t = (f64::from(frame) / fps * 1e6).round() as i64; |
| 6283 | cues.iter().position(|c| { |
| 6284 | c.image.is_none() && c.start_us <= t && t < c.end_us && !c.text.trim().is_empty() |
| 6285 | }) |
| 6286 | } |
| 6287 | |
| 6288 | /// The indices of every cue on screen at timeline frame `frame`, in the order |
| 6289 | /// `cues` lists them (start order from [`burn_cues`]). The same test as |
| 6290 | /// [`cue_on_screen`], for a burn that draws all the cues up at once. |
| 6291 | pub fn cues_on_screen(cues: &[Cue], frame: u32, fps: f64) -> Vec<usize> { |
| 6292 | let t = (f64::from(frame) / fps * 1e6).round() as i64; |
| 6293 | cues.iter() |
| 6294 | .enumerate() |
| 6295 | .filter(|(_, c)| { |
| 6296 | c.image.is_none() && c.start_us <= t && t < c.end_us && !c.text.trim().is_empty() |
| 6297 | }) |
| 6298 | .map(|(i, _)| i) |
| 6299 | .collect() |
| 6300 | } |
| 6301 | |
| 6302 | /// Three planes of one picture, owned: what a burned-in frame is encoded from. |
| 6303 | type Planes<T = u8> = (Vec<T>, Vec<T>, Vec<T>); |
| 6304 | |
| 6305 | /// A picture at 10 bits a sample ([`Enc::encode_wide`]). |
| 6306 | type Planes16 = Planes<u16>; |
| 6307 | |
| 6308 | fn borrow_planes<T>(p: &Planes<T>) -> (&[T], &[T], &[T]) { |
| 6309 | (&p.0, &p.1, &p.2) |
| 6310 | } |
| 6311 | |
| 6312 | /// What one export draws into its pictures: the titles, then the captions |
| 6313 | /// ([`ExportSettings::burn_subtitles`]). The overlay of the cue last drawn is |
| 6314 | /// kept, so a caption on screen for a second is laid out once rather than once |
| 6315 | /// a frame, and each title's overlay is kept the same way. |
| 6316 | struct Burn { |
| 6317 | cues: Vec<Cue>, |
| 6318 | style: TextStyle, |
| 6319 | fps: f64, |
| 6320 | full_range: bool, |
| 6321 | /// The cues drawn last, by index, with the size, the animation state |
| 6322 | /// ([`crate::captionanim::blocks_key`]) and the stacked overlay. |
| 6323 | last: Option<(Vec<usize>, u32, u32, u64, Overlay)>, |
| 6324 | titles: Vec<Title>, |
| 6325 | /// One per title, the overlay it was last drawn as, with what made it ([`TitleKey`]). |
| 6326 | title_last: Vec<Option<(TitleKey, Overlay)>>, |
| 6327 | } |
| 6328 | |
| 6329 | /// What a title's overlay is made from: a frame's size, how much of its text shows and its |
| 6330 | /// motion. A title that does not move keeps the same key, so it is laid out once. |
| 6331 | #[derive(Clone, Debug, PartialEq)] |
| 6332 | struct TitleKey { |
| 6333 | width: u32, |
| 6334 | height: u32, |
| 6335 | size: u32, |
| 6336 | dx: i32, |
| 6337 | dy: i32, |
| 6338 | /// The letters drawn, or `None` for all of them. |
| 6339 | shown: Option<usize>, |
| 6340 | } |
| 6341 | |
| 6342 | /// What a title draws at one frame, as a key: its size, where it is moved and how much of its |
| 6343 | /// text shows, for a `width` x `height` picture. Preview and export both draw a title from this |
| 6344 | /// same motion ([`Title::motion_at`]), so the animation reads the same in both. |
| 6345 | fn title_key(title: &Title, motion: &Motion, width: u32, height: u32) -> TitleKey { |
| 6346 | let size = ((title.style.size as f32 * motion.scale).round() as u32) |
| 6347 | .clamp(crate::text::SIZE_RANGE.0, crate::text::SIZE_RANGE.1); |
| 6348 | TitleKey { |
| 6349 | width, |
| 6350 | height, |
| 6351 | size, |
| 6352 | dx: (motion.dx * width as f32).round() as i32, |
| 6353 | dy: (motion.dy * height as f32).round() as i32, |
| 6354 | shown: motion.revealed(&title.text).map(|s| s.ink), |
| 6355 | } |
| 6356 | } |
| 6357 | |
| 6358 | /// The overlay a title's key stands for: the whole text laid out in the key's size and moved, |
| 6359 | /// with the letters past its reveal left out of the drawing but not out of the layout. |
| 6360 | fn title_overlay(title: &Title, key: &TitleKey) -> Overlay { |
| 6361 | let style = TextStyle { size: key.size, ..title.style.clone() }; |
| 6362 | let lines: Vec<String> = title.text.split('\n').map(str::to_string).collect(); |
| 6363 | let mut ov = match key.shown { |
| 6364 | None => overlay(&style, key.width, key.height, &lines), |
| 6365 | Some(ink) => crate::text::overlay_revealed(&style, key.width, key.height, &lines, ink), |
| 6366 | }; |
| 6367 | if (key.dx, key.dy) != (0, 0) { |
| 6368 | ov = ov.moved(key.dx, key.dy); |
| 6369 | } |
| 6370 | ov |
| 6371 | } |
| 6372 | |
| 6373 | impl Burn { |
| 6374 | /// What the settings and the timeline ask drawn in, or `None` for a picture |
| 6375 | /// left alone. A pick that is not a track of the project is named, not ignored. |
| 6376 | fn new( |
| 6377 | project: &Project, |
| 6378 | settings: &ExportSettings, |
| 6379 | fps: f64, |
| 6380 | full_range: bool, |
| 6381 | ) -> crate::Result<Option<Self>> { |
| 6382 | let titles = project.titles().to_vec(); |
| 6383 | let (cues, style) = match &settings.burn_subtitles { |
| 6384 | Some((pick, style)) => { |
| 6385 | (burn_cues(project, *pick, fps)?, style.clamped()) |
| 6386 | } |
| 6387 | None => (Vec::new(), TextStyle::default()), |
| 6388 | }; |
| 6389 | if cues.is_empty() && titles.is_empty() && settings.burn_subtitles.is_none() { |
| 6390 | return Ok(None); |
| 6391 | } |
| 6392 | Ok(Some(Self { |
| 6393 | cues, |
| 6394 | style, |
| 6395 | fps, |
| 6396 | full_range, |
| 6397 | last: None, |
| 6398 | title_last: vec![None; titles.len()], |
| 6399 | titles, |
| 6400 | })) |
| 6401 | } |
| 6402 | |
| 6403 | /// The picture at timeline frame `frame` with the titles on screen and the |
| 6404 | /// caption drawn in, or `None` where nothing is on screen and the planes go |
| 6405 | /// on untouched. |
| 6406 | fn paint( |
| 6407 | &mut self, |
| 6408 | frame: u32, |
| 6409 | width: u32, |
| 6410 | height: u32, |
| 6411 | planes: (&[u8], &[u8], &[u8]), |
| 6412 | ) -> Option<Planes> { |
| 6413 | let mut out: Option<Planes> = None; |
| 6414 | for (i, t) in self.titles.iter().enumerate() { |
| 6415 | let Some(motion) = t.motion_at(frame) else { |
| 6416 | continue; |
| 6417 | }; |
| 6418 | let alpha = motion.alpha; |
| 6419 | if alpha == 0 { |
| 6420 | continue; |
| 6421 | } |
| 6422 | let key = title_key(t, &motion, width, height); |
| 6423 | if !matches!(&self.title_last[i], Some((k, _)) if *k == key) { |
| 6424 | let ov = title_overlay(t, &key); |
| 6425 | self.title_last[i] = Some((key, ov)); |
| 6426 | } |
| 6427 | let Some((_, ov)) = &self.title_last[i] else { |
| 6428 | continue; |
| 6429 | }; |
| 6430 | let mut planes = out |
| 6431 | .take() |
| 6432 | .unwrap_or_else(|| (planes.0.to_vec(), planes.1.to_vec(), planes.2.to_vec())); |
| 6433 | if alpha == 255 { |
| 6434 | ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range); |
| 6435 | } else { |
| 6436 | ov.faded(alpha).blend_i420( |
| 6437 | &mut planes.0, |
| 6438 | &mut planes.1, |
| 6439 | &mut planes.2, |
| 6440 | self.full_range, |
| 6441 | ); |
| 6442 | } |
| 6443 | out = Some(planes); |
| 6444 | } |
| 6445 | let on = cues_on_screen(&self.cues, frame, self.fps); |
| 6446 | if !on.is_empty() { |
| 6447 | // A static style is keyed by the cues alone, so a cache hit builds nothing. |
| 6448 | // A karaoke cue moves with the clock whatever the style, so it is planned too. |
| 6449 | let lit = on.iter().any(|&i| self.cues[i].real_karaoke().is_some()); |
| 6450 | let planned = (!self.style.caption.is_plain() || lit) |
| 6451 | .then(|| crate::captionanim::plan(&self.style, &self.cues, &on, frame, self.fps)); |
| 6452 | let key = planned.as_deref().map_or(0, crate::captionanim::blocks_key); |
| 6453 | let hit = matches!(&self.last, Some((i, w, h, k, _)) |
| 6454 | if i == &on && (*w, *h) == (width, height) && *k == key); |
| 6455 | if !hit { |
| 6456 | let blocks = planned.unwrap_or_else(|| { |
| 6457 | crate::captionanim::plan(&self.style, &self.cues, &on, frame, self.fps) |
| 6458 | }); |
| 6459 | let ov = overlay_blocks(&self.style, width, height, &blocks); |
| 6460 | self.last = Some((on, width, height, key, ov)); |
| 6461 | } |
| 6462 | if let Some((_, _, _, _, ov)) = self.last.as_ref() { |
| 6463 | let mut planes = out |
| 6464 | .take() |
| 6465 | .unwrap_or_else(|| (planes.0.to_vec(), planes.1.to_vec(), planes.2.to_vec())); |
| 6466 | ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range); |
| 6467 | out = Some(planes); |
| 6468 | } |
| 6469 | } |
| 6470 | out |
| 6471 | } |
| 6472 | } |
| 6473 | |
| 6474 | /// [`Burn::paint`] through an optional burn: the picture as it is when there is |
| 6475 | /// no burn, and as it is with the caption drawn in when there is one. |
| 6476 | fn burned( |
| 6477 | burn: &mut Option<Burn>, |
| 6478 | frame: u32, |
| 6479 | width: u32, |
| 6480 | height: u32, |
| 6481 | planes: (&[u8], &[u8], &[u8]), |
| 6482 | ) -> Option<Planes> { |
| 6483 | burn.as_mut()?.paint(frame, width, height, planes) |
| 6484 | } |
| 6485 | |
| 6486 | /// A lone clip's effects stack drawn on its placed `w` x `h` picture in place, and |
| 6487 | /// the result laid over black where the stack keys, masks or blends it -- what the |
| 6488 | /// layered path draws for the same clip with nothing beneath ([`LayerStack::picture`]). |
| 6489 | #[allow(clippy::too_many_arguments)] |
| 6490 | fn effected<T: Sample>( |
| 6491 | effects: &[crate::effects::Effect], |
| 6492 | planes: &mut Planes<T>, |
| 6493 | w: u32, |
| 6494 | h: u32, |
| 6495 | secs: f64, |
| 6496 | src: f64, |
| 6497 | matrix: Matrix, |
| 6498 | scratch: &mut crate::effects::Scratch<T>, |
| 6499 | ) { |
| 6500 | let (w, h) = (w as usize, h as usize); |
| 6501 | let out = crate::effects::apply(effects, (&mut planes.0, &mut planes.1, &mut planes.2), w, h, secs, src, matrix, scratch); |
| 6502 | crate::effects::over_black((&mut planes.0, &mut planes.1, &mut planes.2), &out, matrix, w, h); |
| 6503 | } |
| 6504 | |
| 6505 | /// One 8-bit code at 10 bits, as the encoder upshifts it (`v << 2 | v >> 6`), so a |
| 6506 | /// widened black is the black of the 10-bit span. |
| 6507 | fn widen_code(v: u8) -> u16 { |
| 6508 | (u16::from(v) << 2) | (u16::from(v) >> 6) |
| 6509 | } |
| 6510 | |
| 6511 | /// [`widen_code`] over a plane, into `out`. |
| 6512 | fn widen_into(src: &[u8], out: &mut Vec<u16>) { |
| 6513 | out.clear(); |
| 6514 | out.extend(src.iter().map(|&v| widen_code(v))); |
| 6515 | } |
| 6516 | |
| 6517 | /// [`burned`] at 10 bits. A caption or a title is an 8-bit overlay, so the picture is |
| 6518 | /// narrowed for it; where the overlay changed a code, that code is written back |
| 6519 | /// widened, and every other code keeps its 10-bit value. |
| 6520 | fn burned16( |
| 6521 | burn: &mut Option<Burn>, |
| 6522 | frame: u32, |
| 6523 | width: u32, |
| 6524 | height: u32, |
| 6525 | planes: (&[u16], &[u16], &[u16]), |
| 6526 | ) -> Option<Planes16> { |
| 6527 | let burn = burn.as_mut()?; |
| 6528 | let narrow = |s: &[u16]| -> Vec<u8> { s.iter().map(|&c| (c >> 2) as u8).collect() }; |
| 6529 | let (ny, nu, nv) = (narrow(planes.0), narrow(planes.1), narrow(planes.2)); |
| 6530 | let painted = burn.paint(frame, width, height, (&ny[..], &nu[..], &nv[..]))?; |
| 6531 | let merge = |orig: &[u16], before: &[u8], after: &[u8]| -> Vec<u16> { |
| 6532 | orig.iter() |
| 6533 | .zip(before.iter().zip(after)) |
| 6534 | .map(|(&o, (&b, &a))| if a == b { o } else { widen_code(a) }) |
| 6535 | .collect() |
| 6536 | }; |
| 6537 | Some(( |
| 6538 | merge(planes.0, &ny, &painted.0[..]), |
| 6539 | merge(planes.1, &nu, &painted.1[..]), |
| 6540 | merge(planes.2, &nv, &painted.2[..]), |
| 6541 | )) |
| 6542 | } |
| 6543 | |
| 6544 | /// The 10-bit placement's scratch: the turn, the pixel-aspect stretch, the grade and the |
| 6545 | /// transform each want a buffer the planes come back borrowed from. |
| 6546 | #[derive(Default)] |
| 6547 | struct Scratch16 { |
| 6548 | turned: Planes16, |
| 6549 | stretched: Planes16, |
| 6550 | graded: Planes16, |
| 6551 | transformed: Planes16, |
| 6552 | } |
| 6553 | |
| 6554 | /// [`place_picture`] at 10 bits: the pixel aspect, the display turn, the tone map, the grade, |
| 6555 | /// the matrix and range remap and the transform, all on 10-bit samples, in the 8-bit order. |
| 6556 | #[expect(clippy::too_many_arguments, reason = "one span's whole 10-bit picture path")] |
| 6557 | fn place_picture16<'a>( |
| 6558 | y: &'a [u16], |
| 6559 | u: &'a [u16], |
| 6560 | v: &'a [u16], |
| 6561 | width: u32, |
| 6562 | height: u32, |
| 6563 | rotation: Rotation, |
| 6564 | pixel_aspect: crate::demux::PixelAspect, |
| 6565 | grade: Option<crate::color::ColorParams>, |
| 6566 | transform: TransformParams, |
| 6567 | remap: Option<Remap>, |
| 6568 | mapper: Option<&ToneMapper>, |
| 6569 | scratch: &'a mut Scratch16, |
| 6570 | canvas: &'a mut Composer, |
| 6571 | ) -> (&'a [u16], &'a [u16], &'a [u16], u32, u32) { |
| 6572 | let Scratch16 { turned, stretched, graded, transformed } = scratch; |
| 6573 | let (y, u, v, width, height) = if pixel_aspect.is_square() { |
| 6574 | (y, u, v, width, height) |
| 6575 | } else { |
| 6576 | let display_width = pixel_aspect.width_factor(width); |
| 6577 | let (dcw, dch) = (display_width.div_ceil(2) as usize, height.div_ceil(2) as usize); |
| 6578 | stretched.0.resize(display_width as usize * height as usize, 0); |
| 6579 | stretched.1.resize(dcw * dch, 0); |
| 6580 | stretched.2.resize(dcw * dch, 0); |
| 6581 | crate::scale::scale_i420( |
| 6582 | y, |
| 6583 | u, |
| 6584 | v, |
| 6585 | width as usize, |
| 6586 | height as usize, |
| 6587 | &mut stretched.0, |
| 6588 | &mut stretched.1, |
| 6589 | &mut stretched.2, |
| 6590 | display_width as usize, |
| 6591 | height as usize, |
| 6592 | ); |
| 6593 | (&stretched.0[..], &stretched.1[..], &stretched.2[..], display_width, height) |
| 6594 | }; |
| 6595 | let (y, u, v, width, height) = match rotation.is_none() { |
| 6596 | true => (y, u, v, width, height), |
| 6597 | false => { |
| 6598 | let (w, h) = crate::scale::rotate_i420_90s_into(y, u, v, width, height, rotation.steps(), turned); |
| 6599 | (&turned.0[..], &turned.1[..], &turned.2[..], w, h) |
| 6600 | } |
| 6601 | }; |
| 6602 | let params = grade.filter(|p| !p.is_identity()); |
| 6603 | let (y, u, v) = match (params, remap, mapper) { |
| 6604 | (None, None, None) => (y, u, v), |
| 6605 | (params, remap, mapper) => { |
| 6606 | let (gy, gu, gv) = graded; |
| 6607 | gy.clear(); |
| 6608 | gy.extend_from_slice(y); |
| 6609 | gu.clear(); |
| 6610 | gu.extend_from_slice(u); |
| 6611 | gv.clear(); |
| 6612 | gv.extend_from_slice(v); |
| 6613 | if let Some(mapper) = mapper { |
| 6614 | mapper.map16(gy, gu, gv, width as usize, height as usize); |
| 6615 | } |
| 6616 | if let Some(params) = params { |
| 6617 | crate::color::apply_yuv_wide(¶ms, gy, gu, gv, width as usize, remap.is_some_and(|r| r.limit)); |
| 6618 | } |
| 6619 | if let Some(remap) = remap { |
| 6620 | if remap.limit { |
| 6621 | crate::colorspace::limit_range::<u16>(gy, gu, gv); |
| 6622 | } |
| 6623 | crate::colorspace::remap::<u16>(remap.from, remap.to, gy, gu, gv, width as usize); |
| 6624 | } |
| 6625 | (&gy[..], &gu[..], &gv[..]) |
| 6626 | } |
| 6627 | }; |
| 6628 | if transform.is_identity() { |
| 6629 | canvas.place_wide(y, u, v, width, height) |
| 6630 | } else { |
| 6631 | let (py, pu, pv, w, h) = canvas.place_transformed_wide(y, u, v, width, height, &transform); |
| 6632 | *transformed = (py, pu, pv); |
| 6633 | (&transformed.0[..], &transformed.1[..], &transformed.2[..], w, h) |
| 6634 | } |
| 6635 | } |
| 6636 | |
| 6637 | /// One decoded picture turned, graded, tone-mapped, remapped and placed on the |
| 6638 | /// canvas -- everything between a source's own samples and the ones an encoder |
| 6639 | /// is fed, which is exactly the work a zero-copy span has none of. |
| 6640 | /// |
| 6641 | /// `rotation` first, before the grade: it is the file's own display matrix, the |
| 6642 | /// turn a player would make before showing the picture at all, and everything |
| 6643 | /// after this -- the grade, the letterbox, the encoder -- is about the picture |
| 6644 | /// as it is *meant* to be seen. `turned`, `graded` and `canvas` are the span's |
| 6645 | /// scratch: the planes come back borrowed from one of them, or from the picture |
| 6646 | /// itself where not a byte was touched. |
| 6647 | #[expect(clippy::too_many_arguments, reason = "one span's whole picture path")] |
| 6648 | fn place_picture<'a>( |
| 6649 | y: &'a [u8], |
| 6650 | u: &'a [u8], |
| 6651 | v: &'a [u8], |
| 6652 | width: u32, |
| 6653 | height: u32, |
| 6654 | rotation: Rotation, |
| 6655 | pixel_aspect: crate::demux::PixelAspect, |
| 6656 | grade: Option<crate::color::ColorParams>, |
| 6657 | transform: TransformParams, |
| 6658 | remap: Option<Remap>, |
| 6659 | mapper: Option<&ToneMapper>, |
| 6660 | turned: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 6661 | stretched: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 6662 | graded: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 6663 | transformed: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 6664 | canvas: &'a mut Composer, |
| 6665 | ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) { |
| 6666 | // The pixel aspect, applied exactly once -- the same single conversion to |
| 6667 | // the square-pixel raster the decode funnel makes, in the same order |
| 6668 | // (stretch the coded width, *then* turn, [`crate::decode::Render::frame`]'s |
| 6669 | // comment carries the 1440x1440 failure the other order produces). A |
| 6670 | // square-pixel file -- every file whose samples are one to one -- borrows |
| 6671 | // the planes through. |
| 6672 | let (y, u, v, width, height) = if pixel_aspect.is_square() { |
| 6673 | (y, u, v, width, height) |
| 6674 | } else { |
| 6675 | let display_width = pixel_aspect.width_factor(width); |
| 6676 | let (dcw, dch) = ( |
| 6677 | display_width.div_ceil(2) as usize, |
| 6678 | height.div_ceil(2) as usize, |
| 6679 | ); |
| 6680 | stretched |
| 6681 | .0 |
| 6682 | .resize(display_width as usize * height as usize, 0); |
| 6683 | stretched.1.resize(dcw * dch, 0); |
| 6684 | stretched.2.resize(dcw * dch, 0); |
| 6685 | crate::scale::scale_i420( |
| 6686 | y, |
| 6687 | u, |
| 6688 | v, |
| 6689 | width as usize, |
| 6690 | height as usize, |
| 6691 | &mut stretched.0, |
| 6692 | &mut stretched.1, |
| 6693 | &mut stretched.2, |
| 6694 | display_width as usize, |
| 6695 | height as usize, |
| 6696 | ); |
| 6697 | ( |
| 6698 | &stretched.0[..], |
| 6699 | &stretched.1[..], |
| 6700 | &stretched.2[..], |
| 6701 | display_width, |
| 6702 | height, |
| 6703 | ) |
| 6704 | }; |
| 6705 | // The file's own turn, taken exactly as playback's decode funnel takes it |
| 6706 | // ([`crate::decode`]): a phone's portrait video is landscape in the file, |
| 6707 | // and the encoder must be fed what the preview showed. A file that states |
| 6708 | // no turn skips this entirely -- the planes go on borrowed. |
| 6709 | let (y, u, v, width, height) = match rotation.is_none() { |
| 6710 | true => (y, u, v, width, height), |
| 6711 | false => { |
| 6712 | let (w, h) = crate::scale::rotate_i420_90s_into( |
| 6713 | y, |
| 6714 | u, |
| 6715 | v, |
| 6716 | width, |
| 6717 | height, |
| 6718 | rotation.steps(), |
| 6719 | turned, |
| 6720 | ); |
| 6721 | (&turned.0[..], &turned.1[..], &turned.2[..], w, h) |
| 6722 | } |
| 6723 | }; |
| 6724 | // The planes are borrowed from the decoder (and `Black::picture` hands the |
| 6725 | // same slice as both u and v), so a grade cannot be applied in place: it |
| 6726 | // goes onto a copy, which the encoder then reads instead. |
| 6727 | let params = grade.filter(|p| !p.is_identity()); |
| 6728 | let (y, u, v) = match (params, remap, mapper) { |
| 6729 | (None, None, None) => (y, u, v), |
| 6730 | (params, remap, mapper) => { |
| 6731 | let (gy, gu, gv) = graded; |
| 6732 | gy.clear(); |
| 6733 | gy.extend_from_slice(y); |
| 6734 | gu.clear(); |
| 6735 | gu.extend_from_slice(u); |
| 6736 | gv.clear(); |
| 6737 | gv.extend_from_slice(v); |
| 6738 | // Tone-map first, so the grade is applied to the SDR picture the |
| 6739 | // canvas showed and not to HDR codes; then remap the graded result. |
| 6740 | // The order playback renders in, and the only order in which |
| 6741 | // preview and export agree. |
| 6742 | if let Some(mapper) = mapper { |
| 6743 | mapper.map(gy, gu, gv, width as usize, height as usize); |
| 6744 | } |
| 6745 | if let Some(params) = params { |
| 6746 | crate::color::apply_yuv(¶ms, gy, gu, gv, width as usize, remap.is_some_and(|r| r.limit)); |
| 6747 | } |
| 6748 | if let Some(remap) = remap { |
| 6749 | // Range before matrix: the matrix arithmetic is written for limited |
| 6750 | // codes, so a full-range picture is brought into that span first. |
| 6751 | if remap.limit { |
| 6752 | crate::colorspace::limit_range(gy, gu, gv); |
| 6753 | } |
| 6754 | crate::colorspace::remap(remap.from, remap.to, gy, gu, gv, width as usize); |
| 6755 | } |
| 6756 | (&gy[..], &gu[..], &gv[..]) |
| 6757 | } |
| 6758 | }; |
| 6759 | // Grade first, place second: the grade is the clip's own pixels and the |
| 6760 | // bars around them are not the clip (see `scale::Composer`). |
| 6761 | if transform.is_identity() { |
| 6762 | canvas.place(y, u, v, width, height) |
| 6763 | } else { |
| 6764 | let (py, pu, pv, w, h) = canvas.place_transformed(y, u, v, width, height, &transform); |
| 6765 | *transformed = (py, pu, pv); |
| 6766 | ( |
| 6767 | &transformed.0[..], |
| 6768 | &transformed.1[..], |
| 6769 | &transformed.2[..], |
| 6770 | w, |
| 6771 | h, |
| 6772 | ) |
| 6773 | } |
| 6774 | } |
| 6775 | |
| 6776 | /// How a span's samples are rewritten on the way into a file whose own matrix is |
| 6777 | /// `to` and whose range is limited ([`ColorDescription::output`]): the matrix they |
| 6778 | /// are coded against, and whether they span the full byte and so need scaling |
| 6779 | /// into the limited span first ([`crate::colorspace::limit_range`]). |
| 6780 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 6781 | struct Remap { |
| 6782 | from: Matrix, |
| 6783 | to: Matrix, |
| 6784 | limit: bool, |
| 6785 | } |
| 6786 | |
| 6787 | /// What [`place_picture`] rewrites a span's samples by -- `None` when they are |
| 6788 | /// already coded against the output's matrix and span its range, and for a gap, |
| 6789 | /// whose 16/128/128 black is black in every matrix here. |
| 6790 | /// |
| 6791 | /// `toned` says the tone map ran on this span: it hands back BT.709 SDR whatever |
| 6792 | /// the source was coded as, so an HDR clip is never *also* given the matrix |
| 6793 | /// treatment its BT.2020 tag would ask for -- one conversion or the other, never |
| 6794 | /// both on one frame -- while a tone-mapped clip on a canvas below 720 lines |
| 6795 | /// still takes its 709 -> 601 step. It is also limited range already, so only an |
| 6796 | /// untouched full-range source is scaled here. |
| 6797 | fn remap_into(color: Option<ColorDescription>, toned: bool, out: Matrix) -> Option<Remap> { |
| 6798 | let from = match toned { |
| 6799 | true => Matrix::Bt709, |
| 6800 | false => color?.matrix, |
| 6801 | }; |
| 6802 | let limit = !toned && color?.full_range; |
| 6803 | (from != out || limit).then_some(Remap { |
| 6804 | from, |
| 6805 | to: out, |
| 6806 | limit, |
| 6807 | }) |
| 6808 | } |
| 6809 | |
| 6810 | /// The picture at timeline `frame`, composed the way [`run`] composes it: the |
| 6811 | /// same span and source frame, placed by [`place_picture`] (turn, pixel aspect, |
| 6812 | /// grade, transform, tone map, fit), dissolved into its successor over the |
| 6813 | /// tail window, and written as the BGRA picture the encoder would have been |
| 6814 | /// given. A gap is black. Visualizer and still clips take the same decoders |
| 6815 | /// export does. |
| 6816 | /// |
| 6817 | /// The output is the project's resolution scaled to fit a `width` x `height` |
| 6818 | /// box at the project's aspect (so a 16:9 project asked for 640x480 comes back |
| 6819 | /// 640x360). Each call opens its own decoder for the one source frame it needs, |
| 6820 | /// so it costs a decoder start; it is for the frame an agent asks for, not a |
| 6821 | /// sequence. |
| 6822 | pub fn compose_at( |
| 6823 | project: &Project, |
| 6824 | meta: &VideoMeta, |
| 6825 | frame: u32, |
| 6826 | width: u32, |
| 6827 | height: u32, |
| 6828 | ) -> crate::Result<crate::decode::Frame> { |
| 6829 | compose_at_with(project, meta, frame, width, height, None) |
| 6830 | } |
| 6831 | |
| 6832 | /// [`compose_at`] with every clip's grade taken off (its colour, its keys and |
| 6833 | /// its LUT): the picture as shot, which is the preview's "before" side and the |
| 6834 | /// frame Auto reads. A copy of the timeline is graded-off, so `project` is left |
| 6835 | /// as it is; nothing here is exported. Sequences a compound clip plays keep |
| 6836 | /// their own grades. |
| 6837 | pub fn compose_ungraded_at(project: &Project, meta: &VideoMeta, frame: u32, width: u32, height: u32) -> crate::Result<crate::decode::Frame> { |
| 6838 | let mut plain = project.clone(); |
| 6839 | for lane in plain.lanes() { |
| 6840 | for idx in 0..plain.lane(lane).len() { |
| 6841 | if !plain.color_keys_of(lane, idx).is_empty() { |
| 6842 | plain.set_color_keys(lane, idx, Vec::new()); |
| 6843 | } |
| 6844 | plain.set_color(lane, idx, None); |
| 6845 | } |
| 6846 | } |
| 6847 | compose_at(&plain, meta, frame, width, height) |
| 6848 | } |
| 6849 | |
| 6850 | /// [`compose_at`] with captions drawn in: `burn` is the subtitle track's index |
| 6851 | /// in [`Project::subtitles`] and the style, as [`ExportSettings::burn_subtitles`] |
| 6852 | /// takes them, and the cue on screen at `frame` is drawn over the output at its |
| 6853 | /// own size. `None` is exactly [`compose_at`]. |
| 6854 | pub fn compose_at_with( |
| 6855 | project: &Project, |
| 6856 | meta: &VideoMeta, |
| 6857 | frame: u32, |
| 6858 | width: u32, |
| 6859 | height: u32, |
| 6860 | burn: Option<(usize, TextStyle)>, |
| 6861 | ) -> crate::Result<crate::decode::Frame> { |
| 6862 | let end = project.media_frames(); |
| 6863 | if frame >= end { |
| 6864 | return Err(format!("frame {frame} is past the end of the timeline ({end} frames)").into()); |
| 6865 | } |
| 6866 | if width == 0 || height == 0 { |
| 6867 | return Err("compose_at: the output size must be non-zero".into()); |
| 6868 | } |
| 6869 | let out = ColorDescription::output_sized(meta.width, meta.height); |
| 6870 | let span = export_spans(project, None) |
| 6871 | .into_iter() |
| 6872 | .find(|s| s.start <= frame && frame - s.start < s.len); |
| 6873 | let layered = layered_at(project, frame); |
| 6874 | let (y, u, v) = match span { |
| 6875 | // Two or more clips cover the frame: each is decoded at this frame and |
| 6876 | // composed bottom to top, exactly as the export composes it. |
| 6877 | _ if layered => { |
| 6878 | let stack = stack_at(project, frame); |
| 6879 | let mut layers = LayerStack::open(project, meta, &stack, out.matrix, None, None)?; |
| 6880 | layers |
| 6881 | .picture(frame)? |
| 6882 | .ok_or_else(|| -> crate::Error { |
| 6883 | format!("compose_at: a clip ends before frame {frame}").into() |
| 6884 | })? |
| 6885 | } |
| 6886 | Some(s) if s.from.is_some() => { |
| 6887 | let (source, in_frame) = s.from.expect("checked above"); |
| 6888 | let offset = frame - s.start; |
| 6889 | let mut a = placed_info(project, meta, source)?; |
| 6890 | let deint = span_deint(project, s.start, &a.path); |
| 6891 | a.rate = crate::deinterlace::counted_rate(deint, a.rate); |
| 6892 | let source_frame = a.rate.source_at(s.source_at(in_frame, offset)); |
| 6893 | let (ay, au, av) = picture_at(project, meta, &a, source_frame, s.start, out.matrix, deint)?; |
| 6894 | match dissolve_window(project, &s) { |
| 6895 | Some((b_source, b_in, window, b_start)) |
| 6896 | if offset >= s.len.saturating_sub(window) => |
| 6897 | { |
| 6898 | let k = offset - (s.len - window); |
| 6899 | let mut b = placed_info(project, meta, b_source)?; |
| 6900 | let b_deint = frame_counting(span_deint(project, b_start, &b.path)); |
| 6901 | b.rate = crate::deinterlace::counted_rate(b_deint, b.rate); |
| 6902 | let b_frame = b.rate.source_at(b_in) + k; |
| 6903 | let (by, bu, bv) = picture_at(project, meta, &b, b_frame, b_start, out.matrix, b_deint)?; |
| 6904 | crate::transitions::blend_planes( |
| 6905 | crate::transitions::kind_at(project, s.start), |
| 6906 | (&ay, &au, &av), |
| 6907 | (&by, &bu, &bv), |
| 6908 | dissolve_weight(k, window), |
| 6909 | meta.width as usize, |
| 6910 | meta.height as usize, |
| 6911 | ) |
| 6912 | } |
| 6913 | _ => (ay, au, av), |
| 6914 | } |
| 6915 | } |
| 6916 | _ => { |
| 6917 | let (w, h) = (meta.width as usize, meta.height as usize); |
| 6918 | ( |
| 6919 | vec![16; w * h], |
| 6920 | vec![128; w.div_ceil(2) * h.div_ceil(2)], |
| 6921 | vec![128; w.div_ceil(2) * h.div_ceil(2)], |
| 6922 | ) |
| 6923 | } |
| 6924 | }; |
| 6925 | // A layered picture's fades were applied per clip inside its stack. |
| 6926 | let (y, u, v) = match picture_fade_at(project, frame).filter(|_| !layered) { |
| 6927 | Some(k) => fade_planes((&y, &u, &v), k), |
| 6928 | None => (y, u, v), |
| 6929 | }; |
| 6930 | let bgra = |
| 6931 | crate::convert::i420_to_bgra(&out, &y, &u, &v, meta.width as usize, meta.height as usize); |
| 6932 | let (tw, th) = fit_box(meta.width, meta.height, width, height); |
| 6933 | let mut bgra = if (tw, th) == (meta.width, meta.height) { |
| 6934 | bgra |
| 6935 | } else { |
| 6936 | resize_bgra(&bgra, meta.width, meta.height, tw, th) |
| 6937 | }; |
| 6938 | // The titles, then the caption, drawn at the size the caller gets, so their |
| 6939 | // size reads the same whatever the output box was asked for. |
| 6940 | for title in project.titles() { |
| 6941 | let Some(motion) = title.motion_at(frame) else { |
| 6942 | continue; |
| 6943 | }; |
| 6944 | let alpha = motion.alpha; |
| 6945 | if alpha == 0 { |
| 6946 | continue; |
| 6947 | } |
| 6948 | let ov = title_overlay(title, &title_key(title, &motion, tw, th)); |
| 6949 | if alpha == 255 { |
| 6950 | ov.blend_bgra(&mut bgra); |
| 6951 | } else { |
| 6952 | ov.faded(alpha).blend_bgra(&mut bgra); |
| 6953 | } |
| 6954 | } |
| 6955 | if let Some((pick, style)) = burn { |
| 6956 | let cues = burn_cues(project, pick, meta.frame_rate)?; |
| 6957 | let on = cues_on_screen(&cues, frame, meta.frame_rate); |
| 6958 | if !on.is_empty() { |
| 6959 | let style = style.clamped(); |
| 6960 | let blocks = crate::captionanim::plan(&style, &cues, &on, frame, meta.frame_rate); |
| 6961 | overlay_blocks(&style, tw, th, &blocks).blend_bgra(&mut bgra); |
| 6962 | } |
| 6963 | } |
| 6964 | Ok(crate::decode::Frame { |
| 6965 | index: frame, |
| 6966 | width: tw, |
| 6967 | height: th, |
| 6968 | bgra, |
| 6969 | }) |
| 6970 | } |
| 6971 | |
| 6972 | /// A source as [`run`] reads it for placement: its path and audio stream, its |
| 6973 | /// rate against the timeline, its colour, the tone map its curve asks for, and |
| 6974 | /// its display-matrix turn and pixel aspect. |
| 6975 | struct Placed { |
| 6976 | path: PathBuf, |
| 6977 | stream: usize, |
| 6978 | rate: Rate, |
| 6979 | color: ColorDescription, |
| 6980 | mapper: Option<ToneMapper>, |
| 6981 | rotation: Rotation, |
| 6982 | pixel_aspect: crate::demux::PixelAspect, |
| 6983 | } |
| 6984 | |
| 6985 | /// The deinterlace setting of the clip the composite shows at `frame`, as it |
| 6986 | /// applies to `path` (`Frame` for anything but interlaced H.264). |
| 6987 | fn span_deint(project: &Project, frame: u32, path: &Path) -> Deinterlace { |
| 6988 | let mode = project |
| 6989 | .composite_clip_at(frame) |
| 6990 | .map_or(Deinterlace::Frame, |(lane, idx)| project.deinterlace_of(lane, idx)); |
| 6991 | crate::deinterlace::effective(mode, path) |
| 6992 | } |
| 6993 | |
| 6994 | /// `Field` counts two pictures a frame, which a picture-per-timeline-frame reader |
| 6995 | /// cannot follow: it takes `Frame` (the same first field at the file's own rate). |
| 6996 | fn frame_counting(mode: Deinterlace) -> Deinterlace { |
| 6997 | if mode == Deinterlace::Field { Deinterlace::Frame } else { mode } |
| 6998 | } |
| 6999 | |
| 7000 | fn placed_info(project: &Project, meta: &VideoMeta, source: usize) -> crate::Result<Placed> { |
| 7001 | let sources = project.sources(); |
| 7002 | let entry = sources |
| 7003 | .get(source) |
| 7004 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; |
| 7005 | let (rate, color, peak, rotation, pixel_aspect) = source_rate(&entry.path, meta.frame_rate); |
| 7006 | let mapper = match color.transfer { |
| 7007 | Transfer::Sdr => None, |
| 7008 | Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, project.tone(), peak)), |
| 7009 | Transfer::Hlg => Some(ToneMapper::new( |
| 7010 | tonemap::Transfer::Hlg, |
| 7011 | project.tone(), |
| 7012 | peak, |
| 7013 | )), |
| 7014 | }; |
| 7015 | Ok(Placed { |
| 7016 | path: entry.path.clone(), |
| 7017 | stream: entry.audio_stream, |
| 7018 | rate, |
| 7019 | color, |
| 7020 | mapper, |
| 7021 | rotation, |
| 7022 | pixel_aspect, |
| 7023 | }) |
| 7024 | } |
| 7025 | |
| 7026 | /// One source picture at `source_frame`, placed as [`run`] places it, as owned |
| 7027 | /// planes at the project's size. `key` is the timeline frame whose grade, |
| 7028 | /// transform, fit and visualizer state apply. |
| 7029 | fn picture_at( |
| 7030 | project: &Project, |
| 7031 | meta: &VideoMeta, |
| 7032 | info: &Placed, |
| 7033 | source_frame: u32, |
| 7034 | key: u32, |
| 7035 | out: Matrix, |
| 7036 | deint: Deinterlace, |
| 7037 | ) -> crate::Result<(Vec<u8>, Vec<u8>, Vec<u8>)> { |
| 7038 | let flags = project.composite_visualizer_at(key); |
| 7039 | let mut decoder = if crate::is_audio(&info.path) || flags & 1 != 0 { |
| 7040 | ClipDecoder::visualizer( |
| 7041 | &info.path, |
| 7042 | info.stream, |
| 7043 | source_frame, |
| 7044 | (meta.width, meta.height), |
| 7045 | meta.frame_rate, |
| 7046 | flags, |
| 7047 | project.composite_viz_paint_at(key), |
| 7048 | )? |
| 7049 | } else { |
| 7050 | ClipDecoder::open_with(&info.path, source_frame, None, None, false, deint)? |
| 7051 | }; |
| 7052 | let Some(picture) = decoder.next()? else { |
| 7053 | return Err(format!("{} ends before frame {source_frame}", info.path.display()).into()); |
| 7054 | }; |
| 7055 | let Frame::Pixels(y, u, v, width, height) = picture else { |
| 7056 | return Err("a single-frame decode produced no pixels".into()); |
| 7057 | }; |
| 7058 | let remap = remap_into(Some(info.color), info.mapper.is_some(), out); |
| 7059 | let grade = project.composite_color_at(key).copied(); |
| 7060 | let transform = project |
| 7061 | .composite_transform_at(key) |
| 7062 | .copied() |
| 7063 | .unwrap_or_default(); |
| 7064 | let mut canvas = Composer::new(meta.width, meta.height, project.composite_fit_at(key)); |
| 7065 | let (mut rotated, mut stretched, mut graded, mut transformed) = Default::default(); |
| 7066 | let (py, pu, pv, _, _) = place_picture( |
| 7067 | y, |
| 7068 | u, |
| 7069 | v, |
| 7070 | width, |
| 7071 | height, |
| 7072 | info.rotation, |
| 7073 | info.pixel_aspect, |
| 7074 | grade, |
| 7075 | transform, |
| 7076 | remap, |
| 7077 | info.mapper.as_ref(), |
| 7078 | &mut rotated, |
| 7079 | &mut stretched, |
| 7080 | &mut graded, |
| 7081 | &mut transformed, |
| 7082 | &mut canvas, |
| 7083 | ); |
| 7084 | Ok((py.to_vec(), pu.to_vec(), pv.to_vec())) |
| 7085 | } |
| 7086 | |
| 7087 | /// The largest size with the project's `w:h` aspect that fits in `bw` x `bh`. |
| 7088 | fn fit_box(w: u32, h: u32, bw: u32, bh: u32) -> (u32, u32) { |
| 7089 | let (w, h, bw, bh) = (w as u64, h as u64, bw as u64, bh as u64); |
| 7090 | let th = (bw * h / w).max(1); |
| 7091 | if th <= bh { |
| 7092 | (bw as u32, th as u32) |
| 7093 | } else { |
| 7094 | let tw = (bh * w / h).max(1); |
| 7095 | (tw as u32, bh as u32) |
| 7096 | } |
| 7097 | } |
| 7098 | |
| 7099 | /// Box-filter resize of a tightly packed BGRA picture. Each destination pixel |
| 7100 | /// averages the source pixels it covers, so an upscale is nearest-neighbour |
| 7101 | /// and a downscale is an area average; no float, so it is byte-stable. |
| 7102 | fn resize_bgra(src: &[u8], sw: u32, sh: u32, dw: u32, dh: u32) -> Vec<u8> { |
| 7103 | fn cover(i: usize, src: usize, dst: usize) -> (usize, usize) { |
| 7104 | let a = i * src / dst; |
| 7105 | let b = ((i + 1) * src / dst).max(a + 1).min(src); |
| 7106 | (a, b) |
| 7107 | } |
| 7108 | let (sw, sh, dw, dh) = (sw as usize, sh as usize, dw as usize, dh as usize); |
| 7109 | let mut out = vec![0u8; dw * dh * 4]; |
| 7110 | for dy in 0..dh { |
| 7111 | let (y0, y1) = cover(dy, sh, dh); |
| 7112 | for dx in 0..dw { |
| 7113 | let (x0, x1) = cover(dx, sw, dw); |
| 7114 | let mut acc = [0u32; 4]; |
| 7115 | for y in y0..y1 { |
| 7116 | for x in x0..x1 { |
| 7117 | let p = (y * sw + x) * 4; |
| 7118 | for (c, a) in acc.iter_mut().enumerate() { |
| 7119 | *a += src[p + c] as u32; |
| 7120 | } |
| 7121 | } |
| 7122 | } |
| 7123 | let n = ((y1 - y0) * (x1 - x0)) as u32; |
| 7124 | let q = (dy * dw + dx) * 4; |
| 7125 | for (c, a) in acc.iter().enumerate() { |
| 7126 | out[q + c] = ((a + n / 2) / n) as u8; |
| 7127 | } |
| 7128 | } |
| 7129 | } |
| 7130 | out |
| 7131 | } |
| 7132 | |
| 7133 | /// What rate `path` was shot at against a timeline at `timeline_fps` |
| 7134 | /// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own |
| 7135 | /// -- a still, a song -- and for one that will not open here: the decoder is |
| 7136 | /// opened a few lines later and fails the export by name, which is a better |
| 7137 | /// error than this one could raise. |
| 7138 | fn source_rate( |
| 7139 | path: &Path, |
| 7140 | timeline_fps: f64, |
| 7141 | ) -> ( |
| 7142 | Rate, |
| 7143 | ColorDescription, |
| 7144 | Option<f32>, |
| 7145 | Rotation, |
| 7146 | crate::demux::PixelAspect, |
| 7147 | ) { |
| 7148 | if crate::is_image(path) || crate::is_audio(path) { |
| 7149 | // A still is BT.601 by construction whatever it was authored as: |
| 7150 | // `decode::rgb_to_i420` is the one matrix that turns its pixels into |
| 7151 | // planes. A song has no picture and the answer is never read. Neither |
| 7152 | // has a display matrix to be turned by, nor an aspect to be widened |
| 7153 | // by: both are authored square. A still's *EXIF* turn is not in this |
| 7154 | // arm either, and for a better reason -- `decode::Still::open` already |
| 7155 | // made it before the planes were written, so `place_picture` is handed |
| 7156 | // the picture the preview showed and must not be told to turn it again. |
| 7157 | return ( |
| 7158 | Rate::REAL_TIME, |
| 7159 | ColorDescription::default(), |
| 7160 | None, |
| 7161 | Rotation::None, |
| 7162 | crate::demux::PixelAspect::SQUARE, |
| 7163 | ); |
| 7164 | } |
| 7165 | match Demuxer::open(path) { |
| 7166 | // ...and one whose rate cannot be named against the timeline's, which |
| 7167 | // `matches_timeline` refuses at import, so nothing on a timeline is on |
| 7168 | // this arm either. |
| 7169 | // |
| 7170 | // The declared peak comes off the same open the space does, which is |
| 7171 | // what keeps export on the number playback's decode funnel read: one |
| 7172 | // header parse, both answers. |
| 7173 | Ok((meta, demuxer)) => ( |
| 7174 | Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), |
| 7175 | meta.color, |
| 7176 | demuxer.light().peak(), |
| 7177 | // The file's own turn, so the encoder is fed the picture the |
| 7178 | // preview shows: the same header read, one more answer. |
| 7179 | meta.rotation, |
| 7180 | // ...and its own sample aspect, for the same reason on the same |
| 7181 | // read: the encoder is fed the shape the preview showed. |
| 7182 | meta.pixel_aspect, |
| 7183 | ), |
| 7184 | // Unreadable here means unreadable below too, where the span dies with a |
| 7185 | // real message; the file's own space is the least of that. |
| 7186 | Err(_) => ( |
| 7187 | Rate::REAL_TIME, |
| 7188 | ColorDescription::default(), |
| 7189 | None, |
| 7190 | Rotation::None, |
| 7191 | crate::demux::PixelAspect::SQUARE, |
| 7192 | ), |
| 7193 | } |
| 7194 | } |
| 7195 | |
| 7196 | /// The audio lanes alone, summed, as a WAV or a FLAC. |
| 7197 | /// |
| 7198 | /// Nothing here re-derives the edit: the play lists are |
| 7199 | /// [`Project::audio_segments_from`] and they are handed to the very |
| 7200 | /// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written |
| 7201 | /// is what was heard -- every lane, mixed the same way, gaps included, which |
| 7202 | /// arrive as real silence from that choke point rather than as a hole this would |
| 7203 | /// have to invent. |
| 7204 | /// |
| 7205 | /// The length is the *timeline's*: each segment resolves its window to whole |
| 7206 | /// samples on its own, so the sum can miss the timeline by a sample or two, and |
| 7207 | /// a source that runs out early would leave the file short. Both are settled by |
| 7208 | /// one `resize` at the end -- padding with silence, trimming what overshot -- |
| 7209 | /// so an exported file is exactly as long as what was edited. |
| 7210 | /// The timeline frames a picture export covers: its range, clipped to the media, or the whole media. |
| 7211 | fn picture_span(project: &Project, settings: &ExportSettings) -> (u32, u32) { |
| 7212 | let media = project.media_frames(); |
| 7213 | match settings.range { |
| 7214 | Some((from, to)) => { |
| 7215 | let from = from.min(media); |
| 7216 | (from, to.min(media).max(from)) |
| 7217 | } |
| 7218 | None => (0, media), |
| 7219 | } |
| 7220 | } |
| 7221 | |
| 7222 | /// The picture at timeline frame `frame` as a PNG file's bytes, at the project's own size. What |
| 7223 | /// the still formats write: [`compose_at_with`] draws it as the export would, titles and burnt |
| 7224 | /// captions included. |
| 7225 | fn still_png(project: &Project, meta: &VideoMeta, frame: u32, settings: &ExportSettings) -> crate::Result<Vec<u8>> { |
| 7226 | let picture = compose_at_with(project, meta, frame, meta.width, meta.height, settings.burn_subtitles.clone())?; |
| 7227 | crate::decode::to_png_bytes(&picture) |
| 7228 | } |
| 7229 | |
| 7230 | /// A numbered PNG run ([`Format::PngSequence`]) into the folder `out`, one file per frame, |
| 7231 | /// named after the folder: `name_00001.png`. A run that fails part way leaves no files behind. |
| 7232 | fn run_png_sequence( |
| 7233 | project: &Project, |
| 7234 | meta: &VideoMeta, |
| 7235 | out: &Path, |
| 7236 | shared: &Arc<Shared>, |
| 7237 | settings: &ExportSettings, |
| 7238 | ) -> crate::Result<()> { |
| 7239 | let (from, to) = picture_span(project, settings); |
| 7240 | let total = to - from; |
| 7241 | std::fs::create_dir_all(out)?; |
| 7242 | let name = out.file_name().and_then(|n| n.to_str()).unwrap_or("frame").to_string(); |
| 7243 | let mut written: Vec<PathBuf> = Vec::new(); |
| 7244 | let result = (|| -> crate::Result<()> { |
| 7245 | for k in 0..total { |
| 7246 | cancelled(shared)?; |
| 7247 | let path = out.join(format!("{name}_{:05}.png", k + 1)); |
| 7248 | std::fs::write(&path, still_png(project, meta, from + k, settings)?)?; |
| 7249 | written.push(path); |
| 7250 | shared.progress.fetch_max(picture_progress(k + 1, total), Ordering::Relaxed); |
| 7251 | } |
| 7252 | Ok(()) |
| 7253 | })(); |
| 7254 | if result.is_err() { |
| 7255 | for path in &written { |
| 7256 | let _ = std::fs::remove_file(path); |
| 7257 | } |
| 7258 | } |
| 7259 | result |
| 7260 | } |
| 7261 | |
| 7262 | /// The poster frame ([`Format::Still`]): the picture at the start of the range, written to `part` |
| 7263 | /// for the caller to publish. |
| 7264 | fn run_still(project: &Project, meta: &VideoMeta, part: &Path, settings: &ExportSettings) -> crate::Result<()> { |
| 7265 | let frame = settings.range.map_or(0, |(from, _)| from); |
| 7266 | std::fs::write(part, still_png(project, meta, frame, settings)?)?; |
| 7267 | Ok(()) |
| 7268 | } |
| 7269 | |
| 7270 | /// The animated GIF ([`Format::Gif`]): the range sampled at [`GifSettings::fps`], each picture |
| 7271 | /// composed at [`GifSettings::width`], handed to the GIF writer one frame at a time. |
| 7272 | fn run_gif( |
| 7273 | project: &Project, |
| 7274 | meta: &VideoMeta, |
| 7275 | part: &Path, |
| 7276 | shared: &Arc<Shared>, |
| 7277 | settings: &ExportSettings, |
| 7278 | ) -> crate::Result<()> { |
| 7279 | let gif = settings.gif; |
| 7280 | // The encoder holds every frame until `finish`, so a GIF is bounded in what it can hold. |
| 7281 | if gif.width == 0 || gif.width > GIF_MAX_WIDTH || gif.fps == 0 || gif.fps > 60 { |
| 7282 | return Err(format!("a GIF is 1 to {GIF_MAX_WIDTH} pixels wide and 1 to 60 frames a second").into()); |
| 7283 | } |
| 7284 | let (from, to) = picture_span(project, settings); |
| 7285 | if f64::from(to - from) / meta.frame_rate > GIF_MAX_SECS { |
| 7286 | return Err(format!("a GIF is at most {GIF_MAX_SECS} s long: export a shorter range").into()); |
| 7287 | } |
| 7288 | let (width, height) = fit_box(meta.width, meta.height, gif.width, GIF_MAX_WIDTH); |
| 7289 | let mut writer = GifWriter::open(width, height, gif.loop_forever)?; |
| 7290 | let fps = f64::from(gif.fps); |
| 7291 | let frames = ((f64::from(to - from) * fps) / meta.frame_rate).ceil() as u32; |
| 7292 | if frames == 0 { |
| 7293 | return Err("the range holds no frames".into()); |
| 7294 | } |
| 7295 | for i in 0..frames { |
| 7296 | cancelled(shared)?; |
| 7297 | // The timeline frame this GIF frame shows, and how long it holds: the hundredths of a |
| 7298 | // second between this frame's start and the next, so the rounding never drifts. |
| 7299 | let at = ((f64::from(i) * meta.frame_rate) / fps) as u32; |
| 7300 | let shown = from + at.min(to - from - 1); |
| 7301 | let next = (f64::from(i + 1) * 100.0 / fps).round() as u32; |
| 7302 | let delay = (next - (f64::from(i) * 100.0 / fps).round() as u32).max(1) as u16; |
| 7303 | let picture = compose_at_with(project, meta, shown, width, height, settings.burn_subtitles.clone())?; |
| 7304 | let rgba: Vec<u8> = picture |
| 7305 | .bgra |
| 7306 | .as_chunks::<4>() |
| 7307 | .0 |
| 7308 | .iter() |
| 7309 | .flat_map(|px| [px[2], px[1], px[0], 255]) |
| 7310 | .collect(); |
| 7311 | writer.push(&rgba, delay)?; |
| 7312 | shared.progress.fetch_max(picture_progress(i + 1, frames), Ordering::Relaxed); |
| 7313 | } |
| 7314 | std::fs::write(part, writer.finish()?)?; |
| 7315 | Ok(()) |
| 7316 | } |
| 7317 | |
| 7318 | /// The widest GIF, and the longest: the encoder keeps every frame until it is finished. |
| 7319 | const GIF_MAX_WIDTH: u32 = 720; |
| 7320 | const GIF_MAX_SECS: f64 = 30.0; |
| 7321 | |
| 7322 | /// The GIF writer, over `ec_image::gif_encode`: 256 colours with dithering (video gradients band |
| 7323 | /// badly without it), looping forever or playing once. |
| 7324 | struct GifWriter(ec_image::gif_encode::Encoder); |
| 7325 | |
| 7326 | impl GifWriter { |
| 7327 | fn open(width: u32, height: u32, loop_forever: bool) -> crate::Result<Self> { |
| 7328 | let opts = ec_image::gif_encode::GifOptions { |
| 7329 | loop_count: if loop_forever { Some(0) } else { None }, |
| 7330 | max_colors: 256, |
| 7331 | dither: true, |
| 7332 | }; |
| 7333 | let encoder = ec_image::gif_encode::Encoder::new(width as u16, height as u16, opts) |
| 7334 | .map_err(|e| format!("GIF: {e}"))?; |
| 7335 | Ok(Self(encoder)) |
| 7336 | } |
| 7337 | |
| 7338 | fn push(&mut self, rgba: &[u8], delay_cs: u16) -> crate::Result<()> { |
| 7339 | self.0.push_rgba8(rgba, delay_cs).map_err(|e| format!("GIF: {e}").into()) |
| 7340 | } |
| 7341 | |
| 7342 | fn finish(self) -> crate::Result<Vec<u8>> { |
| 7343 | self.0.finish().map_err(|e| format!("GIF: {e}").into()) |
| 7344 | } |
| 7345 | } |
| 7346 | |
| 7347 | fn run_audio( |
| 7348 | project: &Project, |
| 7349 | meta: &VideoMeta, |
| 7350 | out: &Path, |
| 7351 | shared: &Shared, |
| 7352 | settings: &ExportSettings, |
| 7353 | sample_rate: Option<u32>, |
| 7354 | ) -> crate::Result<()> { |
| 7355 | let format = settings.format; |
| 7356 | let (samples, audio) = mix_pcm(project, meta, shared, settings, sample_rate, 16)? |
| 7357 | .ok_or("this timeline has no audio to export")?; |
| 7358 | // Written in one go and still cancellable up to here, exactly as the mp4 |
| 7359 | // path is up to its `finish`: the `.part` is what either gets renamed or |
| 7360 | // deleted. |
| 7361 | cancelled(shared)?; |
| 7362 | match format { |
| 7363 | Format::Wav => write_wav(out, &samples, &audio)?, |
| 7364 | Format::Flac => write_flac(out, &samples, &audio)?, |
| 7365 | Format::Mp3 => write_mp3(out, &samples, &audio, audio_kbps_of(settings))?, |
| 7366 | Format::Ogg => write_ogg(out, &samples, &audio)?, |
| 7367 | Format::Opus => write_opus(out, &samples, &audio, project, settings, shared)?, |
| 7368 | _ => unreachable!("the picture formats are `run`"), |
| 7369 | } |
| 7370 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); |
| 7371 | Ok(()) |
| 7372 | } |
| 7373 | |
| 7374 | /// The sample width of a ProRes file's PCM sound: 24 unless |
| 7375 | /// [`ExportSettings::audio_bit_depth`] says 16. |
| 7376 | fn prores_audio_bits(settings: &ExportSettings) -> u8 { |
| 7377 | match settings.audio_bit_depth { |
| 7378 | Some(16) => 16, |
| 7379 | _ => 24, |
| 7380 | } |
| 7381 | } |
| 7382 | |
| 7383 | /// The ProRes file's sound pass: the mix as `bits`-wide samples, `(samples, rate, |
| 7384 | /// channels)`, or `None` for a timeline with no sound. Runs beside the picture. |
| 7385 | fn mix_pcm16( |
| 7386 | project: &Project, |
| 7387 | meta: &VideoMeta, |
| 7388 | shared: &Shared, |
| 7389 | settings: &ExportSettings, |
| 7390 | sample_rate: Option<u32>, |
| 7391 | bits: u8, |
| 7392 | ) -> crate::Result<Option<(Vec<i32>, u32, u16)>> { |
| 7393 | Ok(mix_pcm(project, meta, shared, settings, sample_rate, bits)? |
| 7394 | .map(|(samples, audio)| (samples, audio.sample_rate, audio.channels))) |
| 7395 | } |
| 7396 | |
| 7397 | /// A running ProRes sound pass, joined when dropped for the reason [`AudioPass`] is. |
| 7398 | struct PcmPass(Option<PcmJob>); |
| 7399 | |
| 7400 | /// The ProRes sound pass's thread: `(samples, rate, channels)` or `None` for no sound. |
| 7401 | type PcmJob = thread::JoinHandle<crate::Result<Option<(Vec<i32>, u32, u16)>>>; |
| 7402 | |
| 7403 | impl PcmPass { |
| 7404 | fn take(&mut self) -> Option<PcmJob> { |
| 7405 | self.0.take() |
| 7406 | } |
| 7407 | } |
| 7408 | |
| 7409 | impl Drop for PcmPass { |
| 7410 | fn drop(&mut self) { |
| 7411 | if let Some(job) = self.0.take() { |
| 7412 | let _ = job.join(); |
| 7413 | } |
| 7414 | } |
| 7415 | } |
| 7416 | |
| 7417 | fn join_pcm(job: PcmJob) -> crate::Result<Option<(Vec<i32>, u32, u16)>> { |
| 7418 | job.join() |
| 7419 | .map_err(|_| crate::Error::from("the sound pass stopped without a picture or a reason"))? |
| 7420 | } |
| 7421 | |
| 7422 | /// The audio lanes mixed to 16-bit samples (in an `i32`), the length of the |
| 7423 | /// range: [`run_audio`]'s body up to the write, so a WAV and a ProRes file's PCM |
| 7424 | /// track are the same mix. `None` where the timeline has no sound. |
| 7425 | fn mix_pcm( |
| 7426 | project: &Project, |
| 7427 | meta: &VideoMeta, |
| 7428 | shared: &Shared, |
| 7429 | settings: &ExportSettings, |
| 7430 | sample_rate: Option<u32>, |
| 7431 | bits: u8, |
| 7432 | ) -> crate::Result<Option<(Vec<i32>, AudioMeta)>> { |
| 7433 | let format = settings.format; |
| 7434 | // Full scale of the sample width asked for: 32767 or 8388607. The f32 mix is |
| 7435 | // scaled straight to it, so a 24-bit file is not a widened 16-bit one. |
| 7436 | let full = ((1i64 << (bits - 1)) - 1) as f32; |
| 7437 | let sources = project.audio_sources(); |
| 7438 | let range_start = settings.range.map_or(0, |(s, _)| s); |
| 7439 | let pre = warm_up(project, range_start, meta.frame_rate); |
| 7440 | let offset = range_start - pre; |
| 7441 | let segs = project.audio_segments_from(offset, meta.frame_rate); |
| 7442 | // The equalizers with them, so what is written is what is heard down to the |
| 7443 | // filter: the worker applies them per segment before the lanes are summed |
| 7444 | // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point |
| 7445 | // playback's feeder reads from -- there is no second place here that could |
| 7446 | // apply them differently. |
| 7447 | let eqs = project.audio_eqs_from(offset, meta.frame_rate); |
| 7448 | // ...and the rates with them, for exactly the same reason: a speeded clip is |
| 7449 | // resampled inside the worker playback feeds from, so a WAV of a timeline at |
| 7450 | // 2x is half as long and holds the samples that were heard -- not a |
| 7451 | // second pass here that could disagree with what the ear got. |
| 7452 | let speeds = project.audio_speeds_from(offset, meta.frame_rate); |
| 7453 | // ...and the fades with them, the same choke-point reason again: a clip's |
| 7454 | // envelope runs inside the worker playback feeds from too. |
| 7455 | let fades = project.audio_fades_from(offset, meta.frame_rate); |
| 7456 | // ...and the mix over both: each lane's volume into the sum, the master |
| 7457 | // limiter out of it. The same opener playback's feeder reads from, so a |
| 7458 | // file is written at the levels it was heard at -- there is no second |
| 7459 | // place here that could mix it differently. |
| 7460 | let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade( |
| 7461 | &sources, |
| 7462 | &segs, |
| 7463 | &eqs, |
| 7464 | &speeds, |
| 7465 | &fades, |
| 7466 | meta.frame_rate, |
| 7467 | &project.audio_gains(), |
| 7468 | &project.audio_ducks(), |
| 7469 | &project.audio_voices(), |
| 7470 | project.limiter(), |
| 7471 | sample_rate, |
| 7472 | )? |
| 7473 | else { |
| 7474 | return Ok(None); |
| 7475 | }; |
| 7476 | // The picture path's line, for a file that is sound alone: there is sound |
| 7477 | // by the line above, so this names the encoder writing it. A picture file |
| 7478 | // publishes its own. |
| 7479 | if !format.has_video() { |
| 7480 | *shared.encoders.lock().unwrap() = |
| 7481 | Some(audio_label(project, format, true, None, settings.range.is_some()).to_string()); |
| 7482 | } |
| 7483 | let channels = usize::from(audio.channels); |
| 7484 | let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| { |
| 7485 | e.min(project.media_frames()).saturating_sub(s) |
| 7486 | }); |
| 7487 | let frames = |
| 7488 | (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as u64; |
| 7489 | let total = frames as usize * channels; |
| 7490 | // corner-cut: the whole export sits in memory (4 bytes a sample, so ~23 MB |
| 7491 | // per minute of 48 kHz stereo). `ec-flac` takes it that way and |
| 7492 | // the mp4 path already collects its copied AAC track the same. Upgrade path |
| 7493 | // is ec-riff's incremental writer, fed one block at a time. |
| 7494 | let skip = warm_up_samples(range_start, pre, meta.frame_rate, audio.sample_rate, channels); |
| 7495 | let mut samples: Vec<i32> = Vec::with_capacity(total + skip); |
| 7496 | // Only for a loudness target: the mix at f32, measured and levelled once whole. |
| 7497 | let mut wide: Vec<f32> = Vec::new(); |
| 7498 | for chunk in chunks { |
| 7499 | cancelled(shared)?; |
| 7500 | if shared.loudness.is_some() { |
| 7501 | wide.extend_from_slice(&chunk.samples); |
| 7502 | // The same range-only progress as the plain path below. |
| 7503 | let done = wide.len().saturating_sub(skip).min(total) * PROGRESS_SCALE as usize / total.max(1); |
| 7504 | if !format.has_video() { shared.progress.store(done as u32, Ordering::Relaxed); } |
| 7505 | if wide.len() >= skip + total { |
| 7506 | break; |
| 7507 | } |
| 7508 | continue; |
| 7509 | } |
| 7510 | // Already equalized: the chunks come out of the per-lane workers, which |
| 7511 | // filter each segment before the mix (`open_mixed_streams_eq` above). |
| 7512 | samples.extend( |
| 7513 | chunk |
| 7514 | .samples |
| 7515 | .iter() |
| 7516 | .map(|s| (s.clamp(-1.0, 1.0) * full).round() as i32), |
| 7517 | ); |
| 7518 | // Only the range counts towards the bar: not the pre-roll, not the mix past the end. |
| 7519 | let done = samples.len().saturating_sub(skip).min(total) * PROGRESS_SCALE as usize / total.max(1); |
| 7520 | if !format.has_video() { shared.progress.store(done as u32, Ordering::Relaxed); } |
| 7521 | if samples.len() >= skip + total { |
| 7522 | break; |
| 7523 | } |
| 7524 | } |
| 7525 | if let Some(target) = shared.loudness { |
| 7526 | // The voice warm-up is dropped first, so the gain is measured over the range alone. |
| 7527 | wide.drain(..skip.min(wide.len())); |
| 7528 | wide.resize(total, 0.0); |
| 7529 | level_to_target(&mut wide, audio.sample_rate, audio.channels.max(1), target); |
| 7530 | samples.extend( |
| 7531 | wide.iter().map(|s| (s.clamp(-1.0, 1.0) * full).round() as i32), |
| 7532 | ); |
| 7533 | if !format.has_video() { shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); } |
| 7534 | } else { |
| 7535 | // The pre-roll is in the samples in 16-bit form too, so it goes before the length is set. |
| 7536 | samples.drain(..skip.min(samples.len())); |
| 7537 | } |
| 7538 | samples.resize(total, 0); |
| 7539 | Ok(Some((samples, audio))) |
| 7540 | } |
| 7541 | |
| 7542 | /// The sound alone as AAC in an mp4 box: the `.m4a` file, and the `.mp4` of a |
| 7543 | /// timeline with no picture. The track is the one a picture export carries -- |
| 7544 | /// copied packet for packet where a copy says what the timeline says |
| 7545 | /// ([`copy_audio`]), encoded where it cannot -- so the two files hold the same |
| 7546 | /// samples and differ in the brand alone ([`Mp4Muxer::create_audio_only`]). |
| 7547 | fn run_aac( |
| 7548 | project: &Project, |
| 7549 | meta: &VideoMeta, |
| 7550 | out: &Path, |
| 7551 | shared: &Shared, |
| 7552 | settings: &ExportSettings, |
| 7553 | sample_rate: Option<u32>, |
| 7554 | ) -> crate::Result<()> { |
| 7555 | let track = copy_audio( |
| 7556 | project, |
| 7557 | meta, |
| 7558 | audio_kbps_of(settings), |
| 7559 | false, |
| 7560 | false, |
| 7561 | shared, |
| 7562 | sample_rate, |
| 7563 | settings.range, |
| 7564 | )? |
| 7565 | .ok_or("this timeline has no audio to export")?; |
| 7566 | let track = ExportAudio { |
| 7567 | language: audio_language(project), |
| 7568 | ..track |
| 7569 | }; |
| 7570 | *shared.encoders.lock().unwrap() = Some( |
| 7571 | audio_label( |
| 7572 | project, |
| 7573 | settings.format, |
| 7574 | true, |
| 7575 | Some(track.copied), |
| 7576 | settings.range.is_some(), |
| 7577 | ) |
| 7578 | .to_string(), |
| 7579 | ); |
| 7580 | let mut mp4 = Mp4Muxer::create_audio_only( |
| 7581 | out, |
| 7582 | ¶ms_of(&track), |
| 7583 | settings.format == Format::M4a, |
| 7584 | )?; |
| 7585 | if let Some(frames) = track.pcm_frames { |
| 7586 | mp4.set_audio_frames(frames)?; |
| 7587 | } |
| 7588 | let count = track.packets.len().max(1); |
| 7589 | for (i, packet) in track.packets.iter().enumerate() { |
| 7590 | cancelled(shared)?; |
| 7591 | mp4.write_audio_packet(&packet.bytes)?; |
| 7592 | shared |
| 7593 | .progress |
| 7594 | .fetch_max((i * PROGRESS_SCALE as usize / count) as u32, Ordering::Relaxed); |
| 7595 | } |
| 7596 | cancelled(shared)?; |
| 7597 | mp4.set_chapters(&settings.chapters)?; |
| 7598 | mp4.finish()?; |
| 7599 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); |
| 7600 | Ok(()) |
| 7601 | } |
| 7602 | |
| 7603 | /// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in |
| 7604 | /// this engine, so what the decoder handed over is what the header says. |
| 7605 | fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { |
| 7606 | // Every sample is in hand, so the frame count is known before the header |
| 7607 | // is written: a long enough export gets RF64 instead of a RIFF that would |
| 7608 | // overflow its 32-bit sizes. |
| 7609 | let channels = u64::from(audio.channels.max(1)); |
| 7610 | let options = ec_riff::WavOptions { |
| 7611 | expected_frames: samples.len() as u64 / channels, |
| 7612 | ..Default::default() |
| 7613 | }; |
| 7614 | let mut writer = ec_riff::WavWriter::create_with_options( |
| 7615 | out, |
| 7616 | ec_riff::WavSpec { |
| 7617 | channels: audio.channels, |
| 7618 | sample_rate: audio.sample_rate, |
| 7619 | bits_per_sample: 16, |
| 7620 | sample_format: ec_riff::SampleType::Int, |
| 7621 | }, |
| 7622 | options, |
| 7623 | )?; |
| 7624 | for &sample in samples { |
| 7625 | writer.write_sample(sample as i16)?; |
| 7626 | } |
| 7627 | // Not `drop`: this is what rewrites the RIFF sizes in the header, and its |
| 7628 | // failure is the difference between a finished file and a truncated one. |
| 7629 | writer.finalize()?; |
| 7630 | Ok(()) |
| 7631 | } |
| 7632 | |
| 7633 | /// The same samples as MPEG-1 Layer III, `ec-mp3` doing the encoding -- the |
| 7634 | /// family's own, taking the seat at the same contract (CBR in, frames out, |
| 7635 | /// `Mp3EncoderConfig`'s fields are the old seat's names), so the swap cost the |
| 7636 | /// call sites nothing. |
| 7637 | /// |
| 7638 | /// CBR at the caller's rate, [`DEFAULT_AUDIO_KBPS`] where there was none. Every |
| 7639 | /// offered rate is already a legal Layer III value, so the encoder's snap is a |
| 7640 | /// backstop and not a silent substitution; a sample rate MPEG has no frame for |
| 7641 | /// (anything but the nine MPEG rates 8-48 kHz) is refused there by name rather |
| 7642 | /// than written as something else. |
| 7643 | /// |
| 7644 | /// corner-cut: CBR only -- the card offers rates and not a quality index. Upgrade |
| 7645 | /// path is `Mp3EncoderConfig::vbr_quality` behind a setting of its own. |
| 7646 | fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta, kbps: u32) -> crate::Result<()> { |
| 7647 | let mut encoder = ec_mp3::encode::Mp3Encoder::new(ec_mp3::encode::Mp3EncoderConfig { |
| 7648 | bitrate_kbps: kbps, |
| 7649 | vbr_quality: None, |
| 7650 | }); |
| 7651 | // The samples are the 16-bit ones a WAV of this timeline holds, so the two |
| 7652 | // files are one mix -- and `push_pcm_s16` divides by 32768 exactly as this |
| 7653 | // engine's own decoders do. |
| 7654 | let pcm: Vec<i16> = samples.iter().map(|&s| s as i16).collect(); |
| 7655 | encoder |
| 7656 | .push_pcm_s16(&pcm, audio.channels, audio.sample_rate) |
| 7657 | .map_err(|e| format!("mp3 encode: {e}"))?; |
| 7658 | encoder.finish(); |
| 7659 | let mut file = BufWriter::new(File::create(out)?); |
| 7660 | // `next_packet` after `finish` yields frames until `Eof`, the Xing/Info |
| 7661 | // header first: the loop ends on the only error it can see. |
| 7662 | while let Ok(frame) = encoder.next_packet() { |
| 7663 | file.write_all(&frame)?; |
| 7664 | } |
| 7665 | file.flush()?; |
| 7666 | Ok(()) |
| 7667 | } |
| 7668 | |
| 7669 | /// Where the Vorbis rate loop starts, on `ec-vorbis`'s normalised `[0, 1]` |
| 7670 | /// scale, beside [`VORBIS_TARGET_BPS`] -- the two numbers every `.ogg` this |
| 7671 | /// program writes is coded at. |
| 7672 | /// |
| 7673 | /// A measured operating point, not a taste (2026-09-13 bench, every output |
| 7674 | /// decoded back with **symphonia** -- an independent decoder, and the very one |
| 7675 | /// [`crate::audio`] reopens an export with). The incumbent seat's own 0.85 -- |
| 7676 | /// its top quality that still decoded every fixture to exactly its own length |
| 7677 | /// -- measured 124-176 kbps across this suite's fixtures with correlation |
| 7678 | /// 0.9947-0.9957 against the source. The quality knob alone on the new seat |
| 7679 | /// saturates well under that band (0.98 lands ~87 kbps on a 30-second music |
| 7680 | /// clip), so the seat is driven the way its own rate gates are measured: the |
| 7681 | /// loop starts at 0.85 and is held to a 128 kbps target, which landed |
| 7682 | /// 124-134 kbps actual on the same inputs and beat the incumbent at its own |
| 7683 | /// operating point on every one of them -- correlation 0.9968 against 0.9947 |
| 7684 | /// on the music clip, +3.1 dB PSNR -- at the same size of file. Against |
| 7685 | /// ffmpeg's own libvorbis at `-q 5` (125.8 kbps actual on the same clip) it |
| 7686 | /// reads 0.9968 against 0.9973: par at the same rate. |
| 7687 | const VORBIS_QUALITY: f32 = 0.85; |
| 7688 | |
| 7689 | /// The rate [`VORBIS_QUALITY`]'s loop is held to, in bits per second. Measured |
| 7690 | /// landing within +1..+5% of target across the bench's inputs; the Sound row |
| 7691 | /// stays refused for this format because this target is the encoder's measured |
| 7692 | /// operating point, not a number a card may offer. |
| 7693 | const VORBIS_TARGET_BPS: i32 = 128_000; |
| 7694 | |
| 7695 | /// The same samples as Vorbis I in an Ogg container: `ec-vorbis` encodes, |
| 7696 | /// `ec-ogg` pages. Pure Rust on both halves, like every other encoder here. |
| 7697 | /// |
| 7698 | /// The old seat's two corrections are gone with it, and the going is measured |
| 7699 | /// rather than assumed (2026-09-13, every output decoded back with symphonia). |
| 7700 | /// This encoder numbers its packets the spec's way -- the first audio packet |
| 7701 | /// at granule 0, every packet after at the absolute sample position its block |
| 7702 | /// ends on -- and clamps its final granule to the sample count it was fed, so |
| 7703 | /// a decoder trims the block grid's tail on its own. Written straight through, |
| 7704 | /// every file decodes to exactly the timeline's frame count with the |
| 7705 | /// correlation peak at lag zero, which is what the one-hop pre-roll and the |
| 7706 | /// two granule corrections this function used to carry around the old encoder |
| 7707 | /// were for. |
| 7708 | /// |
| 7709 | /// **Stereo, always.** The format row promises stereo, so a mono mix is |
| 7710 | /// written as dual mono, both channels bit-identical (measured: `max|L-R|` is |
| 7711 | /// exactly 0; the encoder's own channel coupling codes the empty side channel |
| 7712 | /// for almost nothing). The encoder would serve a mono stream, but the row |
| 7713 | /// says stereo and folding the file back down must give exactly what was |
| 7714 | /// mixed. Wider than stereo cannot reach here -- [`crate::audio`] folds 5.1 |
| 7715 | /// to stereo when the source is opened -- but it is refused by name rather |
| 7716 | /// than left to the library's own message. |
| 7717 | /// |
| 7718 | /// corner-cut: one operating point, [`VORBIS_QUALITY`] + |
| 7719 | /// [`VORBIS_TARGET_BPS`], with no user control -- the Sound row is refused for |
| 7720 | /// this format. Upgrade path is a quality picker of its own, worth building |
| 7721 | /// the day the card has a control that speaks in quality rather than kbps. |
| 7722 | fn write_ogg(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { |
| 7723 | if audio.channels > 2 { |
| 7724 | return Err(format!( |
| 7725 | "Ogg Vorbis is written in stereo here and this mix has {} channels", |
| 7726 | audio.channels |
| 7727 | ) |
| 7728 | .into()); |
| 7729 | } |
| 7730 | // The mp3 path's conversion, so the two files are one mix -- the same |
| 7731 | // /32768 scaling this engine's own decoders do -- plus (for a mono mix) |
| 7732 | // the dual-mono widening: the same sample in both channels is the same |
| 7733 | // signal, not a widening of it, so what a player folds back down is what |
| 7734 | // was mixed. |
| 7735 | let pcm: Vec<f32> = match audio.channels < 2 { |
| 7736 | true => samples |
| 7737 | .iter() |
| 7738 | .flat_map(|&s| [f32::from(s as i16) / 32768.0; 2]) |
| 7739 | .collect(), |
| 7740 | false => samples |
| 7741 | .iter() |
| 7742 | .map(|&s| f32::from(s as i16) / 32768.0) |
| 7743 | .collect(), |
| 7744 | }; |
| 7745 | let frames = samples.len() / usize::from(audio.channels).max(1); |
| 7746 | |
| 7747 | let mut encoder = ec_vorbis::VorbisEncoder::new(ec_vorbis::EncoderConfig { |
| 7748 | sample_rate: audio.sample_rate, |
| 7749 | channels: 2, |
| 7750 | bitrate_bps: VORBIS_TARGET_BPS, |
| 7751 | quality: VORBIS_QUALITY, |
| 7752 | }) |
| 7753 | .map_err(|e| format!("vorbis encode: {e}"))?; |
| 7754 | encoder |
| 7755 | .push_interleaved(&pcm) |
| 7756 | .map_err(|e| format!("vorbis encode: {e}"))?; |
| 7757 | encoder.finish(); |
| 7758 | let mut packets = Vec::new(); |
| 7759 | loop { |
| 7760 | match encoder.next_packet() { |
| 7761 | Ok(packet) => packets.push(packet), |
| 7762 | Err(ec_core::Error::Eof) => break, |
| 7763 | Err(ec_core::Error::NeedMore) => continue, |
| 7764 | Err(e) => return Err(format!("vorbis encode: {e}").into()), |
| 7765 | } |
| 7766 | } |
| 7767 | // The three setup headers travel with the encoder, not in the packet |
| 7768 | // stream; with no audio packets there is no stream to page. |
| 7769 | if packets.is_empty() { |
| 7770 | return Err("vorbis encode: no audio packets is not a stream".into()); |
| 7771 | } |
| 7772 | let headers = encoder.headers(); |
| 7773 | let extradata = |
| 7774 | ec_ogg::xiph_lace(&headers).ok_or("vorbis encode: the three headers would not lace")?; |
| 7775 | |
| 7776 | let time_base = |
| 7777 | TimeBase::try_new(1, i64::from(audio.sample_rate)).map_err(|e| format!("ogg mux: {e}"))?; |
| 7778 | let mut params = CodecParameters::new(CodecId::Vorbis); |
| 7779 | params.extradata = Some(Buf::from(extradata)); |
| 7780 | params.media = MediaParameters::Audio(AudioParameters { |
| 7781 | sample_rate: audio.sample_rate, |
| 7782 | layout: ChannelLayout::Stereo, |
| 7783 | ..AudioParameters::default() |
| 7784 | }); |
| 7785 | let mut stream = StreamInfo::new(0, time_base, params); |
| 7786 | stream.duration = Some(frames as i64); |
| 7787 | stream.start_time = Some(0); |
| 7788 | let mut muxer = ec_ogg::OggMuxer::new(File::create(out)?); |
| 7789 | // Without this every audio packet of a short export lands on one page, and |
| 7790 | // the muxer's own note records what that costs: a first-audio-page-is-also- |
| 7791 | // EOS stream decodes short by half a small block in a reference decoder. |
| 7792 | muxer.set_page_target_bytes(Some(OGG_PAGE_BYTES)); |
| 7793 | muxer |
| 7794 | .add_stream(stream) |
| 7795 | .map_err(|e| format!("ogg mux: {e}"))?; |
| 7796 | for packet in &packets { |
| 7797 | // The granule is the encoder's own: the absolute sample position this |
| 7798 | // packet ends at, clamped to the mix's length on the last one. It goes |
| 7799 | // in as side data, which is where `ec-ogg` reads it, because a packet's |
| 7800 | // `pts + duration` would state the position one block late. |
| 7801 | let mut out_packet = |
| 7802 | Packet::new(0, time_base, packet.data.clone()).with_duration(packet.samples); |
| 7803 | out_packet |
| 7804 | .side_data |
| 7805 | .push(ec_ogg::granule_side_data(packet.granule)); |
| 7806 | muxer |
| 7807 | .write_packet(&out_packet) |
| 7808 | .map_err(|e| format!("ogg mux: {e}"))?; |
| 7809 | } |
| 7810 | muxer.finish().map_err(|e| format!("ogg mux: {e}"))?; |
| 7811 | Ok(()) |
| 7812 | } |
| 7813 | |
| 7814 | /// The same samples as Opus in Ogg ([`crate::opus_write`]), at the Sound row's |
| 7815 | /// rate clamped into Opus's own range (6-510 kbps, [`crate::opus_write::DEFAULT_KBPS`] |
| 7816 | /// where none was asked for), with the language and chapters in `OpusTags`. |
| 7817 | /// Cancellable per packet, like the mix before it. |
| 7818 | fn write_opus( |
| 7819 | out: &Path, |
| 7820 | samples: &[i32], |
| 7821 | audio: &AudioMeta, |
| 7822 | project: &Project, |
| 7823 | settings: &ExportSettings, |
| 7824 | shared: &Shared, |
| 7825 | ) -> crate::Result<()> { |
| 7826 | if audio.sample_rate != OPUS_RATE { |
| 7827 | return Err(format!("Opus is coded at 48 kHz and this mix came out at {} Hz", audio.sample_rate).into()); |
| 7828 | } |
| 7829 | let pcm: Vec<f32> = samples.iter().map(|&s| f32::from(s as i16) / 32768.0).collect(); |
| 7830 | let language = audio_language(project); |
| 7831 | let tags = crate::opus_write::Tags { language: language.as_deref(), chapters: &settings.chapters }; |
| 7832 | crate::opus_write::write( |
| 7833 | out, |
| 7834 | &pcm, |
| 7835 | usize::from(audio.channels.max(1)), |
| 7836 | audio.sample_rate, |
| 7837 | settings.audio_kbps.unwrap_or(crate::opus_write::DEFAULT_KBPS), |
| 7838 | &tags, |
| 7839 | &mut |_| cancelled(shared), |
| 7840 | ) |
| 7841 | } |
| 7842 | |
| 7843 | /// The page size [`write_ogg`] asks the Ogg muxer to aim at, in bytes. RFC 3533 |
| 7844 | /// describes pages as "usually 4-8 kB", which is also the muxer's own suggested |
| 7845 | /// general-purpose value. |
| 7846 | const OGG_PAGE_BYTES: usize = 4096; |
| 7847 | |
| 7848 | /// The same samples, losslessly compressed, through [`crate::flac_write`]. The |
| 7849 | /// export is always 16-bit: the samples were scaled to `i16` above. |
| 7850 | fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { |
| 7851 | crate::flac_write::write(out, samples, usize::from(audio.channels), 16, audio.sample_rate) |
| 7852 | } |
| 7853 | |
| 7854 | /// The I420 planes of one black picture, allocated once for a whole export: a |
| 7855 | /// gap in the video lane is encoded, not skipped, or every frame after it would |
| 7856 | /// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention |
| 7857 | /// [`crate::convert`] decodes with. |
| 7858 | struct Black { |
| 7859 | y: Vec<u8>, |
| 7860 | uv: Vec<u8>, |
| 7861 | width: u32, |
| 7862 | height: u32, |
| 7863 | } |
| 7864 | |
| 7865 | impl Black { |
| 7866 | fn new(meta: &VideoMeta) -> Self { |
| 7867 | let (w, h) = (meta.width as usize, meta.height as usize); |
| 7868 | Self { |
| 7869 | y: vec![16; w * h], |
| 7870 | uv: vec![128; w.div_ceil(2) * h.div_ceil(2)], |
| 7871 | width: meta.width, |
| 7872 | height: meta.height, |
| 7873 | } |
| 7874 | } |
| 7875 | |
| 7876 | fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) { |
| 7877 | (&self.y, &self.uv, &self.uv, self.width, self.height) |
| 7878 | } |
| 7879 | } |
| 7880 | |
| 7881 | /// `Err` once a cancel has been asked for. Called at every point where the work |
| 7882 | /// left is more than an instant, so an `esc` at 99.9% still stops the export |
| 7883 | /// instead of quietly completing it. |
| 7884 | fn cancelled(shared: &Shared) -> crate::Result<()> { |
| 7885 | if shared.cancel.load(Ordering::Relaxed) { |
| 7886 | return Err("export cancelled".into()); |
| 7887 | } |
| 7888 | Ok(()) |
| 7889 | } |
| 7890 | |
| 7891 | /// The two containers an export writes, so the picture loop above is one loop: |
| 7892 | /// H.264 goes into mp4, AV1 into Matroska, and nothing else is offered. |
| 7893 | enum Muxer { |
| 7894 | Mp4(Mp4Muxer), |
| 7895 | Mkv(MkvMuxer), |
| 7896 | /// ProRes in QuickTime ([`crate::prores_out::MovWriter`]). |
| 7897 | Mov(crate::prores_out::MovWriter), |
| 7898 | } |
| 7899 | |
| 7900 | impl Muxer { |
| 7901 | fn finish(self) -> crate::Result<()> { |
| 7902 | match self { |
| 7903 | Self::Mp4(mp4) => mp4.finish(), |
| 7904 | Self::Mkv(mkv) => mkv.finish(), |
| 7905 | Self::Mov(mov) => mov.finish(), |
| 7906 | } |
| 7907 | } |
| 7908 | } |
| 7909 | |
| 7910 | /// Test-only panic point, so the worker's own `catch_unwind` branch in |
| 7911 | /// [`start`] is reachable without a codec parser that actually panics: the |
| 7912 | /// variable names the one `.part` whose export dies, and no export but that |
| 7913 | /// one ever matches it, so a concurrent export in the same process is safe. |
| 7914 | fn inject_export_test_panic(out: &Path) { |
| 7915 | if crate::envcfg::var_os("VE_EXPORT_TEST_PANIC").is_some_and(|target| target == out.as_os_str()) { |
| 7916 | panic!("export test panic: the .part is on disk"); |
| 7917 | } |
| 7918 | } |
| 7919 | |
| 7920 | /// Writes one access unit, creating the file on the first one -- the parameter |
| 7921 | /// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once |
| 7922 | /// the encoder has coded something. Units with no coded slice are skipped: a |
| 7923 | /// software encoder may hand back an empty buffer while it buffers, and the |
| 7924 | /// muxer rejects a sample that would carry no picture. |
| 7925 | #[allow( |
| 7926 | clippy::too_many_arguments, |
| 7927 | 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" |
| 7928 | )] |
| 7929 | fn write_video( |
| 7930 | muxer: &mut Option<Muxer>, |
| 7931 | out: &Path, |
| 7932 | meta: &VideoMeta, |
| 7933 | settings: &ExportSettings, |
| 7934 | source_colour: Tags, |
| 7935 | source_language: Option<&str>, |
| 7936 | audio: Option<&AudioParams>, |
| 7937 | packets: &mut Option<Vec<crate::AacPacket>>, |
| 7938 | subs: &mut Vec<SubParams>, |
| 7939 | au: &[u8], |
| 7940 | key: bool, |
| 7941 | ten_bit: bool, |
| 7942 | ) -> crate::Result<()> { |
| 7943 | if settings.format.is_prores() { |
| 7944 | // The encoder's own frame, one sample per picture; the track is declared |
| 7945 | // by the first one, the sound is written after the last. |
| 7946 | let Some(Muxer::Mov(mov)) = muxer else { |
| 7947 | unreachable!("the ProRes seat opens its own muxer") |
| 7948 | }; |
| 7949 | return mov.write_frame(au); |
| 7950 | } |
| 7951 | if settings.format.is_hevc() { |
| 7952 | // The parameter sets are in the access unit -- every intra AU carries |
| 7953 | // VPS, SPS and PPS -- and the record built from them is what *both* |
| 7954 | // containers declare the track with: an mp4's `hvcC` box and a |
| 7955 | // Matroska `CodecPrivate` are the same bytes, so the two files are one |
| 7956 | // stream written twice rather than two. |
| 7957 | let sample = |
| 7958 | crate::mux::annex_b_to_hvcc(au).ok_or("a coded HEVC unit with no slice in it")?; |
| 7959 | if settings.format == Format::Hevc { |
| 7960 | let muxer = match muxer { |
| 7961 | Some(Muxer::Mkv(mkv)) => mkv, |
| 7962 | Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), |
| 7963 | none => { |
| 7964 | let hvcc = hevc_params(au, ten_bit)?; |
| 7965 | let sound = audio.zip(packets.take()); |
| 7966 | let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create_hevc( |
| 7967 | out, |
| 7968 | &HevcParams { |
| 7969 | width: meta.width, |
| 7970 | height: meta.height, |
| 7971 | frame_rate: meta.frame_rate, |
| 7972 | hvcc: &hvcc, |
| 7973 | language: source_language.map(str::to_owned), |
| 7974 | colour: (settings.hdr.transfer != HdrTransfer::Sdr).then_some(source_colour), |
| 7975 | light: (settings.hdr.transfer != HdrTransfer::Sdr) |
| 7976 | .then(|| crate::mux::hdr_light(&settings.hdr)), |
| 7977 | }, |
| 7978 | sound, |
| 7979 | std::mem::take(subs), |
| 7980 | )?)) else { |
| 7981 | unreachable!("just inserted a Matroska muxer") |
| 7982 | }; |
| 7983 | mkv.set_chapters(&settings.chapters)?; |
| 7984 | mkv |
| 7985 | } |
| 7986 | }; |
| 7987 | return muxer.write_frame(&sample, key); |
| 7988 | } |
| 7989 | let muxer = match muxer { |
| 7990 | Some(Muxer::Mp4(mp4)) => mp4, |
| 7991 | Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), |
| 7992 | none => { |
| 7993 | let hvcc = hevc_params(au, ten_bit)?; |
| 7994 | let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_hevc( |
| 7995 | out, |
| 7996 | &HevcParams { |
| 7997 | width: meta.width, |
| 7998 | height: meta.height, |
| 7999 | frame_rate: meta.frame_rate, |
| 8000 | hvcc: &hvcc, |
| 8001 | // mp4 does not state a picture's language yet. |
| 8002 | language: None, |
| 8003 | colour: None, |
| 8004 | light: None, |
| 8005 | }, |
| 8006 | audio, |
| 8007 | )?)) else { |
| 8008 | unreachable!("just inserted an mp4 muxer") |
| 8009 | }; |
| 8010 | // The same `colr` rule as AV1's: the colour a 10-bit SDR export |
| 8011 | // declares, which the bitstream's VUI states as well. |
| 8012 | if source_colour != Tags::default() { |
| 8013 | mp4.set_colour(source_colour); |
| 8014 | } |
| 8015 | if settings.hdr.transfer != HdrTransfer::Sdr { |
| 8016 | mp4.set_hdr(&settings.hdr); |
| 8017 | } |
| 8018 | mp4 |
| 8019 | } |
| 8020 | }; |
| 8021 | return muxer.write_coded_sample(&sample, key); |
| 8022 | } |
| 8023 | if settings.format.is_av1() { |
| 8024 | // Every AV1 stream opens on a keyframe, and a keyframe carries the |
| 8025 | // sequence header the track has to declare: an encoder that handed back |
| 8026 | // neither has produced nothing a decoder can start. The same header goes |
| 8027 | // into a `CodecPrivate` and into an `av1C` -- one record, two containers. |
| 8028 | fn params<'a>( |
| 8029 | meta: &VideoMeta, |
| 8030 | au: &'a [u8], |
| 8031 | language: Option<&str>, |
| 8032 | ten_bit: bool, |
| 8033 | colour: Tags, |
| 8034 | ) -> crate::Result<Av1Params<'a>> { |
| 8035 | Ok(Av1Params { |
| 8036 | width: meta.width, |
| 8037 | height: meta.height, |
| 8038 | frame_rate: meta.frame_rate, |
| 8039 | config: crate::mux::av1_sequence_header(au) |
| 8040 | .ok_or("the first coded picture carries no AV1 sequence header")?, |
| 8041 | language: language.map(str::to_owned), |
| 8042 | ten_bit, |
| 8043 | colour: (colour != Tags::default()).then_some(colour), |
| 8044 | }) |
| 8045 | } |
| 8046 | if matches!(settings.format, Format::Av1 | Format::Webm) { |
| 8047 | let muxer = match muxer { |
| 8048 | Some(Muxer::Mkv(mkv)) => mkv, |
| 8049 | Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), |
| 8050 | none => { |
| 8051 | // The sound with it, all of it: the Matroska muxer writes the |
| 8052 | // packets into the clusters of the pictures they play under. |
| 8053 | let sound = audio.zip(packets.take()); |
| 8054 | let created = match settings.format { |
| 8055 | // WebM has no subtitle track to take ([`export_subtitles`]). |
| 8056 | Format::Webm => MkvMuxer::create_webm(out, ¶ms(meta, au, source_language, ten_bit, source_colour)?, sound)?, |
| 8057 | _ => { |
| 8058 | MkvMuxer::create( |
| 8059 | out, |
| 8060 | ¶ms(meta, au, source_language, ten_bit, source_colour)?, |
| 8061 | sound, |
| 8062 | std::mem::take(subs), |
| 8063 | )? |
| 8064 | } |
| 8065 | }; |
| 8066 | let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(created)) else { |
| 8067 | unreachable!("just inserted a Matroska muxer") |
| 8068 | }; |
| 8069 | mkv.set_chapters(&settings.chapters)?; |
| 8070 | mkv |
| 8071 | } |
| 8072 | }; |
| 8073 | return muxer.write_frame(au, key); |
| 8074 | } |
| 8075 | let muxer = match muxer { |
| 8076 | Some(Muxer::Mp4(mp4)) => mp4, |
| 8077 | Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), |
| 8078 | none => { |
| 8079 | let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1( |
| 8080 | out, |
| 8081 | ¶ms(meta, au, None, ten_bit, source_colour)?, |
| 8082 | audio, |
| 8083 | )?)) else { |
| 8084 | unreachable!("just inserted an mp4 muxer") |
| 8085 | }; |
| 8086 | // The `colr` box states the colour a 10-bit SDR export declares; an |
| 8087 | // export with no colour of its own keeps the output rule's box. |
| 8088 | if source_colour != Tags::default() { |
| 8089 | mp4.set_colour(source_colour); |
| 8090 | } |
| 8091 | mp4 |
| 8092 | } |
| 8093 | }; |
| 8094 | return muxer.write_coded_sample(au, key); |
| 8095 | } |
| 8096 | if !crate::mux::has_coded_slice(au) { |
| 8097 | return Ok(()); |
| 8098 | } |
| 8099 | let muxer = match muxer { |
| 8100 | Some(Muxer::Mp4(mp4)) => mp4, |
| 8101 | Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), |
| 8102 | none => { |
| 8103 | let (sps, pps) = crate::mux::parameter_sets(au) |
| 8104 | .ok_or("the first coded picture carries no SPS/PPS")?; |
| 8105 | let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create( |
| 8106 | out, |
| 8107 | &VideoParams { |
| 8108 | width: meta.width, |
| 8109 | height: meta.height, |
| 8110 | frame_rate: meta.frame_rate, |
| 8111 | sps, |
| 8112 | pps, |
| 8113 | }, |
| 8114 | audio, |
| 8115 | )?)) else { |
| 8116 | unreachable!("just inserted an mp4 muxer") |
| 8117 | }; |
| 8118 | // A file written in its source's own space says so, rather than |
| 8119 | // claiming the space its height would imply |
| 8120 | // ([`ExportSettings::keep_source_colour`]). |
| 8121 | if settings.keep_source_colour || source_colour != Tags::default() { |
| 8122 | mp4.set_colour(source_colour); |
| 8123 | } |
| 8124 | mp4 |
| 8125 | } |
| 8126 | }; |
| 8127 | muxer.write_video_au(au) |
| 8128 | } |
| 8129 | |
| 8130 | /// The `hvcC` record of the first coded unit, or the refusal by name. Split out |
| 8131 | /// because both HEVC containers ask it in the same words. |
| 8132 | fn hevc_params(au: &[u8], ten_bit: bool) -> crate::Result<Vec<u8>> { |
| 8133 | crate::mux::hvcc_record_at(au, ten_bit) |
| 8134 | .ok_or_else(|| crate::Error::from("the first coded picture carries no HEVC VPS/SPS/PPS")) |
| 8135 | } |
| 8136 | |
| 8137 | fn bitrate_for(meta: &VideoMeta) -> u64 { |
| 8138 | let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL; |
| 8139 | (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE) |
| 8140 | } |
| 8141 | |
| 8142 | fn forced(var: &str) -> bool { |
| 8143 | crate::envcfg::var_os(var).is_some_and(|v| v == "1") |
| 8144 | } |
| 8145 | |
| 8146 | /// Hardware where it is available, software everywhere else -- chosen once for |
| 8147 | /// the whole export, so the stream never changes encoder mid-file. Both codecs |
| 8148 | /// have both seats: an AV1 export runs on the plugin's VA-API encoder where the |
| 8149 | /// GPU has one and on `rav1e` where it has not, which is the same pair H.264 has |
| 8150 | /// had and the same silent fallback. |
| 8151 | enum Enc { |
| 8152 | Hw(HwEncoder), |
| 8153 | Sw { |
| 8154 | encoder: Encoder, |
| 8155 | /// The access unit currently lent out: the encoder hands back an owned |
| 8156 | /// `Vec` where the seat's contract lends a slice, so one lives here |
| 8157 | /// between the two. |
| 8158 | au: Vec<u8>, |
| 8159 | }, |
| 8160 | /// AV1 on the GPU, through the same plugin the H.264 seat uses. |
| 8161 | Av1Hw(HwEncoder), |
| 8162 | /// HEVC on the GPU, through that same plugin -- and intra-only there too, |
| 8163 | /// so this and [`Enc::Hevc`] write the same kind of file. |
| 8164 | HevcHw(HwEncoder), |
| 8165 | /// AV1 software at 10 bits: `rav1e`'s 16-bit context. A picture that passes |
| 8166 | /// through the span untouched arrives as 16-bit planes off the 10-bit decode |
| 8167 | /// ([`Enc::encode_wide`]); an 8-bit picture (one composed on the way) is shifted |
| 8168 | /// up to the same scale in [`Enc::encode`]. |
| 8169 | Av1Sw16 { |
| 8170 | context: rav1e::Context<u16>, |
| 8171 | ready: std::collections::VecDeque<(Vec<u8>, bool)>, |
| 8172 | au: Vec<u8>, |
| 8173 | flushed: bool, |
| 8174 | scratch: [Vec<u16>; 3], |
| 8175 | }, |
| 8176 | Av1Sw { |
| 8177 | context: rav1e::Context<u8>, |
| 8178 | /// Temporal units the encoder has finished but the caller has not |
| 8179 | /// collected: `rav1e` reorders and may hand back several at once, while |
| 8180 | /// this interface is one picture in, one unit out (the plugin's own |
| 8181 | /// `ready` queue exists for the same reason). |
| 8182 | ready: std::collections::VecDeque<(Vec<u8>, bool)>, |
| 8183 | /// The unit currently lent out, for the same reason `Sw` owns one. |
| 8184 | au: Vec<u8>, |
| 8185 | flushed: bool, |
| 8186 | }, |
| 8187 | /// HEVC, intra-only and software: `ec-h265` codes every picture an IDR |
| 8188 | /// carrying its own VPS/SPS/PPS. A batch of frames codes on as many lane |
| 8189 | /// encoders as there are pictures, and each encoder's wavefront splits |
| 8190 | /// whatever cores the lanes leave over -- the same shape as the seat it |
| 8191 | /// replaced, the cores spent on frames and inside one picture at the same |
| 8192 | /// time. Asked for by [`ExportSettings::intra_only`]. |
| 8193 | Hevc(HevcEnc), |
| 8194 | /// HEVC, I+P GOPs, software: `ec-h265`'s sequence coder on a worker thread. |
| 8195 | /// The default HEVC seat ([`Enc::open_hevc_gop`]). |
| 8196 | HevcGop(HevcGop), |
| 8197 | /// ProRes, software: `ec-prores` codes one whole frame per call (its own |
| 8198 | /// worker threads inside), so one picture in is one sample out. The 4:2:0 |
| 8199 | /// pictures of the walk are widened to 10 bits and chroma-upsampled to the |
| 8200 | /// profile's layout ([`crate::prores_out`]). |
| 8201 | ProRes { |
| 8202 | encoder: ec_prores::ProResEncoder, |
| 8203 | /// The sample currently lent out. |
| 8204 | au: Vec<u8>, |
| 8205 | /// 4:4:4 profiles (4444, 4444 XQ) code full chroma. |
| 8206 | full_chroma: bool, |
| 8207 | }, |
| 8208 | } |
| 8209 | |
| 8210 | /// The intra HEVC seat. Frames arrive one at a time (the export walk is one |
| 8211 | /// picture per timeline frame) and are held until there is a lane for each, |
| 8212 | /// then coded in parallel and queued in **display order**. `ec-h265`'s |
| 8213 | /// wavefront spreads one picture across the workers it is given and the lanes |
| 8214 | /// spread the frames across the machine, so decode and render keep filling |
| 8215 | /// the next batch while this one codes -- a seat that coded one picture at a |
| 8216 | /// time would serialize the whole walk behind its encoder (measured: 7.4 fps |
| 8217 | /// against 11.8 at 1080p on the same box, which is the regression this |
| 8218 | /// batching exists to prevent). |
| 8219 | /// |
| 8220 | /// corner-cut: a batch of display-size planes sits in memory (~3 MB a frame |
| 8221 | /// at 1080p, so ~37 MB at 12 lanes) and the tail of a timeline is coded on |
| 8222 | /// fewer lanes than the middle. Upgrade path is a pipeline that keeps every |
| 8223 | /// lane fed from a decoder running ahead of the encoder rather than a batch |
| 8224 | /// barrier. |
| 8225 | struct HevcEnc { |
| 8226 | /// Display-size I420 pictures waiting for a lane, in display order. The |
| 8227 | /// encoder pads to its own coded grid, so nothing is pre-padded here. |
| 8228 | pending: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)>, |
| 8229 | /// Coded access units not yet collected, in the same order. |
| 8230 | ready: std::collections::VecDeque<Vec<u8>>, |
| 8231 | /// The unit currently lent out, for the reason `Sw` owns one: the encoder |
| 8232 | /// hands back an owned `Vec`, the seat's contract lends a slice. |
| 8233 | au: Vec<u8>, |
| 8234 | /// One encoder per lane. `ec-h265` is stateless from picture to picture |
| 8235 | /// (every picture is an IDR), so a lane coding frame *n* needs nothing |
| 8236 | /// the other lanes know. |
| 8237 | lanes: Vec<HevcEncoder>, |
| 8238 | /// The display width the planes arrive at; the height lives in each |
| 8239 | /// encoder's config, where the coded grid is derived from it. |
| 8240 | width: usize, |
| 8241 | /// Whether the lanes code at 10 bits: `pending` then holds little-endian |
| 8242 | /// 16-bit samples, which [`HevcEnc::code_batch`] reads back. |
| 8243 | ten_bit: bool, |
| 8244 | } |
| 8245 | |
| 8246 | impl Enc { |
| 8247 | /// Which seat this *is*, said the way [`video_label`] says it -- so the |
| 8248 | /// name a running export shows is the name the card showed, or the honest |
| 8249 | /// difference where the probe and the open disagreed. |
| 8250 | fn label(&self) -> &'static str { |
| 8251 | match self { |
| 8252 | Self::Hw(_) => video_label(Format::Mp4, true, false), |
| 8253 | Self::Sw { .. } => video_label(Format::Mp4, false, false), |
| 8254 | Self::Av1Hw(_) => video_label(Format::Av1, true, false), |
| 8255 | Self::Av1Sw { .. } | Self::Av1Sw16 { .. } => video_label(Format::Av1, false, false), |
| 8256 | Self::HevcHw(_) => video_label(Format::Hevc, true, true), |
| 8257 | Self::Hevc(_) => video_label(Format::Hevc, false, true), |
| 8258 | Self::HevcGop(_) => video_label(Format::Hevc, false, false), |
| 8259 | Self::ProRes { .. } => video_label(Format::ProRes, false, true), |
| 8260 | } |
| 8261 | } |
| 8262 | |
| 8263 | /// The ProRes seat's codec parameters (the sample entry's fourcc rides in |
| 8264 | /// the extradata); `None` for every other seat. |
| 8265 | fn prores_params(&self) -> Option<&ec_core::registry::CodecParameters> { |
| 8266 | match self { |
| 8267 | Self::ProRes { encoder, .. } => Some(ec_core::registry::Encoder::codec_parameters(encoder)), |
| 8268 | _ => None, |
| 8269 | } |
| 8270 | } |
| 8271 | |
| 8272 | /// `ten_bit` is [`wide_ten_bit`]'s answer; it means something to AV1 and HEVC only. |
| 8273 | /// `colour` is what the file declares, in the bitstream as well as the container. |
| 8274 | fn open( |
| 8275 | meta: &VideoMeta, |
| 8276 | settings: &ExportSettings, |
| 8277 | ten_bit: bool, |
| 8278 | colour: ColorDescription, |
| 8279 | ) -> crate::Result<Self> { |
| 8280 | // Which *codec* the picture is, not which container it goes in: both AV1 |
| 8281 | // formats run the same encoder, and so do both HEVC ones. |
| 8282 | if settings.format.is_av1() { |
| 8283 | return Self::open_av1(meta, settings, ten_bit, colour); |
| 8284 | } |
| 8285 | if settings.format.is_hevc() { |
| 8286 | return Self::open_hevc(meta, settings, ten_bit, colour); |
| 8287 | } |
| 8288 | if settings.format.is_prores() { |
| 8289 | return Self::open_prores(meta, settings, colour); |
| 8290 | } |
| 8291 | // A caller's number goes through the same clamp as the computed one: a |
| 8292 | // zero bitrate switches the software encoder's lookahead on, which would |
| 8293 | // break the one-picture-per-call contract `encode` documents below. |
| 8294 | let bitrate = bitrate_of(meta, settings); |
| 8295 | // The plugin wants an exact rational, and the muxer already picks one |
| 8296 | // that is exact at every rate we can read -- `fps * 1000 / 1000` would |
| 8297 | // hand 24000/1001 over as a rounded 23.976, which is the same |
| 8298 | // truncation the container timing had. |
| 8299 | crate::mux::frame_timing(meta.frame_rate)?; |
| 8300 | if let Some(hw) = hw_seat(meta, settings)? { |
| 8301 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware (VA-API plugin)"); } |
| 8302 | return Ok(Self::Hw(hw)); |
| 8303 | } |
| 8304 | // H.264 codes 16x16 macroblocks, and ec-h264's floor is the |
| 8305 | // macroblock itself -- the old encoder took any positive even size. |
| 8306 | // Named here, where a card can show it, rather than let the encoder's |
| 8307 | // error surface from inside an export already under way. |
| 8308 | if meta.width < 16 || meta.height < 16 { |
| 8309 | return Err(format!( |
| 8310 | "{}x{} cannot be written as H.264: the picture is smaller \ |
| 8311 | than one 16x16 macroblock", |
| 8312 | meta.width, meta.height |
| 8313 | ) |
| 8314 | .into()); |
| 8315 | } |
| 8316 | // 4:2:0 addresses its conformance window in *chroma* samples, so an odd |
| 8317 | // picture cannot be cropped back to itself -- and an odd dimension has |
| 8318 | // no chroma plane of its own to begin with. Named rather than padded to |
| 8319 | // something a decoder would then show a column of: the same refusal the |
| 8320 | // HEVC seat makes, and x264's and ffmpeg's own for 4:2:0 H.264. |
| 8321 | if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) { |
| 8322 | return Err(format!( |
| 8323 | "{}x{} cannot be written as H.264: 4:2:0 needs even dimensions", |
| 8324 | meta.width, meta.height |
| 8325 | ) |
| 8326 | .into()); |
| 8327 | } |
| 8328 | let mut cfg = EncoderConfig::new(meta.width, meta.height); |
| 8329 | cfg.framerate = meta.frame_rate as f32; |
| 8330 | cfg.bitrate = bitrate.min(u32::MAX as u64) as u32; |
| 8331 | // Two seconds between key frames, and no B-frames on either path: the |
| 8332 | // muxer times everything by duration alone, which reordering would |
| 8333 | // break. A proxy asks for one frame a GOP, which is every frame its own |
| 8334 | // starting point ([`ExportSettings::intra_only`]). |
| 8335 | cfg.gop_size = match settings.intra_only { |
| 8336 | true => 1, |
| 8337 | false => (meta.frame_rate * 2.0).round().max(1.0) as u32, |
| 8338 | }; |
| 8339 | // Fast, the rung a fallback is allowed to cost -- the cheaper arm of |
| 8340 | // the preset ladder, the one the old seat's own S1 also picked when its |
| 8341 | // Balanced rung halved the rate for the same bitrate. |
| 8342 | cfg.preset = Preset::Fast; |
| 8343 | // 8x8 transform off. At this rung it is half the pure-encode cost |
| 8344 | // (17.2 ms/frame against 35.1 at 720p across all cores, measured at |
| 8345 | // the swap) for at most 0.7 dB BD-PSNR -- against an old seat that ran |
| 8346 | // Constrained Baseline and never had the transform in the first |
| 8347 | // place. The export stays Main-profile CABAC, which is where the |
| 8348 | // quality over the old seat lives; a constant-QP mode would be the |
| 8349 | // place to revisit the rung whole. |
| 8350 | cfg.transform_8x8 = false; |
| 8351 | let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?; |
| 8352 | Ok(Self::Sw { |
| 8353 | encoder, |
| 8354 | au: Vec::new(), |
| 8355 | }) |
| 8356 | } |
| 8357 | |
| 8358 | /// The AV1 pair. The hardware seat is the plugin's, opened by a symbol of |
| 8359 | /// its own (`vh_enc_av1_open`) so a plugin built before AV1 encode existed |
| 8360 | /// simply has none and this falls through -- the same "no" a GPU without an |
| 8361 | /// AV1 encode entrypoint gives, and the same silent fallback either way. |
| 8362 | /// |
| 8363 | /// It is **asked for by name**, which is the one place this pair does not |
| 8364 | /// mirror the H.264 one: the vendored cros-codecs AV1 encoder hung the GPU |
| 8365 | /// on this project's own radeonsi box -- `engine_hw: operation failed`, |
| 8366 | /// then an amdgpu hard recovery and a lost context, measured 2026-08-10 |
| 8367 | /// exporting the 720p fixture. A software encoder that takes half a minute |
| 8368 | /// is a worse export than a hardware one; a driver reset is not an export |
| 8369 | /// at all. So [`EncoderSeat::Auto`] takes `rav1e` here and only |
| 8370 | /// [`EncoderSeat::Hardware`] -- a person picking the GPU for AV1 on the |
| 8371 | /// card, under a row that names the risk -- enters the plugin's seat. It |
| 8372 | /// was an env pin (`VE_HW_AV1=1`) until the card could ask, which is a |
| 8373 | /// switch nobody exporting a film would ever find. |
| 8374 | /// |
| 8375 | /// corner-cut: the upgrade path is a driver this was reproduced against (or a |
| 8376 | /// cros-codecs release that fixes it) plus a probe encode of one frame at |
| 8377 | /// open, after which `Auto` can prefer hardware the way H.264 does. |
| 8378 | fn open_av1( |
| 8379 | meta: &VideoMeta, |
| 8380 | settings: &ExportSettings, |
| 8381 | ten_bit: bool, |
| 8382 | colour: ColorDescription, |
| 8383 | ) -> crate::Result<Self> { |
| 8384 | let bitrate = bitrate_of(meta, settings); |
| 8385 | let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; |
| 8386 | // Two seconds between keyframes, as the H.264 seat does: a seek may only |
| 8387 | // land on one, and this is what a cluster of the Matroska file is. |
| 8388 | let gop = (meta.frame_rate * 2.0).round().max(1.0) as u64; |
| 8389 | // The 10-bit seat is software: the GPU encode is 8-bit only. |
| 8390 | let hw = match ten_bit { |
| 8391 | true => None, |
| 8392 | false => hw_seat(meta, settings)?, |
| 8393 | }; |
| 8394 | if let Some(hw) = hw { |
| 8395 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); } |
| 8396 | return Ok(Self::Av1Hw(hw)); |
| 8397 | } |
| 8398 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software AV1 (rav1e)"); } |
| 8399 | // Seconds per frame, which is what `frame_timing` already has as an |
| 8400 | // exact rational -- 1001/24000 rather than a rounded 23.976. |
| 8401 | let mut cfg = rav1e::EncoderConfig { |
| 8402 | width: meta.width as usize, |
| 8403 | height: meta.height as usize, |
| 8404 | bit_depth: if ten_bit { 10 } else { 8 }, |
| 8405 | chroma_sampling: rav1e::prelude::ChromaSampling::Cs420, |
| 8406 | time_base: rav1e::prelude::Rational::new(u64::from(fps_den), u64::from(fps_num)), |
| 8407 | ..Default::default() |
| 8408 | }; |
| 8409 | cfg.min_key_frame_interval = gop; |
| 8410 | cfg.max_key_frame_interval = gop; |
| 8411 | cfg.bitrate = bitrate.min(i32::MAX as u64) as i32; |
| 8412 | // The fastest preset, with the settings that matter for speed at that |
| 8413 | // preset. Tiles spread one frame over the cores (one tile ran on a single |
| 8414 | // core); low latency drops the lookahead; CDEF and loop restoration are |
| 8415 | // off for speed (a 10 s 1080p export measured the same PSNR against the |
| 8416 | // source either way). Measured: 170 s before, about 17 s after, on a box |
| 8417 | // with load ~15. The `asm` feature in Cargo.toml is the other half. |
| 8418 | cfg.speed_settings = rav1e::prelude::SpeedSettings::from_preset(AV1_SPEED); |
| 8419 | cfg.tiles = AV1_TILES; |
| 8420 | cfg.low_latency = true; |
| 8421 | cfg.speed_settings.cdef = false; |
| 8422 | cfg.speed_settings.lrf = false; |
| 8423 | cfg.speed_settings.multiref = false; |
| 8424 | // What the sequence header says the samples mean, for the reason |
| 8425 | // [`video_signal_type`] gives: a container tag is the second answer a |
| 8426 | // decoder looks at, not the first. Written as rav1e's own enums rather |
| 8427 | // than the H.273 numbers -- the crate has no `from` for the code points, |
| 8428 | // and the output rule only ever picks one of these two spaces. |
| 8429 | let out = colour; |
| 8430 | cfg.pixel_range = rav1e::prelude::PixelRange::Limited; |
| 8431 | cfg.color_description = Some(match out.matrix { |
| 8432 | Matrix::Bt709 => rav1e::prelude::ColorDescription { |
| 8433 | color_primaries: rav1e::prelude::ColorPrimaries::BT709, |
| 8434 | transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT709, |
| 8435 | matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT709, |
| 8436 | }, |
| 8437 | // A 10-bit SDR export of a BT.2020 source: the source's own space. |
| 8438 | Matrix::Bt2020Ncl => rav1e::prelude::ColorDescription { |
| 8439 | color_primaries: rav1e::prelude::ColorPrimaries::BT2020, |
| 8440 | transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT2020_10Bit, |
| 8441 | matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT2020NCL, |
| 8442 | }, |
| 8443 | _ => rav1e::prelude::ColorDescription { |
| 8444 | color_primaries: rav1e::prelude::ColorPrimaries::BT601, |
| 8445 | transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT601, |
| 8446 | matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT601, |
| 8447 | }, |
| 8448 | }); |
| 8449 | let config = rav1e::Config::new() |
| 8450 | .with_encoder_config(cfg) |
| 8451 | .with_threads(std::thread::available_parallelism().map_or(1, |n| n.get())); |
| 8452 | if ten_bit { |
| 8453 | let context = config |
| 8454 | .new_context::<u16>() |
| 8455 | .map_err(|e| format!("software AV1 encoder: {e}"))?; |
| 8456 | return Ok(Self::Av1Sw16 { |
| 8457 | context, |
| 8458 | ready: std::collections::VecDeque::new(), |
| 8459 | au: Vec::new(), |
| 8460 | flushed: false, |
| 8461 | scratch: Default::default(), |
| 8462 | }); |
| 8463 | } |
| 8464 | let context = config |
| 8465 | .new_context::<u8>() |
| 8466 | .map_err(|e| format!("software AV1 encoder: {e}"))?; |
| 8467 | Ok(Self::Av1Sw { |
| 8468 | context, |
| 8469 | ready: std::collections::VecDeque::new(), |
| 8470 | au: Vec::new(), |
| 8471 | flushed: false, |
| 8472 | }) |
| 8473 | } |
| 8474 | |
| 8475 | /// The HEVC pair: the plugin's VA-API seat where the GPU has one, and the |
| 8476 | /// software intra encoder everywhere else -- below the driver's 384x384 |
| 8477 | /// floor, on a plugin too old to carry the symbol, on a GPU with no HEVC |
| 8478 | /// encode entrypoint. Silent either way, because both write the same kind |
| 8479 | /// of file. |
| 8480 | /// |
| 8481 | /// The default is I+P GOPs on the software seat ([`Enc::open_hevc_gop`]). |
| 8482 | /// With [`ExportSettings::intra_only`] it is intra: every picture an IDR, |
| 8483 | /// on the hardware seat where there is one and on the lanes below where |
| 8484 | /// there is not -- an intraframe master in the shape of ProRes or DNxHD, |
| 8485 | /// large files, every frame a cut point. |
| 8486 | /// |
| 8487 | /// The picture is coded at its own size and padded to whole minimum coding |
| 8488 | /// blocks *by the encoder*, which crops the padding back off with the SPS |
| 8489 | /// conformance window, so 1920x1080 is a legal export rather than a |
| 8490 | /// refusal. |
| 8491 | fn open_hevc( |
| 8492 | meta: &VideoMeta, |
| 8493 | settings: &ExportSettings, |
| 8494 | ten_bit: bool, |
| 8495 | colour: ColorDescription, |
| 8496 | ) -> crate::Result<Self> { |
| 8497 | // The muxers time by it and the mp4 one wants an exact rational: asked |
| 8498 | // here so an impossible rate fails before a frame is coded. The same |
| 8499 | // rational goes into the SPS's VUI, whose timing is also where the |
| 8500 | // encoder picks the level from. |
| 8501 | let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; |
| 8502 | // 4:2:0 addresses its conformance window in *chroma* samples, so an odd |
| 8503 | // picture cannot be cropped back to itself -- and an odd dimension has |
| 8504 | // no chroma plane of its own to begin with. Named rather than padded to |
| 8505 | // something a decoder would then show a column of. |
| 8506 | if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) { |
| 8507 | return Err(format!( |
| 8508 | "{}x{} cannot be written as HEVC: 4:2:0 needs even dimensions", |
| 8509 | meta.width, meta.height |
| 8510 | ) |
| 8511 | .into()); |
| 8512 | } |
| 8513 | // The GPU seat is 8-bit only, so a 10-bit export is software. |
| 8514 | let hw = match ten_bit { |
| 8515 | true => None, |
| 8516 | false => hw_seat(meta, settings)?, |
| 8517 | }; |
| 8518 | if let Some(hw) = hw { |
| 8519 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware HEVC intra (VA-API plugin)"); } |
| 8520 | return Ok(Self::HevcHw(hw)); |
| 8521 | } |
| 8522 | if !settings.intra_only { |
| 8523 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC I+P (ec-h265)"); } |
| 8524 | return Self::open_hevc_gop(meta, settings, (fps_num, fps_den), ten_bit, colour); |
| 8525 | } |
| 8526 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC intra (ec-h265)"); } |
| 8527 | // The cores are split between the lanes and the wavefront inside one: |
| 8528 | // twelve lanes of one worker each on this box's twelve threads, |
| 8529 | // fewer lanes on a smaller machine with a wider wavefront each. |
| 8530 | let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); |
| 8531 | let lane_count = cores.clamp(1, HEVC_LANES); |
| 8532 | let per_lane = cores.div_ceil(lane_count); |
| 8533 | let mut lanes = Vec::with_capacity(lane_count); |
| 8534 | for _ in 0..lane_count { |
| 8535 | let mut cfg = HevcEncoderConfig::new(meta.width, meta.height); |
| 8536 | cfg.bit_depth = if ten_bit { 10 } else { 8 }; |
| 8537 | // The bitrate row a user picked, mapped through the same measured |
| 8538 | // anchor as before ([`hevc_qp`]) and held: a *quality* dial, not a |
| 8539 | // rate controller. The encoder's own per-picture target-bits mode |
| 8540 | // would chase the number with a correction pass -- named headroom, |
| 8541 | // not behaviour this seat takes silently. |
| 8542 | cfg.rate_control = RateControl::ConstantQp(hevc_qp(meta, settings)); |
| 8543 | cfg.timing = Some((fps_den, fps_num)); |
| 8544 | cfg.video_signal_type = Some(video_signal_type(colour)); |
| 8545 | apply_hdr(&mut cfg, settings); |
| 8546 | cfg.speed = settings.hevc_speed.unwrap_or_default().preset(); |
| 8547 | cfg.threads = per_lane; |
| 8548 | lanes.push(HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?); |
| 8549 | } |
| 8550 | Ok(Self::Hevc(HevcEnc { |
| 8551 | pending: Vec::new(), |
| 8552 | ready: std::collections::VecDeque::new(), |
| 8553 | au: Vec::new(), |
| 8554 | lanes, |
| 8555 | width: meta.width as usize, |
| 8556 | ten_bit, |
| 8557 | })) |
| 8558 | } |
| 8559 | |
| 8560 | /// The ProRes seat: the profile's encoder at the picture's size, tagged with |
| 8561 | /// the colour the file declares. Progressive, no alpha. |
| 8562 | fn open_prores(meta: &VideoMeta, settings: &ExportSettings, colour: ColorDescription) -> crate::Result<Self> { |
| 8563 | if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) { |
| 8564 | return Err(format!( |
| 8565 | "{}x{} cannot be written as ProRes from a 4:2:0 picture: it needs even dimensions", |
| 8566 | meta.width, meta.height |
| 8567 | ) |
| 8568 | .into()); |
| 8569 | } |
| 8570 | let profile = settings.prores_profile; |
| 8571 | let mut cfg = ec_prores::EncoderConfig::new(profile.codec(), meta.width, meta.height); |
| 8572 | let (primaries, transfer, matrix) = colour.codes(); |
| 8573 | cfg.color = ec_core::frame::ColorInfo { |
| 8574 | primaries: primaries as u8, |
| 8575 | transfer: transfer as u8, |
| 8576 | matrix: matrix as u8, |
| 8577 | full_range: false, |
| 8578 | }; |
| 8579 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software ProRes (ec-prores)"); } |
| 8580 | let encoder = ec_prores::ProResEncoder::new(cfg).map_err(|e| format!("ProRes encoder: {e}"))?; |
| 8581 | Ok(Self::ProRes { encoder, au: Vec::new(), full_chroma: profile.is_444() }) |
| 8582 | } |
| 8583 | |
| 8584 | /// One 10-bit picture of 16-bit planes, at 10-bit scale, in and at most one |
| 8585 | /// access unit out. Asked only of the 10-bit seat, which [`wide_ten_bit`] opens |
| 8586 | /// with the same answer the export loop checks. |
| 8587 | fn encode_wide( |
| 8588 | &mut self, |
| 8589 | y: &[u16], |
| 8590 | u: &[u16], |
| 8591 | v: &[u16], |
| 8592 | width: u32, |
| 8593 | height: u32, |
| 8594 | ) -> crate::Result<Option<(&[u8], bool)>> { |
| 8595 | match self { |
| 8596 | Self::Av1Sw16 { context, ready, au, .. } => { |
| 8597 | submit_av1_16(context, ready, au, [y, u, v], width, height) |
| 8598 | } |
| 8599 | Self::HevcGop(gop) if gop.ten_bit => { |
| 8600 | gop.push_wide(y, u, v, width, height)?; |
| 8601 | Ok(pop_gop(gop)) |
| 8602 | } |
| 8603 | Self::ProRes { encoder, au, full_chroma } => { |
| 8604 | let frame = |
| 8605 | crate::prores_out::upsampled_frame(y, u, v, width as usize, height as usize, *full_chroma)?; |
| 8606 | *au = encoder.encode(&frame).map_err(|e| format!("ProRes encode: {e}"))?; |
| 8607 | Ok(Some((&au[..], true))) |
| 8608 | } |
| 8609 | Self::Hevc(hevc) if hevc.ten_bit => { |
| 8610 | hevc.pending.push((le_bytes(y), le_bytes(u), le_bytes(v))); |
| 8611 | if hevc.pending.len() >= hevc.lanes.len() { |
| 8612 | hevc.code_batch()?; |
| 8613 | } |
| 8614 | Ok(pop_hevc(hevc)) |
| 8615 | } |
| 8616 | _ => Err("a 10-bit picture needs a 10-bit seat".into()), |
| 8617 | } |
| 8618 | } |
| 8619 | |
| 8620 | /// Whether this is a software HEVC seat coding at 10 bits. |
| 8621 | fn hevc_ten_bit(&self) -> bool { |
| 8622 | match self { |
| 8623 | Self::HevcGop(gop) => gop.ten_bit, |
| 8624 | Self::Hevc(hevc) => hevc.ten_bit, |
| 8625 | _ => false, |
| 8626 | } |
| 8627 | } |
| 8628 | |
| 8629 | /// One picture in, at most one access unit out, and whether that unit is one |
| 8630 | /// a decoder may be started from -- which only the Matroska muxer asks, the |
| 8631 | /// mp4 one reading its own sync flag off the IDR slice. |
| 8632 | /// |
| 8633 | /// The H.264 seat keeps the contract structurally: `ec-h264` buffers |
| 8634 | /// nothing -- no lookahead, and B pictures coded as none -- so one call is |
| 8635 | /// one access unit by construction. The HEVC seat's lanes hold a small |
| 8636 | /// batch of pictures until there is a lane for each, so it says "at most |
| 8637 | /// one" and means it; the old H.264 seat only kept the contract because |
| 8638 | /// its GOP-buffering lookahead needed a zero bitrate and this path was |
| 8639 | /// always CBR. |
| 8640 | fn encode( |
| 8641 | &mut self, |
| 8642 | y: &[u8], |
| 8643 | u: &[u8], |
| 8644 | v: &[u8], |
| 8645 | width: u32, |
| 8646 | height: u32, |
| 8647 | intra: bool, |
| 8648 | ) -> crate::Result<Option<(&[u8], bool)>> { |
| 8649 | // A composed 8-bit picture on the 10-bit HEVC seat: shifted up to the |
| 8650 | // seat's scale, the same shift the AV1 10-bit seat makes. |
| 8651 | if self.hevc_ten_bit() { |
| 8652 | let up = |p: &[u8]| p.iter().map(|&v| u16::from(v) << 2 | u16::from(v) >> 6).collect::<Vec<u16>>(); |
| 8653 | let (y, u, v) = (up(y), up(u), up(v)); |
| 8654 | return self.encode_wide(&y, &u, &v, width, height); |
| 8655 | } |
| 8656 | if let Self::ProRes { encoder, au, full_chroma } = self { |
| 8657 | // A composed 8-bit picture: widened to 10 bits and upsampled in one pass. |
| 8658 | let frame = |
| 8659 | crate::prores_out::upsampled_frame_8(y, u, v, width as usize, height as usize, *full_chroma)?; |
| 8660 | *au = encoder.encode(&frame).map_err(|e| format!("ProRes encode: {e}"))?; |
| 8661 | return Ok(Some((&au[..], true))); |
| 8662 | } |
| 8663 | match self { |
| 8664 | Self::Av1Hw(hw) => { |
| 8665 | let au = hw.encode(y, u, v, width, height, false)?; |
| 8666 | // What the *bitstream* says, not what was asked for: an AV1 |
| 8667 | // keyframe carries the sequence header, which is the same mark |
| 8668 | // `demux` reads a sync point off. A driver that emitted one |
| 8669 | // unasked is then still a seek target, and one that skipped a |
| 8670 | // requested keyframe cannot be mistaken for a decoder's start. |
| 8671 | Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some()))) |
| 8672 | } |
| 8673 | Self::Av1Sw16 { |
| 8674 | context, |
| 8675 | ready, |
| 8676 | au, |
| 8677 | scratch, |
| 8678 | .. |
| 8679 | } => { |
| 8680 | // An 8-bit picture on the 10-bit seat: each sample scaled up to |
| 8681 | // the same range (255 maps to 1023, not 1020). |
| 8682 | let (w, h) = (width as usize, height as usize); |
| 8683 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 8684 | for (dst, (src, n)) in scratch.iter_mut().zip([(y, w * h), (u, cw * ch), (v, cw * ch)]) { |
| 8685 | dst.clear(); |
| 8686 | dst.extend(src[..n].iter().map(|&s| { |
| 8687 | let s = u16::from(s); |
| 8688 | (s << 2) | (s >> 6) |
| 8689 | })); |
| 8690 | } |
| 8691 | let [sy, su, sv] = &*scratch; |
| 8692 | submit_av1_16(context, ready, au, [&sy[..], &su[..], &sv[..]], width, height) |
| 8693 | } |
| 8694 | Self::Av1Sw { |
| 8695 | context, ready, au, .. |
| 8696 | } => { |
| 8697 | let mut frame = context.new_frame(); |
| 8698 | let (w, h) = (width as usize, height as usize); |
| 8699 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 8700 | frame.planes[0].copy_from_raw_u8(&y[..w * h], w, 1); |
| 8701 | frame.planes[1].copy_from_raw_u8(&u[..cw * ch], cw, 1); |
| 8702 | frame.planes[2].copy_from_raw_u8(&v[..cw * ch], cw, 1); |
| 8703 | if let Err(e) = context.send_frame(frame) { |
| 8704 | return Err(format!("software AV1 encode: {e}").into()); |
| 8705 | } |
| 8706 | collect_av1(context, ready)?; |
| 8707 | Ok(pop_av1(ready, au)) |
| 8708 | } |
| 8709 | // Every unit this seat hands back is an IDR carrying its own |
| 8710 | // parameter sets (the plugin codes HEVC intra-only), so every one of |
| 8711 | // them is a sync point -- said as a constant rather than parsed back |
| 8712 | // out of the bitstream, because it is this encoder's configuration |
| 8713 | // and not a driver's choice. |
| 8714 | Self::HevcHw(hw) => Ok(hw |
| 8715 | .encode(y, u, v, width, height, true)? |
| 8716 | .map(|au| (au, true))), |
| 8717 | Self::Hevc(hevc) => { |
| 8718 | // The display-size planes are kept as they came: `ec-h265` |
| 8719 | // pads to its own coded grid and crops back through the SPS |
| 8720 | // conformance window. |
| 8721 | hevc.pending.push((y.to_vec(), u.to_vec(), v.to_vec())); |
| 8722 | if hevc.pending.len() >= hevc.lanes.len() { |
| 8723 | hevc.code_batch()?; |
| 8724 | } |
| 8725 | // Every intra AU is an IDR, so every one of them is a key |
| 8726 | // frame -- which is what an intraframe master means. |
| 8727 | Ok(pop_hevc(hevc)) |
| 8728 | } |
| 8729 | Self::HevcGop(gop) => { |
| 8730 | gop.push(y, u, v, width, height)?; |
| 8731 | Ok(pop_gop(gop)) |
| 8732 | } |
| 8733 | // A key frame is asked for on every picture where the file is an |
| 8734 | // intraframe one, and the flag says what was asked: the mp4 muxer |
| 8735 | // reads its own sync marks off the IDR slices either way, so this |
| 8736 | // is what a Matroska one would be told. |
| 8737 | Self::Hw(hw) => Ok(hw |
| 8738 | .encode(y, u, v, width, height, intra)? |
| 8739 | .map(|au| (au, intra))), |
| 8740 | Self::ProRes { .. } => unreachable!("the ProRes seat is handled before this match"), |
| 8741 | Self::Sw { encoder, au } => { |
| 8742 | // The key flag is what the bitstream says -- an IDR where the |
| 8743 | // GOP asked for one, every picture on an intraframe export -- |
| 8744 | // which is what the hardware seat's `intra` carries too. The |
| 8745 | // planes go in as borrows; the old seat was handed a copy. |
| 8746 | let view = PictureView::i420(width, height, y, u, v); |
| 8747 | let coded = encoder |
| 8748 | .encode(&view) |
| 8749 | .map_err(|e| format!("software encode: {e}"))?; |
| 8750 | *au = coded.au; |
| 8751 | Ok(Some((&au[..], coded.key_frame)).filter(|(au, _)| !au.is_empty())) |
| 8752 | } |
| 8753 | } |
| 8754 | } |
| 8755 | |
| 8756 | /// What a decoded buffer must look like to reach this seat without ever |
| 8757 | /// being read back -- `None` for every seat that reads bytes, which is both |
| 8758 | /// software encoders and the intra HEVC one. |
| 8759 | /// |
| 8760 | /// The AV1 hardware seat is left out on purpose: it is entered only when a |
| 8761 | /// person picks it by name because the vendored encoder reset this project's GPU |
| 8762 | /// ([`Enc::open_av1`]), and a path that cannot be measured is not one to |
| 8763 | /// widen. |
| 8764 | /// `&mut` because an isolated seat has to *ask* the process it lives in |
| 8765 | /// ([`crate::hwproc`]), which is a round trip on its socket. |
| 8766 | fn dma_want(&mut self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> { |
| 8767 | match self { |
| 8768 | Self::Hw(hw) | Self::HevcHw(hw) => hw.dma_want(meta.width, meta.height), |
| 8769 | _ => None, |
| 8770 | } |
| 8771 | } |
| 8772 | |
| 8773 | /// One picture the decoder left on the GPU in, at most one access unit out. |
| 8774 | /// Same answer as [`Enc::encode`], including which units a decoder may be |
| 8775 | /// started from, because it is the same encoder -- only the picture took |
| 8776 | /// another way in. |
| 8777 | /// |
| 8778 | /// `intra` therefore carries here too, and not for symmetry's sake: a proxy |
| 8779 | /// of a file already small enough is coded at that file's own size |
| 8780 | /// ([`crate::proxy::size_for`]), which is the one case where an intraframe |
| 8781 | /// export's decoder and encoder agree on a surface and the buffer goes |
| 8782 | /// straight across. An access unit marked as no sync point there would give |
| 8783 | /// a stand-in whose whole reason to exist is that every frame is one. |
| 8784 | fn encode_dma(&mut self, dma: &DmaFrame, intra: bool) -> crate::Result<Option<(&[u8], bool)>> { |
| 8785 | match self { |
| 8786 | Self::Hw(hw) => Ok(hw.encode_dma(dma, intra)?.map(|au| (au, intra))), |
| 8787 | // Every picture an IDR here, exactly as in [`Enc::encode`]. |
| 8788 | Self::HevcHw(hw) => Ok(hw.encode_dma(dma, true)?.map(|au| (au, true))), |
| 8789 | // Unreachable through [`Enc::dma_want`], which is the only thing |
| 8790 | // that puts a span's decoder on this path. |
| 8791 | _ => Err("this encoder takes pictures as bytes, not as buffers".into()), |
| 8792 | } |
| 8793 | } |
| 8794 | |
| 8795 | /// End of stream; call until it returns `None`. |
| 8796 | fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> { |
| 8797 | match self { |
| 8798 | Self::Av1Hw(hw) => { |
| 8799 | let au = hw.drain()?; |
| 8800 | Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some()))) |
| 8801 | } |
| 8802 | Self::Av1Sw16 { |
| 8803 | context, |
| 8804 | ready, |
| 8805 | au, |
| 8806 | flushed, |
| 8807 | .. |
| 8808 | } => { |
| 8809 | if !*flushed { |
| 8810 | *flushed = true; |
| 8811 | context.flush(); |
| 8812 | collect_av1(context, ready)?; |
| 8813 | } |
| 8814 | Ok(pop_av1(ready, au)) |
| 8815 | } |
| 8816 | Self::Av1Sw { |
| 8817 | context, |
| 8818 | ready, |
| 8819 | au, |
| 8820 | flushed, |
| 8821 | } => { |
| 8822 | if !*flushed { |
| 8823 | *flushed = true; |
| 8824 | context.flush(); |
| 8825 | collect_av1(context, ready)?; |
| 8826 | } |
| 8827 | Ok(pop_av1(ready, au)) |
| 8828 | } |
| 8829 | Self::HevcHw(hw) => Ok(hw.drain()?.map(|au| (au, true))), |
| 8830 | // The tail batch: fewer frames than lanes, coded on as many |
| 8831 | // encoders as there are frames left. |
| 8832 | Self::Hevc(hevc) => { |
| 8833 | if !hevc.pending.is_empty() { |
| 8834 | hevc.code_batch()?; |
| 8835 | } |
| 8836 | Ok(pop_hevc(hevc)) |
| 8837 | } |
| 8838 | Self::HevcGop(gop) => { |
| 8839 | gop.finish()?; |
| 8840 | Ok(pop_gop(gop)) |
| 8841 | } |
| 8842 | Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))), |
| 8843 | // Nothing is held back: every picture `encode` took already came |
| 8844 | // back with its access unit, so end of stream is the empty answer. |
| 8845 | Self::Sw { .. } | Self::ProRes { .. } => Ok(None), |
| 8846 | } |
| 8847 | } |
| 8848 | } |
| 8849 | |
| 8850 | impl HevcEnc { |
| 8851 | /// The whole pending batch, one frame per lane, collected back in the |
| 8852 | /// order it went out -- `std::thread::scope`, because the encode borrows |
| 8853 | /// the planes and the lanes rather than copying them again. A panic inside |
| 8854 | /// a lane comes back as an error rather than unwinding the export thread. |
| 8855 | fn code_batch(&mut self) -> crate::Result<()> { |
| 8856 | let width = self.width; |
| 8857 | let chroma = width / 2; |
| 8858 | let pending = std::mem::take(&mut self.pending); |
| 8859 | let ten_bit = self.ten_bit; |
| 8860 | let coded: Vec<crate::Result<Vec<u8>>> = std::thread::scope(|scope| { |
| 8861 | let lanes: Vec<_> = self |
| 8862 | .lanes |
| 8863 | .iter() |
| 8864 | .zip(pending.iter()) |
| 8865 | .map(|(encoder, (y, cb, cr))| { |
| 8866 | scope.spawn(move || { |
| 8867 | let coded = if ten_bit { |
| 8868 | let samples = |p: &[u8]| -> Vec<u16> { |
| 8869 | p.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect() |
| 8870 | }; |
| 8871 | let (y, cb, cr) = (samples(y), samples(cb), samples(cr)); |
| 8872 | encoder.encode_idr_samples(&y, width, &cb, chroma, &cr, chroma) |
| 8873 | } else { |
| 8874 | encoder.encode_idr_planes(y, width, cb, chroma, cr, chroma) |
| 8875 | }; |
| 8876 | coded |
| 8877 | .map(|coded| coded.au) |
| 8878 | .map_err(|e| crate::Error::from(format!("software HEVC encode: {e}"))) |
| 8879 | }) |
| 8880 | }) |
| 8881 | .collect(); |
| 8882 | lanes |
| 8883 | .into_iter() |
| 8884 | .map(|lane| { |
| 8885 | lane.join() |
| 8886 | .unwrap_or_else(|_| Err("an HEVC encode lane panicked".into())) |
| 8887 | }) |
| 8888 | .collect() |
| 8889 | }); |
| 8890 | for au in coded { |
| 8891 | self.ready.push_back(au?); |
| 8892 | } |
| 8893 | Ok(()) |
| 8894 | } |
| 8895 | } |
| 8896 | |
| 8897 | /// The oldest coded intra AU, lent out under the same "valid until the next |
| 8898 | /// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key |
| 8899 | /// flag is not a guess. |
| 8900 | fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> { |
| 8901 | hevc.au = hevc.ready.pop_front()?; |
| 8902 | Some((&hevc.au[..], true)) |
| 8903 | } |
| 8904 | |
| 8905 | /// The longest GOP the HEVC seat asks for, in pictures. `ec-h265` codes GOPs |
| 8906 | /// concurrently only up to this length, and the sequence coder's own limit is |
| 8907 | /// 256; a 60 fps export is 60 pictures and a faster one takes the serial path. |
| 8908 | const HEVC_GOP_MAX_KEYINT: usize = 64; |
| 8909 | |
| 8910 | impl Enc { |
| 8911 | /// The HEVC I+P seat: `ec-h265`'s sequence coder, an IDR once a second at |
| 8912 | /// the picture's own rate with P pictures between, on a worker thread. |
| 8913 | /// |
| 8914 | /// The export walk pushes one picture at a time and the encoder pulls its |
| 8915 | /// frames from an iterator, so the two meet on a bounded channel: the walk |
| 8916 | /// is never more than one GOP ahead of the worker. The encoder codes whole |
| 8917 | /// GOPs concurrently on [`default_threads`](ec_h265::encoder::default_threads) |
| 8918 | /// workers, which is at most six, and hands the pictures back in order. |
| 8919 | /// |
| 8920 | /// Rate: an explicit bitrate row goes to bitrate control at that rate, the |
| 8921 | /// same number the H.264 seat codes at. No bitrate is the automatic quality |
| 8922 | /// row, constant QP at [`HEVC_GOP_QP`]: a quality default of its own, not |
| 8923 | /// the intra seat's [`hevc_qp`], whose anchor is measured on intra pictures. |
| 8924 | fn open_hevc_gop( |
| 8925 | meta: &VideoMeta, |
| 8926 | settings: &ExportSettings, |
| 8927 | (fps_num, fps_den): (u32, u32), |
| 8928 | ten_bit: bool, |
| 8929 | colour: ColorDescription, |
| 8930 | ) -> crate::Result<Self> { |
| 8931 | let keyint = hevc_gop_keyint(meta.frame_rate); |
| 8932 | let mut cfg = HevcEncoderConfig::new(meta.width, meta.height); |
| 8933 | cfg.bit_depth = if ten_bit { 10 } else { 8 }; |
| 8934 | cfg.rate_control = match settings.bitrate { |
| 8935 | Some(_) => RateControl::Bitrate { |
| 8936 | kbps: (bitrate_of(meta, settings) / 1000).max(1) as u32, |
| 8937 | fps: meta.frame_rate, |
| 8938 | }, |
| 8939 | None => RateControl::ConstantQp(HEVC_GOP_QP), |
| 8940 | }; |
| 8941 | cfg.keyint = keyint; |
| 8942 | cfg.threads = ec_h265::encoder::default_threads(); |
| 8943 | cfg.timing = Some((fps_den, fps_num)); |
| 8944 | cfg.video_signal_type = Some(video_signal_type(colour)); |
| 8945 | apply_hdr(&mut cfg, settings); |
| 8946 | cfg.speed = settings.hevc_speed.unwrap_or_default().preset(); |
| 8947 | let encoder = HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?; |
| 8948 | let (frames_tx, frames_rx) = sync_channel::<VideoFrame>(keyint); |
| 8949 | let (au_tx, coded) = std::sync::mpsc::channel::<(Vec<u8>, bool)>(); |
| 8950 | // The P pictures refer to a second picture parameter set, which the |
| 8951 | // samples do not keep: the first unit carries it, so the record the |
| 8952 | // container builds from that unit holds it. |
| 8953 | let p_pps = encoder.p_picture_parameter_set(); |
| 8954 | let worker = thread::Builder::new() |
| 8955 | .name("ec-h265-gop".into()) |
| 8956 | .spawn(move || { |
| 8957 | let mut picture = 0usize; |
| 8958 | encoder |
| 8959 | .encode_sequence_with(frames_rx, |pic| { |
| 8960 | // Every GOP opens on an IDR, so a picture's key flag is |
| 8961 | // its place in the sequence. |
| 8962 | let key = picture.is_multiple_of(keyint); |
| 8963 | let au = if picture == 0 { |
| 8964 | with_parameter_set(pic.au, &p_pps) |
| 8965 | } else { |
| 8966 | pic.au |
| 8967 | }; |
| 8968 | picture += 1; |
| 8969 | // A closed receiver is an export dropped part way: the |
| 8970 | // rest is unwanted, and draining it is not an error. |
| 8971 | let _ = au_tx.send((au, key)); |
| 8972 | Ok(()) |
| 8973 | }) |
| 8974 | .map_err(|e| e.to_string()) |
| 8975 | }) |
| 8976 | .map_err(|e| format!("HEVC software encoder: {e}"))?; |
| 8977 | Ok(Self::HevcGop(HevcGop { |
| 8978 | frames: Some(frames_tx), |
| 8979 | worker: Some(worker), |
| 8980 | coded, |
| 8981 | ready: std::collections::VecDeque::new(), |
| 8982 | au: Vec::new(), |
| 8983 | ten_bit, |
| 8984 | })) |
| 8985 | } |
| 8986 | } |
| 8987 | |
| 8988 | /// The GOP the I+P seat codes at this frame rate: an IDR about a second apart. |
| 8989 | fn hevc_gop_keyint(frame_rate: f64) -> usize { |
| 8990 | (frame_rate.round() as usize).clamp(2, HEVC_GOP_MAX_KEYINT) |
| 8991 | } |
| 8992 | |
| 8993 | /// What an HEVC export codes as, in the words an export start names: the I+P |
| 8994 | /// GOP and its key interval and rate, or `intra-only`. `None` for any other |
| 8995 | /// format. The rate is the bitrate the file aims at, or, with no bitrate given, |
| 8996 | /// the quality mode the automatic row codes at: constant QP ([`HEVC_GOP_QP`]), named |
| 8997 | /// with its number and with how to ask for a fixed rate instead. |
| 8998 | pub fn hevc_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<String> { |
| 8999 | if !settings.format.is_hevc() { |
| 9000 | return None; |
| 9001 | } |
| 9002 | if settings.intra_only { |
| 9003 | return Some(match settings.bitrate { |
| 9004 | Some(_) => "intra-only".to_string(), |
| 9005 | None => format!( |
| 9006 | "intra-only, constant quality QP {} on the software seat (the GPU seat codes at the automatic rate); pass bitrate_kbps for a fixed rate", |
| 9007 | hevc_qp(meta, settings) |
| 9008 | ), |
| 9009 | }); |
| 9010 | } |
| 9011 | let seconds = hevc_gop_keyint(meta.frame_rate) as f64 / meta.frame_rate; |
| 9012 | let every = if (seconds - seconds.round()).abs() < 1e-6 { |
| 9013 | format!("{} s", seconds.round() as u64) |
| 9014 | } else { |
| 9015 | format!("{seconds:.2} s") |
| 9016 | }; |
| 9017 | let rate = match settings.bitrate { |
| 9018 | Some(_) => rate_words(bitrate_of(meta, settings) / 1000), |
| 9019 | None => format!("constant quality QP {HEVC_GOP_QP}; pass bitrate_kbps for a fixed rate"), |
| 9020 | }; |
| 9021 | Some(format!("I+P GOP ({every} keyframes), {rate}")) |
| 9022 | } |
| 9023 | |
| 9024 | /// What an AV1 export codes as, in the words an export start names. AV1 is always |
| 9025 | /// coded at a bitrate, so with none given the automatic target is named as one |
| 9026 | /// (chosen from the picture size and frame rate). `None` for any other format. |
| 9027 | pub fn av1_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<String> { |
| 9028 | if !settings.format.is_av1() { |
| 9029 | return None; |
| 9030 | } |
| 9031 | let rate = rate_words(bitrate_of(meta, settings) / 1000); |
| 9032 | Some(match settings.bitrate { |
| 9033 | Some(_) => format!("average bitrate {rate}"), |
| 9034 | None => format!("average bitrate {rate} chosen from the picture size and frame rate; pass bitrate_kbps for a fixed rate"), |
| 9035 | }) |
| 9036 | } |
| 9037 | |
| 9038 | /// A rate in kilobits a second, in the words a reply uses: `4 Mb/s` on a whole megabit, `6.2 Mb/s` |
| 9039 | /// above one, else `850 kb/s`. |
| 9040 | fn rate_words(kbps: u64) -> String { |
| 9041 | if kbps.is_multiple_of(1000) { |
| 9042 | format!("{} Mb/s", kbps / 1000) |
| 9043 | } else if kbps >= 1000 { |
| 9044 | format!("{:.1} Mb/s", kbps as f64 / 1000.0) |
| 9045 | } else { |
| 9046 | format!("{kbps} kb/s") |
| 9047 | } |
| 9048 | } |
| 9049 | |
| 9050 | /// The words an export start names when the source's chroma is reduced to 4:2:0 on |
| 9051 | /// the way out, e.g. `VP9 4:4:4 source: chroma reduced to 4:2:0 for export`. `codec` |
| 9052 | /// and `chroma` are the source's; the chroma is read off the stream |
| 9053 | /// ([`Demuxer::chroma`]). `None` where nothing is reduced: a 4:2:0 or grey source, |
| 9054 | /// or a sound-only format, which has no picture to reduce. |
| 9055 | pub fn chroma_reduction_words(codec: Codec, chroma: Chroma, settings: &ExportSettings) -> Option<String> { |
| 9056 | let format = match chroma { |
| 9057 | Chroma::C422 => "4:2:2", |
| 9058 | Chroma::C444 => "4:4:4", |
| 9059 | _ => return None, |
| 9060 | }; |
| 9061 | if !settings.format.has_video() { |
| 9062 | return None; |
| 9063 | } |
| 9064 | Some(format!("{} {format} source: chroma reduced to 4:2:0 for export", codec.name())) |
| 9065 | } |
| 9066 | |
| 9067 | /// The I+P seat's state: the worker running the sequence coder, the channel |
| 9068 | /// the frames go to it on, and the access units it has handed back. |
| 9069 | struct HevcGop { |
| 9070 | /// The frames for the worker, in display order. `None` once the sequence |
| 9071 | /// has ended, which is what lets the worker finish its last GOP. |
| 9072 | frames: Option<SyncSender<VideoFrame>>, |
| 9073 | worker: Option<thread::JoinHandle<Result<(), String>>>, |
| 9074 | /// Access units and their key flags, in coding order, which is display order. |
| 9075 | coded: Receiver<(Vec<u8>, bool)>, |
| 9076 | /// Units collected from `coded` and not yet handed to the caller. |
| 9077 | ready: std::collections::VecDeque<(Vec<u8>, bool)>, |
| 9078 | /// The unit currently lent out, for the reason `Sw` owns one. |
| 9079 | au: Vec<u8>, |
| 9080 | /// Whether the sequence codes at 10 bits: its frames are I010 then. |
| 9081 | ten_bit: bool, |
| 9082 | } |
| 9083 | |
| 9084 | impl HevcGop { |
| 9085 | fn push(&mut self, y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> crate::Result<()> { |
| 9086 | let frame = i420_frame(y, u, v, width, height)?; |
| 9087 | self.send(frame) |
| 9088 | } |
| 9089 | |
| 9090 | /// One 10-bit picture of 16-bit samples, as the I010 frame the 10-bit sequence takes. |
| 9091 | fn push_wide(&mut self, y: &[u16], u: &[u16], v: &[u16], width: u32, height: u32) -> crate::Result<()> { |
| 9092 | let frame = i010_frame(y, u, v, width, height)?; |
| 9093 | self.send(frame) |
| 9094 | } |
| 9095 | |
| 9096 | fn send(&mut self, frame: VideoFrame) -> crate::Result<()> { |
| 9097 | if self |
| 9098 | .frames |
| 9099 | .as_ref() |
| 9100 | .is_some_and(|tx| tx.send(frame).is_ok()) |
| 9101 | { |
| 9102 | self.collect(); |
| 9103 | return Ok(()); |
| 9104 | } |
| 9105 | // The worker has stopped on its own: its error is the answer. |
| 9106 | self.finish()?; |
| 9107 | Err("the HEVC encoder stopped before the export ended".into()) |
| 9108 | } |
| 9109 | |
| 9110 | /// Ends the sequence and waits for the worker's last GOP. |
| 9111 | fn finish(&mut self) -> crate::Result<()> { |
| 9112 | self.frames = None; |
| 9113 | if let Some(worker) = self.worker.take() { |
| 9114 | match worker.join() { |
| 9115 | Ok(Ok(())) => {} |
| 9116 | Ok(Err(e)) => return Err(format!("software HEVC encode: {e}").into()), |
| 9117 | Err(_) => return Err("the HEVC encoder thread panicked".into()), |
| 9118 | } |
| 9119 | } |
| 9120 | self.collect(); |
| 9121 | Ok(()) |
| 9122 | } |
| 9123 | |
| 9124 | fn collect(&mut self) { |
| 9125 | while let Ok(unit) = self.coded.try_recv() { |
| 9126 | self.ready.push_back(unit); |
| 9127 | } |
| 9128 | } |
| 9129 | } |
| 9130 | |
| 9131 | /// One I420 picture at the display size, as the sequence coder takes it. |
| 9132 | fn i420_frame(y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> crate::Result<VideoFrame> { |
| 9133 | let (w, h) = (width as usize, height as usize); |
| 9134 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 9135 | let planes = vec![ |
| 9136 | ec_core::frame::Plane::new(y[..w * h].to_vec(), w), |
| 9137 | ec_core::frame::Plane::new(u[..cw * ch].to_vec(), cw), |
| 9138 | ec_core::frame::Plane::new(v[..cw * ch].to_vec(), cw), |
| 9139 | ]; |
| 9140 | VideoFrame::try_new(ec_core::frame::PixelFormat::I420, width, height, planes) |
| 9141 | .map_err(|e| format!("HEVC frame: {e}").into()) |
| 9142 | } |
| 9143 | |
| 9144 | /// One 10-bit I010 picture at the display size: 16-bit little-endian samples, the |
| 9145 | /// stride in bytes, as the sequence coder takes it. |
| 9146 | fn i010_frame(y: &[u16], u: &[u16], v: &[u16], width: u32, height: u32) -> crate::Result<VideoFrame> { |
| 9147 | let (w, h) = (width as usize, height as usize); |
| 9148 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 9149 | let planes = vec![ |
| 9150 | ec_core::frame::Plane::new(le_bytes(&y[..w * h]), w * 2), |
| 9151 | ec_core::frame::Plane::new(le_bytes(&u[..cw * ch]), cw * 2), |
| 9152 | ec_core::frame::Plane::new(le_bytes(&v[..cw * ch]), cw * 2), |
| 9153 | ]; |
| 9154 | VideoFrame::try_new(ec_core::frame::PixelFormat::I010, width, height, planes) |
| 9155 | .map_err(|e| format!("HEVC frame: {e}").into()) |
| 9156 | } |
| 9157 | |
| 9158 | /// Little-endian bytes of 16-bit samples. |
| 9159 | fn le_bytes(samples: &[u16]) -> Vec<u8> { |
| 9160 | samples.iter().flat_map(|s| s.to_le_bytes()).collect() |
| 9161 | } |
| 9162 | |
| 9163 | /// `au` with `nal` (one Annex-B unit) placed before its first coded slice, so |
| 9164 | /// after the parameter sets that open the unit. `au` comes back as it went in |
| 9165 | /// where it has no slice. |
| 9166 | fn with_parameter_set(au: Vec<u8>, nal: &[u8]) -> Vec<u8> { |
| 9167 | let starts = (0..au.len().saturating_sub(3)).filter(|&i| au[i..i + 3] == [0, 0, 1]); |
| 9168 | for start in starts { |
| 9169 | // The NAL unit type is the six bits after the forbidden bit. |
| 9170 | if (au[start + 3] >> 1) & 0x3F < 32 { |
| 9171 | // A four-byte start code keeps its leading zero in front of the new unit. |
| 9172 | let at = if start > 0 && au[start - 1] == 0 { |
| 9173 | start - 1 |
| 9174 | } else { |
| 9175 | start |
| 9176 | }; |
| 9177 | let mut out = Vec::with_capacity(au.len() + nal.len()); |
| 9178 | out.extend_from_slice(&au[..at]); |
| 9179 | out.extend_from_slice(nal); |
| 9180 | out.extend_from_slice(&au[at..]); |
| 9181 | return out; |
| 9182 | } |
| 9183 | } |
| 9184 | au |
| 9185 | } |
| 9186 | |
| 9187 | fn pop_gop(gop: &mut HevcGop) -> Option<(&[u8], bool)> { |
| 9188 | let (au, key) = gop.ready.pop_front()?; |
| 9189 | gop.au = au; |
| 9190 | Some((&gop.au[..], key)) |
| 9191 | } |
| 9192 | /// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a |
| 9193 | /// user picked -- the card has no QP control and this codec has no rate control, |
| 9194 | /// so the two are joined by measurement rather than promised to each other. |
| 9195 | /// |
| 9196 | /// The encoder codes ~0.6 bits per pixel at QP 27 ([`HEVC_BPP_AT_27`], measured |
| 9197 | /// on the 720p and 1080p benches to within 4% of each other), and a step of 6 QP |
| 9198 | /// is a factor of two in rate, which is the classic HEVC relation. So the QP |
| 9199 | /// that would land on a target is `27 + 6 * log2(0.6 / target)` -- and it is |
| 9200 | /// clamped, because this is a *quality* dial and not a rate controller: below QP |
| 9201 | /// 22 the file grows without a picture to show for it, and past QP 40 an |
| 9202 | /// intra-only frame goes blocky in a way no bitrate row asked for. A 1080p30 |
| 9203 | /// timeline at the automatic 6.2 Mbps therefore codes at QP 40 and comes out |
| 9204 | /// bigger than that, which is what "intra-only, large files" on the format row |
| 9205 | /// means: the row buys quality, not a size. |
| 9206 | fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 { |
| 9207 | let pixels = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate; |
| 9208 | let target = bitrate_of(meta, settings) as f64 / pixels.max(1.0); |
| 9209 | let qp = 27.0 + 6.0 * (HEVC_BPP_AT_27 / target.max(f64::MIN_POSITIVE)).log2(); |
| 9210 | (qp.round() as i32).clamp(HEVC_QP_MIN, HEVC_QP_MAX) |
| 9211 | } |
| 9212 | |
| 9213 | /// What the *bitstream* says the samples mean, in the words a sequence header |
| 9214 | /// spells them -- the same H.273 code points [`crate::mux`] writes into the |
| 9215 | /// container, from the same colour the export declares there ([`source_sdr_colour`] or the |
| 9216 | /// [`ColorDescription::output`] rule), so the two halves of a file cannot drift apart. |
| 9217 | /// |
| 9218 | /// This exists because a container tag is not enough: libavcodec takes the |
| 9219 | /// bitstream's answer first, and a stream that says nothing is "unspecified", |
| 9220 | /// which renders BT.601 -- a visible shift on a 709 export that a player reads |
| 9221 | /// from the wrong matrix. Every export is limited range, which is what |
| 9222 | /// `video_full_range_flag = false` says here. |
| 9223 | fn video_signal_type(colour: ColorDescription) -> HevcVideoSignalType { |
| 9224 | let (primaries, transfer, matrix) = colour.codes(); |
| 9225 | HevcVideoSignalType { |
| 9226 | // "Unspecified", which is what every encoder here writes: the field is |
| 9227 | // the analogue system a picture came off, and none of these did. |
| 9228 | video_format: 5, |
| 9229 | video_full_range_flag: false, |
| 9230 | colour_description: Some(HevcColourDescription { |
| 9231 | colour_primaries: primaries as u8, |
| 9232 | transfer_characteristics: transfer as u8, |
| 9233 | matrix_coeffs: matrix as u8, |
| 9234 | }), |
| 9235 | } |
| 9236 | } |
| 9237 | |
| 9238 | /// The HDR extras of an HEVC export, in the bitstream: BT.2020's chroma sample |
| 9239 | /// location (type 2, top-left) in the VUI, and the mastering display and content |
| 9240 | /// light SEIs where [`ExportSettings::hdr`] gives them. Nothing for an SDR export, |
| 9241 | /// whose stream stays byte-identical to what it was. |
| 9242 | fn apply_hdr(cfg: &mut HevcEncoderConfig, settings: &ExportSettings) { |
| 9243 | let hdr = &settings.hdr; |
| 9244 | if hdr.transfer == HdrTransfer::Sdr { |
| 9245 | return; |
| 9246 | } |
| 9247 | cfg.chroma_sample_loc = Some((2, 2)); |
| 9248 | cfg.mastering_display = hdr.mastering_display.map(|m| ec_h265_syntax::sei::MasteringDisplay { |
| 9249 | display_primaries: m.primaries, |
| 9250 | white_point: m.white_point, |
| 9251 | max_luminance: m.max_luminance, |
| 9252 | min_luminance: m.min_luminance, |
| 9253 | }); |
| 9254 | cfg.content_light.max_cll = hdr.max_cll.map(f32::from); |
| 9255 | cfg.content_light.max_fall = hdr.max_fall.map(f32::from); |
| 9256 | } |
| 9257 | |
| 9258 | /// The colour a 10-bit export declares when every clip is SDR in one matrix: that |
| 9259 | /// matrix, limited range, the source's own rather than the output rule's. `None` |
| 9260 | /// for a mixed timeline, an HDR one or an empty one, which keep the rule. |
| 9261 | fn source_sdr_colour(colours: &[ColorDescription]) -> Option<ColorDescription> { |
| 9262 | let first = *colours.first()?; |
| 9263 | let same = colours |
| 9264 | .iter() |
| 9265 | .all(|c| c.transfer == Transfer::Sdr && c.matrix == first.matrix); |
| 9266 | (same && first.transfer == Transfer::Sdr).then_some(ColorDescription { |
| 9267 | matrix: first.matrix, |
| 9268 | transfer: Transfer::Sdr, |
| 9269 | full_range: false, |
| 9270 | }) |
| 9271 | } |
| 9272 | |
| 9273 | /// Whether a software export is written at 10 bits: the setting where it names a |
| 9274 | /// depth, the source's own where it does not. AV1 and HEVC have the choice -- |
| 9275 | /// H.264 is 8-bit here -- and a depth the file cannot be is refused. The HEVC |
| 9276 | /// hardware seat is 8-bit, so a 10-bit HEVC export falls back to software |
| 9277 | /// ([`open_hevc`]). |
| 9278 | fn wide_ten_bit( |
| 9279 | settings: &ExportSettings, |
| 9280 | source_ten_bit: impl FnOnce() -> bool, |
| 9281 | ) -> crate::Result<bool> { |
| 9282 | // ProRes is coded at 10 bits whatever the setting says (it has no 8-bit |
| 9283 | // sample), so the walk keeps 10-bit sources at 10 bits. |
| 9284 | if settings.format.is_prores() { |
| 9285 | return Ok(true); |
| 9286 | } |
| 9287 | if !settings.format.is_av1() && !settings.format.is_hevc() { |
| 9288 | return Ok(false); |
| 9289 | } |
| 9290 | // An HDR transfer is a 10-bit claim: 8 bits of PQ bands visibly. |
| 9291 | if settings.hdr.transfer != HdrTransfer::Sdr { |
| 9292 | return match settings.video_bit_depth { |
| 9293 | Some(8) => Err("an HDR export is 10-bit: PQ and HLG are not carried in 8 bits".into()), |
| 9294 | Some(10) | None => Ok(true), |
| 9295 | Some(bits) => Err(format!("an AV1 or HEVC export is 8 or 10 bits, not {bits}").into()), |
| 9296 | }; |
| 9297 | } |
| 9298 | match settings.video_bit_depth { |
| 9299 | None => Ok(source_ten_bit()), |
| 9300 | Some(8) => Ok(false), |
| 9301 | Some(10) => Ok(true), |
| 9302 | Some(bits) => Err(format!("an AV1 or HEVC export is 8 or 10 bits, not {bits}").into()), |
| 9303 | } |
| 9304 | } |
| 9305 | |
| 9306 | /// The colour an HDR HEVC export declares, or `None` for an SDR export; `Err` |
| 9307 | /// where the settings ask for HDR of something that cannot carry it. |
| 9308 | fn hdr_colour_of(settings: &ExportSettings) -> crate::Result<Option<ColorDescription>> { |
| 9309 | let hdr = &settings.hdr; |
| 9310 | let Some(colour) = hdr.transfer.colour() else { |
| 9311 | if hdr.mastering_display.is_some() || hdr.max_cll.is_some() || hdr.max_fall.is_some() { |
| 9312 | return Err("mastering display and MaxCLL/MaxFALL need an HDR transfer (PQ or HLG)".into()); |
| 9313 | } |
| 9314 | return Ok(None); |
| 9315 | }; |
| 9316 | if !settings.format.is_hevc() { |
| 9317 | return Err(format!("{} cannot be written as HDR: only HEVC is", settings.format.name()).into()); |
| 9318 | } |
| 9319 | if settings.keep_source_colour { |
| 9320 | return Err("an HDR export cannot also keep its source's colour".into()); |
| 9321 | } |
| 9322 | Ok(Some(colour)) |
| 9323 | } |
| 9324 | |
| 9325 | fn transfer_name(t: Transfer) -> &'static str { |
| 9326 | match t { |
| 9327 | Transfer::Sdr => "SDR", |
| 9328 | Transfer::Pq => "PQ", |
| 9329 | Transfer::Hlg => "HLG", |
| 9330 | } |
| 9331 | } |
| 9332 | |
| 9333 | /// Every temporal unit `rav1e` has finished, moved into the queue in display |
| 9334 | /// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is |
| 9335 | /// through) are the two ways it says there is nothing more; `Encoded` means a |
| 9336 | /// picture was coded but not yet packetised, which is a *keep asking* -- taking |
| 9337 | /// it for an end leaves the tail of the export inside the encoder. |
| 9338 | fn collect_av1<T: rav1e::prelude::Pixel>( |
| 9339 | context: &mut rav1e::Context<T>, |
| 9340 | ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>, |
| 9341 | ) -> crate::Result<()> { |
| 9342 | use rav1e::prelude::{EncoderStatus, FrameType}; |
| 9343 | loop { |
| 9344 | match context.receive_packet() { |
| 9345 | Ok(packet) => ready.push_back((packet.data, packet.frame_type == FrameType::KEY)), |
| 9346 | Err(EncoderStatus::Encoded) => {} |
| 9347 | Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()), |
| 9348 | Err(e) => return Err(format!("software AV1 encode: {e}").into()), |
| 9349 | } |
| 9350 | } |
| 9351 | } |
| 9352 | |
| 9353 | /// The oldest finished unit, moved into the buffer that is lent out -- the same |
| 9354 | /// "valid until the next call" contract the plugin's slice has. |
| 9355 | fn pop_av1<'a>( |
| 9356 | ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>, |
| 9357 | au: &'a mut Vec<u8>, |
| 9358 | ) -> Option<(&'a [u8], bool)> { |
| 9359 | let (unit, key) = ready.pop_front()?; |
| 9360 | *au = unit; |
| 9361 | Some((&au[..], key)) |
| 9362 | } |
| 9363 | |
| 9364 | /// One picture of 16-bit planes into the 10-bit `rav1e` context, and whatever |
| 9365 | /// unit it finished. The planes are the picture's own size, 4:2:0. |
| 9366 | fn submit_av1_16<'a>( |
| 9367 | context: &mut rav1e::Context<u16>, |
| 9368 | ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>, |
| 9369 | au: &'a mut Vec<u8>, |
| 9370 | planes: [&[u16]; 3], |
| 9371 | width: u32, |
| 9372 | height: u32, |
| 9373 | ) -> crate::Result<Option<(&'a [u8], bool)>> { |
| 9374 | let (w, h) = (width as usize, height as usize); |
| 9375 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 9376 | let mut frame = context.new_frame(); |
| 9377 | // A plane's rows sit `stride` apart from its origin, past any padding. |
| 9378 | let fill = |plane: &mut rav1e::prelude::Plane<u16>, src: &[u16], w: usize, h: usize| { |
| 9379 | let stride = plane.cfg.stride; |
| 9380 | let dst = plane.data_origin_mut(); |
| 9381 | for (row, line) in src.chunks_exact(w).take(h).enumerate() { |
| 9382 | dst[row * stride..row * stride + w].copy_from_slice(line); |
| 9383 | } |
| 9384 | }; |
| 9385 | fill(&mut frame.planes[0], &planes[0][..w * h], w, h); |
| 9386 | fill(&mut frame.planes[1], &planes[1][..cw * ch], cw, ch); |
| 9387 | fill(&mut frame.planes[2], &planes[2][..cw * ch], cw, ch); |
| 9388 | if let Err(e) = context.send_frame(frame) { |
| 9389 | return Err(format!("software AV1 encode: {e}").into()); |
| 9390 | } |
| 9391 | collect_av1(context, ready)?; |
| 9392 | Ok(pop_av1(ready, au)) |
| 9393 | } |
| 9394 | |
| 9395 | /// A 10-bit plane narrowed to 8 bits for the composition that runs at 8 bits: the |
| 9396 | /// same truncation [`crate::decode::narrow_av1`] makes on playback. |
| 9397 | fn narrow_10(src: &[u16], dst: &mut Vec<u8>) { |
| 9398 | dst.clear(); |
| 9399 | dst.extend(src.iter().map(|&s| (s >> 2) as u8)); |
| 9400 | } |
| 9401 | |
| 9402 | /// The frame as an 8-bit composition takes it: a 10-bit picture narrowed into |
| 9403 | /// `scratch`, anything else as it came. |
| 9404 | fn narrowed<'a>(frame: Frame<'a>, scratch: &'a mut [Vec<u8>; 3]) -> Frame<'a> { |
| 9405 | match frame { |
| 9406 | Frame::Wide(y, u, v, width, height) => { |
| 9407 | let [sy, su, sv] = scratch; |
| 9408 | narrow_10(y, sy); |
| 9409 | narrow_10(u, su); |
| 9410 | narrow_10(v, sv); |
| 9411 | Frame::Pixels(&sy[..], &su[..], &sv[..], width, height) |
| 9412 | } |
| 9413 | other => other, |
| 9414 | } |
| 9415 | } |
| 9416 | |
| 9417 | /// I420 straight out of the decoder: the export never converts to BGRA and back, |
| 9418 | /// which would cost two conversions and a generation of colour precision. |
| 9419 | /// |
| 9420 | /// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`, |
| 9421 | /// which only speaks BGRA. A hardware decode that fails *before* the first |
| 9422 | /// picture falls back to software, exactly as playback's does -- nothing has |
| 9423 | /// been encoded yet, so the span can be taken over cleanly. One that fails |
| 9424 | /// after the first picture fails the export, which then deletes the |
| 9425 | /// half-written file: a restart there would re-encode what the muxer holds. |
| 9426 | enum ClipDecoder { |
| 9427 | /// A stream, decoded on a thread of its own: the encode of picture *n* and |
| 9428 | /// the decode of picture *n + 1* are the two halves an export used to do in |
| 9429 | /// turns, each idle while the other worked. The channel is two pictures |
| 9430 | /// deep, so the decoder runs no further ahead than that (a 1080p I420 |
| 9431 | /// picture is 3.1 MB) and a slow encoder still stops it. |
| 9432 | /// |
| 9433 | /// The thread is also where the plugin is *opened*: a VA-API session is not |
| 9434 | /// ours to hand between threads ([`crate::decode::open_worker_deferred`] |
| 9435 | /// keeps the same rule), which is why the open's error comes back down the |
| 9436 | /// channel rather than out of [`ClipDecoder::open`]. |
| 9437 | Streamed(Streamed), |
| 9438 | /// A still image: one picture, handed out for as long as the span runs. |
| 9439 | /// It is decoded here rather than in `run`'s loop for the same reason the |
| 9440 | /// other two are opened there -- the span's pictures come from one place, |
| 9441 | /// and no thread can make one picture arrive sooner. |
| 9442 | Still(crate::decode::Still), |
| 9443 | /// A clip played backwards ([`Reversed`]): its pictures, last to first. |
| 9444 | Reversed(Box<Reversed>), |
| 9445 | /// An audio file playing as a picture: each `next` paints one visualizer |
| 9446 | /// frame from peaks already decoded ([`crate::decode::visualizer_i420`]). |
| 9447 | Visualizer { |
| 9448 | peaks: Vec<(f32, f32)>, |
| 9449 | width: u32, |
| 9450 | height: u32, |
| 9451 | fps: f64, |
| 9452 | next: u32, |
| 9453 | flags: u8, |
| 9454 | paint: u64, |
| 9455 | /// This seat's own painting scratch, kept for the whole export: the |
| 9456 | /// same reuse the playback worker's thread does. |
| 9457 | scratch: crate::decode::VizScratch, |
| 9458 | y: Vec<u8>, |
| 9459 | u: Vec<u8>, |
| 9460 | v: Vec<u8>, |
| 9461 | }, |
| 9462 | } |
| 9463 | |
| 9464 | /// One 8-bit picture owned: its three planes and the size. |
| 9465 | type Owned = (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32); |
| 9466 | |
| 9467 | /// A clip's pictures in reverse ([`ClipDecoder::reversed`]). |
| 9468 | struct Reversed { |
| 9469 | path: PathBuf, |
| 9470 | walk: crate::reverse::Walk, |
| 9471 | /// The block being served, oldest first: the next picture is the last one. |
| 9472 | block: Vec<Owned>, |
| 9473 | /// The picture last handed out, which `next` lends. |
| 9474 | current: Option<Owned>, |
| 9475 | /// The clip's deinterlace setting; `Field` makes the numbers above fields. |
| 9476 | deint: Deinterlace, |
| 9477 | } |
| 9478 | |
| 9479 | impl Reversed { |
| 9480 | fn next(&mut self) -> crate::Result<Option<Frame<'_>>> { |
| 9481 | if self.block.is_empty() && !self.fill()? { |
| 9482 | return Ok(None); |
| 9483 | } |
| 9484 | self.current = self.block.pop(); |
| 9485 | Ok(self |
| 9486 | .current |
| 9487 | .as_ref() |
| 9488 | .map(|(y, u, v, w, h)| Frame::Pixels(y, u, v, *w, *h))) |
| 9489 | } |
| 9490 | |
| 9491 | /// Decodes the next block down, forwards, into `block`. `false` when the window |
| 9492 | /// has no frames left, or the file gave none. |
| 9493 | fn fill(&mut self) -> crate::Result<bool> { |
| 9494 | let Some((start, end)) = self.walk.next() else { |
| 9495 | return Ok(false); |
| 9496 | }; |
| 9497 | let mut decoder = ClipDecoder::open_with(&self.path, start, None, None, false, self.deint)?; |
| 9498 | for _ in start..end { |
| 9499 | match decoder.next()? { |
| 9500 | Some(Frame::Pixels(y, u, v, w, h)) => { |
| 9501 | if self.block.is_empty() { |
| 9502 | // The pictures' real size is known now: hold as many as the |
| 9503 | // budget allows from the next block on. |
| 9504 | let bytes = y.len() + u.len() + v.len(); |
| 9505 | self.walk.set_cap(crate::reverse::block_cap(bytes)); |
| 9506 | } |
| 9507 | self.block.push((y.to_vec(), u.to_vec(), v.to_vec(), w, h)); |
| 9508 | } |
| 9509 | Some(_) => return Err("a reversed clip's decoder produced no pixels".into()), |
| 9510 | None => break, |
| 9511 | } |
| 9512 | } |
| 9513 | Ok(!self.block.is_empty()) |
| 9514 | } |
| 9515 | } |
| 9516 | |
| 9517 | /// The planes of one 10-bit picture, borrowed from its seat: luma, the two |
| 9518 | /// chroma planes, and the size. |
| 9519 | type Wide16View<'a> = (&'a [u16], &'a [u16], &'a [u16], u32, u32); |
| 9520 | |
| 9521 | /// The receiving half of a decode thread, plus the picture it last handed out |
| 9522 | /// -- which is what lets `next` keep lending planes rather than moving them. |
| 9523 | /// |
| 9524 | /// The first two fields are in this order on purpose, and it is the order |
| 9525 | /// [`crate::decode::FrameStream`] states for the same pair: Rust drops fields as |
| 9526 | /// they are declared, so the receiver disconnects *first* -- the only thing that |
| 9527 | /// wakes a decoder parked in a full `send` -- and the join inside |
| 9528 | /// [`DecodeThread::drop`] runs second. The other way round is a hang and not a |
| 9529 | /// slow path. |
| 9530 | struct Streamed { |
| 9531 | frames: Receiver<crate::Result<Option<Yuv>>>, |
| 9532 | /// Held only to be dropped: joining is all it does, and it must happen |
| 9533 | /// after the receiver above (`_lib` in `crate::hw` is kept the same way). |
| 9534 | /// Its result is the software decoder a stopped span leaves behind, if any. |
| 9535 | _thread: DecodeThread<Option<Kept>>, |
| 9536 | current: Option<Yuv>, |
| 9537 | /// Whether the thread has said "no more pictures" in as many words. What |
| 9538 | /// separates a stream that ended from a thread that vanished: after this, |
| 9539 | /// the channel is disconnected because the decoder is *done*, and a further |
| 9540 | /// ask is end of stream rather than a failure. |
| 9541 | ended: bool, |
| 9542 | /// Where the decoder goes when this span is done with it, if it may be kept. |
| 9543 | park: Option<Park>, |
| 9544 | } |
| 9545 | |
| 9546 | /// What a software decode thread leaves behind when it is stopped: the |
| 9547 | /// decoder, and the pictures it had decoded past the last one its span took, |
| 9548 | /// in order -- the ones the channel still held, then the ones it had not sent. |
| 9549 | type Kept = (Box<SwDecoder>, VecDeque<Yuv>); |
| 9550 | |
| 9551 | /// The way back from a span's [`Streamed`] to the [`Parked`] lot: the lot, the |
| 9552 | /// file, and the flag that asks the decode thread to stop at its next picture. |
| 9553 | struct Park { |
| 9554 | lot: Arc<Parked>, |
| 9555 | path: PathBuf, |
| 9556 | stop: Arc<AtomicBool>, |
| 9557 | } |
| 9558 | |
| 9559 | /// Software H.264 decoders from spans that have ended, kept so that the next |
| 9560 | /// span of the same file can carry on from where they stopped instead of |
| 9561 | /// seeking back to a sync sample and decoding the whole GOP in front of its in |
| 9562 | /// point again (a long-GOP source pays up to a GOP per clip that way). |
| 9563 | /// |
| 9564 | /// Only a decoder that is *resumable* is ever taken: see [`resumable`]. Hardware |
| 9565 | /// sessions are never kept, since whether a span gets one is the hardware's |
| 9566 | /// answer and not this lot's. |
| 9567 | #[derive(Default)] |
| 9568 | struct Parked(Mutex<VecDeque<ParkedDecoder>>); |
| 9569 | |
| 9570 | /// Most decoders kept at once. Each holds a demuxer and its reference pictures, |
| 9571 | /// so the lot stays small: a dissolve needs two, and a multi-source edit a few. |
| 9572 | const PARKED_MAX: usize = 4; |
| 9573 | |
| 9574 | /// One decoder in the lot: the file it reads, the decoder itself, and the |
| 9575 | /// pictures it decoded that no span took (see [`Kept`]). |
| 9576 | struct ParkedDecoder { |
| 9577 | path: PathBuf, |
| 9578 | decoder: Box<SwDecoder>, |
| 9579 | backlog: VecDeque<Yuv>, |
| 9580 | } |
| 9581 | |
| 9582 | impl Parked { |
| 9583 | fn keep(&self, entry: ParkedDecoder) { |
| 9584 | let Ok(mut lot) = self.0.lock() else { return }; |
| 9585 | lot.push_back(entry); |
| 9586 | while lot.len() > PARKED_MAX { |
| 9587 | lot.pop_front(); |
| 9588 | } |
| 9589 | } |
| 9590 | |
| 9591 | /// The decoder that can serve a span of `path` starting at `start`, taken |
| 9592 | /// out of the lot and wound forward to that picture: whatever it holds |
| 9593 | /// before `start` is dropped, and the rest is what the span decodes from. |
| 9594 | fn take(&self, path: &Path, start: u32) -> Option<ParkedDecoder> { |
| 9595 | let mut lot = self.0.lock().ok()?; |
| 9596 | let at = lot |
| 9597 | .iter() |
| 9598 | .position(|entry| entry.path == path && entry.serves(start))?; |
| 9599 | let mut entry = lot.remove(at)?; |
| 9600 | let start = i64::from(start); |
| 9601 | while entry.backlog.front().is_some() |
| 9602 | && entry.decoder.index() - (entry.backlog.len() as i64) < start |
| 9603 | { |
| 9604 | entry.backlog.pop_front(); |
| 9605 | } |
| 9606 | entry.decoder.start = start as u32; |
| 9607 | Some(entry) |
| 9608 | } |
| 9609 | } |
| 9610 | |
| 9611 | impl ParkedDecoder { |
| 9612 | /// Whether this decoder can serve a span starting at `start`: asked of the |
| 9613 | /// file itself, where a fresh decoder would seek to. |
| 9614 | fn serves(&self, start: u32) -> bool { |
| 9615 | let Ok((_, mut demuxer)) = Demuxer::open(&self.path) else { |
| 9616 | return false; |
| 9617 | }; |
| 9618 | let restart = demuxer.seek_to_sync_at_or_before(start); |
| 9619 | resumable( |
| 9620 | self.decoder.index(), |
| 9621 | self.backlog.len(), |
| 9622 | self.decoder.origin(), |
| 9623 | restart, |
| 9624 | i64::from(start), |
| 9625 | ) |
| 9626 | } |
| 9627 | } |
| 9628 | |
| 9629 | /// Whether a decoder can carry on for a span starting at display frame `start` |
| 9630 | /// instead of a fresh one opened there. `next` is the display index of the |
| 9631 | /// picture it produces next, `backlog` how many decoded pictures sit before |
| 9632 | /// that, unclaimed; `origin` is the sync sample it was started at, and |
| 9633 | /// `restart` the sync sample a fresh decoder for `start` would start at. |
| 9634 | /// |
| 9635 | /// Two things must hold. The span's first picture must still be held or not |
| 9636 | /// yet decoded, since a decoder cannot go back. And the decoder must have been |
| 9637 | /// started at the sample a fresh one would start at, so that it has read the |
| 9638 | /// same access units from the same point and produces the same pictures -- a |
| 9639 | /// later sync sample is a restart the decoder did not make, and one that is not |
| 9640 | /// an IDR would be decoded from references the fresh one does not have. |
| 9641 | fn resumable(next: i64, backlog: usize, origin: i64, restart: i64, start: i64) -> bool { |
| 9642 | next - (backlog as i64) <= start && restart == origin |
| 9643 | } |
| 9644 | |
| 9645 | /// A decode thread, joined when its span's decoder is dropped -- the rule |
| 9646 | /// [`crate::decode::Worker`] is written for: a thread abandoned mid |
| 9647 | /// `vaInitialize` outlives the process, and Mesa's `atexit` handlers then free |
| 9648 | /// the state it is still reading, which is a SIGSEGV at exit long after the |
| 9649 | /// export succeeded. |
| 9650 | struct DecodeThread<T = ()>(Option<thread::JoinHandle<T>>); |
| 9651 | |
| 9652 | impl<T> DecodeThread<T> { |
| 9653 | /// The thread's result, once it has finished. Joins it if it has not. |
| 9654 | fn finish(&mut self) -> Option<T> { |
| 9655 | self.0.take().and_then(|handle| handle.join().ok()) |
| 9656 | } |
| 9657 | } |
| 9658 | |
| 9659 | impl<T> Drop for DecodeThread<T> { |
| 9660 | fn drop(&mut self) { |
| 9661 | if let Some(handle) = self.0.take() { |
| 9662 | // The receiver is already gone (see `Streamed`'s field order), so a |
| 9663 | // decoder blocked on `send` has been woken and this waits only for |
| 9664 | // the thread to unwind its VA-API session. |
| 9665 | let _ = handle.join(); |
| 9666 | } |
| 9667 | } |
| 9668 | } |
| 9669 | |
| 9670 | impl Drop for Streamed { |
| 9671 | fn drop(&mut self) { |
| 9672 | let Some(park) = self.park.take() else { |
| 9673 | return; |
| 9674 | }; |
| 9675 | // Ask the decoder to stop, then take what it sends until it does: its |
| 9676 | // next send is answered by this drain and its next look at the flag |
| 9677 | // ends it, dropping the sender, which is what the drain waits for. |
| 9678 | park.stop.store(true, Ordering::Relaxed); |
| 9679 | let mut backlog = VecDeque::new(); |
| 9680 | // A GPU buffer is not kept: a hardware decoder is waiting on the |
| 9681 | // surfaces it has lent, and nothing here would hand them back. |
| 9682 | while let Ok(item) = self.frames.recv() { |
| 9683 | if let Ok(Some(frame @ (Yuv::Pixels { .. } | Yuv::Wide { .. }))) = item { |
| 9684 | backlog.push_back(frame); |
| 9685 | } |
| 9686 | } |
| 9687 | if let Some((decoder, rest)) = self._thread.finish().flatten() { |
| 9688 | backlog.extend(rest); |
| 9689 | park.lot.keep(ParkedDecoder { |
| 9690 | path: park.path, |
| 9691 | decoder, |
| 9692 | backlog, |
| 9693 | }); |
| 9694 | } |
| 9695 | } |
| 9696 | } |
| 9697 | |
| 9698 | /// One picture on its way from a decode thread to the encoder: its bytes, or |
| 9699 | /// the GPU buffer they are still in. |
| 9700 | enum Yuv { |
| 9701 | Pixels { |
| 9702 | y: Vec<u8>, |
| 9703 | u: Vec<u8>, |
| 9704 | v: Vec<u8>, |
| 9705 | width: u32, |
| 9706 | height: u32, |
| 9707 | }, |
| 9708 | /// The same picture at 16 bits a sample, at 10-bit scale: what a 10-bit export |
| 9709 | /// encodes whole ([`Enc::encode_wide`]). |
| 9710 | Wide { |
| 9711 | y: Vec<u16>, |
| 9712 | u: Vec<u16>, |
| 9713 | v: Vec<u16>, |
| 9714 | width: u32, |
| 9715 | height: u32, |
| 9716 | }, |
| 9717 | /// Never read back and never copied: a DRM-PRIME handle the encoder imports |
| 9718 | /// on the other side of the channel. Sending it is sending an integer, and |
| 9719 | /// what keeps the buffer from being decoded over is the channel's own depth |
| 9720 | /// (see [`crate::hw::HwSession::next_frame_dma`]). |
| 9721 | Dma(DmaFrame), |
| 9722 | } |
| 9723 | |
| 9724 | impl Yuv { |
| 9725 | /// The decoder's own buffer copied out, which is what it costs to hand a |
| 9726 | /// picture to another thread when the pixels have to travel. |
| 9727 | fn pixels(y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> Self { |
| 9728 | Self::Pixels { |
| 9729 | y: y.to_vec(), |
| 9730 | u: u.to_vec(), |
| 9731 | v: v.to_vec(), |
| 9732 | width, |
| 9733 | height, |
| 9734 | } |
| 9735 | } |
| 9736 | } |
| 9737 | |
| 9738 | /// What [`ExportHandle::stage`] calls a stabilised clip's shake being measured. |
| 9739 | pub const MEASURING_SHAKE: &str = "Measuring shake"; |
| 9740 | |
| 9741 | /// How a layer opened for an export measures a stabilised clip with no finished |
| 9742 | /// analysis ([`LayerFeed::open`]): under this cancel flag, reporting to this |
| 9743 | /// stage ([`Shared::measuring`]). |
| 9744 | type Measure<'a> = (&'a AtomicBool, &'a AtomicU32); |
| 9745 | |
| 9746 | /// The luma of file frames `lo..hi` of `path` as a layer's decoder hands them to |
| 9747 | /// [`LayerFeed::advance`] -- before the file's display turn and pixel stretch -- |
| 9748 | /// for the stabilise analysis, whose maps move those same planes. `each` takes |
| 9749 | /// the frame number, the luma plane and its size, and stops the walk with `false`. |
| 9750 | pub(crate) fn each_layer_luma( |
| 9751 | path: &Path, |
| 9752 | lo: u32, |
| 9753 | hi: u32, |
| 9754 | mut each: impl FnMut(u32, &[u8], u32, u32) -> bool, |
| 9755 | ) -> crate::Result<()> { |
| 9756 | let mut decoder = ClipDecoder::open(path, lo, None, None, false)?; |
| 9757 | for index in lo..hi { |
| 9758 | match decoder.next()? { |
| 9759 | Some(Frame::Pixels(y, _, _, w, h)) => { |
| 9760 | if !each(index, y, w, h) { |
| 9761 | break; |
| 9762 | } |
| 9763 | } |
| 9764 | Some(_) => return Err("stabilise: the decoder gave no 8-bit pixels".into()), |
| 9765 | None => break, |
| 9766 | } |
| 9767 | } |
| 9768 | Ok(()) |
| 9769 | } |
| 9770 | |
| 9771 | /// One picture as the export loop sees it: planes to grade and place, or a |
| 9772 | /// buffer that goes straight into the encoder. |
| 9773 | enum Frame<'a> { |
| 9774 | Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32), |
| 9775 | /// A 10-bit picture at 10-bit scale, which only a 10-bit export asks for. |
| 9776 | Wide(&'a [u16], &'a [u16], &'a [u16], u32, u32), |
| 9777 | Dma(&'a DmaFrame), |
| 9778 | } |
| 9779 | |
| 9780 | impl ClipDecoder { |
| 9781 | /// A decoder for `path` from `start_frame`. `parked` is the lot a span's |
| 9782 | /// software decoder may be taken from and returned to; `None` never keeps one. |
| 9783 | fn open( |
| 9784 | path: &Path, |
| 9785 | start_frame: u32, |
| 9786 | want: Option<DmaWant>, |
| 9787 | parked: Option<&Arc<Parked>>, |
| 9788 | wide: bool, |
| 9789 | ) -> crate::Result<Self> { |
| 9790 | Self::open_with(path, start_frame, want, parked, wide, Deinterlace::Frame) |
| 9791 | } |
| 9792 | |
| 9793 | /// [`open`](Self::open) for a clip with a deinterlace setting. `Field` over an |
| 9794 | /// interlaced file makes `start_frame` a field number and every picture a field. |
| 9795 | fn open_with( |
| 9796 | path: &Path, |
| 9797 | start_frame: u32, |
| 9798 | want: Option<DmaWant>, |
| 9799 | parked: Option<&Arc<Parked>>, |
| 9800 | wide: bool, |
| 9801 | deint: Deinterlace, |
| 9802 | ) -> crate::Result<Self> { |
| 9803 | // Before either decoder: an image is not a stream, so `start_frame` |
| 9804 | // means nothing to it -- every frame of a still span is the same |
| 9805 | // picture, which is what playback shows for it too. |
| 9806 | if crate::is_image(path) { |
| 9807 | return Ok(Self::Still(crate::decode::Still::open_at(path, start_frame)?)); |
| 9808 | } |
| 9809 | let path = path.to_path_buf(); |
| 9810 | let (tx, frames) = sync_channel(2); |
| 9811 | let stop = Arc::new(AtomicBool::new(false)); |
| 9812 | let park = parked.map(|lot| Park { |
| 9813 | lot: Arc::clone(lot), |
| 9814 | path: path.clone(), |
| 9815 | stop: Arc::clone(&stop), |
| 9816 | }); |
| 9817 | let thread_park = parked.map(|lot| (Arc::clone(lot), Arc::clone(&stop))); |
| 9818 | let handle = thread::Builder::new() |
| 9819 | .name("export-decode".into()) |
| 9820 | .spawn(move || decode_stream(&path, start_frame, want, &tx, thread_park, wide, deint))?; |
| 9821 | Ok(Self::Streamed(Streamed { |
| 9822 | frames, |
| 9823 | _thread: DecodeThread(Some(handle)), |
| 9824 | current: None, |
| 9825 | ended: false, |
| 9826 | park, |
| 9827 | })) |
| 9828 | } |
| 9829 | |
| 9830 | fn visualizer( |
| 9831 | path: &Path, |
| 9832 | stream: usize, |
| 9833 | start_frame: u32, |
| 9834 | (width, height): (u32, u32), |
| 9835 | fps: f64, |
| 9836 | flags: u8, |
| 9837 | paint: u64, |
| 9838 | ) -> crate::Result<Self> { |
| 9839 | let peaks = crate::waveform::peaks(path, stream, crate::decode::VIZ_BUCKETS_PER_SEC) |
| 9840 | .ok() |
| 9841 | .flatten() |
| 9842 | .unwrap_or_default(); |
| 9843 | let fps = if fps.is_finite() && fps > 0.0 { |
| 9844 | fps |
| 9845 | } else { |
| 9846 | 30.0 |
| 9847 | }; |
| 9848 | Ok(Self::Visualizer { |
| 9849 | peaks, |
| 9850 | width, |
| 9851 | height, |
| 9852 | fps, |
| 9853 | next: start_frame, |
| 9854 | flags, |
| 9855 | paint, |
| 9856 | scratch: crate::decode::VizScratch::default(), |
| 9857 | y: Vec::new(), |
| 9858 | u: Vec::new(), |
| 9859 | v: Vec::new(), |
| 9860 | }) |
| 9861 | } |
| 9862 | |
| 9863 | /// The pictures of `path` from file frame `top` down to `lo`, last to first: |
| 9864 | /// a clip played backwards. Decoded forwards a block at a time and served from |
| 9865 | /// the back, so the memory held is one block ([`crate::reverse`]), and always |
| 9866 | /// 8-bit software pictures -- the block is copied out of the decoder, which a GPU |
| 9867 | /// buffer or a 10-bit plane does not allow. |
| 9868 | fn reversed(path: &Path, top: u32, lo: u32, deint: Deinterlace) -> Self { |
| 9869 | let mut sync = crate::reverse::sync_frames(path); |
| 9870 | if deint == Deinterlace::Field { |
| 9871 | sync.iter_mut().for_each(|f| *f *= 2); |
| 9872 | } |
| 9873 | Self::Reversed(Box::new(Reversed { |
| 9874 | deint, |
| 9875 | path: path.to_path_buf(), |
| 9876 | walk: crate::reverse::Walk::new( |
| 9877 | sync, |
| 9878 | lo, |
| 9879 | top + 1, |
| 9880 | // Until a picture says how big they are: the biggest the engine takes. |
| 9881 | crate::reverse::block_cap(3840 * 2160 * 3 / 2), |
| 9882 | ), |
| 9883 | block: Vec::new(), |
| 9884 | current: None, |
| 9885 | })) |
| 9886 | } |
| 9887 | |
| 9888 | /// The next picture, borrowed until the call after -- as tightly packed |
| 9889 | /// I420, or as the GPU buffer the decoder wrote it into. |
| 9890 | fn next(&mut self) -> crate::Result<Option<Frame<'_>>> { |
| 9891 | match self { |
| 9892 | Self::Still(still) => { |
| 9893 | let (y, u, v, width, height) = still.picture(); |
| 9894 | Ok(Some(Frame::Pixels(y, u, v, width, height))) |
| 9895 | } |
| 9896 | Self::Reversed(reversed) => reversed.next(), |
| 9897 | Self::Visualizer { |
| 9898 | peaks, |
| 9899 | width, |
| 9900 | height, |
| 9901 | fps, |
| 9902 | next, |
| 9903 | flags, |
| 9904 | paint, |
| 9905 | scratch, |
| 9906 | y, |
| 9907 | u, |
| 9908 | v, |
| 9909 | } => { |
| 9910 | let (yy, uu, vv) = crate::decode::visualizer_i420( |
| 9911 | scratch, |
| 9912 | peaks, |
| 9913 | f64::from(*next) / *fps, |
| 9914 | *width, |
| 9915 | *height, |
| 9916 | *flags, |
| 9917 | *paint, |
| 9918 | ); |
| 9919 | *y = yy; |
| 9920 | *u = uu; |
| 9921 | *v = vv; |
| 9922 | *next += 1; |
| 9923 | Ok(Some(Frame::Pixels(y, u, v, *width & !1, *height & !1))) |
| 9924 | } |
| 9925 | Self::Streamed(stream) if stream.ended => Ok(None), |
| 9926 | Self::Streamed(stream) => match stream.frames.recv() { |
| 9927 | Ok(Ok(Some(frame))) => Ok(Some(match stream.current.insert(frame) { |
| 9928 | Yuv::Pixels { |
| 9929 | y, |
| 9930 | u, |
| 9931 | v, |
| 9932 | width, |
| 9933 | height, |
| 9934 | } => Frame::Pixels(y, u, v, *width, *height), |
| 9935 | Yuv::Wide { |
| 9936 | y, |
| 9937 | u, |
| 9938 | v, |
| 9939 | width, |
| 9940 | height, |
| 9941 | } => Frame::Wide(y, u, v, *width, *height), |
| 9942 | Yuv::Dma(dma) => Frame::Dma(dma), |
| 9943 | })), |
| 9944 | Ok(Ok(None)) => { |
| 9945 | stream.ended = true; |
| 9946 | Ok(None) |
| 9947 | } |
| 9948 | Ok(Err(e)) => Err(e), |
| 9949 | Err(_) => Err("the decoder stopped without a picture or a reason".into()), |
| 9950 | }, |
| 9951 | } |
| 9952 | } |
| 9953 | } |
| 9954 | |
| 9955 | /// One span's decode, on its own thread: open the file (hardware if the plugin |
| 9956 | /// will have it, software otherwise) and send every picture until the encoder |
| 9957 | /// stops taking them. |
| 9958 | /// |
| 9959 | /// Hardware that fails, before the first picture or after some, hands the rest |
| 9960 | /// of the span to the software seat at the first picture not yet sent. |
| 9961 | /// |
| 9962 | /// Every way this returns says which way it was, down the channel: a picture, an |
| 9963 | /// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not |
| 9964 | /// one of them -- a silent close is a panicked thread, and the receiver treats |
| 9965 | /// it as the failure it is rather than as a source that ran out. |
| 9966 | /// |
| 9967 | /// With `parked`, a software decode takes a parked decoder for this file when |
| 9968 | /// one can serve `start_frame`, and a decoder that is asked to stop (its span |
| 9969 | /// was dropped) is handed back: see [`Streamed`]'s drop. |
| 9970 | fn decode_stream( |
| 9971 | path: &Path, |
| 9972 | start_frame: u32, |
| 9973 | want: Option<DmaWant>, |
| 9974 | tx: &SyncSender<crate::Result<Option<Yuv>>>, |
| 9975 | parked: Option<(Arc<Parked>, Arc<AtomicBool>)>, |
| 9976 | wide: bool, |
| 9977 | deint: Deinterlace, |
| 9978 | ) -> Option<Kept> { |
| 9979 | // A 10-bit export decodes in software: the hardware seat hands 8-bit planes. |
| 9980 | let opened = match forced("VE_SW") || wide { |
| 9981 | // The decode door's own gate ([`crate::decode::open_hw`]): a VP9 4:2:2 or 4:4:4 |
| 9982 | // stream is never offered to the GPU, which would refuse it on stderr. |
| 9983 | false => crate::decode::open_hw(path, start_frame).map(|hw| Pictures::Hw(Box::new(hw))), |
| 9984 | true => None, |
| 9985 | }; |
| 9986 | // Pictures decoded ahead of the span that a parked decoder still holds. |
| 9987 | let (mut decoder, mut backlog) = match opened { |
| 9988 | Some(hw) => (hw, VecDeque::new()), |
| 9989 | None => match parked |
| 9990 | .as_ref() |
| 9991 | .and_then(|(lot, _)| lot.take(path, start_frame)) |
| 9992 | { |
| 9993 | Some(kept) => (Pictures::Sw(kept.decoder), kept.backlog), |
| 9994 | None => match Pictures::software(path, start_frame, wide, deint) { |
| 9995 | Ok(sw) => (sw, VecDeque::new()), |
| 9996 | Err(e) => { |
| 9997 | let _ = tx.send(Err(e)); |
| 9998 | return None; |
| 9999 | } |
| 10000 | }, |
| 10001 | }, |
| 10002 | }; |
| 10003 | // Pictures handed down the channel. Hardware that dies hands the rest of the |
| 10004 | // span to the software seat at `start_frame + decoded`: the first picture |
| 10005 | // not yet sent, so nothing already encoded is repeated. |
| 10006 | let mut decoded = 0u32; |
| 10007 | loop { |
| 10008 | // Asked to stop: the span is over, and a software decoder that has not |
| 10009 | // reached its end is what the next span may take up. |
| 10010 | if parked |
| 10011 | .as_ref() |
| 10012 | .is_some_and(|(_, stop)| stop.load(Ordering::Relaxed)) |
| 10013 | { |
| 10014 | return match decoder { |
| 10015 | Pictures::Sw(sw) if sw.parkable() && !sw.flushed() => Some((sw, backlog)), |
| 10016 | _ => None, |
| 10017 | }; |
| 10018 | } |
| 10019 | // Hardware that ends before its first picture has failed the same way |
| 10020 | // one that errors there has: the mid-GOP AV1 seek ends the stream with |
| 10021 | // nothing (see `decode::run_hw`), and it falls back here too. |
| 10022 | let next = match backlog.pop_front() { |
| 10023 | Some(frame) => Ok(Some(frame)), |
| 10024 | None => decoder.next(want), |
| 10025 | }; |
| 10026 | let next = match next { |
| 10027 | Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(_)) => { |
| 10028 | Err("hardware gave no picture from the start frame".into()) |
| 10029 | } |
| 10030 | other => other, |
| 10031 | }; |
| 10032 | let frame = match next { |
| 10033 | Ok(Some(frame)) => frame, |
| 10034 | Ok(None) => { |
| 10035 | let _ = tx.send(Ok(None)); |
| 10036 | return None; |
| 10037 | } |
| 10038 | Err(e) => { |
| 10039 | if matches!(decoder, Pictures::Hw(_)) { |
| 10040 | // Before the first picture, or after some: either way the |
| 10041 | // software seat takes the span from the first picture not yet |
| 10042 | // sent (`decoded` is 0 in the first case), so nothing is |
| 10043 | // encoded twice and nothing is skipped. |
| 10044 | if std::env::var_os("EDITH_DEBUG").is_some() || decoded > 0 { eprintln!( |
| 10045 | "export decode: hardware failed at frame {} ({e}); falling back to software", |
| 10046 | start_frame + decoded |
| 10047 | ); } |
| 10048 | match Pictures::software(path, start_frame + decoded, wide, deint) { |
| 10049 | Ok(sw) => { |
| 10050 | decoder = sw; |
| 10051 | continue; |
| 10052 | } |
| 10053 | Err(sw_refusal) => { |
| 10054 | let _ = tx.send(Err(sw_refusal)); |
| 10055 | return None; |
| 10056 | } |
| 10057 | } |
| 10058 | } |
| 10059 | let _ = tx.send(Err(e)); |
| 10060 | return None; |
| 10061 | } |
| 10062 | }; |
| 10063 | // The consumer went away: the span ended early, or the export was |
| 10064 | // cancelled. Either way there is nothing left to decode for. A parked |
| 10065 | // span drains the channel before it drops it, so this is not reached. |
| 10066 | if tx.send(Ok(Some(frame))).is_err() { |
| 10067 | return None; |
| 10068 | } |
| 10069 | decoded += 1; |
| 10070 | } |
| 10071 | } |
| 10072 | |
| 10073 | /// The stream decoders, on the thread that opened them. |
| 10074 | enum Pictures { |
| 10075 | Hw(Box<HwSession>), |
| 10076 | /// `ec-h264`, on this thread. |
| 10077 | Sw(Box<SwDecoder>), |
| 10078 | /// `ec-av1`, on a thread of its own -- see [`Av1Stream`]. |
| 10079 | Av1(Box<Av1Stream>), |
| 10080 | } |
| 10081 | |
| 10082 | impl Pictures { |
| 10083 | /// The software seat for `path`: `ec-h264` for H.264, `ec-av1` on its own |
| 10084 | /// thread for AV1, and the pulled seats (`ec-h265`, `ec-vp9`, `ec-vp8`) for the |
| 10085 | /// rest. The codec is read once here, so it decides which seat takes the file. |
| 10086 | fn software(path: &Path, start_frame: u32, wide: bool, deint: Deinterlace) -> crate::Result<Self> { |
| 10087 | let (meta, demuxer) = Demuxer::open(path)?; |
| 10088 | match meta.codec { |
| 10089 | Codec::H264 => Ok(Self::Sw(Box::new(SwDecoder::new(demuxer, start_frame, wide, deint)))), |
| 10090 | Codec::Av1 => Ok(Self::Av1(Box::new(Av1Stream::spawn(demuxer, start_frame, wide)?))), |
| 10091 | _ => Ok(Self::Sw(Box::new(SwDecoder::open(path, start_frame, wide, deint)?))), |
| 10092 | } |
| 10093 | } |
| 10094 | |
| 10095 | /// The next picture, owned, ready to cross the channel. `want` is what the |
| 10096 | /// export's encoder can read straight off the GPU: where the hardware |
| 10097 | /// decoder can hand such a buffer over there is no copy here at all, and |
| 10098 | /// everything else is the 3 MB memcpy out of the decoder's own buffer that |
| 10099 | /// buys the decode and the encode their overlap. |
| 10100 | fn next(&mut self, want: Option<DmaWant>) -> crate::Result<Option<Yuv>> { |
| 10101 | match (self, want) { |
| 10102 | (Self::Hw(hw), Some(want)) => Ok(match hw.next_frame_dma(want)? { |
| 10103 | Some(HwPicture::Dma(dma)) => Some(Yuv::Dma(dma)), |
| 10104 | Some(HwPicture::Pixels(y, u, v, width, height)) => { |
| 10105 | Some(Yuv::pixels(y, u, v, width, height)) |
| 10106 | } |
| 10107 | None => None, |
| 10108 | }), |
| 10109 | (Self::Hw(hw), None) => Ok(hw |
| 10110 | .next_frame()? |
| 10111 | .map(|(y, u, v, width, height)| Yuv::pixels(y, u, v, width, height))), |
| 10112 | (Self::Av1(av1), _) => av1.next(), |
| 10113 | (Self::Sw(sw), _) => { |
| 10114 | if !sw.advance()? { |
| 10115 | return Ok(None); |
| 10116 | } |
| 10117 | if let Some((y, u, v, width, height)) = sw.picture16() { |
| 10118 | return Ok(Some(Yuv::Wide { |
| 10119 | y: y.to_vec(), |
| 10120 | u: u.to_vec(), |
| 10121 | v: v.to_vec(), |
| 10122 | width, |
| 10123 | height, |
| 10124 | })); |
| 10125 | } |
| 10126 | let (y, u, v, width, height) = sw.picture(); |
| 10127 | Ok(Some(Yuv::pixels(y, u, v, width, height))) |
| 10128 | } |
| 10129 | } |
| 10130 | } |
| 10131 | } |
| 10132 | |
| 10133 | /// The software decoder one export span reads from: H.264 with its own reorder |
| 10134 | /// and flush, or one of the pulled seats playback's spans read too. |
| 10135 | struct SwDecoder { |
| 10136 | demuxer: Demuxer, |
| 10137 | /// The first display index the export takes. Pictures before it are decoded |
| 10138 | /// (the target references them) and then dropped. |
| 10139 | start: u32, |
| 10140 | seat: SwSeat, |
| 10141 | } |
| 10142 | |
| 10143 | enum SwSeat { |
| 10144 | H264(Box<H264Seat>), |
| 10145 | /// `wide` is the 10-bit plane buffer when this seat decodes at 10 bits. |
| 10146 | Pulled { |
| 10147 | stream: Box<Pulled>, |
| 10148 | out: I420, |
| 10149 | wide: Option<Wide>, |
| 10150 | }, |
| 10151 | } |
| 10152 | |
| 10153 | struct H264Seat { |
| 10154 | decoder: H264Decoder, |
| 10155 | /// Display index of the next picture the decoder will produce. Signed: a |
| 10156 | /// sync sample inside what the edit list trims is before frame 0. |
| 10157 | index: i64, |
| 10158 | /// The display index the decoder started at (its sync sample), what |
| 10159 | /// [`resumable`] compares a later span's restart against. |
| 10160 | origin: i64, |
| 10161 | /// Set once the demuxer runs dry: `flush` has then released what the |
| 10162 | /// decoder's reorder still held, and only those pictures are left. |
| 10163 | flushed: bool, |
| 10164 | frame: Option<VideoFrame>, |
| 10165 | /// Whether the export is 10-bit, and the High 10 picture taken for it. |
| 10166 | wide: bool, |
| 10167 | deep: crate::decode::Deep, |
| 10168 | /// Deinterlaces an interlaced stream (a pass-through for every other). |
| 10169 | deint: crate::deinterlace::Deinterlacer, |
| 10170 | /// Pictures the deinterlacer released that `advance` has not handed over yet: |
| 10171 | /// the second field of a frame in field mode. |
| 10172 | pending: VecDeque<(i64, VideoFrame)>, |
| 10173 | } |
| 10174 | |
| 10175 | impl SwDecoder { |
| 10176 | fn open(path: &Path, start_frame: u32, wide: bool, deint: Deinterlace) -> crate::Result<Self> { |
| 10177 | let (meta, mut demuxer) = Demuxer::open(path)?; |
| 10178 | // Decoding restarts at a sync sample, so pictures between it and the in |
| 10179 | // point are decoded (the target references them) and then dropped. |
| 10180 | let seat = match Pulled::open(meta.codec, &mut demuxer, start_frame, deint) { |
| 10181 | Some(stream) => SwSeat::Pulled { |
| 10182 | stream: Box::new(stream), |
| 10183 | out: I420::default(), |
| 10184 | // Only HEVC and the intra-only professional codecs have a 10-bit seat; the others narrow as they always did. |
| 10185 | wide: (wide && (matches!(meta.codec, Codec::Hevc | Codec::ProRes | Codec::Dnxhd) || (meta.codec == Codec::Raw && demuxer.bit_depth() >= 10))).then(Wide::default), |
| 10186 | }, |
| 10187 | None if meta.codec == Codec::H264 => { |
| 10188 | SwSeat::H264(H264Seat::open(&mut demuxer, start_frame, wide, deint)) |
| 10189 | } |
| 10190 | // AV1 never gets here: `Pictures::software` gives it `Av1Stream`. |
| 10191 | None => return Err(format!("{} has no export seat", meta.codec.name()).into()), |
| 10192 | }; |
| 10193 | Ok(Self { |
| 10194 | demuxer, |
| 10195 | start: start_frame, |
| 10196 | seat, |
| 10197 | }) |
| 10198 | } |
| 10199 | |
| 10200 | /// Decodes up to and including the next picture at or after the in point. |
| 10201 | /// `false` at end of stream. |
| 10202 | fn advance(&mut self) -> crate::Result<bool> { |
| 10203 | match &mut self.seat { |
| 10204 | SwSeat::H264(seat) => seat.advance(&mut self.demuxer, self.start), |
| 10205 | SwSeat::Pulled { stream, out, wide } => loop { |
| 10206 | let next = match wide { |
| 10207 | Some(wide) => stream.next_wide(&mut self.demuxer, wide)?, |
| 10208 | None => stream.next(&mut self.demuxer, out)?, |
| 10209 | }; |
| 10210 | let Some(due) = next else { |
| 10211 | return Ok(false); |
| 10212 | }; |
| 10213 | if due >= i64::from(self.start) { |
| 10214 | return Ok(true); |
| 10215 | } |
| 10216 | }, |
| 10217 | } |
| 10218 | } |
| 10219 | |
| 10220 | /// The 10-bit planes of the picture `advance` stopped on, when this seat |
| 10221 | /// decodes at 10 bits; `None` otherwise. |
| 10222 | fn picture16(&self) -> Option<Wide16View<'_>> { |
| 10223 | match &self.seat { |
| 10224 | SwSeat::Pulled { wide: Some(w), .. } => Some((&w.y, &w.u, &w.v, w.width, w.height)), |
| 10225 | SwSeat::H264(s) if s.deep.in_wide => { |
| 10226 | let w = &s.deep.wide; |
| 10227 | Some((&w.y, &w.u, &w.v, w.width, w.height)) |
| 10228 | } |
| 10229 | _ => None, |
| 10230 | } |
| 10231 | } |
| 10232 | |
| 10233 | /// The picture `advance` stopped on, as planes and size. |
| 10234 | fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) { |
| 10235 | match &self.seat { |
| 10236 | SwSeat::H264(seat) if seat.deep.on => { |
| 10237 | let n = &seat.deep.narrow; |
| 10238 | (&n.y, &n.u, &n.v, n.width, n.height) |
| 10239 | } |
| 10240 | SwSeat::H264(seat) => { |
| 10241 | let frame = seat.frame.as_ref().expect("advance stored a picture"); |
| 10242 | let [y, u, v] = [&frame.planes[0], &frame.planes[1], &frame.planes[2]]; |
| 10243 | debug_assert_eq!(y.stride, frame.width as usize, "padded luma plane"); |
| 10244 | (&y.data, &u.data, &v.data, frame.width, frame.height) |
| 10245 | } |
| 10246 | SwSeat::Pulled { out, .. } => (&out.y, &out.u, &out.v, out.width, out.height), |
| 10247 | } |
| 10248 | } |
| 10249 | } |
| 10250 | |
| 10251 | /// An AV1 software span: [`decode_av1`] runs on a thread of its own and sends |
| 10252 | /// every picture down a channel two deep, the same shape [`Streamed`] gives a |
| 10253 | /// stream decoded elsewhere. The thread is needed because `ec-av1` pushes its |
| 10254 | /// pictures through a callback rather than handing them out one at a time. |
| 10255 | struct Av1Stream { |
| 10256 | frames: Receiver<crate::Result<Option<Yuv>>>, |
| 10257 | /// Held only to be joined: field order matters, as it does for |
| 10258 | /// [`Streamed`] -- `frames` drops first and wakes a decoder parked in a |
| 10259 | /// full `send`, and the join runs after. |
| 10260 | _thread: DecodeThread, |
| 10261 | /// Whether the thread has said "no more pictures" in as many words. |
| 10262 | ended: bool, |
| 10263 | } |
| 10264 | |
| 10265 | impl Av1Stream { |
| 10266 | fn spawn(demuxer: Demuxer, start_frame: u32, wide: bool) -> crate::Result<Self> { |
| 10267 | let (tx, frames) = sync_channel(2); |
| 10268 | let handle = thread::Builder::new() |
| 10269 | .name("export-decode-av1".into()) |
| 10270 | .spawn(move || decode_av1(demuxer, start_frame, wide, &tx))?; |
| 10271 | Ok(Self { |
| 10272 | frames, |
| 10273 | _thread: DecodeThread(Some(handle)), |
| 10274 | ended: false, |
| 10275 | }) |
| 10276 | } |
| 10277 | |
| 10278 | fn next(&mut self) -> crate::Result<Option<Yuv>> { |
| 10279 | if self.ended { |
| 10280 | return Ok(None); |
| 10281 | } |
| 10282 | match self.frames.recv() { |
| 10283 | Ok(Ok(Some(frame))) => Ok(Some(frame)), |
| 10284 | Ok(Ok(None)) => { |
| 10285 | self.ended = true; |
| 10286 | Ok(None) |
| 10287 | } |
| 10288 | Ok(Err(e)) => Err(e), |
| 10289 | Err(_) => Err("the decoder stopped without a picture or a reason".into()), |
| 10290 | } |
| 10291 | } |
| 10292 | } |
| 10293 | |
| 10294 | /// The chroma plane size `len` samples can be, for a `width` x `height` luma |
| 10295 | /// picture: full (4:4:4), half the width (4:2:2) or a quarter (4:2:0, odd sizes |
| 10296 | /// rounding up). `None` for any other count, which no decoder here produces. |
| 10297 | pub(crate) fn chroma_shape(len: usize, width: usize, height: usize) -> Option<(usize, usize)> { |
| 10298 | let (half_w, half_h) = (width.div_ceil(2), height.div_ceil(2)); |
| 10299 | [(width, height), (half_w, height), (half_w, half_h)] |
| 10300 | .into_iter() |
| 10301 | .find(|&(cw, ch)| cw * ch == len) |
| 10302 | } |
| 10303 | |
| 10304 | /// A chroma plane of `cw` x `ch` samples averaged down to `ow` x `oh`, the |
| 10305 | /// 4:2:0 size of the luma. A dimension that already matches is kept one sample |
| 10306 | /// to one; one that is larger takes the mean of the (at most two) source |
| 10307 | /// samples under each output sample, rounded to nearest. Samples keep the |
| 10308 | /// depth they came in at, so a 10-bit picture averages in 10 bits and |
| 10309 | /// [`crate::decode::narrow_av1`] shifts it as it would any other. |
| 10310 | pub(crate) fn chroma_420<T: Copy + Into<u32>>(src: &[T], cw: usize, ch: usize, ow: usize, oh: usize) -> Vec<u32> { |
| 10311 | // The source run under output index `i` along one axis. |
| 10312 | let run = |src_len: usize, out_len: usize, i: usize| match src_len == out_len { |
| 10313 | true => (i, i + 1), |
| 10314 | false => (2 * i, (2 * i + 2).min(src_len)), |
| 10315 | }; |
| 10316 | let mut out = Vec::with_capacity(ow * oh); |
| 10317 | for oy in 0..oh { |
| 10318 | let (y0, y1) = run(ch, oh, oy); |
| 10319 | for ox in 0..ow { |
| 10320 | let (x0, x1) = run(cw, ow, ox); |
| 10321 | let (mut sum, mut n) = (0u32, 0u32); |
| 10322 | for sy in y0..y1 { |
| 10323 | for sx in x0..x1 { |
| 10324 | sum += src[sy * cw + sx].into(); |
| 10325 | n += 1; |
| 10326 | } |
| 10327 | } |
| 10328 | out.push((sum + n / 2) / n); |
| 10329 | } |
| 10330 | } |
| 10331 | out |
| 10332 | } |
| 10333 | |
| 10334 | /// The AV1 software seat for the export: the same walk `decode::run_av1` makes |
| 10335 | /// for playback, one chunk at a time. `ec-av1` takes a whole OBU stream, so the |
| 10336 | /// demuxer's access units are gathered from one sync sample (a sequence header |
| 10337 | /// leads it) up to the next, and each chunk decodes to its end -- its hidden |
| 10338 | /// frames are references, and the frames they hold back in output order are |
| 10339 | /// the tail. Shown pictures before `start_frame` are decoded and dropped. |
| 10340 | /// |
| 10341 | /// Pictures are narrowed to 8-bit I420 by the same [`narrow_av1`] playback |
| 10342 | /// uses, so an export and a playback of one file hand the encoder the same |
| 10343 | /// planes. A 4:2:2 or 4:4:4 picture has its chroma averaged down to 4:2:0 first |
| 10344 | /// ([`chroma_420`]), since the composer and every software encoder take I420 and |
| 10345 | /// nothing else. A decode refusal ends the span with the error, after the |
| 10346 | /// pictures already sent. |
| 10347 | fn decode_av1( |
| 10348 | mut demuxer: Demuxer, |
| 10349 | start_frame: u32, |
| 10350 | wide: bool, |
| 10351 | tx: &SyncSender<crate::Result<Option<Yuv>>>, |
| 10352 | ) { |
| 10353 | let depth = demuxer.bit_depth(); |
| 10354 | // A monochrome stream states it in its sequence header; see the chroma below. |
| 10355 | let gray = demuxer.chroma() == Some(Chroma::Gray); |
| 10356 | // Decoding restarts at a sync sample; see [`SwDecoder::new`]. |
| 10357 | let mut index = demuxer.seek_to_sync_at_or_before(start_frame); |
| 10358 | let mut pending: Option<Vec<u8>> = None; |
| 10359 | let mut demux_dry = false; |
| 10360 | loop { |
| 10361 | // One chunk: the access units from a sync sample up to the next one. |
| 10362 | let mut stream = pending.take().unwrap_or_default(); |
| 10363 | while !demux_dry && pending.is_none() { |
| 10364 | match demuxer.next_access_unit() { |
| 10365 | Ok(Some(au)) => { |
| 10366 | if !stream.is_empty() && crate::decode::leads_with_sequence_header(&au) { |
| 10367 | pending = Some(au); |
| 10368 | } else { |
| 10369 | stream.extend_from_slice(&au); |
| 10370 | } |
| 10371 | } |
| 10372 | Ok(None) => demux_dry = true, |
| 10373 | Err(e) => { |
| 10374 | let _ = tx.send(Err(e)); |
| 10375 | return; |
| 10376 | } |
| 10377 | } |
| 10378 | } |
| 10379 | if stream.is_empty() { |
| 10380 | let _ = tx.send(Ok(None)); |
| 10381 | return; |
| 10382 | } |
| 10383 | // Set by the sink when the consumer is gone, or when a picture is |
| 10384 | // refused; `Eof` is the sentinel that stops the chunk's decode there. |
| 10385 | let mut gone = false; |
| 10386 | let mut refused = None; |
| 10387 | let decode = decode_stream_with(&stream, |picture, _, shown| { |
| 10388 | if !shown { |
| 10389 | return Ok(()); |
| 10390 | } |
| 10391 | let due = index; |
| 10392 | index += 1; |
| 10393 | if due < i64::from(start_frame) { |
| 10394 | return Ok(()); |
| 10395 | } |
| 10396 | let (w, h) = (picture.width, picture.height); |
| 10397 | let (ow, oh) = (w.div_ceil(2), h.div_ceil(2)); |
| 10398 | // 4:2:2 and 4:4:4 pictures are averaged down to the 4:2:0 the |
| 10399 | // composer and every software encoder take ([`chroma_420`]). A |
| 10400 | // monochrome stream carries no chroma, and the decoder hands back |
| 10401 | // zeros in its place: the neutral grey is written instead, at the |
| 10402 | // depth the samples are held in (512 for 10-bit). |
| 10403 | let Some((cw, ch)) = chroma_shape(picture.u.len(), w, h) else { |
| 10404 | refused = Some(format!( |
| 10405 | "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", |
| 10406 | picture.u.len() |
| 10407 | )); |
| 10408 | return Err(Av1Error::Eof); |
| 10409 | }; |
| 10410 | let half = if gray { |
| 10411 | let mid = 1u16 << (depth - 1); |
| 10412 | Some(Av1Picture { |
| 10413 | width: w, |
| 10414 | height: h, |
| 10415 | y: picture.y.clone(), |
| 10416 | u: vec![mid; ow * oh], |
| 10417 | v: vec![mid; ow * oh], |
| 10418 | }) |
| 10419 | } else if (cw, ch) != (ow, oh) { |
| 10420 | let down = |plane: &[u16]| -> Vec<u16> { |
| 10421 | chroma_420(plane, cw, ch, ow, oh) |
| 10422 | .into_iter() |
| 10423 | .map(|s| s as u16) |
| 10424 | .collect() |
| 10425 | }; |
| 10426 | Some(Av1Picture { |
| 10427 | width: w, |
| 10428 | height: h, |
| 10429 | y: picture.y.clone(), |
| 10430 | u: down(&picture.u), |
| 10431 | v: down(&picture.v), |
| 10432 | }) |
| 10433 | } else { |
| 10434 | None |
| 10435 | }; |
| 10436 | let src = half.as_ref().unwrap_or(picture); |
| 10437 | let frame = if wide { |
| 10438 | // At 10-bit scale: a 10-bit stream's samples are there already, an |
| 10439 | // 8-bit one (in a 10-bit export) is shifted up by two. |
| 10440 | // A 12-bit one is rounded down by two. |
| 10441 | let plane = |s: &[u16]| -> Vec<u16> { |
| 10442 | s.iter() |
| 10443 | .map(|&x| match depth { |
| 10444 | ..=9 => x << (10 - depth), |
| 10445 | 10 => x, |
| 10446 | _ => ((x + (1 << (depth - 11))) >> (depth - 10)).min(1023), |
| 10447 | }) |
| 10448 | .collect() |
| 10449 | }; |
| 10450 | Yuv::Wide { |
| 10451 | y: plane(&src.y), |
| 10452 | u: plane(&src.u), |
| 10453 | v: plane(&src.v), |
| 10454 | width: w as u32, |
| 10455 | height: h as u32, |
| 10456 | } |
| 10457 | } else { |
| 10458 | let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new()); |
| 10459 | crate::decode::narrow_av1(src, depth, &mut y, &mut u, &mut v); |
| 10460 | Yuv::Pixels { |
| 10461 | y, |
| 10462 | u, |
| 10463 | v, |
| 10464 | width: w as u32, |
| 10465 | height: h as u32, |
| 10466 | } |
| 10467 | }; |
| 10468 | if tx.send(Ok(Some(frame))).is_err() { |
| 10469 | gone = true; |
| 10470 | return Err(Av1Error::Eof); |
| 10471 | } |
| 10472 | Ok(()) |
| 10473 | }); |
| 10474 | if gone { |
| 10475 | return; |
| 10476 | } |
| 10477 | if let Some(msg) = refused { |
| 10478 | let _ = tx.send(Err(msg.into())); |
| 10479 | return; |
| 10480 | } |
| 10481 | if let Err(e) = decode { |
| 10482 | let msg = format!("software AV1 decode failed at picture {index}: {e}"); |
| 10483 | let _ = tx.send(Err(msg.into())); |
| 10484 | return; |
| 10485 | } |
| 10486 | } |
| 10487 | } |
| 10488 | |
| 10489 | impl SwDecoder { |
| 10490 | /// The H.264 seat over an opened demuxer. Decoding restarts at a sync |
| 10491 | /// sample, so pictures between it and the in point are decoded (the target |
| 10492 | /// references them) and then dropped. |
| 10493 | fn new(mut demuxer: Demuxer, start_frame: u32, wide: bool, deint: Deinterlace) -> Self { |
| 10494 | let seat = SwSeat::H264(H264Seat::open(&mut demuxer, start_frame, wide, deint)); |
| 10495 | Self { |
| 10496 | demuxer, |
| 10497 | start: start_frame, |
| 10498 | seat, |
| 10499 | } |
| 10500 | } |
| 10501 | |
| 10502 | /// Whether this decoder can be parked for a later span: only the H.264 seat |
| 10503 | /// has a display index to resume from, so the pulled seats never are. |
| 10504 | fn parkable(&self) -> bool { |
| 10505 | // An interlaced seat holds a picture back for its successor, so it has |
| 10506 | // no display index a later span could resume from. |
| 10507 | matches!(&self.seat, SwSeat::H264(s) if !s.deint.is_interlaced()) |
| 10508 | } |
| 10509 | |
| 10510 | /// The display index the seat's next picture will carry; `0` off the H.264 seat. |
| 10511 | fn index(&self) -> i64 { |
| 10512 | match &self.seat { |
| 10513 | SwSeat::H264(seat) => seat.index, |
| 10514 | SwSeat::Pulled { .. } => 0, |
| 10515 | } |
| 10516 | } |
| 10517 | |
| 10518 | /// The display index the seat started at; `0` off the H.264 seat. |
| 10519 | fn origin(&self) -> i64 { |
| 10520 | match &self.seat { |
| 10521 | SwSeat::H264(seat) => seat.origin, |
| 10522 | SwSeat::Pulled { .. } => 0, |
| 10523 | } |
| 10524 | } |
| 10525 | |
| 10526 | /// Set once the demuxer ran dry. Always `true` off the H.264 seat, which is |
| 10527 | /// what keeps a pulled decoder from being parked (see [`SwDecoder::parkable`]). |
| 10528 | fn flushed(&self) -> bool { |
| 10529 | match &self.seat { |
| 10530 | SwSeat::H264(seat) => seat.flushed || seat.deint.is_interlaced(), |
| 10531 | SwSeat::Pulled { .. } => true, |
| 10532 | } |
| 10533 | } |
| 10534 | } |
| 10535 | |
| 10536 | impl H264Seat { |
| 10537 | /// A fresh `ec-h264` seat whose first picture is display index `index`. |
| 10538 | /// |
| 10539 | /// An interlaced stream lands one picture earlier than the in point, so the |
| 10540 | /// deinterlacer has the picture before it, as a sequential decode does. |
| 10541 | fn open(demuxer: &mut Demuxer, start: u32, wide: bool, mode: Deinterlace) -> Box<Self> { |
| 10542 | let deint = crate::deinterlace::Deinterlacer::with_mode( |
| 10543 | mode, |
| 10544 | demuxer.h264_interlaced(), |
| 10545 | i64::from(start), |
| 10546 | ec_core::frame::Interlace::Progressive, |
| 10547 | ) |
| 10548 | .cadenced(mode, demuxer); |
| 10549 | let index = demuxer.seek_to_sync_at_or_before(deint.landing(start)); |
| 10550 | Box::new(Self { |
| 10551 | deint, |
| 10552 | ..*Self::at(index, wide) |
| 10553 | }) |
| 10554 | } |
| 10555 | |
| 10556 | fn at(index: i64, wide: bool) -> Box<Self> { |
| 10557 | Box::new(Self { |
| 10558 | decoder: H264Decoder::new(CodecParameters::new(CodecId::H264)) |
| 10559 | .expect("ec-h264 takes its own codec id"), |
| 10560 | index, |
| 10561 | origin: index, |
| 10562 | flushed: false, |
| 10563 | frame: None, |
| 10564 | wide, |
| 10565 | deep: Default::default(), |
| 10566 | deint: crate::deinterlace::Deinterlacer::new(false, 0, ec_core::frame::Interlace::Progressive), |
| 10567 | pending: VecDeque::new(), |
| 10568 | }) |
| 10569 | } |
| 10570 | |
| 10571 | /// Decodes up to and including the next picture at or after the in point, |
| 10572 | /// leaving it in `frame`. `false` at end of stream. Pictures leave the |
| 10573 | /// decoder in display order -- clause C.4.5.3, the same contract the |
| 10574 | /// playback seat keeps -- so the landing index, itself a display index by |
| 10575 | /// the demuxer's contract, counts one to one with them. |
| 10576 | fn advance(&mut self, demuxer: &mut Demuxer, start: u32) -> crate::Result<bool> { |
| 10577 | loop { |
| 10578 | // The second field of the frame the last call took the first of. |
| 10579 | if let Some((due, pic)) = self.pending.pop_front() { |
| 10580 | if due < i64::from(start) { |
| 10581 | continue; |
| 10582 | } |
| 10583 | self.deep.load(&pic, self.wide); |
| 10584 | self.frame = Some(pic); |
| 10585 | return Ok(true); |
| 10586 | } |
| 10587 | if !self.flushed { |
| 10588 | match demuxer.next_access_unit()? { |
| 10589 | Some(au) => self |
| 10590 | .decoder |
| 10591 | .send_packet(&Packet::new(0, TimeBase::new(1, 1), au)) |
| 10592 | .map_err(|e| format!("decode at picture {}: {e}", self.index))?, |
| 10593 | None => { |
| 10594 | self.flushed = true; |
| 10595 | self.decoder |
| 10596 | .flush() |
| 10597 | .map_err(|e| format!("decode at end of stream: {e}"))?; |
| 10598 | } |
| 10599 | } |
| 10600 | } |
| 10601 | match self.decoder.receive_frame() { |
| 10602 | Ok(frame) => { |
| 10603 | let ec_core::frame::Frame::Video(pic) = frame else { |
| 10604 | continue; |
| 10605 | }; |
| 10606 | let tag = self.index; |
| 10607 | self.index += 1; |
| 10608 | // Held one picture back while the deinterlacer waits for |
| 10609 | // the successor; below the in point it only primes. In |
| 10610 | // field mode it releases two, queued for the loop's top. |
| 10611 | self.pending.extend(self.deint.push_all(tag, pic)); |
| 10612 | } |
| 10613 | // End of stream counts once the flush has happened; before it, |
| 10614 | // either answer means go back for the next access unit. The |
| 10615 | // last picture an interlaced stream held leaves first. |
| 10616 | Err(e) if e.is_eof() && self.flushed => { |
| 10617 | self.pending.extend(self.deint.finish_all()); |
| 10618 | if self.pending.is_empty() { |
| 10619 | return Ok(false); |
| 10620 | } |
| 10621 | } |
| 10622 | Err(e) if e.is_need_more() || e.is_eof() => {} |
| 10623 | Err(e) => return Err(format!("decode at picture {}: {e}", self.index).into()), |
| 10624 | } |
| 10625 | } |
| 10626 | } |
| 10627 | } |
| 10628 | |
| 10629 | #[cfg(test)] |
| 10630 | mod tests { |
| 10631 | /// A standalone file's soft track is titled with its language's name, or left |
| 10632 | /// untitled, and never with its file name; an embedded track keeps the title |
| 10633 | /// its container gave it. |
| 10634 | #[test] |
| 10635 | fn a_soft_track_is_titled_by_its_language_never_its_file_name() { |
| 10636 | let file = |language: &str| SubtitleTrack { |
| 10637 | path: "/media/talk.fr.srt".into(), |
| 10638 | track: None, |
| 10639 | language: language.into(), |
| 10640 | name: String::new(), |
| 10641 | label: "talk.fr.srt".into(), |
| 10642 | cues: Vec::new(), |
| 10643 | bitmap: false, |
| 10644 | refused: None, |
| 10645 | }; |
| 10646 | assert_eq!(subtitle_title(&file("fra")), "French"); |
| 10647 | assert_eq!(subtitle_title(&file("")), "", "unset: no title, and never the file name"); |
| 10648 | let embedded = SubtitleTrack { |
| 10649 | track: Some(3), |
| 10650 | name: "Signs".into(), |
| 10651 | ..file("fra") |
| 10652 | }; |
| 10653 | assert_eq!(subtitle_title(&embedded), "Signs"); |
| 10654 | } |
| 10655 | |
| 10656 | /// Two caption lanes, one per palette track: a pick list names the lanes it |
| 10657 | /// keeps, and an empty one keeps them all -- in the plan and in the file. |
| 10658 | #[test] |
| 10659 | fn a_pick_list_keeps_only_the_lanes_it_names() { |
| 10660 | use crate::project::{LaneKind, SubClip}; |
| 10661 | let track = |label: &str, text: &str| SubtitleTrack { |
| 10662 | path: "/nonexistent/film.mkv".into(), |
| 10663 | track: Some(1), |
| 10664 | language: "eng".into(), |
| 10665 | name: label.into(), |
| 10666 | label: label.into(), |
| 10667 | bitmap: false, |
| 10668 | cues: vec![Cue { |
| 10669 | start_us: 0, |
| 10670 | end_us: 1_000_000, |
| 10671 | text: text.into(), |
| 10672 | image: None, |
| 10673 | words: Vec::new(), |
| 10674 | karaoke: Vec::new(), |
| 10675 | }], |
| 10676 | refused: None, |
| 10677 | }; |
| 10678 | let mut project = Project::single("/nonexistent/a.mp4", 150) |
| 10679 | .with_subtitles(vec![track("one", "first words"), track("two", "second words")]); |
| 10680 | for track in 0..2 { |
| 10681 | let lane = project.add_lane(LaneKind::Subtitle); |
| 10682 | project |
| 10683 | .place_sub( |
| 10684 | lane, |
| 10685 | 0, |
| 10686 | SubClip { |
| 10687 | start: 0, |
| 10688 | frames: 150, |
| 10689 | track, |
| 10690 | in_us: 0, |
| 10691 | out_us: 1_000_000, |
| 10692 | link: None, |
| 10693 | }, |
| 10694 | ) |
| 10695 | .expect("an empty lane takes the placement"); |
| 10696 | } |
| 10697 | let names = |subs: &[SubParams]| subs.iter().map(|s| s.name.clone()).collect::<Vec<_>>(); |
| 10698 | |
| 10699 | let only_zero = lane_subtitles(&project, 30.0, None, &[0]); |
| 10700 | assert_eq!(names(&only_zero), ["one"], "pick [0] keeps track 0's lane alone"); |
| 10701 | assert_eq!(only_zero[0].cues[0].text, "first words"); |
| 10702 | |
| 10703 | let all = lane_subtitles(&project, 30.0, None, &[]); |
| 10704 | assert_eq!(names(&all), ["one", "two"], "an empty pick list keeps every lane"); |
| 10705 | |
| 10706 | let plan = planned_subtitles(&project, Format::Mp4, [0]); |
| 10707 | assert!(plan.contains("S1 one") && !plan.contains("two"), "plan: {plan}"); |
| 10708 | let plan = planned_subtitles(&project, Format::Mp4, Vec::<usize>::new()); |
| 10709 | assert!(plan.contains("S1 one") && plan.contains("S2 two"), "plan: {plan}"); |
| 10710 | } |
| 10711 | |
| 10712 | /// Four palette tracks, lanes S1 and S2 holding tracks 0 and 2: the file writes the tracks in |
| 10713 | /// the order the caller gave them, placed or not, and the card names them in that order. |
| 10714 | #[test] |
| 10715 | fn soft_tracks_are_written_in_the_order_the_caller_gave() { |
| 10716 | use crate::project::{LaneKind, SubClip}; |
| 10717 | let track = |label: &str| SubtitleTrack { |
| 10718 | path: "/nonexistent/film.srt".into(), |
| 10719 | track: None, |
| 10720 | language: "eng".into(), |
| 10721 | name: label.into(), |
| 10722 | label: label.into(), |
| 10723 | bitmap: false, |
| 10724 | cues: vec![Cue { |
| 10725 | start_us: 0, |
| 10726 | end_us: 1_000_000, |
| 10727 | text: format!("{label} words"), |
| 10728 | image: None, |
| 10729 | words: Vec::new(), |
| 10730 | karaoke: Vec::new(), |
| 10731 | }], |
| 10732 | refused: None, |
| 10733 | }; |
| 10734 | let mut project = Project::single("/nonexistent/a.mp4", 150) |
| 10735 | .with_subtitles(vec![track("one"), track("two"), track("three"), track("four")]); |
| 10736 | for track in [0, 2] { |
| 10737 | let lane = project.add_lane(LaneKind::Subtitle); |
| 10738 | project |
| 10739 | .place_sub( |
| 10740 | lane, |
| 10741 | 0, |
| 10742 | SubClip { |
| 10743 | start: 0, |
| 10744 | frames: 150, |
| 10745 | track, |
| 10746 | in_us: 0, |
| 10747 | out_us: 1_000_000, |
| 10748 | link: None, |
| 10749 | }, |
| 10750 | ) |
| 10751 | .expect("an empty lane takes the placement"); |
| 10752 | } |
| 10753 | let lanes = project.subtitle_lanes(); |
| 10754 | let (s1, s2) = (lanes[0], lanes[1]); |
| 10755 | |
| 10756 | assert_eq!(soft_order(&project, &lanes, &[2, 0]), [SoftEntry::Lane(s2), SoftEntry::Lane(s1)]); |
| 10757 | assert_eq!(soft_order(&project, &lanes, &[0, 2]), [SoftEntry::Lane(s1), SoftEntry::Lane(s2)]); |
| 10758 | assert_eq!(soft_order(&project, &lanes, &[3, 1]), [SoftEntry::Track(3), SoftEntry::Track(1)]); |
| 10759 | assert_eq!(soft_order(&project, &lanes, &[]), [SoftEntry::Lane(s1), SoftEntry::Lane(s2)]); |
| 10760 | |
| 10761 | let plan = planned_subtitles(&project, Format::Mp4, [2, 0]); |
| 10762 | assert!(plan.contains("2 lanes → embedded (S2 three, S1 one)"), "plan: {plan}"); |
| 10763 | let plan = planned_subtitles(&project, Format::Mp4, [3, 1]); |
| 10764 | assert!(plan.contains("2 tracks → embedded (four, two)"), "plan: {plan}"); |
| 10765 | let plan = planned_subtitles(&project, Format::Mp4, [3, 2, 1, 0]); |
| 10766 | assert!(plan.contains("4 tracks → embedded (four, S2 three, two, S1 one)"), "plan: {plan}"); |
| 10767 | } |
| 10768 | |
| 10769 | /// A ranged file names a track with no cue inside the range as dropped, and carries the rest; |
| 10770 | /// a standalone ASS script with override blocks is named as styling the file drops. |
| 10771 | #[test] |
| 10772 | fn a_range_drops_tracks_with_no_cue_in_it_and_ass_styling_is_named() { |
| 10773 | use crate::project::{LaneKind, SubClip}; |
| 10774 | let track = |label: &str, path: &str| SubtitleTrack { |
| 10775 | path: path.into(), |
| 10776 | track: None, |
| 10777 | language: "eng".into(), |
| 10778 | name: label.into(), |
| 10779 | label: label.into(), |
| 10780 | bitmap: false, |
| 10781 | cues: vec![Cue { |
| 10782 | start_us: 0, |
| 10783 | end_us: 1_000_000, |
| 10784 | text: format!("{label} words"), |
| 10785 | image: None, |
| 10786 | words: Vec::new(), |
| 10787 | karaoke: Vec::new(), |
| 10788 | }], |
| 10789 | refused: None, |
| 10790 | }; |
| 10791 | let ass = std::env::temp_dir().join(format!("edith_export_styling_{}.ass", std::process::id())); |
| 10792 | std::fs::write( |
| 10793 | &ass, |
| 10794 | "[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", |
| 10795 | ) |
| 10796 | .expect("a scratch script"); |
| 10797 | let mut project = Project::single("/nonexistent/a.mp4", 150) |
| 10798 | .with_subtitles(vec![track("one", ass.to_str().unwrap()), track("two", "/nonexistent/film.srt")]); |
| 10799 | for t in 0..2 { |
| 10800 | let lane = project.add_lane(LaneKind::Subtitle); |
| 10801 | project |
| 10802 | .place_sub( |
| 10803 | lane, |
| 10804 | 0, |
| 10805 | SubClip { |
| 10806 | start: 0, |
| 10807 | frames: 30, |
| 10808 | track: t, |
| 10809 | in_us: 0, |
| 10810 | out_us: 1_000_000, |
| 10811 | link: None, |
| 10812 | }, |
| 10813 | ) |
| 10814 | .expect("an empty lane takes the placement"); |
| 10815 | } |
| 10816 | // Cues sit in the first second (frames 0 to 30 at 30 fps): a range after it has none. |
| 10817 | let late = planned_subtitles_in(&project, Format::Mp4, [0, 1], Some((60, 150)), 30.0); |
| 10818 | assert!(late.contains("S1 one — no cues in range") && late.contains("S2 two — no cues in range"), "plan: {late}"); |
| 10819 | assert!(!late.contains("→ embedded"), "plan: {late}"); |
| 10820 | let early = planned_subtitles_in(&project, Format::Mp4, [0, 1], Some((0, 30)), 30.0); |
| 10821 | assert!(early.contains("2 lanes → embedded (S1 one, S2 two)"), "plan: {early}"); |
| 10822 | |
| 10823 | assert_eq!(stripped_styling(&project, &[0, 1]), ["one"], "the ASS script's override tags"); |
| 10824 | assert!(stripped_styling(&project, &[1]).is_empty(), "a plain SRT has no styling to drop"); |
| 10825 | let _ = std::fs::remove_file(&ass); |
| 10826 | } |
| 10827 | |
| 10828 | #[test] |
| 10829 | fn fit_picture_clips_sets_every_picture_clip_on_the_copy() { |
| 10830 | let mut p = Project::single("/nonexistent/a.mp4", 90); |
| 10831 | let before = p.lane(Lane::V1)[0].fit; |
| 10832 | assert_eq!(before, FitPolicy::Fit, "a clip starts on its own default"); |
| 10833 | assert_eq!( |
| 10834 | fit_picture_clips(&mut p, FitPolicy::Fill), |
| 10835 | FitOutcome { lanes: vec![(Lane::V1, 1)], overlays: 0 }, |
| 10836 | "one picture clip" |
| 10837 | ); |
| 10838 | assert_eq!(p.lane(Lane::V1)[0].fit, FitPolicy::Fill); |
| 10839 | assert_eq!(p.fit_of(Lane::V1, 0), FitPolicy::Fill); |
| 10840 | } |
| 10841 | |
| 10842 | /// The I+P seat's automatic quality is its own default, not the intra |
| 10843 | /// seat's mapping: at 1080p30 the intra mapping clamps to QP 40 and the |
| 10844 | /// GOP seat must name QP 28 instead. |
| 10845 | #[test] |
| 10846 | fn the_gop_default_is_not_the_intra_seats_clamped_qp() { |
| 10847 | let m = meta(1920, 1080); |
| 10848 | let auto = ExportSettings { format: Format::HevcMp4, ..Default::default() }; |
| 10849 | assert_eq!(hevc_qp(&m, &auto), 40, "the intra mapping clamps at 1080p30"); |
| 10850 | assert_eq!( |
| 10851 | hevc_mode_words(&m, &auto), |
| 10852 | Some("I+P GOP (1 s keyframes), constant quality QP 28; pass bitrate_kbps for a fixed rate".to_string()) |
| 10853 | ); |
| 10854 | } |
| 10855 | |
| 10856 | #[test] |
| 10857 | fn hevc_and_av1_words_name_the_quality_or_the_rate() { |
| 10858 | let m = meta(1920, 1080); |
| 10859 | let auto = |format| ExportSettings { format, ..Default::default() }; |
| 10860 | let fixed = |format| ExportSettings { format, bitrate: Some(4_000_000), ..Default::default() }; |
| 10861 | // With no bitrate the HEVC row is constant QP: the number is the one the encoder is given. |
| 10862 | assert_eq!( |
| 10863 | hevc_mode_words(&m, &auto(Format::HevcMp4)), |
| 10864 | Some(format!("I+P GOP (1 s keyframes), constant quality QP {HEVC_GOP_QP}; pass bitrate_kbps for a fixed rate")) |
| 10865 | ); |
| 10866 | assert_eq!( |
| 10867 | hevc_mode_words(&m, &fixed(Format::HevcMp4)), |
| 10868 | Some("I+P GOP (1 s keyframes), 4 Mb/s".to_string()) |
| 10869 | ); |
| 10870 | assert_eq!(hevc_mode_words(&m, &auto(Format::Mp4)), None, "not an HEVC format"); |
| 10871 | // AV1 is coded at a bitrate: the automatic one is named as the target it is. |
| 10872 | let target = av1_mode_words(&m, &auto(Format::Av1)).expect("an AV1 format"); |
| 10873 | assert!(target.starts_with("average bitrate ") && target.contains("pass bitrate_kbps"), "{target}"); |
| 10874 | assert_eq!(av1_mode_words(&m, &fixed(Format::Av1Mp4)), Some("average bitrate 4 Mb/s".to_string())); |
| 10875 | assert_eq!(rate_words(6220), "6.2 Mb/s"); |
| 10876 | assert_eq!(rate_words(850), "850 kb/s"); |
| 10877 | assert_eq!(av1_mode_words(&m, &auto(Format::HevcMp4)), None, "not an AV1 format"); |
| 10878 | } |
| 10879 | |
| 10880 | #[test] |
| 10881 | fn fit_picture_clips_leaves_a_transformed_overlay_on_its_own_fit() { |
| 10882 | use crate::transform::TransformParams; |
| 10883 | let mut p = Project::single("/nonexistent/a.mp4", 90); |
| 10884 | let v2 = Lane::new(LaneKind::Video, 1); |
| 10885 | assert_eq!(p.add_lane(LaneKind::Video), v2); |
| 10886 | let logo = p.lane(Lane::V1)[0].clone(); |
| 10887 | assert!(p.place(v2, 0, logo), "a logo on V2"); |
| 10888 | // The logo as the project has it: 0.3 of the canvas width, 80% opaque, moved up and right. |
| 10889 | let placed = TransformParams { pos_x: 0.32, pos_y: -0.32, scale: 0.3, opacity: 0.8, ..Default::default() }; |
| 10890 | assert!(p.set_transform(v2, 0, Some(placed))); |
| 10891 | assert_eq!( |
| 10892 | fit_picture_clips(&mut p, FitPolicy::Fill), |
| 10893 | FitOutcome { lanes: vec![(Lane::V1, 1)], overlays: 1 }, |
| 10894 | "the base picture refits, the overlay does not" |
| 10895 | ); |
| 10896 | assert_eq!(p.fit_of(Lane::V1, 0), FitPolicy::Fill); |
| 10897 | assert_eq!(p.fit_of(v2, 0), FitPolicy::Fit, "the overlay keeps its own fit"); |
| 10898 | assert_eq!(p.transform_of(v2, 0), Some(&placed), "and its placement"); |
| 10899 | |
| 10900 | // An identity transform is not an overlay: it refits like any full-frame clip. |
| 10901 | assert!(p.set_transform(v2, 0, Some(TransformParams::default()))); |
| 10902 | assert_eq!(fit_picture_clips(&mut p, FitPolicy::Fill).overlays, 0); |
| 10903 | assert_eq!(p.fit_of(v2, 0), FitPolicy::Fill); |
| 10904 | } |
| 10905 | |
| 10906 | #[test] |
| 10907 | fn a_caption_and_a_title_clash_only_in_the_same_place_and_on_screen_together() { |
| 10908 | use crate::project::Title; |
| 10909 | use crate::text::TextStyle; |
| 10910 | let cue = |start_s: f64, end_s: f64, text: &str| Cue { |
| 10911 | start_us: (start_s * 1e6) as i64, |
| 10912 | end_us: (end_s * 1e6) as i64, |
| 10913 | text: text.into(), |
| 10914 | image: None, |
| 10915 | words: Vec::new(), |
| 10916 | karaoke: Vec::new(), |
| 10917 | }; |
| 10918 | let title = |start: u32, frames: u32, text: &str, place: Place| Title { |
| 10919 | start, |
| 10920 | frames, |
| 10921 | text: text.into(), |
| 10922 | style: TextStyle { place, ..TextStyle::default() }, |
| 10923 | fade_in: 0, |
| 10924 | fade_out: 0, |
| 10925 | in_anim: Default::default(), |
| 10926 | out_anim: Default::default(), |
| 10927 | anim_frames: 0, |
| 10928 | }; |
| 10929 | // Captions 86.0 to 88.0 s; a bottom title from frame 2163 (86.52 s at 25 fps) for 3 s. |
| 10930 | let cues = [cue(86.0, 88.0, "hello")]; |
| 10931 | let titles = [title(2163, 75, "EVENING, MIRADOURO", Place::Bottom)]; |
| 10932 | let clash = caption_title_clash(&cues, &titles, Place::Bottom, 25.0).expect("same place, on screen together"); |
| 10933 | assert!((clash.0 - 86.52).abs() < 0.01, "the clash starts where both are up: {clash:?}"); |
| 10934 | assert_eq!(clash.1, 0); |
| 10935 | assert_eq!(caption_title_clash(&cues, &titles, Place::Top, 25.0), None, "a top caption clears a bottom title"); |
| 10936 | // The title is up after the captions end: no clash. |
| 10937 | let late = [title(2300, 25, "LATE", Place::Bottom)]; |
| 10938 | assert_eq!(caption_title_clash(&cues, &late, Place::Bottom, 25.0), None, "not on screen together"); |
| 10939 | // A blank cue is no words on the picture. |
| 10940 | let blank = [cue(86.0, 88.0, " ")]; |
| 10941 | assert_eq!(caption_title_clash(&blank, &titles, Place::Bottom, 25.0), None); |
| 10942 | } |
| 10943 | |
| 10944 | #[test] |
| 10945 | fn h264_levels_follow_table_a1() { |
| 10946 | use super::h264_level_idc; |
| 10947 | assert_eq!(h264_level_idc(1280, 720, 30, 1), 31); |
| 10948 | assert_eq!(h264_level_idc(1920, 1080, 30, 1), 40); |
| 10949 | assert_eq!(h264_level_idc(1920, 1080, 60, 1), 42); |
| 10950 | assert_eq!(h264_level_idc(2560, 1440, 30, 1), 50); |
| 10951 | assert_eq!(h264_level_idc(3840, 1608, 24000, 1001), 51); |
| 10952 | assert_eq!(h264_level_idc(3840, 2160, 60, 1), 52); |
| 10953 | assert_eq!(h264_level_idc(640, 360, 30, 1), 30); |
| 10954 | } |
| 10955 | |
| 10956 | use super::*; |
| 10957 | |
| 10958 | /// The bar of a *feature film*: a picture count times a permille is a |
| 10959 | /// product that has to be computed in `u64`, or a timeline past ~4.5 M |
| 10960 | /// pictures (42 hours at 30 fps) overflowed the `u32` this used to be -- |
| 10961 | /// a panic in debug inside the export thread, and a bar that thrashed in |
| 10962 | /// release. Every value here is a fraction of the whole, so none of them |
| 10963 | /// may leave the scale, and the counts straddle the old overflow point. |
| 10964 | #[test] |
| 10965 | fn a_films_frame_count_does_not_overflow_the_bar() { |
| 10966 | // The straddle, in the very product the old shape computed: `boundary` |
| 10967 | // is the largest picture count whose `done * band` still fitted a |
| 10968 | // `u32`, and one more is where it began to wrap -- a panic in debug, |
| 10969 | // inside the export thread. |
| 10970 | let band = u64::from(PROGRESS_SCALE - AUDIO_BAND); |
| 10971 | let boundary = u64::from(u32::MAX) / band; |
| 10972 | assert!(boundary * band <= u64::from(u32::MAX)); |
| 10973 | assert!((boundary + 1) * band > u64::from(u32::MAX)); |
| 10974 | for total in [boundary as u32 + 1, 21_600_000, u32::MAX] { |
| 10975 | assert_eq!(picture_progress(total, total), PROGRESS_SCALE, "{total}"); |
| 10976 | assert_eq!(picture_progress(0, total), AUDIO_BAND, "{total}"); |
| 10977 | let half = picture_progress(total / 2, total); |
| 10978 | assert!( |
| 10979 | (AUDIO_BAND..PROGRESS_SCALE).contains(&half), |
| 10980 | "half of {total} is {half}" |
| 10981 | ); |
| 10982 | assert!( |
| 10983 | picture_progress(total - 1, total) <= PROGRESS_SCALE, |
| 10984 | "{total}" |
| 10985 | ); |
| 10986 | } |
| 10987 | } |
| 10988 | |
| 10989 | /// How a decode thread ended is never guessed from the channel being shut. |
| 10990 | /// A source that genuinely ran out says so, and the span ends on it; a |
| 10991 | /// thread that died without a word is a failure, because reading it as end |
| 10992 | /// of stream would truncate the picture and *report the export finished*. |
| 10993 | #[test] |
| 10994 | fn a_decoder_that_dies_without_a_word_is_not_end_of_stream() { |
| 10995 | let streamed = |handle, frames| { |
| 10996 | ClipDecoder::Streamed(Streamed { |
| 10997 | frames, |
| 10998 | _thread: DecodeThread(Some(handle)), |
| 10999 | current: None, |
| 11000 | ended: false, |
| 11001 | park: None, |
| 11002 | }) |
| 11003 | }; |
| 11004 | |
| 11005 | let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2); |
| 11006 | // Said its piece, then finished: the span walks on to its next clip. |
| 11007 | let handle = thread::spawn(move || { |
| 11008 | tx.send(Ok(None)).expect("the receiver is alive"); |
| 11009 | None |
| 11010 | }); |
| 11011 | let mut ended = streamed(handle, frames); |
| 11012 | assert!(ended.next().expect("a clean end is not an error").is_none()); |
| 11013 | // ...and asking again is the same answer and not a disconnect error. |
| 11014 | assert!(ended.next().expect("still not an error").is_none()); |
| 11015 | |
| 11016 | let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2); |
| 11017 | // Died holding the sender: the channel shuts with nothing said. |
| 11018 | let handle = thread::spawn(move || { |
| 11019 | let _tx = tx; |
| 11020 | panic!("decoder died"); |
| 11021 | }); |
| 11022 | let mut died = streamed(handle, frames); |
| 11023 | let Err(e) = died.next() else { |
| 11024 | panic!("a silent death must fail the export, not end the clip") |
| 11025 | }; |
| 11026 | assert!( |
| 11027 | e.to_string().contains("without a picture or a reason"), |
| 11028 | "{e}" |
| 11029 | ); |
| 11030 | } |
| 11031 | |
| 11032 | /// When a parked decoder may carry on for a later span. A decoder cannot go |
| 11033 | /// back, so the span must start at or after the first picture it still |
| 11034 | /// holds; and it must have been started at the sync sample a fresh decoder |
| 11035 | /// would seek to, or the pictures after it would not be the fresh ones. |
| 11036 | #[test] |
| 11037 | fn a_parked_decoder_resumes_only_where_a_fresh_one_would_match() { |
| 11038 | // Stopped at display 330 with two decoded pictures unclaimed (328 and |
| 11039 | // 329), started at the sync sample 250. |
| 11040 | let stopped = |start| resumable(330, 2, 250, 250, start); |
| 11041 | assert!(stopped(328), "the first held picture is the span's first"); |
| 11042 | assert!(stopped(329), "the second held picture is the span's first"); |
| 11043 | assert!(stopped(330), "the span starts where the decoder stopped"); |
| 11044 | assert!(stopped(400), "a span further on decodes on to its picture"); |
| 11045 | assert!(!stopped(327), "a span before what is held needs a restart"); |
| 11046 | // Nothing unclaimed: the decoder's own position is the first picture. |
| 11047 | assert!(resumable(330, 0, 250, 250, 330)); |
| 11048 | assert!(!resumable(330, 0, 250, 250, 329)); |
| 11049 | // A fresh decoder for the span would seek to a later sync sample than |
| 11050 | // the one this decoder started at, so this one is not the same decode. |
| 11051 | assert!(!resumable(330, 2, 250, 300, 400)); |
| 11052 | // And one that started at a later sync sample than a fresh one would |
| 11053 | // is not the same decode either. |
| 11054 | assert!(!resumable(330, 2, 300, 250, 330)); |
| 11055 | } |
| 11056 | |
| 11057 | /// Three seconds of two tones, one per channel, interleaved: enough shape |
| 11058 | /// that a correlation says something and enough length that the encoder |
| 11059 | /// settles into a mode. |
| 11060 | fn two_tones(secs: usize) -> Vec<f32> { |
| 11061 | (0..OPUS_RATE as usize * secs) |
| 11062 | .flat_map(|i| { |
| 11063 | let t = i as f32 / OPUS_RATE as f32; |
| 11064 | let tau = std::f32::consts::TAU; |
| 11065 | [ |
| 11066 | 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin(), |
| 11067 | 0.25 * (tau * 880.0 * t).sin(), |
| 11068 | ] |
| 11069 | }) |
| 11070 | .collect() |
| 11071 | } |
| 11072 | |
| 11073 | /// Three seconds of the same two tones summed onto one channel: the mono |
| 11074 | /// mix `opus-rs 0.1.26` mis-encoded at every rate, which is why a mono |
| 11075 | /// export kept the AAC path until `ec-opus` took the seat. |
| 11076 | fn mono_tones(secs: usize) -> Vec<f32> { |
| 11077 | (0..OPUS_RATE as usize * secs) |
| 11078 | .map(|i| { |
| 11079 | let t = i as f32 / OPUS_RATE as f32; |
| 11080 | let tau = std::f32::consts::TAU; |
| 11081 | 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin() |
| 11082 | }) |
| 11083 | .collect() |
| 11084 | } |
| 11085 | |
| 11086 | /// The best correlation of one channel of `got` against `want`, and the |
| 11087 | /// offset it sat at. `stride` is the interleave width: 2 for the stereo |
| 11088 | /// fixtures, 1 for mono. |
| 11089 | fn align(want: &[f32], got: &[f32], stride: usize) -> (f64, usize) { |
| 11090 | let (mut best, mut at) = (-2.0, 0); |
| 11091 | let window = OPUS_RATE as usize; |
| 11092 | for lag in 0..1400 { |
| 11093 | let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); |
| 11094 | for (x, y) in want[..window] |
| 11095 | .iter() |
| 11096 | .step_by(stride) |
| 11097 | .zip(got[lag * stride..].iter().step_by(stride)) |
| 11098 | { |
| 11099 | num += f64::from(*x) * f64::from(*y); |
| 11100 | da += f64::from(*x) * f64::from(*x); |
| 11101 | db += f64::from(*y) * f64::from(*y); |
| 11102 | } |
| 11103 | let c = num / (da.sqrt() * db.sqrt()).max(1e-12); |
| 11104 | if c > best { |
| 11105 | (best, at) = (c, lag); |
| 11106 | } |
| 11107 | } |
| 11108 | (best, at) |
| 11109 | } |
| 11110 | |
| 11111 | fn ec_decode(packets: &[crate::AacPacket]) -> Vec<f32> { |
| 11112 | let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]); |
| 11113 | let mut pcm = Vec::new(); |
| 11114 | for packet in packets { |
| 11115 | pcm.extend( |
| 11116 | decoder |
| 11117 | .decode_packet(&packet.bytes) |
| 11118 | .expect("a valid packet"), |
| 11119 | ); |
| 11120 | } |
| 11121 | pcm |
| 11122 | } |
| 11123 | |
| 11124 | /// [`ec_decode`] for a mono packet stream: one stream, no coupling. |
| 11125 | fn ec_decode_mono(packets: &[crate::AacPacket]) -> Vec<f32> { |
| 11126 | let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 0, &[0]); |
| 11127 | let mut pcm = Vec::new(); |
| 11128 | for packet in packets { |
| 11129 | pcm.extend( |
| 11130 | decoder |
| 11131 | .decode_packet(&packet.bytes) |
| 11132 | .expect("a valid packet"), |
| 11133 | ); |
| 11134 | } |
| 11135 | pcm |
| 11136 | } |
| 11137 | |
| 11138 | /// Why [`OPUS_MAX_KBPS`] is a cap, why [`OPUS_PRE_SKIP`] is a constant and |
| 11139 | /// why [`opus_fidelity`] exists at all -- all three measured here through |
| 11140 | /// the same decoder door the product reads every Opus file back with, the |
| 11141 | /// decoder being the witness and the *encoder* the one under test. |
| 11142 | /// |
| 11143 | /// The second half pins the two failures the seat's move here fixed: under |
| 11144 | /// `opus-rs 0.1.26` the encoder wrote stereo packets that only its own |
| 11145 | /// decoder read back above roughly 165 kbps (fidelity 0.06 at 256), and it |
| 11146 | /// mis-encoded mono at every rate -- which is what the old 128 cap and the |
| 11147 | /// mono-mix-keeps-AAC rule stood on. Both asserts are survival now, and a |
| 11148 | /// regression fails here, loudly: that is the signal to lower |
| 11149 | /// [`OPUS_MAX_KBPS`] again, not a reason to widen it quietly. |
| 11150 | #[test] |
| 11151 | fn the_opus_encoder_is_pinned_to_the_band_it_was_measured_in() { |
| 11152 | let pcm = two_tones(3); |
| 11153 | for kbps in [96, OPUS_MAX_KBPS] { |
| 11154 | let (packets, pre_skip) = encode_opus(&pcm, kbps, 2) |
| 11155 | .expect("the encoder opens") |
| 11156 | .expect("and inside the band it passes its own round trip"); |
| 11157 | assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16); |
| 11158 | assert_eq!( |
| 11159 | packets.len(), |
| 11160 | pcm.len().div_ceil(OPUS_FRAME * 2) + 2, |
| 11161 | "one packet per 20 ms frame, plus the warm-up and the flush" |
| 11162 | ); |
| 11163 | let decoded = ec_decode(&packets); |
| 11164 | let (c, lag) = align(&pcm, &decoded, 2); |
| 11165 | // From the first audible sample, head included -- and the head is |
| 11166 | // why this is 0.98 and not the 0.999 below: the encoder's first |
| 11167 | // audible 20 ms comes out a few dB down (one frame of cold start; |
| 11168 | // a second warm-up frame changes the numbers in no decimal place), |
| 11169 | // so that ramp is stated rather than hidden behind a loose |
| 11170 | // threshold. |
| 11171 | assert!(c >= 0.98, "{kbps} kbps came back at correlation {c:.4}"); |
| 11172 | let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..], 2); |
| 11173 | assert!( |
| 11174 | settled >= 0.999, |
| 11175 | "{kbps} kbps past the first frame: correlation {settled:.4}" |
| 11176 | ); |
| 11177 | // The whole point of the number in the header: drop exactly that |
| 11178 | // many samples and the sound starts where the timeline says. A lag |
| 11179 | // that is not it is a file that plays late or eats its own head. |
| 11180 | assert_eq!( |
| 11181 | lag, |
| 11182 | usize::from(pre_skip), |
| 11183 | "{kbps} kbps: the declared pre-skip is not where the sound starts" |
| 11184 | ); |
| 11185 | // ...and the tail is all there: the flush frame pushed the last |
| 11186 | // samples out, so what is left after the pre-skip covers the input. |
| 11187 | assert!( |
| 11188 | decoded.len() - usize::from(pre_skip) * 2 >= pcm.len(), |
| 11189 | "{kbps} kbps: the track ends {} samples short of the timeline", |
| 11190 | (pcm.len() + usize::from(pre_skip) * 2 - decoded.len()) / 2 |
| 11191 | ); |
| 11192 | // The gate the export runs before it writes anything, on a track |
| 11193 | // that deserves to pass it. |
| 11194 | let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip), 2); |
| 11195 | assert!( |
| 11196 | fidelity >= OPUS_MIN_FIDELITY, |
| 11197 | "{kbps} kbps scored {fidelity:.4} on its own round trip" |
| 11198 | ); |
| 11199 | } |
| 11200 | |
| 11201 | // Mono, the shape `opus-rs 0.1.26` mis-encoded at every rate and the |
| 11202 | // reason a mono mix kept the AAC path: straight through the same seat, |
| 11203 | // including at the rate where the old encoder was already writing |
| 11204 | // stereo noise, let alone mono. |
| 11205 | let mono = mono_tones(3); |
| 11206 | for kbps in [96, 256] { |
| 11207 | let (packets, pre_skip) = encode_opus(&mono, kbps, 1) |
| 11208 | .expect("the encoder opens") |
| 11209 | .expect("and mono passes its own round trip"); |
| 11210 | assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16); |
| 11211 | let decoded = ec_decode_mono(&packets); |
| 11212 | let (c, lag) = align(&mono, &decoded, 1); |
| 11213 | assert!( |
| 11214 | c >= 0.98, |
| 11215 | "mono at {kbps} kbps came back at correlation {c:.4}" |
| 11216 | ); |
| 11217 | let (settled, _) = align(&mono[OPUS_FRAME..], &decoded[OPUS_FRAME..], 1); |
| 11218 | assert!( |
| 11219 | settled >= 0.999, |
| 11220 | "mono at {kbps} kbps past the first frame: correlation {settled:.4}" |
| 11221 | ); |
| 11222 | assert_eq!( |
| 11223 | lag, |
| 11224 | usize::from(pre_skip), |
| 11225 | "mono at {kbps} kbps: the declared pre-skip is not where the sound starts" |
| 11226 | ); |
| 11227 | assert!( |
| 11228 | decoded.len() - usize::from(pre_skip) >= mono.len(), |
| 11229 | "mono at {kbps} kbps: the track ends {} samples short of the timeline", |
| 11230 | mono.len() + usize::from(pre_skip) - decoded.len() |
| 11231 | ); |
| 11232 | let fidelity = opus_fidelity(&packets, &mono, usize::from(pre_skip), 1); |
| 11233 | assert!( |
| 11234 | fidelity >= OPUS_MIN_FIDELITY, |
| 11235 | "mono at {kbps} kbps scored {fidelity:.4} on its own round trip" |
| 11236 | ); |
| 11237 | } |
| 11238 | } |
| 11239 | |
| 11240 | /// The gate on a track too long to listen to whole: it samples, and the |
| 11241 | /// middle of what it hears is the answer. A track whose sound is *not* what |
| 11242 | /// was encoded fails it; one bad five-second window does not, which is |
| 11243 | /// deliberate and measured ([`opus_fidelity`] carries the distribution: |
| 11244 | /// five windows of a good film's mix score under 0.95, the lowest 0.803). |
| 11245 | /// A silent track is not a failure either, which is what it used to be |
| 11246 | /// scored as -- 0.0 against a denominator of nothing, and an all-quiet |
| 11247 | /// timeline fell back to AAC for it. |
| 11248 | /// |
| 11249 | /// 61 s of sound: one second past the minute the gate stops listening whole, |
| 11250 | /// which is what puts this on the sampled path at all. |
| 11251 | #[test] |
| 11252 | fn a_long_track_is_judged_by_the_middle_of_what_it_samples() { |
| 11253 | let pcm = two_tones(61); |
| 11254 | let (packets, pre_skip) = encode_opus(&pcm, 96, 2) |
| 11255 | .expect("the encoder opens") |
| 11256 | .expect("and passes its own round trip"); |
| 11257 | assert!( |
| 11258 | packets.len() > FIDELITY_WINDOW * FIDELITY_WINDOWS, |
| 11259 | "{} packets is not the sampled path", |
| 11260 | packets.len() |
| 11261 | ); |
| 11262 | let pre_skip = usize::from(pre_skip); |
| 11263 | let whole = opus_fidelity(&packets, &pcm, pre_skip, 2); |
| 11264 | assert!(whole >= OPUS_MIN_FIDELITY, "a good track scored {whole:.4}"); |
| 11265 | |
| 11266 | // One window's worth of the *mix* replaced by its own phase inverse: |
| 11267 | // the packets still decode, they are simply no longer this sound. Placed |
| 11268 | // on a window the gate samples -- window 6 of the twelve, by the same |
| 11269 | // arithmetic the gate spreads them with. The track still passes, and |
| 11270 | // that is the measured decision, not an oversight: this codec really |
| 11271 | // does score 0.80 on five seconds of film it otherwise handles at 0.998. |
| 11272 | let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1); |
| 11273 | let from = (6 * step * OPUS_FRAME).saturating_sub(pre_skip) * 2; |
| 11274 | let mut one_bad = pcm.clone(); |
| 11275 | for sample in &mut one_bad[from..(from + FIDELITY_WINDOW * OPUS_FRAME * 2).min(pcm.len())] { |
| 11276 | *sample = -*sample; |
| 11277 | } |
| 11278 | let dip = opus_fidelity(&packets, &one_bad, pre_skip, 2); |
| 11279 | assert!( |
| 11280 | dip >= OPUS_MIN_FIDELITY, |
| 11281 | "one ruined window sank the whole track ({dip:.4})" |
| 11282 | ); |
| 11283 | |
| 11284 | // ...and the shape the gate is actually for, which is what a rate the |
| 11285 | // encoder cannot hold does: the track is not the mix any more, not one |
| 11286 | // window of it. The middle of the list moves with it. |
| 11287 | let mut ruined = pcm.clone(); |
| 11288 | for sample in &mut ruined[pcm.len() / 4..] { |
| 11289 | *sample = -*sample; |
| 11290 | } |
| 11291 | let ruined = opus_fidelity(&packets, &ruined, pre_skip, 2); |
| 11292 | assert!( |
| 11293 | ruined < OPUS_MIN_FIDELITY, |
| 11294 | "a track that is no longer the mix scored {ruined:.4}" |
| 11295 | ); |
| 11296 | |
| 11297 | // ...and silence is silence: nothing to correlate is not a round trip |
| 11298 | // that failed. Short, because the floor is the same on either path. |
| 11299 | let quiet = vec![0f32; OPUS_RATE as usize * 2 * 2]; |
| 11300 | let (packets, pre_skip) = encode_opus(&quiet, 96, 2) |
| 11301 | .expect("the encoder opens") |
| 11302 | .expect("silence is written as Opus, not sent to AAC"); |
| 11303 | let fidelity = opus_fidelity(&packets, &quiet, usize::from(pre_skip), 2); |
| 11304 | assert!( |
| 11305 | fidelity >= OPUS_MIN_FIDELITY, |
| 11306 | "a silent track scored {fidelity:.4} and would fall back to AAC" |
| 11307 | ); |
| 11308 | } |
| 11309 | |
| 11310 | /// The one rule that keeps a picture from being converted twice: a frame the |
| 11311 | /// tone map has already brought to BT.709 is never handed the 2020 matrix as |
| 11312 | /// well, on either canvas -- and everything else about the remap is |
| 11313 | /// unchanged by the tone map existing. |
| 11314 | #[test] |
| 11315 | fn a_tone_mapped_span_is_never_matrix_remapped_too() { |
| 11316 | let hdr = ColorDescription { |
| 11317 | matrix: Matrix::Bt2020Ncl, |
| 11318 | transfer: Transfer::Pq, |
| 11319 | full_range: false, |
| 11320 | }; |
| 11321 | let sdr = ColorDescription::default(); // BT.601 |
| 11322 | // The (from, to) pair of a remap, which is all these cases are about. |
| 11323 | let pair = |remap: Option<Remap>| remap.map(|r| (r.from, r.to)); |
| 11324 | for out in [Matrix::Bt709, Matrix::Bt601] { |
| 11325 | let toned = pair(remap_into(Some(hdr), true, out)); |
| 11326 | assert!( |
| 11327 | toned.is_none_or(|(from, _)| from == Matrix::Bt709), |
| 11328 | "tone-mapped onto a {out:?} canvas asked for {toned:?}" |
| 11329 | ); |
| 11330 | // Untouched by any of this: the 2020 clip that was *not* tone-mapped |
| 11331 | // (an unreachable state today, and still the matrix answer), the |
| 11332 | // ordinary 601-on-709 reconcile, and a gap. |
| 11333 | assert_eq!( |
| 11334 | pair(remap_into(Some(hdr), false, out)), |
| 11335 | (out != Matrix::Bt2020Ncl).then_some((Matrix::Bt2020Ncl, out)) |
| 11336 | ); |
| 11337 | assert_eq!( |
| 11338 | pair(remap_into(Some(sdr), false, out)), |
| 11339 | (out != Matrix::Bt601).then_some((Matrix::Bt601, out)) |
| 11340 | ); |
| 11341 | assert_eq!(remap_into(None, false, out), None); |
| 11342 | } |
| 11343 | assert_eq!( |
| 11344 | pair(remap_into(Some(hdr), true, Matrix::Bt601)), |
| 11345 | Some((Matrix::Bt709, Matrix::Bt601)), |
| 11346 | "a tone-mapped clip below 720 lines still takes its 709 -> 601 step" |
| 11347 | ); |
| 11348 | } |
| 11349 | |
| 11350 | /// A full-range source is scaled into the limited span before it is matrix |
| 11351 | /// converted, and only an untouched one: a tone-mapped picture is already |
| 11352 | /// limited, and a limited source has nothing to scale. |
| 11353 | #[test] |
| 11354 | fn a_full_range_source_is_limited_before_it_is_remapped() { |
| 11355 | let full = ColorDescription { |
| 11356 | matrix: Matrix::Bt709, |
| 11357 | transfer: Transfer::Sdr, |
| 11358 | full_range: true, |
| 11359 | }; |
| 11360 | let limited = ColorDescription { |
| 11361 | full_range: false, |
| 11362 | ..full |
| 11363 | }; |
| 11364 | assert_eq!( |
| 11365 | remap_into(Some(full), false, Matrix::Bt709), |
| 11366 | Some(Remap { |
| 11367 | from: Matrix::Bt709, |
| 11368 | to: Matrix::Bt709, |
| 11369 | limit: true, |
| 11370 | }), |
| 11371 | "same matrix, but the range still has to come down" |
| 11372 | ); |
| 11373 | assert_eq!(remap_into(Some(limited), false, Matrix::Bt709), None); |
| 11374 | assert_eq!(remap_into(Some(full), true, Matrix::Bt709), None); |
| 11375 | } |
| 11376 | |
| 11377 | /// The picture as [`place_picture`] hands it to the encoder: a full-range |
| 11378 | /// source on a canvas of its own size, so the placement is the identity and |
| 11379 | /// what comes out is exactly the range change. |
| 11380 | #[test] |
| 11381 | fn a_full_range_picture_is_placed_as_limited_codes() { |
| 11382 | let (w, h) = (4u32, 2u32); |
| 11383 | let y = [0u8, 255, 130, 130, 0, 255, 130, 130]; |
| 11384 | let (u, v) = ([0u8, 255], [255u8, 0]); |
| 11385 | let mut canvas = Composer::new(w, h, crate::scale::FitPolicy::default()); |
| 11386 | let (mut turned, mut stretched, mut graded, mut transformed) = ( |
| 11387 | (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()), |
| 11388 | (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()), |
| 11389 | (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()), |
| 11390 | (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()), |
| 11391 | ); |
| 11392 | let remap = Some(Remap { |
| 11393 | from: Matrix::Bt709, |
| 11394 | to: Matrix::Bt709, |
| 11395 | limit: true, |
| 11396 | }); |
| 11397 | let (py, pu, pv, _, _) = place_picture( |
| 11398 | &y, |
| 11399 | &u, |
| 11400 | &v, |
| 11401 | w, |
| 11402 | h, |
| 11403 | Rotation::default(), |
| 11404 | crate::demux::PixelAspect::SQUARE, |
| 11405 | None, |
| 11406 | TransformParams::default(), |
| 11407 | remap, |
| 11408 | None, |
| 11409 | &mut turned, |
| 11410 | &mut stretched, |
| 11411 | &mut graded, |
| 11412 | &mut transformed, |
| 11413 | &mut canvas, |
| 11414 | ); |
| 11415 | assert_eq!(py, [16, 235, 128, 128, 16, 235, 128, 128]); |
| 11416 | assert_eq!(pu, [16, 240]); |
| 11417 | assert_eq!(pv, [240, 16]); |
| 11418 | } |
| 11419 | |
| 11420 | /// A track of three cues, in whichever clock `track` says: `Some(n)` is a |
| 11421 | /// track of the media file, `None` a `.srt` beside it. |
| 11422 | fn subtitles(path: &str, track: Option<u64>) -> SubtitleTrack { |
| 11423 | SubtitleTrack { |
| 11424 | path: path.into(), |
| 11425 | track, |
| 11426 | language: "eng".into(), |
| 11427 | name: String::new(), |
| 11428 | label: "eng".into(), |
| 11429 | bitmap: false, |
| 11430 | cues: vec![ |
| 11431 | Cue { |
| 11432 | start_us: 500_000, |
| 11433 | end_us: 1_500_000, |
| 11434 | text: "first".into(), |
| 11435 | image: None, |
| 11436 | words: Vec::new(), |
| 11437 | karaoke: Vec::new(), |
| 11438 | }, |
| 11439 | Cue { |
| 11440 | start_us: 2_000_000, |
| 11441 | end_us: 3_250_000, |
| 11442 | text: "second".into(), |
| 11443 | image: None, |
| 11444 | words: Vec::new(), |
| 11445 | karaoke: Vec::new(), |
| 11446 | }, |
| 11447 | Cue { |
| 11448 | start_us: 4_000_000, |
| 11449 | end_us: 4_750_000, |
| 11450 | text: "third".into(), |
| 11451 | image: None, |
| 11452 | words: Vec::new(), |
| 11453 | karaoke: Vec::new(), |
| 11454 | }, |
| 11455 | ], |
| 11456 | refused: None, |
| 11457 | } |
| 11458 | } |
| 11459 | |
| 11460 | /// A standalone subtitle file is timed against the timeline itself -- there |
| 11461 | /// is no clip to hang it on -- so a cut moves the pictures and not it. What |
| 11462 | /// it does get is the exported length: a cue past the end of the file would |
| 11463 | /// otherwise be a block after the last picture. |
| 11464 | /// |
| 11465 | /// The pair of this, the embedded clock, is measured against a real exported |
| 11466 | /// file in `tests/export_subs.rs`; both live in one function and this is the |
| 11467 | /// half that needs no encoder. |
| 11468 | #[test] |
| 11469 | fn a_subtitle_file_beside_the_media_keeps_the_timelines_own_clock() { |
| 11470 | // 5 seconds at 30, with `[0.5s, 2.5s)` cut out of it: 3 seconds left. |
| 11471 | let mut project = Project::single("/nonexistent/film.mp4", 150); |
| 11472 | let track = subtitles("/nonexistent/film.srt", None); |
| 11473 | assert!(project.ripple_delete(15, 60)); |
| 11474 | assert_eq!(project.timeline_frames(), 90); |
| 11475 | let cues = timeline_cues(&project, &track, 30.0); |
| 11476 | assert_eq!( |
| 11477 | cues, |
| 11478 | vec![ |
| 11479 | Cue { |
| 11480 | start_us: 500_000, |
| 11481 | end_us: 1_500_000, |
| 11482 | text: "first".into(), |
| 11483 | image: None, |
| 11484 | words: Vec::new(), |
| 11485 | karaoke: Vec::new(), |
| 11486 | }, |
| 11487 | // Clipped to the three seconds the export writes... |
| 11488 | Cue { |
| 11489 | start_us: 2_000_000, |
| 11490 | end_us: 3_000_000, |
| 11491 | text: "second".into(), |
| 11492 | image: None, |
| 11493 | words: Vec::new(), |
| 11494 | karaoke: Vec::new(), |
| 11495 | }, |
| 11496 | // ...and the one wholly past the end is not written at all. |
| 11497 | ] |
| 11498 | ); |
| 11499 | // A track *of a file* the project no longer plays has no span to be |
| 11500 | // carried through either, so it falls back to the same clock rather |
| 11501 | // than exporting nothing. |
| 11502 | let orphan = subtitles("/nonexistent/other.mkv", Some(2)); |
| 11503 | assert_eq!(timeline_cues(&project, &orphan, 30.0).len(), 2); |
| 11504 | } |
| 11505 | |
| 11506 | /// The embedded clock, without an encoder in it: the cut moves the cues with |
| 11507 | /// the pictures, and a cue nothing clipped keeps its own microseconds. |
| 11508 | #[test] |
| 11509 | fn a_track_of_the_media_is_carried_through_the_cut() { |
| 11510 | let mut project = Project::single("/nonexistent/film.mkv", 150); |
| 11511 | let track = subtitles("/nonexistent/film.mkv", Some(2)); |
| 11512 | assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out"); |
| 11513 | let cues = timeline_cues(&project, &track, 30.0); |
| 11514 | assert_eq!( |
| 11515 | cues, |
| 11516 | vec![ |
| 11517 | // The first cue was wholly inside the cut. The second straddled |
| 11518 | // its far edge and kept the 0.75s that is still there... |
| 11519 | Cue { |
| 11520 | start_us: 500_000, |
| 11521 | end_us: 1_250_000, |
| 11522 | text: "second".into(), |
| 11523 | image: None, |
| 11524 | words: Vec::new(), |
| 11525 | karaoke: Vec::new(), |
| 11526 | }, |
| 11527 | // ...and the third simply moves back the two seconds that went. |
| 11528 | Cue { |
| 11529 | start_us: 2_000_000, |
| 11530 | end_us: 2_750_000, |
| 11531 | text: "third".into(), |
| 11532 | image: None, |
| 11533 | words: Vec::new(), |
| 11534 | karaoke: Vec::new(), |
| 11535 | }, |
| 11536 | ] |
| 11537 | ); |
| 11538 | } |
| 11539 | |
| 11540 | #[test] |
| 11541 | fn export_spans_clips_to_the_marked_range_keeping_absolute_start() { |
| 11542 | let project = Project::single("/nonexistent/film.mkv", 150); |
| 11543 | // The whole timeline, unmarked: one span, the source's own length. |
| 11544 | let whole = export_spans(&project, None); |
| 11545 | assert_eq!(whole.len(), 1); |
| 11546 | assert_eq!((whole[0].start, whole[0].len), (0, 150)); |
| 11547 | // A range wholly inside the span: `start` stays the timeline's own |
| 11548 | // coordinate ([`composite_color_at`] needs that), and the length is |
| 11549 | // exactly what the mark asked for. |
| 11550 | let clipped = export_spans(&project, Some((30, 100))); |
| 11551 | assert_eq!(clipped.len(), 1); |
| 11552 | assert_eq!((clipped[0].start, clipped[0].len), (30, 70)); |
| 11553 | // A range past the end of the media clamps to it rather than reading |
| 11554 | // short on the wrong side. |
| 11555 | let past_end = export_spans(&project, Some((100, 500))); |
| 11556 | assert_eq!((past_end[0].start, past_end[0].len), (100, 50)); |
| 11557 | } |
| 11558 | |
| 11559 | #[test] |
| 11560 | fn bitrate_clamps_at_both_ends() { |
| 11561 | let meta = |width, height, frame_rate| VideoMeta { |
| 11562 | width, |
| 11563 | height, |
| 11564 | frame_rate, |
| 11565 | frame_count: 1, |
| 11566 | codec: crate::demux::Codec::H264, |
| 11567 | color: Default::default(), |
| 11568 | matrix_assumed: false, |
| 11569 | rotation: Rotation::None, |
| 11570 | // Square pixels, coded where they are declared: a meta no container |
| 11571 | // wrote, so nothing was read to disagree with it. |
| 11572 | coded_width: width, |
| 11573 | coded_height: height, |
| 11574 | pixel_aspect: crate::demux::PixelAspect::SQUARE, |
| 11575 | }; |
| 11576 | // 1280 * 720 * 30 * 0.1 |
| 11577 | assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); |
| 11578 | assert_eq!(bitrate_for(&meta(320, 240, 30.0)), 230_400, "tiny"); |
| 11579 | assert_eq!( |
| 11580 | bitrate_for(&meta(160, 120, 15.0)), |
| 11581 | MIN_BITRATE, |
| 11582 | "tinier floors" |
| 11583 | ); |
| 11584 | assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge"); |
| 11585 | // A rate somebody typed goes through untouched to its own ceiling, which |
| 11586 | // is above where the derived one stops: the card offers 50 Mbps, and a |
| 11587 | // second clamp here would write a file at a bitrate nobody picked. |
| 11588 | let asked = |bps| { |
| 11589 | bitrate_of( |
| 11590 | &meta(1920, 1080, 30.0), |
| 11591 | &ExportSettings { |
| 11592 | bitrate: Some(bps), |
| 11593 | ..Default::default() |
| 11594 | }, |
| 11595 | ) |
| 11596 | }; |
| 11597 | assert_eq!(asked(50_000_000), 50_000_000, "the card's ceiling travels"); |
| 11598 | assert_eq!(asked(21_000_000), 21_000_000, "past the derived range"); |
| 11599 | assert_eq!(asked(600_000), 600_000, "a sub-Mbps ask travels"); |
| 11600 | assert_eq!(asked(999_000_000), MAX_EXPLICIT_BITRATE, "still bounded"); |
| 11601 | assert_eq!(asked(1), MIN_BITRATE, "and floored"); |
| 11602 | } |
| 11603 | |
| 11604 | /// A clip's fade takes the copy path away, exactly as an equalizer does: |
| 11605 | /// a copied AAC packet cannot carry gain math nobody put in the file. The |
| 11606 | /// bug this guards is [`forces_encode`] gating on `equalized`/`mastered` |
| 11607 | /// but never checking a clip's own `fade_in`/`fade_out` at all -- the |
| 11608 | /// default Web MP4 export then labelled and took the "AAC copy" path for |
| 11609 | /// a project whose picture showed a fade, and the fade never reached the |
| 11610 | /// file. |
| 11611 | #[test] |
| 11612 | fn a_fade_forces_the_audio_to_be_re_encoded() { |
| 11613 | let mut project = Project::single("/nonexistent/film.mp4", 90); |
| 11614 | assert!(!forces_encode(&project, false), "flat, so a copy is fine"); |
| 11615 | assert!(project.set_fade_in( |
| 11616 | crate::project::Lane::new(crate::project::LaneKind::Audio, 0), |
| 11617 | 0, |
| 11618 | 15 |
| 11619 | )); |
| 11620 | assert!( |
| 11621 | forces_encode(&project, false), |
| 11622 | "a fade-in on the only clip must force a re-encode" |
| 11623 | ); |
| 11624 | } |
| 11625 | |
| 11626 | fn meta(width: u32, height: u32) -> VideoMeta { |
| 11627 | VideoMeta { |
| 11628 | width, |
| 11629 | height, |
| 11630 | frame_rate: 30.0, |
| 11631 | frame_count: 1, |
| 11632 | codec: crate::demux::Codec::H264, |
| 11633 | color: Default::default(), |
| 11634 | matrix_assumed: false, |
| 11635 | rotation: Rotation::None, |
| 11636 | // Square pixels, coded where they are declared: a meta no |
| 11637 | // container wrote, so nothing was read to disagree with it. |
| 11638 | coded_width: width, |
| 11639 | coded_height: height, |
| 11640 | pixel_aspect: crate::demux::PixelAspect::SQUARE, |
| 11641 | } |
| 11642 | } |
| 11643 | |
| 11644 | /// The bitrate row a user picked, read as the quality tier it is: a higher |
| 11645 | /// row is a lower QP, the band is honoured at both ends, and the same |
| 11646 | /// picture at the same rate gets the same number whatever its size (the |
| 11647 | /// mapping is bits per *pixel*, which is what makes 720p and 1080p one |
| 11648 | /// table). |
| 11649 | #[test] |
| 11650 | fn the_quality_rows_map_onto_quantisers_that_only_go_one_way() { |
| 11651 | let at = |width, height, mbps: Option<u64>| { |
| 11652 | hevc_qp( |
| 11653 | &meta(width, height), |
| 11654 | &ExportSettings { |
| 11655 | bitrate: mbps.map(|m| m * 1_000_000), |
| 11656 | ..Default::default() |
| 11657 | }, |
| 11658 | ) |
| 11659 | }; |
| 11660 | // 20 Mbps at 1080p30 is 0.32 bits a pixel against the 0.6 measured at |
| 11661 | // QP 27, which is just over half: five QP up, and QP is not an |
| 11662 | // arithmetic scale, so this is the number the formula gives. |
| 11663 | assert_eq!(at(1920, 1080, Some(20)), 32); |
| 11664 | // Every step down the card is a step up in QP, never sideways. |
| 11665 | let rows: Vec<i32> = [20, 12, 8, 4, 2, 1] |
| 11666 | .into_iter() |
| 11667 | .map(|mbps| at(1920, 1080, Some(mbps))) |
| 11668 | .collect(); |
| 11669 | assert!( |
| 11670 | rows.windows(2).all(|w| w[0] <= w[1]), |
| 11671 | "a lower bitrate row must never code at a lower QP: {rows:?}" |
| 11672 | ); |
| 11673 | assert_eq!(*rows.last().unwrap(), HEVC_QP_MAX, "the floor is clamped"); |
| 11674 | // ...and the top of the range is the clamp, not an unbounded number: 20 |
| 11675 | // Mbps at 320x240 is 8.7 bits a pixel, which no picture needs. |
| 11676 | assert_eq!(at(320, 240, Some(20)), HEVC_QP_MIN); |
| 11677 | // The same bits per pixel is the same quantiser at any size: 1080p at |
| 11678 | // 20 Mbps and 720p at 8.9 Mbps are one picture quality. |
| 11679 | assert_eq!(at(1920, 1080, Some(20)), at(1280, 720, Some(9))); |
| 11680 | // The automatic bitrate is 0.1 bpp at every size, so it is one QP |
| 11681 | // everywhere -- the honest end of "intra-only, large files": the file |
| 11682 | // will be bigger than the row says, and the row buys quality. |
| 11683 | assert_eq!(at(1920, 1080, None), at(1280, 720, None)); |
| 11684 | } |
| 11685 | |
| 11686 | /// An odd picture cannot be cropped back to itself in 4:2:0 -- the |
| 11687 | /// conformance window is stated in chroma samples -- so it is refused by |
| 11688 | /// name rather than written a column wider than the timeline. |
| 11689 | #[test] |
| 11690 | fn an_odd_picture_is_refused_an_hevc_export_by_name() { |
| 11691 | let settings = ExportSettings { |
| 11692 | format: Format::Hevc, |
| 11693 | ..Default::default() |
| 11694 | }; |
| 11695 | let refused = Enc::open(&meta(1919, 1080), &settings, false, ColorDescription::default()) |
| 11696 | .err() |
| 11697 | .expect("an odd width has no chroma plane") |
| 11698 | .to_string(); |
| 11699 | assert!(refused.contains("1919x1080"), "{refused}"); |
| 11700 | assert!(refused.contains("even"), "{refused}"); |
| 11701 | // ...and the even one it neighbours opens. |
| 11702 | assert!(Enc::open(&meta(1920, 1080), &settings, false, ColorDescription::default()).is_ok()); |
| 11703 | } |
| 11704 | |
| 11705 | /// H.264 codes 16x16 macroblocks and ec-h264's floor is the macroblock |
| 11706 | /// itself -- the old encoder took any positive even size -- so a |
| 11707 | /// sub-macroblock picture is refused by name, like every other seat |
| 11708 | /// refusal, rather than surfaced from inside a running export. |
| 11709 | #[test] |
| 11710 | fn a_sub_macroblock_picture_is_refused_an_h264_export_by_name() { |
| 11711 | let settings = ExportSettings { |
| 11712 | format: Format::Mp4, |
| 11713 | seat: EncoderSeat::Software, |
| 11714 | ..Default::default() |
| 11715 | }; |
| 11716 | let refused = Enc::open(&meta(8, 8), &settings, false, ColorDescription::default()) |
| 11717 | .err() |
| 11718 | .expect("8x8 is smaller than one macroblock") |
| 11719 | .to_string(); |
| 11720 | assert!(refused.contains("8x8"), "{refused}"); |
| 11721 | assert!(refused.contains("16x16"), "{refused}"); |
| 11722 | } |
| 11723 | |
| 11724 | /// Weights ramp from just above 0 to just below 1 and never touch either |
| 11725 | /// end -- the frame *after* the window is where a viewer would see plain |
| 11726 | /// B, and the window itself never quite repeats a hard cut's own instant. |
| 11727 | #[test] |
| 11728 | fn dissolve_weight_ramps_strictly_between_zero_and_one() { |
| 11729 | assert_eq!( |
| 11730 | dissolve_weight(0, 1), |
| 11731 | 0.5, |
| 11732 | "a one-frame window is the midpoint" |
| 11733 | ); |
| 11734 | assert_eq!(dissolve_weight(0, 4), 0.2); |
| 11735 | assert_eq!(dissolve_weight(1, 4), 0.4); |
| 11736 | assert_eq!(dissolve_weight(2, 4), 0.6); |
| 11737 | assert_eq!(dissolve_weight(3, 4), 0.8); |
| 11738 | } |
| 11739 | |
| 11740 | /// [`dissolve_window`] reads [`crate::project::Clip::transition_out`] back |
| 11741 | /// only once adjacency is re-checked at render time: two clips a split |
| 11742 | /// just made, still touching, still name B by its own source and its own |
| 11743 | /// timeline start. |
| 11744 | #[test] |
| 11745 | fn dissolve_window_names_bs_source_in_frame_window_and_start() { |
| 11746 | use crate::project::{Lane, Project}; |
| 11747 | let mut p = Project::single("/nonexistent/film.mkv", 20); |
| 11748 | assert!(p.split(15)); |
| 11749 | assert!(p.set_transition_out(Lane::V1, 0, 5)); |
| 11750 | let spans = export_spans(&p, None); |
| 11751 | let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span"); |
| 11752 | assert_eq!( |
| 11753 | dissolve_window(&p, a_span), |
| 11754 | Some((0, 15, 5, 15)), |
| 11755 | "b's source, b's in_frame, the window, b's timeline start" |
| 11756 | ); |
| 11757 | } |
| 11758 | |
| 11759 | /// A `transition_out` set while two clips touched, then made stale by a |
| 11760 | /// trim that opens a gap between them: the number is still in storage, |
| 11761 | /// [`dissolve_window`] reads `None` from it, and the span renders as the |
| 11762 | /// hard cut two clips that no longer touch actually are. |
| 11763 | #[test] |
| 11764 | fn a_stale_transition_out_after_a_trim_renders_as_a_hard_cut() { |
| 11765 | use crate::project::{Edge, Lane, Project}; |
| 11766 | let mut p = Project::single("/nonexistent/film.mkv", 20); |
| 11767 | assert!(p.split(15)); |
| 11768 | assert!(p.set_transition_out(Lane::V1, 0, 5)); |
| 11769 | assert!(p.trim(Lane::V1, 1, Edge::Start, 18, &[100]), "opens a gap"); |
| 11770 | let spans = export_spans(&p, None); |
| 11771 | let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span"); |
| 11772 | assert!( |
| 11773 | dissolve_window(&p, a_span).is_none(), |
| 11774 | "b no longer abuts a; hard cut" |
| 11775 | ); |
| 11776 | } |
| 11777 | } |
| 11778 | |
| 11779 | #[cfg(test)] |
| 11780 | mod audio_language_tests { |
| 11781 | use super::*; |
| 11782 | |
| 11783 | fn asset(name: &str) -> PathBuf { |
| 11784 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 11785 | } |
| 11786 | |
| 11787 | /// `test_multilang.mp4` has an `und` track 0 and a `fra` track 1. |
| 11788 | #[test] |
| 11789 | fn a_stream_states_its_language_or_none() { |
| 11790 | let path = asset("test_multilang.mp4"); |
| 11791 | assert_eq!(stream_language(&path, 0), None, "und is no language"); |
| 11792 | assert_eq!(stream_language(&path, 1).as_deref(), Some("fra")); |
| 11793 | assert_eq!(stream_language(&path, 9), None, "a track the file does not have"); |
| 11794 | } |
| 11795 | |
| 11796 | /// The tag is the one language every clip shares; any disagreement or any `und` leaves it out. |
| 11797 | #[test] |
| 11798 | fn the_mix_takes_a_language_only_when_every_clip_shares_it() { |
| 11799 | let s = |l: &str| Some(l.to_string()); |
| 11800 | assert_eq!(shared_language([s("fra"), s("fra")]), s("fra")); |
| 11801 | assert_eq!(shared_language([s("fra"), s("eng")]), None, "two languages"); |
| 11802 | assert_eq!(shared_language([s("fra"), None]), None, "one clip states none"); |
| 11803 | assert_eq!(shared_language(Vec::<Option<String>>::new()), None, "no sound at all"); |
| 11804 | } |
| 11805 | |
| 11806 | /// The clips on the audio lanes name the streams the sound comes from: a `und` clip beside |
| 11807 | /// a `fra` one leaves the tag out. |
| 11808 | #[test] |
| 11809 | fn a_mix_of_und_and_french_clips_has_no_tag() { |
| 11810 | let path = asset("test_multilang.mp4"); |
| 11811 | let mut p = Project::single(&path, 30); |
| 11812 | assert_eq!(audio_language(&p), None, "the first track is und"); |
| 11813 | let fra = p.import(&path, 1); |
| 11814 | assert!(p.append_clip(fra, 30)); |
| 11815 | assert_eq!(audio_language(&p), None, "the und clip is still on A1"); |
| 11816 | } |
| 11817 | } |
| 11818 | |
| 11819 | #[cfg(test)] |
| 11820 | mod burn_stack_tests { |
| 11821 | #[test] |
| 11822 | fn two_overlapping_cues_are_both_drawn_stacked() { |
| 11823 | use super::{Burn, Cue, cues_on_screen}; |
| 11824 | use crate::text::TextStyle; |
| 11825 | let cue = |text: &str| Cue { |
| 11826 | start_us: 0, |
| 11827 | end_us: 5_000_000, |
| 11828 | text: text.to_string(), |
| 11829 | image: None, |
| 11830 | words: Vec::new(), |
| 11831 | karaoke: Vec::new(), |
| 11832 | }; |
| 11833 | let (w, h) = (640u32, 360u32); |
| 11834 | let paint = |cues: Vec<Cue>| { |
| 11835 | let mut burn = Burn { |
| 11836 | cues, |
| 11837 | style: TextStyle { |
| 11838 | boxed: false, |
| 11839 | ..TextStyle::default() |
| 11840 | }, |
| 11841 | fps: 30.0, |
| 11842 | full_range: false, |
| 11843 | last: None, |
| 11844 | titles: Vec::new(), |
| 11845 | title_last: Vec::new(), |
| 11846 | }; |
| 11847 | let y = vec![40u8; (w * h) as usize]; |
| 11848 | let u = vec![128u8; (w / 2 * (h / 2)) as usize]; |
| 11849 | let v = u.clone(); |
| 11850 | burn.paint(30, w, h, (&y, &u, &v)) |
| 11851 | .expect("a caption is drawn") |
| 11852 | }; |
| 11853 | // The rows that carry a lit (white) pixel in the luma plane. |
| 11854 | let lit_rows = |planes: &(Vec<u8>, Vec<u8>, Vec<u8>)| -> Vec<u32> { |
| 11855 | (0..h) |
| 11856 | .filter(|&r| { |
| 11857 | let row = &planes.0[(r * w) as usize..((r + 1) * w) as usize]; |
| 11858 | row.iter().any(|&l| l > 40) |
| 11859 | }) |
| 11860 | .collect() |
| 11861 | }; |
| 11862 | let cues = vec![cue("First cue"), cue("Second cue")]; |
| 11863 | assert_eq!(cues_on_screen(&cues, 30, 30.0), vec![0, 1], "both are on screen"); |
| 11864 | let one = lit_rows(&paint(vec![cue("First cue")])); |
| 11865 | let both = lit_rows(&paint(cues)); |
| 11866 | assert!( |
| 11867 | both.len() >= 2 * one.len() - 1, |
| 11868 | "second cue not drawn: {} lit rows against {} for the first alone", |
| 11869 | both.len(), |
| 11870 | one.len() |
| 11871 | ); |
| 11872 | // The first cue keeps its place on the bottom edge; the second stacks above. |
| 11873 | assert_eq!(both.last(), one.last(), "the first cue moved"); |
| 11874 | } |
| 11875 | } |
| 11876 | |
| 11877 | #[cfg(test)] |
| 11878 | mod chroma_420_tests { |
| 11879 | use super::*; |
| 11880 | |
| 11881 | fn asset(name: &str) -> PathBuf { |
| 11882 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 11883 | } |
| 11884 | |
| 11885 | /// The layout a chroma plane's sample count names, for each subsampling. |
| 11886 | #[test] |
| 11887 | fn a_chroma_count_names_its_layout() { |
| 11888 | assert_eq!(chroma_shape(64 * 64, 64, 64), Some((64, 64)), "4:4:4"); |
| 11889 | assert_eq!(chroma_shape(32 * 64, 64, 64), Some((32, 64)), "4:2:2"); |
| 11890 | assert_eq!(chroma_shape(32 * 32, 64, 64), Some((32, 32)), "4:2:0"); |
| 11891 | assert_eq!(chroma_shape(3 * 3, 5, 3), Some((3, 3)), "odd 4:4:4 keeps its width"); |
| 11892 | assert_eq!(chroma_shape(3 * 2, 5, 3), Some((3, 2)), "odd 4:2:2"); |
| 11893 | assert_eq!(chroma_shape(7, 5, 3), None, "no layout has seven samples"); |
| 11894 | } |
| 11895 | |
| 11896 | /// A 2x2 block of 4:4:4 chroma becomes its rounded mean. |
| 11897 | #[test] |
| 11898 | fn a_444_block_averages_to_its_rounded_mean() { |
| 11899 | let src: Vec<u16> = vec![1, 2, 3, 4]; |
| 11900 | assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![3], "(10 + 2) / 4"); |
| 11901 | let src: Vec<u16> = vec![0, 0, 0, 1]; |
| 11902 | assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![0], "a quarter rounds down"); |
| 11903 | let src: Vec<u16> = vec![0, 0, 1, 1]; |
| 11904 | assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![1], "a half rounds up"); |
| 11905 | } |
| 11906 | |
| 11907 | /// 4:2:2 has full height, so only the rows pair up. |
| 11908 | #[test] |
| 11909 | fn a_422_plane_pairs_rows_only() { |
| 11910 | // Two columns, four rows: rows (0,1) and (2,3) average, columns stay apart. |
| 11911 | let src: Vec<u8> = vec![10, 100, 20, 200, 30, 0, 40, 0]; |
| 11912 | assert_eq!(chroma_420(&src, 2, 4, 2, 2), vec![15, 150, 35, 0]); |
| 11913 | } |
| 11914 | |
| 11915 | /// An odd edge averages the samples there are, and 10-bit samples stay in 10 bits. |
| 11916 | #[test] |
| 11917 | fn an_odd_edge_and_ten_bit_samples_are_handled() { |
| 11918 | // 3x3 chroma down to 2x2: the last column and row are a single sample each, |
| 11919 | // so the corner is the 8 alone and the edge pairs are (2, 5) and (6, 7). |
| 11920 | let src: Vec<u16> = (0..9).collect(); |
| 11921 | assert_eq!(chroma_420(&src, 3, 3, 2, 2), vec![2, 4, 7, 8]); |
| 11922 | // A 10-bit mean is still a 10-bit value, not a truncated 8-bit one. |
| 11923 | let src: Vec<u16> = vec![1023, 1023, 1022, 1023]; |
| 11924 | assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![1023]); |
| 11925 | } |
| 11926 | |
| 11927 | /// The AV1 seat hands the composer 4:2:0 planes for every layout edith decodes |
| 11928 | /// (4:2:0, 4:2:2, 4:4:4 and gray), at the size a 4:2:0 picture would have. |
| 11929 | #[test] |
| 11930 | fn every_av1_fixture_arrives_as_420() { |
| 11931 | for name in ["test_av1_444.mp4", "test_av1_422.mp4", "test_av1_12bit.mp4"] { |
| 11932 | let mut pictures = Pictures::software(&asset(name), 0, false, Deinterlace::Frame).expect(name); |
| 11933 | let Ok(Some(Yuv::Pixels { u, v, width, height, .. })) = pictures.next(None) else { |
| 11934 | panic!("{name}: no picture"); |
| 11935 | }; |
| 11936 | let (cw, ch) = (width.div_ceil(2) as usize, height.div_ceil(2) as usize); |
| 11937 | assert_eq!((u.len(), v.len()), (cw * ch, cw * ch), "{name}: chroma is 4:2:0"); |
| 11938 | } |
| 11939 | for name in ["test_av1_gray.mp4", "test_av1_420.mp4"] { |
| 11940 | let mut pictures = Pictures::software(&asset(name), 0, false, Deinterlace::Frame).expect(name); |
| 11941 | let Ok(Some(Yuv::Pixels { y, u, v, width, height })) = pictures.next(None) else { |
| 11942 | panic!("{name}: no picture"); |
| 11943 | }; |
| 11944 | let (cw, ch) = (width.div_ceil(2) as usize, height.div_ceil(2) as usize); |
| 11945 | assert_eq!(y.len(), (width * height) as usize, "{name}: luma"); |
| 11946 | assert_eq!((u.len(), v.len()), (cw * ch, cw * ch), "{name}: chroma is 4:2:0"); |
| 11947 | if name.contains("gray") { |
| 11948 | assert!(u.iter().chain(&v).all(|&s| s == 128), "{name}: grey chroma is 128"); |
| 11949 | } |
| 11950 | } |
| 11951 | } |
| 11952 | } |
| 11953 | |
| 11954 | #[cfg(test)] |
| 11955 | mod planned_sound_tests { |
| 11956 | use super::*; |
| 11957 | |
| 11958 | fn asset(name: &str) -> PathBuf { |
| 11959 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 11960 | } |
| 11961 | |
| 11962 | /// The sound [`planned_seats`] predicts for `timeline` in an mp4, with the |
| 11963 | /// picture's meta taken from `picture`. |
| 11964 | fn predicted_sound(timeline: &str, picture: &str) -> &'static str { |
| 11965 | let project = Project::single(asset(timeline), 30); |
| 11966 | let (meta, _) = Demuxer::open(&asset(picture)).expect("the picture's file opens"); |
| 11967 | let settings = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 11968 | planned_seats(&project, &meta, &settings).1 |
| 11969 | } |
| 11970 | |
| 11971 | /// A DTS track is decoded by `ec-dts`, so the export predicts an encode of its |
| 11972 | /// sound (as it does for an mp3), not the "can't be decoded" card. |
| 11973 | #[test] |
| 11974 | fn a_dts_source_is_predicted_as_an_encode() { |
| 11975 | assert_eq!( |
| 11976 | predicted_sound("test_dts.mkv", "test_dts.mkv"), |
| 11977 | "AAC · SW encode (ec-aac)" |
| 11978 | ); |
| 11979 | } |
| 11980 | |
| 11981 | /// An mp3 on the timeline has no sample table to copy from: the sound is |
| 11982 | /// decoded and encoded as AAC, not copied. |
| 11983 | #[test] |
| 11984 | fn a_standalone_mp3_source_is_predicted_as_an_encode() { |
| 11985 | assert_eq!( |
| 11986 | predicted_sound("test_tone.mp3", "test_av.mp4"), |
| 11987 | "AAC · SW encode (ec-aac)" |
| 11988 | ); |
| 11989 | } |
| 11990 | |
| 11991 | /// The untouched AAC of an mp4 is still the copy it was. |
| 11992 | #[test] |
| 11993 | fn an_untouched_aac_mp4_is_still_predicted_as_a_copy() { |
| 11994 | assert_eq!(predicted_sound("test_av.mp4", "test_av.mp4"), "AAC copy"); |
| 11995 | } |
| 11996 | |
| 11997 | /// The HDR meta and picture size of a fixture, as the export reads them. |
| 11998 | fn meta_of(name: &str) -> VideoMeta { |
| 11999 | Demuxer::open(&asset(name)).expect("the fixture opens").0 |
| 12000 | } |
| 12001 | |
| 12002 | /// A PQ source is tone-mapped to SDR in every picture export, and the plan says so. |
| 12003 | #[test] |
| 12004 | fn a_pq_source_is_predicted_as_tone_mapped() { |
| 12005 | let project = Project::single(asset("test_pq.mp4"), 30); |
| 12006 | let meta = meta_of("test_pq.mp4"); |
| 12007 | let settings = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 12008 | let expected = match ColorDescription::output_sized(meta.width, meta.height).matrix { |
| 12009 | Matrix::Bt601 => "HDR (PQ) source tone-mapped to SDR BT.601", |
| 12010 | _ => "HDR (PQ) source tone-mapped to SDR BT.709", |
| 12011 | }; |
| 12012 | assert_eq!(planned_tone(&project, &meta, &settings).as_deref(), Some(expected)); |
| 12013 | } |
| 12014 | |
| 12015 | /// The matrix the words name is the one the file is tagged with: a standard-definition |
| 12016 | /// canvas is BT.601 and an HD one BT.709, whatever the source's own size, and a |
| 12017 | /// `size` setting moves the canvas the rule is applied to. |
| 12018 | #[test] |
| 12019 | fn the_tone_map_names_the_matrix_of_the_size_it_is_written_at() { |
| 12020 | let project = Project::single(asset("test_pq.mp4"), 30); |
| 12021 | let mut hd = meta_of("test_pq.mp4"); |
| 12022 | hd.width = 1920; |
| 12023 | hd.height = 1080; |
| 12024 | let mut sd = hd; |
| 12025 | sd.width = 720; |
| 12026 | sd.height = 576; |
| 12027 | let mp4 = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 12028 | assert_eq!( |
| 12029 | planned_tone(&project, &hd, &mp4).as_deref(), |
| 12030 | Some("HDR (PQ) source tone-mapped to SDR BT.709") |
| 12031 | ); |
| 12032 | assert_eq!( |
| 12033 | planned_tone(&project, &sd, &mp4).as_deref(), |
| 12034 | Some("HDR (PQ) source tone-mapped to SDR BT.601"), |
| 12035 | "720x576 is SD, and is tagged BT.601" |
| 12036 | ); |
| 12037 | let small = ExportSettings { size: Some((640, 360)), ..mp4.clone() }; |
| 12038 | assert_eq!( |
| 12039 | planned_tone(&project, &hd, &small).as_deref(), |
| 12040 | Some("HDR (PQ) source tone-mapped to SDR BT.601"), |
| 12041 | "a 640x360 export is SD though the project is HD" |
| 12042 | ); |
| 12043 | let hd_again = ExportSettings { size: Some((1280, 720)), ..mp4.clone() }; |
| 12044 | assert_eq!( |
| 12045 | planned_tone(&project, &sd, &hd_again).as_deref(), |
| 12046 | Some("HDR (PQ) source tone-mapped to SDR BT.709"), |
| 12047 | "a 1280x720 export of an SD canvas is HD" |
| 12048 | ); |
| 12049 | } |
| 12050 | |
| 12051 | /// A preview that keeps its source's curve is not tone-mapped, and an SDR timeline or a |
| 12052 | /// sound-only format has nothing to say. |
| 12053 | #[test] |
| 12054 | fn only_a_tone_mapped_picture_is_predicted_as_one() { |
| 12055 | let pq = Project::single(asset("test_hdr_sei.mkv"), 30); |
| 12056 | let meta = meta_of("test_hdr_sei.mkv"); |
| 12057 | let keep = ExportSettings { |
| 12058 | format: Format::Mp4, |
| 12059 | keep_source_colour: true, |
| 12060 | ..Default::default() |
| 12061 | }; |
| 12062 | assert_eq!(planned_tone(&pq, &meta, &keep), None, "a preview keeps the curve"); |
| 12063 | let mp4 = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 12064 | assert!(planned_tone(&pq, &meta, &mp4).is_some(), "the mkv's PQ too"); |
| 12065 | let sdr = Project::single(asset("test_av.mp4"), 30); |
| 12066 | assert_eq!(planned_tone(&sdr, &meta, &mp4), None, "an SDR timeline"); |
| 12067 | let wav = ExportSettings { format: Format::Wav, ..Default::default() }; |
| 12068 | assert_eq!(planned_tone(&pq, &meta, &wav), None, "no picture to tone-map"); |
| 12069 | } |
| 12070 | |
| 12071 | /// A size setting draws the export at that size, coded size included, and leaves every |
| 12072 | /// other fact of the project's canvas as it is; no size is the project's canvas. |
| 12073 | #[test] |
| 12074 | fn a_size_setting_moves_the_canvas_and_only_the_canvas() { |
| 12075 | let meta = meta_of("test_av.mp4"); |
| 12076 | let none = ExportSettings::default(); |
| 12077 | assert_eq!(output_meta(&meta, &none), meta); |
| 12078 | let small = ExportSettings { size: Some((640, 360)), ..Default::default() }; |
| 12079 | let out = output_meta(&meta, &small); |
| 12080 | assert_eq!((out.width, out.height), (640, 360)); |
| 12081 | assert_eq!((out.coded_width, out.coded_height), (640, 360)); |
| 12082 | assert_eq!(out.frame_rate, meta.frame_rate); |
| 12083 | assert_eq!(out.frame_count, meta.frame_count); |
| 12084 | assert_eq!(out.pixel_aspect, meta.pixel_aspect); |
| 12085 | } |
| 12086 | |
| 12087 | /// An mkv export that is encoded names the codec its mix will get: Opus when the sources |
| 12088 | /// put it at 48 kHz mono or stereo, AAC otherwise. `test_av1.mkv` is 44.1 kHz stereo AAC, |
| 12089 | /// so its export is AAC, as its done line says; `test_seek_chirp.mkv` is 48 kHz mono Opus. |
| 12090 | #[test] |
| 12091 | fn a_matroska_export_names_the_codec_its_mix_will_get() { |
| 12092 | let settings = ExportSettings { format: Format::Av1, ..Default::default() }; |
| 12093 | let aac = Project::single(asset("test_av1.mkv"), 30); |
| 12094 | let meta = meta_of("test_av1.mkv"); |
| 12095 | let (_, sound) = planned_seats(&aac, &meta, &settings); |
| 12096 | assert_eq!(sound, "AAC · SW encode (ec-aac)"); |
| 12097 | let opus = Project::single(asset("test_seek_chirp.mkv"), 30); |
| 12098 | let meta = meta_of("test_seek_chirp.mkv"); |
| 12099 | let (_, sound) = planned_seats(&opus, &meta, &settings); |
| 12100 | assert_eq!(sound, "Opus · SW encode (ec-opus)"); |
| 12101 | } |
| 12102 | } |
| 12103 | |
| 12104 | #[cfg(test)] |
| 12105 | mod vp9_444_tests { |
| 12106 | use super::*; |
| 12107 | |
| 12108 | #[test] |
| 12109 | fn a_422_or_444_source_names_its_reduction_on_a_video_export() { |
| 12110 | let mut settings = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 12111 | assert_eq!( |
| 12112 | chroma_reduction_words(Codec::Vp9, Chroma::C444, &settings).as_deref(), |
| 12113 | Some("VP9 4:4:4 source: chroma reduced to 4:2:0 for export"), |
| 12114 | ); |
| 12115 | assert_eq!( |
| 12116 | chroma_reduction_words(Codec::Vp9, Chroma::C422, &settings).as_deref(), |
| 12117 | Some("VP9 4:2:2 source: chroma reduced to 4:2:0 for export"), |
| 12118 | ); |
| 12119 | assert_eq!( |
| 12120 | chroma_reduction_words(Codec::H264, Chroma::C444, &settings).as_deref(), |
| 12121 | Some("H.264 4:4:4 source: chroma reduced to 4:2:0 for export"), |
| 12122 | ); |
| 12123 | assert!(chroma_reduction_words(Codec::Vp9, Chroma::C420, &settings).is_none()); |
| 12124 | assert!(chroma_reduction_words(Codec::Vp9, Chroma::Gray, &settings).is_none()); |
| 12125 | for format in [Format::Wav, Format::Flac, Format::Mp3, Format::Ogg, Format::M4a, Format::Opus] { |
| 12126 | settings.format = format; |
| 12127 | assert!( |
| 12128 | chroma_reduction_words(Codec::Vp9, Chroma::C444, &settings).is_none(), |
| 12129 | "{format:?} has no picture to reduce", |
| 12130 | ); |
| 12131 | } |
| 12132 | } |
| 12133 | |
| 12134 | /// A VP9 profile 1 4:4:4 file is never offered to the GPU on an export: the decode |
| 12135 | /// door's gate refuses it before the plugin is asked, so the plugin's refusal never |
| 12136 | /// reaches stderr. Stderr is not read in-process; the seam is the plugin's attempt count. |
| 12137 | #[test] |
| 12138 | fn a_vp9_444_export_never_offers_the_file_to_the_gpu() { |
| 12139 | let path = std::env::temp_dir().join(format!("edith-vp9-444-{}.webm", std::process::id())); |
| 12140 | let generated = std::process::Command::new("ffmpeg") |
| 12141 | .args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=64x64:rate=5:duration=1"]) |
| 12142 | .args(["-c:v", "libvpx-vp9", "-pix_fmt", "yuv444p", "-f", "webm"]) |
| 12143 | .arg(&path) |
| 12144 | .status() |
| 12145 | .map(|status| status.success() && path.exists()) |
| 12146 | .unwrap_or(false); |
| 12147 | if !generated { |
| 12148 | eprintln!("no ffmpeg with libvpx-vp9: the 4:4:4 fixture cannot be generated, skipping"); |
| 12149 | return; |
| 12150 | } |
| 12151 | let chroma = Demuxer::open(&path).ok().and_then(|(_, demuxer)| demuxer.chroma()); |
| 12152 | assert_eq!(chroma, Some(Chroma::C444), "the fixture is a 4:4:4 stream"); |
| 12153 | let (tx, rx) = sync_channel(64); |
| 12154 | let before = crate::hw::OPEN_ATTEMPTS.with(|n| n.get()); |
| 12155 | let _ = decode_stream(&path, 0, None, &tx, None, false, Deinterlace::Frame); |
| 12156 | let after = crate::hw::OPEN_ATTEMPTS.with(|n| n.get()); |
| 12157 | drop(rx); |
| 12158 | let _ = std::fs::remove_file(&path); |
| 12159 | assert_eq!(after, before, "the GPU was asked for a decoder for a 4:4:4 VP9 file"); |
| 12160 | } |
| 12161 | } |