edith
Clone
https://git.tahinli.com/Tahinli/edith.git
0 watching0 forksRust18.3 MiB6a8d990Tahinli15 days ago1049 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. |
| 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::hwproc::SeatRate; |
| 84 | use crate::mux::{ |
| 85 | AudioParams, Av1Params, CopyParams, HevcParams, MkvMuxer, Mp4Muxer, SubParams, VideoParams, |
| 86 | }; |
| 87 | use crate::project::{Deinterlace, Lane, LaneKind, Project, Rate, Speed, Title}; |
| 88 | use crate::scale::{Composer, FitPolicy, Sample}; |
| 89 | use crate::subtitle::{Cue, SubtitleTrack}; |
| 90 | use crate::text::{Overlay, Place, TextStyle, overlay, overlay_blocks}; |
| 91 | use crate::titleanim::Motion; |
| 92 | use crate::tonemap::{self, ToneMapper}; |
| 93 | use crate::transform::TransformParams; |
| 94 | |
| 95 | /// Progress is reported in permille: an atomic integer the render loop can read |
| 96 | /// without a lock, fine enough for any progress bar. |
| 97 | pub(crate) const PROGRESS_SCALE: u32 = 1_000; |
| 98 | |
| 99 | /// The head of the bar the *sound* owns, before a picture is written at all. |
| 100 | /// The mix is decoded, encoded and measured before the muxer exists ([`run`] |
| 101 | /// says why), and on a feature film that is a minute or two in which a bar |
| 102 | /// pinned at zero is the only thing on screen -- which reads as an export that |
| 103 | /// has hung. Small, because the picture is still nearly all of the work. |
| 104 | pub(crate) const AUDIO_BAND: u32 = PROGRESS_SCALE / 20; |
| 105 | |
| 106 | /// Where the bar stands with `done` of `total` pictures written: the sound's |
| 107 | /// band is already behind it ([`AUDIO_BAND`]), so the picture fills what is |
| 108 | /// left rather than starting again from zero. |
| 109 | fn picture_progress(done: u32, total: u32) -> u32 { |
| 110 | // In `u64`: this is a picture count times a permille, and a film past |
| 111 | // ~4.5 M pictures (42 hours at 30 fps) overflowed the `u32` this used to be |
| 112 | // computed in -- a panic in debug inside the export thread, which a caller |
| 113 | // reads as `export worker panicked` on a file that was never written, and a |
| 114 | // bar that thrashed in release. The result is under the scale by |
| 115 | // construction, so the narrowing back is exact. |
| 116 | let band = u64::from(PROGRESS_SCALE - AUDIO_BAND); |
| 117 | let done = u64::from(done.min(total)); |
| 118 | AUDIO_BAND + (done * band / u64::from(total.max(1))) as u32 |
| 119 | } |
| 120 | |
| 121 | /// D2 rate control: bits per pixel per second, then a sane range. 720p30 lands |
| 122 | /// at 2.76 Mbps, which S1 measured the software encoder hitting within 1%. |
| 123 | const BITS_PER_PIXEL: f64 = 0.1; |
| 124 | /// The floor under a rate somebody *asked* for, and under the derived one: 100 |
| 125 | /// kbps, so a sub-Mbps budget -- a lo-fi delivery, a tiny picture, a |
| 126 | /// phone-rate master -- is a rate this export is written at. A megabit was the |
| 127 | /// old floor, and it silently rewrote every such ask. Nothing below this is |
| 128 | /// worth a container: the sound's own row starts at 128 kbps. |
| 129 | const MIN_BITRATE: u64 = 100_000; |
| 130 | const MAX_BITRATE: u64 = 20_000_000; |
| 131 | |
| 132 | /// The ceiling on a bitrate somebody *asked* for, which is a different question |
| 133 | /// from where the derived one stops: [`MAX_BITRATE`] is the top of the automatic |
| 134 | /// figure's sane range, and a rate a person typed is not that program's guess to |
| 135 | /// bound. Nothing in either encoder objects to it -- the VA-API seat takes a |
| 136 | /// `u64` and the software ones a `u32`/`i32`, all of which hold this with room |
| 137 | /// -- so the old shared ceiling was only ever the auto range wearing two hats. |
| 138 | const MAX_EXPLICIT_BITRATE: u64 = 50_000_000; |
| 139 | |
| 140 | /// The rates the sound may be coded at, smallest first -- what a front-end |
| 141 | /// offers and what [`ExportSettings::audio_kbps`] is clamped into. Every one of |
| 142 | /// them is a legal MPEG-1 Layer III value, so the MP3 path writes the figure it |
| 143 | /// was given rather than the nearest one `ec-mp3` snaps to. |
| 144 | pub const AUDIO_KBPS: [u32; 4] = [128, 192, 256, 320]; |
| 145 | |
| 146 | /// The sound rate AAC alone may be coded at, above the rows [`AUDIO_KBPS`] offers. |
| 147 | pub const AAC_MAX_KBPS: u32 = 384; |
| 148 | |
| 149 | const QP_SOFTWARE_REFUSAL: &str = "a constant QP (qp) is written by the hardware seat and the software HEVC encoders only: pass seat hardware for this format, or bitrate_kbps for a fixed rate"; |
| 150 | |
| 151 | /// What the sound is coded at when nobody picked: the rate this project wrote |
| 152 | /// before the choice existed. 256 and not the encoders' own 128, because an |
| 153 | /// export is a master a person edits from again and this is a second lossy |
| 154 | /// generation over sources that may already have been one -- measured on the |
| 155 | /// suite's fixtures, an untouched clip re-encoded moves 0.15 dB here against |
| 156 | /// 0.46 dB at 128, and 32 KB/s beside a 2.76 Mbps picture is not a size anyone |
| 157 | /// is counting. |
| 158 | pub const DEFAULT_AUDIO_KBPS: u32 = 256; |
| 159 | |
| 160 | /// `rav1e`'s fastest preset. Anything slower is minutes per second of timeline |
| 161 | /// on a build with no assembly, which is what this one is. |
| 162 | const AV1_SPEED: u8 = 10; |
| 163 | |
| 164 | /// Tiles per software AV1 frame, the knob that spreads one picture over the |
| 165 | /// cores (see `Enc::open_av1`). A power of two; `rav1e` rounds it to a legal |
| 166 | /// layout for the frame size. |
| 167 | const AV1_TILES: usize = 32; |
| 168 | |
| 169 | /// How many lane encoders the intra HEVC seat spreads frames across. Twelve |
| 170 | /// is where the 2026-08-11 bench stopped scaling on this box; more lanes |
| 171 | /// only holds more decoded frames in memory. The cores the lanes leave over |
| 172 | /// go to the wavefront inside each lane's encoder. |
| 173 | const HEVC_LANES: usize = 12; |
| 174 | /// Bits per pixel an intra HEVC encoder spends at QP 27: 0.607 at 720p and |
| 175 | /// 0.586 at 1080p on the old seat's bench, and `ec-h265` lands on the same |
| 176 | /// 0.6 anchor. What [`hevc_qp`] maps a bitrate row through. |
| 177 | const HEVC_BPP_AT_27: f64 = 0.6; |
| 178 | /// The band [`hevc_qp`] is clamped into, for the reason stated there. |
| 179 | const HEVC_QP_MIN: i32 = 22; |
| 180 | const HEVC_QP_MAX: i32 = 40; |
| 181 | /// The quantiser the I+P GOP seat codes at when no bitrate is given: its |
| 182 | /// automatic quality, a constant-quality default in its own right. It is not |
| 183 | /// [`hevc_qp`]: that maps the automatic *bitrate* through the intra anchor |
| 184 | /// ([`HEVC_BPP_AT_27`]), which is measured on intra pictures. P pictures cost |
| 185 | /// far fewer bits, so the same mapping pushed a 1080p30 GOP export to the clamp |
| 186 | /// at QP 40 (652 kb/s at 31.8 dB mean PSNR on a 33 s timeline). |
| 187 | /// |
| 188 | /// 28 is chosen so that a default is never visibly worse than the H.264 default |
| 189 | /// on any source, and it matches x265's CRF 28 convention. Measured on 1080p30 |
| 190 | /// 10 s sources (kbps, PSNR dB against the source): |
| 191 | /// |
| 192 | /// | source | H.264 default | QP 28 | QP 31 | |
| 193 | /// |----------|---------------|----------------|----------------| |
| 194 | /// | testsrc2 | 6298, 44.08 | 6390, 41.84 | 4080, 39.50 | |
| 195 | /// | mandel | 6246, 35.98 | 11365, 38.37 | 6742, 36.21 | |
| 196 | /// |
| 197 | /// At QP 28 the GOP default is 2.2 dB under H.264 on testsrc2 at equal size |
| 198 | /// (+1.5%), and 2.4 dB above it on mandel at +82% bytes. QP 31 is 4.6 dB under |
| 199 | /// on testsrc2, which is visibly worse on synthetic content, so it is not the |
| 200 | /// default. File size is traded for never being far below H.264 quality: on |
| 201 | /// natural content the GOP default is larger than the H.264 file. |
| 202 | const HEVC_GOP_QP: i32 = 28; |
| 203 | |
| 204 | /// What an export writes. H.264-in-mp4, AV1 and HEVC -- each of the last two in |
| 205 | /// Matroska or in mp4, the user's pick of container -- are the *video* pairs |
| 206 | /// with both an encoder and a decoder under this project's no-install rule, and |
| 207 | /// pure-Rust encoder: `ec-riff`, `ec-flac`, `ec-mp3` and `ec-vorbis`. Opus |
| 208 | /// still has none as a *file* -- the Matroska seat is `ec-opus`, but a standalone |
| 209 | /// `.opus` row this project does not offer. |
| 210 | /// (AAC has one too -- `ec-aac`, which is what a re-encoded video track's |
| 211 | /// sound leaves through -- but AAC is a container's own audio, never a file of |
| 212 | /// its own here.) VP9 and VP8 are the |
| 213 | /// codecs that come in through the plugin and stop there, HEVC having |
| 214 | /// gained an encoder (an intra-only one, which the rows say). A front-end says |
| 215 | /// so rather than hiding the row. |
| 216 | /// |
| 217 | /// **Every video format carries sound.** Which way it carries it is the only |
| 218 | /// difference: copied packet for packet where a copy can say what the timeline |
| 219 | /// says, decoded and encoded again ([`encode_audio`]) where it cannot. |
| 220 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 221 | pub enum Format { |
| 222 | /// Picture and sound: video re-encoded, AAC copied -- or re-encoded too, |
| 223 | /// where a copy could not carry the edit (a second audio lane to mix in, a |
| 224 | /// speeded clip, an equalized one, a source no mp4 sample table holds). |
| 225 | #[default] |
| 226 | Mp4, |
| 227 | /// AV1 in Matroska, with the timeline's AAC beside it: this engine's |
| 228 | /// Matroska writer carries an audio track ([`crate::mux::MkvMuxer`]) and its |
| 229 | /// reader reads one back, symphonia's `mkv` reader being what |
| 230 | /// `audio::Track::open` opens it with. |
| 231 | Av1, |
| 232 | /// The same AV1 stream in an mp4, for everything that plays mp4 and not |
| 233 | /// Matroska. The sample entry `mp4 0.14` cannot write is written by hand |
| 234 | /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own, |
| 235 | /// unchanged. |
| 236 | Av1Mp4, |
| 237 | /// HEVC in Matroska: I+P GOPs from `ec-h265` ([`Enc::open_hevc`]), or with |
| 238 | /// [`ExportSettings::intra_only`] an intraframe master, every frame an IDR. |
| 239 | Hevc, |
| 240 | /// The same HEVC stream in an mp4 (`hvc1`), for everything that plays mp4 |
| 241 | /// and not Matroska -- the AV1 pair's split, for the same reason. |
| 242 | HevcMp4, |
| 243 | /// AV1 in WebM, with Opus beside it: the open web's container. The same |
| 244 | /// AV1 encoder as [`Format::Av1`]; the sound is always Opus, mixed at 48 kHz |
| 245 | /// ([`start`]) because WebM carries no other audio, and the file carries no |
| 246 | /// subtitles ([`planned_subtitles`] says so). No copy path: a source's own |
| 247 | /// packets are not AV1 or Opus in general. |
| 248 | Webm, |
| 249 | /// The audio lanes alone, 16-bit PCM. |
| 250 | Wav, |
| 251 | /// The audio lanes alone, losslessly compressed. |
| 252 | Flac, |
| 253 | /// The audio lanes alone, MPEG-1 Layer III CBR (`ec-mp3`) at the rate |
| 254 | /// [`ExportSettings::audio_kbps`] asks for. |
| 255 | Mp3, |
| 256 | /// The audio lanes alone, Vorbis I in an Ogg container -- `ec-vorbis` |
| 257 | /// encoding, `ec-ogg` paging. Quality-coded and not rate-coded, which |
| 258 | /// is why [`audio_rate_refusal`] takes the Sound row away here: see |
| 259 | /// [`VORBIS_QUALITY`] for the operating point and how it was measured. |
| 260 | Ogg, |
| 261 | /// The audio lanes alone as AAC in an mp4 box with the `M4A ` brand -- the |
| 262 | /// file a player picks an audio parser for. The same track an mp4 of a |
| 263 | /// timeline with no picture carries ([`run_aac`]), which is an [`Format::Mp4`] |
| 264 | /// and not this one: the difference is the brand alone. |
| 265 | M4a, |
| 266 | /// The audio lanes alone as Opus in Ogg (RFC 7845), mixed at 48 kHz and |
| 267 | /// coded by `ec-opus` at [`ExportSettings::audio_kbps`] |
| 268 | /// ([`crate::opus_write`]). |
| 269 | Opus, |
| 270 | /// Apple ProRes in a QuickTime `.mov`, the profile in |
| 271 | /// [`ExportSettings::prores_profile`]: always 10-bit, software (`ec-prores`), |
| 272 | /// every frame a key frame, progressive, no alpha. The sound is 16-bit |
| 273 | /// little-endian PCM (`sowt`) at the timeline's rate, not AAC. See |
| 274 | /// [`crate::prores_out`] for the chroma upsampling the 4:2:0 compositor needs. |
| 275 | ProRes, |
| 276 | /// A numbered run of PNG pictures, one per timeline frame of the range (or the |
| 277 | /// whole timeline): `<folder name>_00001.png` onward, written into the folder the |
| 278 | /// export names. No sound. Each picture is the project's own size, with titles and |
| 279 | /// burnt captions as the export draws them ([`compose_at_with`]). |
| 280 | PngSequence, |
| 281 | /// One PNG picture: the frame at the start of the range (frame 0 without one), at |
| 282 | /// the project's own size. The poster frame. No sound. |
| 283 | Still, |
| 284 | /// An animated GIF of the range, at [`ExportSettings::gif`]. Not written yet: the |
| 285 | /// GIF encoder is still to come, so this format refuses by name ([`GifWriter`]). |
| 286 | Gif, |
| 287 | } |
| 288 | |
| 289 | impl Format { |
| 290 | /// The extension a file of this format is named with -- a front-end builds |
| 291 | /// the destination path from it, so the name never disagrees with the bytes. |
| 292 | pub fn ext(self) -> &'static str { |
| 293 | match self { |
| 294 | Self::Mp4 | Self::Av1Mp4 | Self::HevcMp4 => "mp4", |
| 295 | Self::Av1 | Self::Hevc => "mkv", |
| 296 | Self::Webm => "webm", |
| 297 | Self::Wav => "wav", |
| 298 | Self::Flac => "flac", |
| 299 | Self::Mp3 => "mp3", |
| 300 | Self::Ogg => "ogg", |
| 301 | Self::M4a => "m4a", |
| 302 | Self::Opus => "opus", |
| 303 | Self::ProRes => "mov", |
| 304 | Self::PngSequence | Self::Still => "png", |
| 305 | Self::Gif => "gif", |
| 306 | } |
| 307 | } |
| 308 | |
| 309 | /// Whether this format carries the picture. The bitrate settings are video |
| 310 | /// settings and mean nothing to the audio-only ones. |
| 311 | pub fn has_video(self) -> bool { |
| 312 | matches!( |
| 313 | self, |
| 314 | Self::Mp4 | Self::Av1 | Self::Av1Mp4 | Self::Hevc | Self::HevcMp4 | Self::Webm | Self::ProRes |
| 315 | ) |
| 316 | } |
| 317 | |
| 318 | /// Whether it shows a picture at all: a video format, or the PNG and GIF ones. |
| 319 | pub fn shows_picture(self) -> bool { |
| 320 | self.has_video() || matches!(self, Self::PngSequence | Self::Still | Self::Gif) |
| 321 | } |
| 322 | |
| 323 | /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs |
| 324 | /// and which of the two AV1 containers is being written are separate |
| 325 | /// questions, and this is the first. |
| 326 | pub fn is_av1(self) -> bool { |
| 327 | matches!(self, Self::Av1 | Self::Av1Mp4 | Self::Webm) |
| 328 | } |
| 329 | |
| 330 | /// The same question for HEVC, and the same answer for both its containers: |
| 331 | /// one encoder, two boxes to put its stream in. |
| 332 | pub fn is_hevc(self) -> bool { |
| 333 | matches!(self, Self::Hevc | Self::HevcMp4) |
| 334 | } |
| 335 | |
| 336 | /// Whether the file is an mp4 box file (mp4, hevc-mp4, av1-mp4 or m4a), which is what faststart lays out. |
| 337 | pub fn is_mp4_family(self) -> bool { |
| 338 | matches!(self, Self::Mp4 | Self::HevcMp4 | Self::Av1Mp4 | Self::M4a) |
| 339 | } |
| 340 | |
| 341 | /// Whether the picture is ProRes in a QuickTime file ([`Format::ProRes`]). |
| 342 | pub fn is_prores(self) -> bool { |
| 343 | self == Self::ProRes |
| 344 | } |
| 345 | |
| 346 | /// Whether the file is a Matroska one. Only that container carries this |
| 347 | /// project's Opus track ([`encode_opus`]): an mp4 may hold Opus by spec, but |
| 348 | /// the crate that writes the mp4s here has no sample entry for it, so the |
| 349 | /// mp4 formats stay on AAC and say so. |
| 350 | fn is_mkv(self) -> bool { |
| 351 | matches!(self, Self::Av1 | Self::Hevc | Self::Webm) |
| 352 | } |
| 353 | |
| 354 | /// What the format is called where a refusal names it. |
| 355 | pub fn name(self) -> &'static str { |
| 356 | match self { |
| 357 | Self::Mp4 => "an mp4", |
| 358 | Self::Webm => "a WebM", |
| 359 | Self::Av1 => "an AV1 Matroska", |
| 360 | Self::Av1Mp4 => "an AV1 mp4", |
| 361 | Self::Hevc => "an HEVC Matroska", |
| 362 | Self::HevcMp4 => "an HEVC mp4", |
| 363 | Self::Wav => "a WAV", |
| 364 | Self::Flac => "a FLAC", |
| 365 | Self::Mp3 => "an MP3", |
| 366 | Self::Ogg => "an Ogg Vorbis", |
| 367 | Self::M4a => "an M4A", |
| 368 | Self::Opus => "an Ogg Opus", |
| 369 | Self::ProRes => "a ProRes QuickTime", |
| 370 | Self::PngSequence => "a PNG sequence", |
| 371 | Self::Still => "a PNG still", |
| 372 | Self::Gif => "an animated GIF", |
| 373 | } |
| 374 | } |
| 375 | } |
| 376 | |
| 377 | /// Which encoder writes the picture, as a person picks it on a card. Three |
| 378 | /// discrete choices and not a switch, because "whatever is best" and "the GPU, |
| 379 | /// and say so if there is none" are different answers: a driver that encodes |
| 380 | /// badly wants [`Software`](Self::Software), and a person who *needs* the GPU |
| 381 | /// (a long delivery, a machine whose CPU is doing something else) wants to be |
| 382 | /// told when it is not there rather than to wait out a silent fallback. |
| 383 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 384 | pub enum EncoderSeat { |
| 385 | /// Hardware where this machine has a seat for the picked codec, software |
| 386 | /// everywhere else -- what every export did before there was a choice, and |
| 387 | /// still what an unpicked project does. |
| 388 | #[default] |
| 389 | Auto, |
| 390 | /// The GPU or nothing: no silent fallback, and [`Enc::open`] refuses in |
| 391 | /// words before a byte is written. The only way to the plugin's AV1 seat, |
| 392 | /// which [`Auto`](Self::Auto) will not enter (see [`Enc::open_av1`]). |
| 393 | Hardware, |
| 394 | /// The software encoder even where a seat exists -- for a driver that |
| 395 | /// encodes badly, and for the AV1 pair, where it is what `Auto` picks too. |
| 396 | Software, |
| 397 | } |
| 398 | |
| 399 | impl EncoderSeat { |
| 400 | pub const ALL: [EncoderSeat; 3] = [Self::Auto, Self::Hardware, Self::Software]; |
| 401 | |
| 402 | /// What a card row and a project file call it. The file's keyword too, so |
| 403 | /// the two can never drift ([`crate::edith`]). |
| 404 | pub fn name(self) -> &'static str { |
| 405 | match self { |
| 406 | Self::Auto => "auto", |
| 407 | Self::Hardware => "hardware", |
| 408 | Self::Software => "software", |
| 409 | } |
| 410 | } |
| 411 | |
| 412 | /// Reads one back. `None` for anything else, which a project file refuses |
| 413 | /// by name rather than silently exporting on another seat. |
| 414 | pub fn from_name(name: &[u8]) -> Option<Self> { |
| 415 | Self::ALL.into_iter().find(|s| s.name().as_bytes() == name) |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | /// The six ProRes profiles ([`Format::ProRes`]). The first four code 4:2:2, the |
| 420 | /// last two 4:4:4; the encoder's rate is Apple's nominal one for the profile and |
| 421 | /// the picture size, so a profile *is* the quality row ([`ExportSettings::bitrate`] |
| 422 | /// means nothing to ProRes). |
| 423 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 424 | pub enum ProResProfile { |
| 425 | Proxy, |
| 426 | Lt, |
| 427 | Standard, |
| 428 | #[default] |
| 429 | Hq, |
| 430 | P4444, |
| 431 | P4444Xq, |
| 432 | } |
| 433 | |
| 434 | impl ProResProfile { |
| 435 | pub const ALL: [ProResProfile; 6] = |
| 436 | [Self::Proxy, Self::Lt, Self::Standard, Self::Hq, Self::P4444, Self::P4444Xq]; |
| 437 | |
| 438 | /// What a card row calls it. |
| 439 | pub fn name(self) -> &'static str { |
| 440 | match self { |
| 441 | Self::Proxy => "ProRes 422 Proxy", |
| 442 | Self::Lt => "ProRes 422 LT", |
| 443 | Self::Standard => "ProRes 422", |
| 444 | Self::Hq => "ProRes 422 HQ", |
| 445 | Self::P4444 => "ProRes 4444", |
| 446 | Self::P4444Xq => "ProRes 4444 XQ", |
| 447 | } |
| 448 | } |
| 449 | |
| 450 | /// Whether the profile codes full-resolution chroma (4:4:4). |
| 451 | pub fn is_444(self) -> bool { |
| 452 | matches!(self, Self::P4444 | Self::P4444Xq) |
| 453 | } |
| 454 | |
| 455 | fn codec(self) -> ec_prores::Profile { |
| 456 | match self { |
| 457 | Self::Proxy => ec_prores::Profile::Proxy, |
| 458 | Self::Lt => ec_prores::Profile::Lt, |
| 459 | Self::Standard => ec_prores::Profile::Standard, |
| 460 | Self::Hq => ec_prores::Profile::Hq, |
| 461 | Self::P4444 => ec_prores::Profile::P4444, |
| 462 | Self::P4444Xq => ec_prores::Profile::P4444Xq, |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | /// The HDR transfer an HEVC export is written on ([`HdrOutput::transfer`]). |
| 468 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 469 | pub enum HdrTransfer { |
| 470 | /// No HDR: the export is SDR as it always was (tone-mapped from HDR sources). |
| 471 | #[default] |
| 472 | Sdr, |
| 473 | /// SMPTE ST 2084 (HDR10): BT.2020 primaries and matrix, limited range, 10-bit. |
| 474 | Pq, |
| 475 | /// ARIB STD-B67 (HLG): BT.2020 primaries and matrix, limited range, 10-bit. |
| 476 | Hlg, |
| 477 | } |
| 478 | |
| 479 | impl HdrTransfer { |
| 480 | pub const ALL: [HdrTransfer; 3] = [Self::Sdr, Self::Pq, Self::Hlg]; |
| 481 | |
| 482 | pub fn name(self) -> &'static str { |
| 483 | match self { |
| 484 | Self::Sdr => "SDR", |
| 485 | Self::Pq => "PQ (HDR10)", |
| 486 | Self::Hlg => "HLG", |
| 487 | } |
| 488 | } |
| 489 | |
| 490 | fn colour(self) -> Option<ColorDescription> { |
| 491 | let transfer = match self { |
| 492 | Self::Sdr => return None, |
| 493 | Self::Pq => Transfer::Pq, |
| 494 | Self::Hlg => Transfer::Hlg, |
| 495 | }; |
| 496 | Some(ColorDescription { matrix: Matrix::Bt2020Ncl, transfer, full_range: false }) |
| 497 | } |
| 498 | } |
| 499 | |
| 500 | /// A SMPTE ST 2086 mastering display, in the units the SEI states: chromaticities |
| 501 | /// in 0.00002 steps, luminance in 0.0001 cd/m2. |
| 502 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 503 | pub struct MasteringDisplay { |
| 504 | /// Green, blue, red `(x, y)`, in that order (the SEI's). |
| 505 | pub primaries: [(u16, u16); 3], |
| 506 | pub white_point: (u16, u16), |
| 507 | /// Peak luminance, 0.0001 cd/m2 (1000 nits = 10_000_000). |
| 508 | pub max_luminance: u32, |
| 509 | /// Black level, 0.0001 cd/m2 (0.005 nits = 50). |
| 510 | pub min_luminance: u32, |
| 511 | } |
| 512 | |
| 513 | impl MasteringDisplay { |
| 514 | /// A BT.2020-primaries, D65 display with the given peak and black, in nits. |
| 515 | pub fn bt2020(max_nits: f32, min_nits: f32) -> Self { |
| 516 | Self { |
| 517 | primaries: [(8500, 39850), (6550, 2300), (35400, 14600)], |
| 518 | white_point: (15635, 16450), |
| 519 | max_luminance: (max_nits * 10_000.0).round() as u32, |
| 520 | min_luminance: (min_nits * 10_000.0).round() as u32, |
| 521 | } |
| 522 | } |
| 523 | |
| 524 | /// A DCI-P3 (D65) display, the usual HDR10 grading monitor, with the given |
| 525 | /// peak and black in nits. |
| 526 | pub fn p3_d65(max_nits: f32, min_nits: f32) -> Self { |
| 527 | Self { |
| 528 | primaries: [(13250, 34500), (7500, 3000), (34000, 16000)], |
| 529 | white_point: (15635, 16450), |
| 530 | max_luminance: (max_nits * 10_000.0).round() as u32, |
| 531 | min_luminance: (min_nits * 10_000.0).round() as u32, |
| 532 | } |
| 533 | } |
| 534 | } |
| 535 | |
| 536 | /// HDR output of an HEVC export ([`ExportSettings::hdr`]). The default is none: |
| 537 | /// every export that does not set it is the SDR file it always was. |
| 538 | /// |
| 539 | /// With a transfer set the file is 10-bit (an explicit |
| 540 | /// [`ExportSettings::video_bit_depth`] of 8 is refused), tagged BT.2020 primaries |
| 541 | /// and matrix with that transfer in the bitstream VUI, the mp4 `colr` box or the |
| 542 | /// Matroska `Colour` element, and the HDR sources are *not* tone-mapped. |
| 543 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 544 | pub struct HdrOutput { |
| 545 | pub transfer: HdrTransfer, |
| 546 | /// Written as a mastering display colour volume SEI (in the bitstream). |
| 547 | pub mastering_display: Option<MasteringDisplay>, |
| 548 | /// MaxCLL in cd/m2, with `max_fall`, written as a content light level SEI. |
| 549 | pub max_cll: Option<u16>, |
| 550 | /// MaxFALL in cd/m2. |
| 551 | pub max_fall: Option<u16>, |
| 552 | } |
| 553 | |
| 554 | /// What the caller gets to decide about the output. The codec is not among it: |
| 555 | /// [`Format`] names a container *and* what goes in it, because every pair we |
| 556 | /// can write is a pair we can also read back. |
| 557 | #[derive(Debug, Clone, Default, PartialEq)] |
| 558 | pub struct ExportSettings { |
| 559 | /// Bits per second, clamped to the same sane range the automatic value uses. |
| 560 | /// `None` picks it from the picture size and frame rate. Video only. |
| 561 | pub bitrate: Option<u64>, |
| 562 | /// A constant quantiser (0..51 for H.264 and HEVC) instead of a bitrate. |
| 563 | pub qp: Option<u32>, |
| 564 | /// Which encoder writes the picture ([`EncoderSeat`]). Was a `force_sw` |
| 565 | /// flag, which could say "not the GPU" and never "the GPU or say so". |
| 566 | /// [`EncoderSeat::Software`] is what the `VE_SW_ENC` env pin still forces |
| 567 | /// on every export of a run. |
| 568 | pub seat: EncoderSeat, |
| 569 | /// The file to write. Defaults to [`Format::Mp4`], which is what every |
| 570 | /// caller wrote before there was a choice. |
| 571 | pub format: Format, |
| 572 | /// The sample depth an AV1 software export is written at: `Some(8)` or |
| 573 | /// `Some(10)`, and `None` follows the source -- 10 where any video source of |
| 574 | /// the timeline is 10-bit. AV1 and software HEVC (H.264 stays 8-bit, and so do |
| 575 | /// the hardware AV1 and HEVC seats, which the 10-bit seats do not take). An HDR |
| 576 | /// transfer ([`ExportSettings::hdr`]) and ProRes are always 10-bit. |
| 577 | /// |
| 578 | /// A 10-bit export is decoded at 10 bits and encoded from its 16-bit planes |
| 579 | /// ([`Enc::encode_wide`]) wherever the span passes its picture through |
| 580 | /// untouched. A picture composed on the way (a grade, a transform, a fade, a |
| 581 | /// dissolve, a caption, a tone map, a layer) is composed at 8 bits as it always |
| 582 | /// was and shifted up to the file's depth, so the file is 10-bit either way. |
| 583 | pub video_bit_depth: Option<u8>, |
| 584 | /// What the *sound* is coded at, in kbps, wherever an encoder writes it -- |
| 585 | /// the AAC of a video export as much as an MP3. `None` is |
| 586 | /// [`DEFAULT_AUDIO_KBPS`], which is what every caller wrote before there |
| 587 | /// was a choice, so a settings value nobody touched writes the same bytes |
| 588 | /// it used to. Means nothing to WAV and FLAC, which code no rate, and |
| 589 | /// nothing to a *copied* AAC track, which carries its source's. |
| 590 | pub audio_kbps: Option<u32>, |
| 591 | /// Code the sound at [`ExportSettings::audio_kbps`] even where its packets could be copied. |
| 592 | pub reencode_audio: bool, |
| 593 | /// Bits per sample of the PCM sound in a ProRes `.mov`: 16 or 24. `None` (and |
| 594 | /// anything else) is 24. No other format reads it. |
| 595 | pub audio_bit_depth: Option<u8>, |
| 596 | /// Which of the project's subtitle tracks travel with the file: indices into |
| 597 | /// [`Project::subtitles`], which is the same list a front-end picks rows of. |
| 598 | /// As many as the timeline holds, in the order given -- the file declares |
| 599 | /// them in that order and a player's subtitle menu lists them in it. Empty |
| 600 | /// writes none -- what every caller wrote before there was a choice, so an |
| 601 | /// export of a timeline without subtitles is the file it always was, byte |
| 602 | /// for byte. |
| 603 | /// |
| 604 | /// Every container that carries picture carries them: Matroska as |
| 605 | /// `S_TEXT/UTF8` blocks, an mp4 as a `tx3g` timed-text track |
| 606 | /// ([`crate::mux::Mp4Muxer::write_subtitles`]). A Matroska block names its |
| 607 | /// track in one byte, so a Matroska file carries at most |
| 608 | /// [`crate::mux::MAX_SUB_TRACKS`] of them and asking for more is refused by |
| 609 | /// name rather than truncated; an mp4 numbers its tracks in 32 bits and has |
| 610 | /// no such ceiling. |
| 611 | pub subtitles: Vec<usize>, |
| 612 | /// Writes no soft subtitle track at all -- not the lanes, not the picks. The |
| 613 | /// captions a file carries are then only the ones [`burn_subtitles`] drew |
| 614 | /// into its picture. `false` is what every caller wrote before there was a |
| 615 | /// choice, so the lanes and the picks decide as they always did. |
| 616 | /// |
| 617 | /// [`burn_subtitles`]: ExportSettings::burn_subtitles |
| 618 | pub no_soft_subtitles: bool, |
| 619 | /// Code every picture as a key frame a decoder may be started from: no |
| 620 | /// frame references another, the file is an intraframe master in the shape |
| 621 | /// of ProRes, and a seek to any frame at all is one decode. |
| 622 | /// |
| 623 | /// Bigger files for that, so it is off for delivery and on for the |
| 624 | /// stand-ins [`crate::proxy`] makes, which exist precisely to be seeked |
| 625 | /// through. This is the switch of the H.264 and HEVC pairs; on HEVC the |
| 626 | /// software seat then codes every picture an IDR ([`Enc::open_hevc`]) and |
| 627 | /// the hardware seat is already intra. AV1 has no such switch. |
| 628 | pub intra_only: bool, |
| 629 | /// Captions drawn into the picture: the track at this index in |
| 630 | /// [`Project::subtitles`] (the index [`ExportSettings::subtitles`] and |
| 631 | /// [`crate::PlaybackSession::timeline_cues`] take), its cue on screen at |
| 632 | /// each timeline frame, drawn in this style ([`crate::text`]). `None` writes |
| 633 | /// the picture as it is -- what every caller wrote before there was a |
| 634 | /// choice. |
| 635 | /// |
| 636 | /// A burned-in picture is never copied out of its source: it is decoded, |
| 637 | /// drawn and encoded, so [`exact_refusal`] names the copy it gives up. The |
| 638 | /// cues are the ones the timeline plays, so a rippled edit captions what it |
| 639 | /// shows, the way the soft track does. |
| 640 | pub burn_subtitles: Option<(usize, TextStyle)>, |
| 641 | /// Write the picture in the space its **source** declares -- no tone map to |
| 642 | /// SDR, no matrix conversion -- and tag the file with it, instead of |
| 643 | /// converting everything into the space the output height implies. |
| 644 | /// |
| 645 | /// For a preview file and nothing else ([`crate::proxy`]): it makes the |
| 646 | /// stand-in a smaller copy of the film rather than a rendition of it, so |
| 647 | /// the screen tone-maps it live with whatever preset the project is set to |
| 648 | /// -- and it takes the per-frame conversion off the *source's* full |
| 649 | /// resolution, which on a 4K HDR film was 48 ms a frame and the whole of a |
| 650 | /// proxy's cost (measured 2026-08-13). |
| 651 | /// |
| 652 | /// A delivery export must leave it off: an mp4 in BT.2020 PQ is a file for |
| 653 | /// this editor to read back, not one to hand anybody. |
| 654 | pub keep_source_colour: bool, |
| 655 | /// Half-open `[start, end)` in timeline frames, or `None` for the whole |
| 656 | /// timeline -- what every caller wrote before there was a choice, so an |
| 657 | /// export nobody has marked in or out on writes the same bytes it always |
| 658 | /// did. Session state, like the mark itself: never saved to a `.edith`. |
| 659 | pub range: Option<(u32, u32)>, |
| 660 | /// The Exact quality row: this file must be the source's own coded |
| 661 | /// picture, copied wherever [`CopyPlan`] already says a copy is exactly |
| 662 | /// what the timeline says. `bitrate` and `seat` mean nothing to a copied |
| 663 | /// track, but a fallback re-encode (a cut off a sync point, a grade, a |
| 664 | /// speed, a transform) still honours them, so a copy-minded caller sends |
| 665 | /// `bitrate: None` beside this and gets the automatic figure rather than |
| 666 | /// a preset's. |
| 667 | /// |
| 668 | /// [`exact_refusal`] is the gate a front-end asks before the button is |
| 669 | /// pressed; [`run`] asks it again, which is what makes this a setting a |
| 670 | /// worker can trust rather than one only the card checked. |
| 671 | pub exact: bool, |
| 672 | /// The picture's size in pixels for this export alone, `(width, height)`: |
| 673 | /// the canvas the file is drawn and encoded at, in place of the project's |
| 674 | /// resolution. The project itself is not touched -- [`start`] applies it to |
| 675 | /// the export's own copy of the settings, and every clip refits on that |
| 676 | /// canvas by its fit mode, as it does when the project's resolution changes. |
| 677 | /// `None` is the project's own size, as every caller wrote before there was |
| 678 | /// a choice. Each side must be a picture size ([`crate::is_resolution`]) and |
| 679 | /// even, which the caller checks: a size here is trusted as given. |
| 680 | pub size: Option<(u32, u32)>, |
| 681 | /// Chapter marks the file carries, `(start in ns, title)` each, sorted by start. An mp4 gets |
| 682 | /// them as a Nero `chpl` and a QuickTime chapter track, a Matroska file as a `Chapters` |
| 683 | /// element. Empty writes none, which is what every caller wrote before there was a choice. |
| 684 | pub chapters: Vec<(u64, String)>, |
| 685 | /// Level the mixed sound to this integrated loudness under this true-peak ceiling before it |
| 686 | /// is coded ([`LoudnessTarget`]). `None` writes the mix at the level it was heard at, which |
| 687 | /// is what every caller wrote before there was a choice. A track is never *copied* when this |
| 688 | /// is set: a packet copy carries no gain. |
| 689 | pub loudness: Option<LoudnessTarget>, |
| 690 | /// The ProRes profile of a [`Format::ProRes`] export; means nothing to any |
| 691 | /// other format. Defaults to [`ProResProfile::Hq`]. |
| 692 | pub prores_profile: ProResProfile, |
| 693 | /// HDR output of an HEVC export ([`Format::Hevc`], [`Format::HevcMp4`]); see |
| 694 | /// [`HdrOutput`]. Refused for every other format. The default is none. |
| 695 | pub hdr: HdrOutput, |
| 696 | /// Speed preset of the software HEVC encoder ([`Format::Hevc`], [`Format::HevcMp4`]); means |
| 697 | /// nothing to any other format. `None` is [`HevcSpeed::Default`], the encoder's own search, |
| 698 | /// bit-identical to every export written before there was a choice. |
| 699 | pub hevc_speed: Option<HevcSpeed>, |
| 700 | /// What a GIF asks for beyond the picture ([`Format::Gif`]); means nothing to any other format. |
| 701 | pub gif: GifSettings, |
| 702 | /// Seconds between key frames of a video export's H.264, HEVC or AV1 picture, `None` for the |
| 703 | /// encoder's own. Refused with [`ExportSettings::intra_only`], which codes every picture a key frame. |
| 704 | pub keyframe_s: Option<f64>, |
| 705 | /// Lays an mp4 out `ftyp`, `moov`, `mdat` so it can start playing before its end. Means |
| 706 | /// something only to [`Format::Mp4`], [`Format::HevcMp4`], [`Format::Av1Mp4`] and [`Format::M4a`]. |
| 707 | pub faststart: bool, |
| 708 | } |
| 709 | |
| 710 | /// The settings of an animated GIF ([`Format::Gif`]): its width in pixels (the height follows |
| 711 | /// the project's aspect), its frame rate, and whether it loops. The default is the size and rate |
| 712 | /// a GIF is usually shared at: 480 pixels wide, 15 frames a second, looping forever. |
| 713 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 714 | pub struct GifSettings { |
| 715 | pub width: u32, |
| 716 | pub fps: u32, |
| 717 | pub loop_forever: bool, |
| 718 | } |
| 719 | |
| 720 | impl Default for GifSettings { |
| 721 | fn default() -> Self { |
| 722 | Self { width: 480, fps: 15, loop_forever: true } |
| 723 | } |
| 724 | } |
| 725 | |
| 726 | /// Speed preset of the software HEVC encoder (`ec-h265`'s `Preset`). `Fast` costs about 0-3% |
| 727 | /// BD-rate for 1.2-1.6x speed, `Faster` up to 27% for about 1.5-2x. |
| 728 | #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] |
| 729 | pub enum HevcSpeed { |
| 730 | #[default] |
| 731 | Default, |
| 732 | Fast, |
| 733 | Faster, |
| 734 | } |
| 735 | |
| 736 | impl HevcSpeed { |
| 737 | fn preset(self) -> ec_h265::encoder::Preset { |
| 738 | match self { |
| 739 | Self::Default => ec_h265::encoder::Preset::Default, |
| 740 | Self::Fast => ec_h265::encoder::Preset::Fast, |
| 741 | Self::Faster => ec_h265::encoder::Preset::Faster, |
| 742 | } |
| 743 | } |
| 744 | } |
| 745 | |
| 746 | /// An export-time loudness normalisation: one gain over the whole mix, from |
| 747 | /// [`crate::loudness::gain_to_target`], so the integrated loudness lands on `lufs` and the true |
| 748 | /// peak is held at or under `true_peak_dbtp` (the gain is cut back, never a limiter). |
| 749 | #[derive(Debug, Clone, Copy, PartialEq)] |
| 750 | pub struct LoudnessTarget { |
| 751 | pub lufs: f64, |
| 752 | pub true_peak_dbtp: f64, |
| 753 | } |
| 754 | |
| 755 | // Plain finite figures, never NaN: the settings that hold one are `Eq`. |
| 756 | impl Eq for LoudnessTarget {} |
| 757 | |
| 758 | /// Measures `samples` (interleaved) and scales them by the gain that reaches `target`. |
| 759 | fn level_to_target(samples: &mut [f32], rate: u32, channels: u16, target: LoudnessTarget) { |
| 760 | let mut meter = crate::loudness::Meter::new(rate, channels); |
| 761 | meter.push(samples); |
| 762 | let gain = crate::loudness::gain_to_target(&meter.finish(), target.lufs, target.true_peak_dbtp); |
| 763 | if gain != 0.0 { |
| 764 | let g = 10f32.powf(gain as f32 / 20.0); |
| 765 | for s in samples.iter_mut() { |
| 766 | *s *= g; |
| 767 | } |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | /// The export's picture size: the project's canvas, or the [`ExportSettings::size`] |
| 772 | /// this export is asked to draw at. Everything that decides what the file's picture |
| 773 | /// is (the encoder's seat, the copy's gate, the colour matrix) asks it through here, |
| 774 | /// so the answer each gives is the one the file has. |
| 775 | pub fn output_meta(meta: &VideoMeta, settings: &ExportSettings) -> VideoMeta { |
| 776 | match settings.size { |
| 777 | // The coded size goes with the drawn one: a copy's gate compares the coded pair with its |
| 778 | // source's, and a picture drawn at another size is not a copy of anything. |
| 779 | Some((width, height)) => VideoMeta { |
| 780 | width, |
| 781 | height, |
| 782 | coded_width: width, |
| 783 | coded_height: height, |
| 784 | ..*meta |
| 785 | }, |
| 786 | None => *meta, |
| 787 | } |
| 788 | } |
| 789 | |
| 790 | /// What [`fit_picture_clips`] did: the full-frame clips it put on the policy, per lane (a lane |
| 791 | /// with none is left out), and how many transformed overlays it left on their own fit. |
| 792 | #[derive(Debug, Clone, PartialEq, Eq, Default)] |
| 793 | pub struct FitOutcome { |
| 794 | pub lanes: Vec<(Lane, usize)>, |
| 795 | pub overlays: usize, |
| 796 | } |
| 797 | |
| 798 | /// Puts every full-frame picture clip of `project` on `fit`, in place. Meant for the export's own |
| 799 | /// copy of the timeline ([`start`] takes it by value), so the project a user edits keeps its |
| 800 | /// clips' fit modes. A clip refits on the export's canvas by its fit mode, so this is how an |
| 801 | /// export asks for `fit` on the pictures that fill the frame. |
| 802 | /// |
| 803 | /// A clip placed by a transform (moved, scaled, cropped, faded or animated) is an overlay and |
| 804 | /// keeps its own fit: `fill` would crop it to the canvas's shape, so a logo would lose its |
| 805 | /// aspect on a vertical canvas. Its size stays relative to the canvas width, as in the project. |
| 806 | /// The whole change is one undo step on the copy, which nothing reads. |
| 807 | pub fn fit_picture_clips(project: &mut Project, fit: FitPolicy) -> FitOutcome { |
| 808 | let videos: Vec<Lane> = project.lanes().into_iter().filter(|l| l.kind == LaneKind::Video).collect(); |
| 809 | project.begin_batch(); |
| 810 | let mut outcome = FitOutcome::default(); |
| 811 | for lane in videos { |
| 812 | let mut count = 0; |
| 813 | for idx in 0..project.lane(lane).len() { |
| 814 | if is_placed(project, lane, idx) { |
| 815 | outcome.overlays += 1; |
| 816 | } else { |
| 817 | project.set_fit(lane, idx, fit); |
| 818 | count += 1; |
| 819 | } |
| 820 | } |
| 821 | if count > 0 { |
| 822 | outcome.lanes.push((lane, count)); |
| 823 | } |
| 824 | } |
| 825 | project.end_batch(); |
| 826 | outcome |
| 827 | } |
| 828 | |
| 829 | /// Whether the clip at `idx` of `lane` is placed by a transform that is not the identity, or has |
| 830 | /// a placement animation: the overlays [`fit_picture_clips`] leaves alone. |
| 831 | fn is_placed(project: &Project, lane: Lane, idx: usize) -> bool { |
| 832 | project.transform_of(lane, idx).is_some_and(|t| !t.is_identity()) |
| 833 | || !project.transform_keys_of(lane, idx).is_empty() |
| 834 | } |
| 835 | |
| 836 | /// The first moment a burned caption and a title show together in the same place. `cues` are the |
| 837 | /// burn's cues ([`burn_cues`]) and `place` the burn's own place; a title sits where its |
| 838 | /// `style.place` says, so a clash is a caption and a title with the same place on screen at once. |
| 839 | /// Returns the moment in seconds and the index into `titles` of the title, the earliest such |
| 840 | /// moment; `None` when no caption and title clash. |
| 841 | pub fn caption_title_clash(cues: &[Cue], titles: &[Title], place: Place, fps: f64) -> Option<(f64, usize)> { |
| 842 | let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64; |
| 843 | let mut first: Option<(i64, usize)> = None; |
| 844 | for (i, t) in titles.iter().enumerate().filter(|(_, t)| t.style.place == place) { |
| 845 | let (start, end) = (us(t.start), us(t.end())); |
| 846 | for c in cues.iter().filter(|c| c.image.is_none() && !c.text.trim().is_empty()) { |
| 847 | let lo = c.start_us.max(start); |
| 848 | if lo < c.end_us.min(end) && first.is_none_or(|(f, _)| lo < f) { |
| 849 | first = Some((lo, i)); |
| 850 | } |
| 851 | } |
| 852 | } |
| 853 | first.map(|(lo, i)| (lo as f64 / 1e6, i)) |
| 854 | } |
| 855 | |
| 856 | /// The lowest H.264 level (Table A-1) whose frame size and macroblock rate |
| 857 | /// hold `width`x`height` at `fps_num/fps_den`, as the `level_idc` byte; 62 |
| 858 | /// past the table. One table for both seats: the software encoder writes it |
| 859 | /// into its SPS (its default is 3.0, which is out of spec above 720p30) and |
| 860 | /// the plugin hands it to the driver. |
| 861 | pub fn h264_level_idc(width: u32, height: u32, fps_num: u32, fps_den: u32) -> u8 { |
| 862 | const LEVELS: [(u8, u64, u64); 17] = [ |
| 863 | (10, 1485, 99), |
| 864 | (11, 3000, 396), |
| 865 | (12, 6000, 396), |
| 866 | (13, 11880, 396), |
| 867 | (20, 11880, 396), |
| 868 | (21, 19800, 792), |
| 869 | (22, 20250, 1620), |
| 870 | (30, 40500, 1620), |
| 871 | (31, 108000, 3600), |
| 872 | (32, 216000, 5120), |
| 873 | (40, 245760, 8192), |
| 874 | (41, 245760, 8192), |
| 875 | (42, 522240, 8704), |
| 876 | (50, 589824, 22080), |
| 877 | (51, 983040, 36864), |
| 878 | (52, 2073600, 36864), |
| 879 | (60, 4177920, 139264), |
| 880 | ]; |
| 881 | let frame_mbs = u64::from(width.div_ceil(16)) * u64::from(height.div_ceil(16)); |
| 882 | let fps = f64::from(fps_num.max(1)) / f64::from(fps_den.max(1)); |
| 883 | let mbps = (frame_mbs as f64 * fps).ceil() as u64; |
| 884 | LEVELS |
| 885 | .iter() |
| 886 | .find(|&&(_, max_mbps, max_fs)| mbps <= max_mbps && frame_mbs <= max_fs) |
| 887 | .map_or(62, |&(idc, ..)| idc) |
| 888 | } |
| 889 | |
| 890 | struct Shared { |
| 891 | /// Fraction of the job done, in [`PROGRESS_SCALE`]ths. |
| 892 | /// |
| 893 | /// **Every stage that can run beside another writes this with `fetch_max`, |
| 894 | /// never `store`.** The sound and the picture are two threads publishing |
| 895 | /// two bands of one bar ([`AUDIO_BAND`]): a `store` from the lower band |
| 896 | /// pulls the bar backwards every time the other thread has already moved |
| 897 | /// it on, which is what a person sees as a progress bar that stutters |
| 898 | /// backwards -- 5,458 backward steps over one film export before this rule |
| 899 | /// was written down. A `store` is only correct where nothing else can be |
| 900 | /// publishing at all, which now means the terminal [`PROGRESS_SCALE`] and |
| 901 | /// the audio-only export ([`run_audio`]) that has no second thread. The |
| 902 | /// rule outlives one attempt at the file: an export rerun in software |
| 903 | /// because the hardware seat died writes this same atomic, and the bar |
| 904 | /// holds where the dead seat left it rather than starting again. |
| 905 | progress: AtomicU32, |
| 906 | cancel: AtomicBool, |
| 907 | finished: AtomicBool, |
| 908 | outcome: Mutex<Option<crate::Result<()>>>, |
| 909 | /// The encoders this job really opened, published the moment they are |
| 910 | /// chosen and never changed after -- one seat for the whole file, which is |
| 911 | /// what [`Enc`] states. `None` until then. The one thing that joins it |
| 912 | /// afterwards is how much of the edit never got a picture |
| 913 | /// ([`Shared::truncated`]), and [`ExportHandle::encoders`] does that |
| 914 | /// joining, so a notice cannot land on the line twice. |
| 915 | encoders: Mutex<Option<String>>, |
| 916 | /// Timeline frames of the edit the walk could not write because a file ran |
| 917 | /// out before its clip did ([`run`]'s break). The bar reaches its end |
| 918 | /// whatever happens, so without this a truncated file reads as a whole one. |
| 919 | /// Published the moment the walk gives up and read by |
| 920 | /// [`ExportHandle::encoders`] beside the seat line. |
| 921 | truncated: AtomicU32, |
| 922 | /// A stage that runs before a span can encode -- a stabilised clip's shake |
| 923 | /// being measured ([`crate::stabilise::ensure`]) -- as `1 +` its thousandths |
| 924 | /// done, `0` while none runs. Its own fraction, beside [`Shared::progress`] |
| 925 | /// rather than in it, which holds still meanwhile ([`ExportHandle::stage`]). |
| 926 | measuring: AtomicU32, |
| 927 | /// [`ExportSettings::loudness`], for the audio stages that only see `Shared`. |
| 928 | loudness: Option<LoudnessTarget>, |
| 929 | } |
| 930 | |
| 931 | /// A running export. Poll [`is_finished`](ExportHandle::is_finished) once per |
| 932 | /// rendered frame and take the [`result`](ExportHandle::result) when it flips; |
| 933 | /// dropping the handle does *not* stop the worker, [`cancel`](ExportHandle::cancel) |
| 934 | /// does. |
| 935 | pub struct ExportHandle { |
| 936 | shared: Arc<Shared>, |
| 937 | /// The length of the file this export writes, in seconds: the range's, or the |
| 938 | /// picture and sound's end for a whole-timeline export. Known before the first frame. |
| 939 | length_secs: f64, |
| 940 | } |
| 941 | |
| 942 | impl ExportHandle { |
| 943 | /// Fraction of the timeline written, `0.0..=1.0`. |
| 944 | pub fn progress(&self) -> f32 { |
| 945 | self.shared.progress.load(Ordering::Relaxed) as f32 / PROGRESS_SCALE as f32 |
| 946 | } |
| 947 | |
| 948 | /// The length of the file this export writes, in seconds: the frames it holds at the |
| 949 | /// canvas's frame rate, which is the file's duration as a player shows it (a range is |
| 950 | /// cut to the picture's end the same way the encoder cuts it). |
| 951 | pub fn length_secs(&self) -> f64 { |
| 952 | self.length_secs |
| 953 | } |
| 954 | |
| 955 | /// Asks the worker to stop at its next checkpoint and delete the partial |
| 956 | /// file. The outcome then reports the cancellation as an error. Checkpoints |
| 957 | /// run to the last instant before the rename, so even a cancel at full |
| 958 | /// progress leaves no output. |
| 959 | pub fn cancel(&self) { |
| 960 | self.shared.cancel.store(true, Ordering::Relaxed); |
| 961 | } |
| 962 | |
| 963 | /// Whether [`cancel`](Self::cancel) was asked: the worker has not yet reached its |
| 964 | /// next checkpoint, so the export is still running though it is going to stop. |
| 965 | pub fn is_cancelling(&self) -> bool { |
| 966 | self.shared.cancel.load(Ordering::Relaxed) |
| 967 | } |
| 968 | |
| 969 | pub fn is_finished(&self) -> bool { |
| 970 | self.shared.finished.load(Ordering::Acquire) |
| 971 | } |
| 972 | |
| 973 | /// What this export is encoding with -- the video seat and what the sound |
| 974 | /// is doing -- as the worker chose them, hardware fallback included. |
| 975 | /// `None` for the first instants of a job, before the encoder is open. |
| 976 | /// |
| 977 | /// ...and, where a file ran out under its clip, how much of the edit never |
| 978 | /// got a picture. Composed here rather than written into the stored line, |
| 979 | /// because that line is published more than once on a rerun (a hardware |
| 980 | /// seat that died) and a notice appended at the write site lands twice. |
| 981 | pub fn encoders(&self) -> Option<String> { |
| 982 | let line = self.shared.encoders.lock().unwrap().clone()?; |
| 983 | Some(match self.shared.truncated.load(Ordering::Relaxed) { |
| 984 | 0 => line, |
| 985 | past => format!("{line} · {past} frames of the edit past the last picture"), |
| 986 | }) |
| 987 | } |
| 988 | |
| 989 | /// The stage the export is in when it is not encoding: its name and its own |
| 990 | /// fraction done, `0.0..=1.0` -- `("Measuring shake", 0.4)` while a stabilised |
| 991 | /// clip with no finished analysis is measured. `None` while it encodes, when |
| 992 | /// [`progress`](Self::progress) is the one to show. |
| 993 | pub fn stage(&self) -> Option<(&'static str, f32)> { |
| 994 | match self.shared.measuring.load(Ordering::Relaxed) { |
| 995 | 0 => None, |
| 996 | n => Some((MEASURING_SHAKE, ((n - 1) as f32 / 1000.0).clamp(0.0, 1.0))), |
| 997 | } |
| 998 | } |
| 999 | |
| 1000 | /// The outcome, once — taken out of the handle, so a caller that already |
| 1001 | /// reported it sees `None` afterwards. `None` while the export is running. |
| 1002 | pub fn result(&self) -> Option<crate::Result<()>> { |
| 1003 | self.shared.outcome.lock().unwrap().take() |
| 1004 | } |
| 1005 | } |
| 1006 | |
| 1007 | /// Starts the worker. Failures are reported through the handle rather than |
| 1008 | /// returned, so a caller has exactly one place to look. The files to read are |
| 1009 | /// the project's own [`sources`](Project::sources) -- every clip names one -- |
| 1010 | /// so nothing but the edit list decides what is decoded. |
| 1011 | pub fn start( |
| 1012 | project: Project, |
| 1013 | meta: VideoMeta, |
| 1014 | out: &Path, |
| 1015 | settings: &ExportSettings, |
| 1016 | sample_rate: Option<u32>, |
| 1017 | ) -> ExportHandle { |
| 1018 | let settings = settings.clone(); |
| 1019 | // The canvas this export draws at: the project's, unless the settings name another. |
| 1020 | let meta = output_meta(&meta, &settings); |
| 1021 | let media = project.media_frames(); |
| 1022 | let frames = match settings.range { |
| 1023 | Some((from, to)) => to.min(media).saturating_sub(from), |
| 1024 | None => media, |
| 1025 | }; |
| 1026 | let length_secs = f64::from(frames) / meta.frame_rate; |
| 1027 | let shared = Arc::new(Shared { |
| 1028 | progress: AtomicU32::new(0), |
| 1029 | cancel: AtomicBool::new(false), |
| 1030 | finished: AtomicBool::new(false), |
| 1031 | outcome: Mutex::new(None), |
| 1032 | encoders: Mutex::new(None), |
| 1033 | truncated: AtomicU32::new(0), |
| 1034 | measuring: AtomicU32::new(0), |
| 1035 | loudness: settings.loudness, |
| 1036 | }); |
| 1037 | let worker = Arc::clone(&shared); |
| 1038 | // A second handle to the same slot, held outside the caught body below -- |
| 1039 | // what settles it if that body never gets to its own [`settle`] call at |
| 1040 | // all, because a codec parser deep inside `run` panicked instead of |
| 1041 | // returning the parse error it should have. Without this a panic there |
| 1042 | // strands the slot: [`ExportHandle::is_finished`] never flips, and a |
| 1043 | // proxy or export that hit a malformed frame sits in "Making" forever. |
| 1044 | let panic_worker = Arc::clone(&worker); |
| 1045 | let out = out.to_path_buf(); |
| 1046 | // `<out>.part`, appended rather than substituted: the temporary of |
| 1047 | // `a.export.mp4` is `a.export.mp4.part`, which no other export claims. |
| 1048 | let mut part = out.clone().into_os_string(); |
| 1049 | part.push(".part"); |
| 1050 | let part = PathBuf::from(part); |
| 1051 | let spawned = thread::Builder::new().name("export".into()).spawn(move || { |
| 1052 | let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { |
| 1053 | // Every file this export will read, named before a byte of one is. |
| 1054 | // These are the project's own sources and can be nothing else: a |
| 1055 | // stand-in ([`crate::proxy`]) is a substitution playback makes when it |
| 1056 | // opens a span, and nothing here knows such a thing exists. Printed so |
| 1057 | // that "the delivery came off the film itself" is a grep rather than a |
| 1058 | // belief. |
| 1059 | for source in project.sources() { |
| 1060 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export source: {}", source.path.display()); } |
| 1061 | } |
| 1062 | // The rename is the last step and the only one that publishes a file |
| 1063 | // under the name the caller asked for; it stays on the same directory, |
| 1064 | // so it is atomic. |
| 1065 | // |
| 1066 | // An emptied timeline is a legal project and an illegal file: no |
| 1067 | // picture, no sound, and a muxer that is never created because no coded |
| 1068 | // frame arrives. Refused by name here -- before the format is even |
| 1069 | // looked at, so an mp4 and a WAV refuse in the same words -- rather than |
| 1070 | // left to write a file of no frames that nothing opens. Every caller of |
| 1071 | // `start` comes through this, the app's own door |
| 1072 | // (`PlaybackSession::is_empty`) being only the first fence. |
| 1073 | // |
| 1074 | // An audio-only timeline has no picture to give a file, and an mp4 of |
| 1075 | // it would be black picture over the sound -- minutes of encoding for a |
| 1076 | // video of nothing. So an mp4 of it is written as the sound alone, the |
| 1077 | // same AAC track in an mp4 with no picture entry ([`run_aac`]); the |
| 1078 | // Matroska and WebM containers, which have no such form, are refused by |
| 1079 | // name. The app says the same on the format row before a destination |
| 1080 | // is even picked (`mp4_refusal`). |
| 1081 | let written = match settings.format { |
| 1082 | _ if project.timeline_frames() == 0 => { |
| 1083 | Err("the timeline is empty: there is nothing to export".into()) |
| 1084 | } |
| 1085 | Format::PngSequence | Format::Still | Format::Gif if !has_picture(&project) => Err(format!( |
| 1086 | "the timeline has no picture: {} would be black. Export an mp4, an \ |
| 1087 | M4A, WAV, FLAC, MP3, Ogg or Opus, which are the sound itself", |
| 1088 | settings.format.name() |
| 1089 | ) |
| 1090 | .into()), |
| 1091 | // The pictures are composed one timeline frame at a time, with no sound. |
| 1092 | Format::PngSequence => run_png_sequence(&project, &meta, &out, &worker, &settings), |
| 1093 | Format::Still => run_still(&project, &meta, &part, &settings), |
| 1094 | Format::Gif => run_gif(&project, &meta, &part, &worker, &settings), |
| 1095 | format if format.ext() == "mp4" && !has_picture(&project) => { |
| 1096 | run_aac(&project, &meta, &part, &worker, &settings, sample_rate) |
| 1097 | } |
| 1098 | format if format.has_video() && !has_picture(&project) => Err(format!( |
| 1099 | "the timeline has no picture: {} would be black. Export an mp4, an \ |
| 1100 | M4A, WAV, FLAC, MP3, Ogg or Opus, which are the sound itself", |
| 1101 | format.name() |
| 1102 | ) |
| 1103 | .into()), |
| 1104 | format if format.has_video() => { |
| 1105 | let first = run(&project, &meta, &part, &worker, &settings, sample_rate); |
| 1106 | match first { |
| 1107 | // The hardware encoder's *process* died under the driver |
| 1108 | // ([`crate::hwproc`]) -- the editor is still here, and the |
| 1109 | // file is still owed. Written again by the software encoder |
| 1110 | // for this codec, from the first frame: the pictures the |
| 1111 | // dead seat coded are not ones this one may continue from. |
| 1112 | // |
| 1113 | // Not where a person picked the GPU by name: that export |
| 1114 | // refuses in words, the same answer [`hw_seat`] already |
| 1115 | // gives a machine with no seat at all, rather than quietly |
| 1116 | // spending an hour in an encoder nobody chose. |
| 1117 | Err(e) |
| 1118 | if crate::hwproc::is_lost(&e) |
| 1119 | && settings.seat != EncoderSeat::Hardware => |
| 1120 | { |
| 1121 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export video: {e}; writing it again in software"); } |
| 1122 | let _ = std::fs::remove_file(&part); |
| 1123 | // The bar is *not* put back to zero: the rerun writes |
| 1124 | // it with `fetch_max` like everything else |
| 1125 | // ([`Shared::progress`]), so it holds where the dead |
| 1126 | // seat left it and moves again once the software |
| 1127 | // encoder passes that mark. A person whose GPU has just |
| 1128 | // died is the last one who should also watch the bar |
| 1129 | // run backwards. |
| 1130 | let mut software = settings.clone(); |
| 1131 | software.seat = EncoderSeat::Software; |
| 1132 | run(&project, &meta, &part, &worker, &software, sample_rate) |
| 1133 | } |
| 1134 | other => other, |
| 1135 | } |
| 1136 | } |
| 1137 | Format::M4a => run_aac(&project, &meta, &part, &worker, &settings, sample_rate), |
| 1138 | // Opus codes at 48 kHz and nothing else, so the mix is made there. |
| 1139 | Format::Opus => run_audio(&project, &meta, &part, &worker, &settings, Some(OPUS_RATE)), |
| 1140 | _ => run_audio(&project, &meta, &part, &worker, &settings, sample_rate), |
| 1141 | }; |
| 1142 | let result = match settings.format { |
| 1143 | // A run of pictures is written into the folder it was asked for, which has no |
| 1144 | // temporary of its own to publish. |
| 1145 | Format::PngSequence => written, |
| 1146 | _ => written.and_then(|()| std::fs::rename(&part, &out).map_err(Into::into)), |
| 1147 | }; |
| 1148 | if result.is_err() { |
| 1149 | // The muxer -- and with it the file handle -- died with `run`. |
| 1150 | let _ = std::fs::remove_file(&part); |
| 1151 | } |
| 1152 | settle(&worker, result); |
| 1153 | })); |
| 1154 | if let Err(payload) = caught { |
| 1155 | // The body above panicked before it could settle its own slot -- |
| 1156 | // the panic message becomes the outcome, so a caller sees a |
| 1157 | // failure and a notice rather than a bar that never moves again. |
| 1158 | let message = payload |
| 1159 | .downcast_ref::<&str>() |
| 1160 | .map(ToString::to_string) |
| 1161 | .or_else(|| payload.downcast_ref::<String>().cloned()) |
| 1162 | .unwrap_or_else(|| "unknown panic".to_string()); |
| 1163 | if !panic_worker.finished.load(Ordering::Acquire) { |
| 1164 | // ...and the `.part` the body left behind is deleted here: the |
| 1165 | // module promises every failure path removes it, and the only |
| 1166 | // path that did was the body's own `result.is_err()` arm, which |
| 1167 | // a panic never reaches. Done inside this branch only -- a body |
| 1168 | // that *did* settle has already renamed or deleted the file. |
| 1169 | let _ = std::fs::remove_file(&part); |
| 1170 | settle( |
| 1171 | &panic_worker, |
| 1172 | Err(format!("export worker panicked: {message}").into()), |
| 1173 | ); |
| 1174 | } |
| 1175 | } |
| 1176 | }); |
| 1177 | if let Err(e) = spawned { |
| 1178 | settle(&shared, Err(e.into())); |
| 1179 | } |
| 1180 | ExportHandle { shared, length_secs } |
| 1181 | } |
| 1182 | |
| 1183 | /// Whether any video lane holds anything at all -- what tells an audio-only |
| 1184 | /// timeline from one that merely opens on a gap. Asked of the *lanes* rather |
| 1185 | /// than of the sources, because a project may name a video file no clip plays |
| 1186 | /// from any more. |
| 1187 | fn has_picture(project: &Project) -> bool { |
| 1188 | // A title is a picture of its own: a timeline of nothing but a title card |
| 1189 | // over black is a picture, not a black one. |
| 1190 | !project.titles().is_empty() |
| 1191 | || project |
| 1192 | .lanes() |
| 1193 | .into_iter() |
| 1194 | .any(|lane| lane.kind == LaneKind::Video && !project.lane(lane).is_empty()) |
| 1195 | } |
| 1196 | |
| 1197 | /// Whether any audio lane holds anything, [`has_picture`]'s pair: what tells a |
| 1198 | /// timeline whose export will carry sound from one whose file has none. |
| 1199 | fn has_sound(project: &Project) -> bool { |
| 1200 | project |
| 1201 | .lanes() |
| 1202 | .into_iter() |
| 1203 | .any(|lane| lane.kind == LaneKind::Audio && !project.lane(lane).is_empty()) |
| 1204 | } |
| 1205 | |
| 1206 | /// Whether any equalizer on the sound is doing something -- the one edit a |
| 1207 | /// packet copy cannot carry, so an mp4 whose lane has one is decoded and |
| 1208 | /// re-encoded ([`encode_audio`]) instead of copied. Asked of every audio lane: |
| 1209 | /// the copy path has exactly one by the time it asks, and [`planned_audio`] is |
| 1210 | /// asked before that is settled. |
| 1211 | fn equalized(project: &Project) -> bool { |
| 1212 | project.audio_lanes().into_iter().any(|lane| { |
| 1213 | (0..project.lane(lane).len()) |
| 1214 | .any(|idx| project.eq_of(lane, idx).is_some_and(|eq| !eq.is_identity())) |
| 1215 | }) |
| 1216 | } |
| 1217 | |
| 1218 | /// How many timeline frames before a ranged export's start the mix is opened, so the voice |
| 1219 | /// chain's envelopes and the noise reduction's overlap are warm when the range begins |
| 1220 | /// instead of starting from silence ([`voice`](crate::voice)). Half a second, as far back as |
| 1221 | /// the timeline goes; none when no lane has a processor on. [`warm_up_samples`] is how much |
| 1222 | /// of the mix's front that is, taken off again. |
| 1223 | fn warm_up(project: &Project, offset: u32, fps: f64) -> u32 { |
| 1224 | if offset == 0 || !project.audio_voices().iter().any(crate::voice::VoiceFx::is_active) { |
| 1225 | return 0; |
| 1226 | } |
| 1227 | offset.min((fps * 0.5).ceil() as u32) |
| 1228 | } |
| 1229 | |
| 1230 | /// How many interleaved samples the `pre` frames of [`warm_up`] before `range_start` are: |
| 1231 | /// the samples the timeline's mix puts between the two frames, counted with the mixer's own |
| 1232 | /// rounding ([`timeline_sample`](crate::audio::timeline_sample)), so the range starts on the |
| 1233 | /// same sample a full export has there. Rounding the pre-roll's own length instead can miss |
| 1234 | /// by one at 29.97 or 23.976 fps. |
| 1235 | fn warm_up_samples(range_start: u32, pre: u32, fps: f64, rate: u32, channels: usize) -> usize { |
| 1236 | let at = |frame: u32| crate::audio::timeline_sample(f64::from(frame) / fps, rate); |
| 1237 | (at(range_start) - at(range_start - pre)) as usize * channels |
| 1238 | } |
| 1239 | |
| 1240 | /// Whether the *mix* is doing something -- a lane turned off unity, a lane |
| 1241 | /// ducked under another, or a limiter in circuit. [`equalized`]'s pair, and a |
| 1242 | /// copy cannot carry any of them: all live where the lanes are summed |
| 1243 | /// ([`AudioSession::open_mixed_streams_master`]), and a copied packet was never |
| 1244 | /// summed at all. An mp4 whose timeline is mixed is decoded and re-encoded. |
| 1245 | fn mastered(project: &Project) -> bool { |
| 1246 | project.limiter().is_active() |
| 1247 | || project.audio_gains().iter().any(|&g| g != 1.0) |
| 1248 | || project.audio_ducks().iter().any(|lane| !lane.is_empty()) |
| 1249 | || project.audio_voices().iter().any(crate::voice::VoiceFx::is_active) |
| 1250 | } |
| 1251 | |
| 1252 | /// Whether any audio clip has a fade -- [`equalized`]'s pair again: a fade is |
| 1253 | /// gain math on decoded samples ([`crate::project::Fade::apply`]), and a |
| 1254 | /// packet copy carries neither an equalizer nor a fade. An mp4 whose timeline |
| 1255 | /// has one is decoded and re-encoded so the fade actually reaches the file. |
| 1256 | fn faded(project: &Project) -> bool { |
| 1257 | project.audio_lanes().into_iter().any(|lane| { |
| 1258 | project |
| 1259 | .lane(lane) |
| 1260 | .iter() |
| 1261 | .any(|c| c.fade_in > 0 || c.fade_out > 0) |
| 1262 | }) |
| 1263 | } |
| 1264 | |
| 1265 | /// The bitrate an export codes at: the caller's number clamped into what an |
| 1266 | /// asked-for rate may be ([`MIN_BITRATE`]..[`MAX_EXPLICIT_BITRATE`]), the |
| 1267 | /// derived one where there was none. Clamped rather than refused, for the |
| 1268 | /// reason [`Enc::open`] states. |
| 1269 | fn bitrate_of(meta: &VideoMeta, settings: &ExportSettings) -> u64 { |
| 1270 | settings.bitrate.map_or_else( |
| 1271 | || bitrate_for(meta), |
| 1272 | |b| b.clamp(MIN_BITRATE, MAX_EXPLICIT_BITRATE), |
| 1273 | ) |
| 1274 | } |
| 1275 | |
| 1276 | fn rate_of(meta: &VideoMeta, settings: &ExportSettings) -> SeatRate { |
| 1277 | match settings.qp { |
| 1278 | Some(qp) => SeatRate::ConstantQp(qp), |
| 1279 | None => SeatRate::Bitrate(bitrate_of(meta, settings)), |
| 1280 | } |
| 1281 | } |
| 1282 | |
| 1283 | /// The pictures between key frames the caller asked for, `None` for the encoder's own. |
| 1284 | fn gop_frames(meta: &VideoMeta, settings: &ExportSettings) -> Option<u32> { |
| 1285 | settings.keyframe_s.map(|s| (meta.frame_rate * s).round().max(1.0) as u32) |
| 1286 | } |
| 1287 | |
| 1288 | /// The rate the sound codes at: the caller's pick clamped into the offered |
| 1289 | /// range, [`DEFAULT_AUDIO_KBPS`] where there was none. Clamped and not refused, |
| 1290 | /// for [`bitrate_of`]'s reason -- a number out of range is a caller's slip and |
| 1291 | /// not a file worth failing. |
| 1292 | fn audio_kbps_of(settings: &ExportSettings) -> u32 { |
| 1293 | // 384 is above the offered rows, which a preset asks for (YouTube's AAC); MP3 has no such rate. |
| 1294 | let ceiling = if settings.format == Format::Mp3 { AUDIO_KBPS[3] } else { AAC_MAX_KBPS }; |
| 1295 | settings.audio_kbps.map_or(DEFAULT_AUDIO_KBPS, |k| k.clamp(AUDIO_KBPS[0], ceiling)) |
| 1296 | } |
| 1297 | |
| 1298 | /// The hardware seat for these settings, opened exactly as the export opens it |
| 1299 | /// -- the same pins, the same dimensions a driver may refuse -- or `None` where |
| 1300 | /// the software encoder takes the file. The single place that choice is made, |
| 1301 | /// which is what lets [`planned_video`] *measure* it instead of promising it. |
| 1302 | /// |
| 1303 | /// `Err` is the one answer the software encoder does **not** take over from: |
| 1304 | /// [`EncoderSeat::Hardware`] asked for the GPU by name and this machine has no |
| 1305 | /// seat for the codec, so the export refuses in words rather than falling back |
| 1306 | /// to an encoder nobody picked. Every caller is before a file exists |
| 1307 | /// ([`Enc::open`] runs ahead of the muxer), which is what makes the refusal |
| 1308 | /// free. |
| 1309 | fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Option<HwEncoder>> { |
| 1310 | if settings.seat == EncoderSeat::Software || forced("VE_SW_ENC") { |
| 1311 | return Ok(None); |
| 1312 | } |
| 1313 | let opened = open_hw_seat(meta, settings); |
| 1314 | if opened.is_none() && settings.seat == EncoderSeat::Hardware { |
| 1315 | return Err(format!( |
| 1316 | "hardware encoding was asked for and this machine has no VA-API seat for {}: \ |
| 1317 | pick Auto or Software on the export card", |
| 1318 | settings.format.name() |
| 1319 | ) |
| 1320 | .into()); |
| 1321 | } |
| 1322 | Ok(opened) |
| 1323 | } |
| 1324 | |
| 1325 | /// The plugin half of [`hw_seat`]: what the driver gives for this codec and |
| 1326 | /// this picture, with no policy in it but the AV1 one. |
| 1327 | fn open_hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> { |
| 1328 | let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?; |
| 1329 | let rate = rate_of(meta, settings); |
| 1330 | match settings.format { |
| 1331 | // Both HEVC formats sit on the plugin's HEVC seat, GOP or intra as the |
| 1332 | // export asks. `None` here is the plugin's own "no" -- no entrypoint, or |
| 1333 | // a picture under the driver's 384x384 floor -- and the software seat |
| 1334 | // takes it. The colour goes in at the open, from the same |
| 1335 | // [`ColorDescription::output`] rule the software seat's VUI and both |
| 1336 | // containers' tags come from, so the file cannot say one thing in its |
| 1337 | // bitstream and another in its header. |
| 1338 | format if format.is_hevc() && settings.intra_only => HwEncoder::open_hevc_intra( |
| 1339 | meta.width, |
| 1340 | meta.height, |
| 1341 | fps_num, |
| 1342 | fps_den, |
| 1343 | rate, |
| 1344 | ColorDescription::output_sized(meta.width, meta.height), |
| 1345 | ), |
| 1346 | format if format.is_hevc() => HwEncoder::open_hevc( |
| 1347 | meta.width, |
| 1348 | meta.height, |
| 1349 | fps_num, |
| 1350 | fps_den, |
| 1351 | rate, |
| 1352 | ColorDescription::output_sized(meta.width, meta.height), |
| 1353 | gop_frames(meta, settings), |
| 1354 | ), |
| 1355 | // Asked for by name only, for the reason [`Enc::open_av1`] states in |
| 1356 | // full: `Auto` takes the software encoder here and nowhere else. Both |
| 1357 | // AV1 formats sit on it: the container is not the encoder's business. |
| 1358 | format if format.is_av1() && settings.seat != EncoderSeat::Hardware => None, |
| 1359 | format if format.is_av1() => { |
| 1360 | HwEncoder::open_av1(meta.width, meta.height, fps_num, fps_den, rate, gop_frames(meta, settings)) |
| 1361 | } |
| 1362 | // An intra-only H.264 file is a *different seat*, not the same seat with |
| 1363 | // a flag on the pictures: asking this one for a key frame every time |
| 1364 | // gets I slices that are not IDRs and carry no parameter sets, which is |
| 1365 | // a file with one starting point in it however many I pictures it holds |
| 1366 | // (measured: a 60-frame hardware proxy, 1 sync point of 60). `None` |
| 1367 | // where the plugin is older than that seat, and then the software |
| 1368 | // encoder takes the file -- its `gop_size = 1` writes what was asked |
| 1369 | // for, slowly, which is the only honest fallback here. |
| 1370 | // |
| 1371 | // Only H.264 reaches this arm: the arms above take every HEVC and AV1 format. |
| 1372 | _ if settings.intra_only => { |
| 1373 | HwEncoder::open_intra(meta.width, meta.height, fps_num, fps_den, rate) |
| 1374 | } |
| 1375 | _ => HwEncoder::open(meta.width, meta.height, fps_num, fps_den, rate, gop_frames(meta, settings)), |
| 1376 | } |
| 1377 | } |
| 1378 | |
| 1379 | /// True when an Annex B HEVC access unit holds an IRAP picture (NAL types 16..=23). |
| 1380 | fn hevc_irap(au: &[u8]) -> bool { |
| 1381 | au.windows(4) |
| 1382 | .any(|w| w[0] == 0 && w[1] == 0 && w[2] == 1 && (16..=23).contains(&((w[3] >> 1) & 0x3F))) |
| 1383 | } |
| 1384 | |
| 1385 | /// What a hardware encode is called wherever one is named -- the card's line |
| 1386 | /// before the export and the progress line during it. |
| 1387 | const HW_LABEL: &str = "HW encode (VA-API)"; |
| 1388 | |
| 1389 | /// ...and what a card says instead where [`EncoderSeat::Hardware`] was picked |
| 1390 | /// and there is no seat: the export's own refusal in the width of a card row, |
| 1391 | /// shown *before* the button is pressed rather than a minute into a file. |
| 1392 | pub const NO_HW_SEAT: &str = "no HW seat here — pick Auto or Software"; |
| 1393 | |
| 1394 | /// How a front-end names a video seat: which of the two encoders has the file, |
| 1395 | /// and which library that is. Not the codec -- a caller shows this beside the |
| 1396 | /// format it picked, and `rav1e` names AV1 as `ec-h264` names H.264. One |
| 1397 | /// place, so what a card says before an export and what its progress line says |
| 1398 | /// during one cannot drift apart. |
| 1399 | fn video_label(format: Format, hw: bool, intra: bool) -> &'static str { |
| 1400 | match (format, hw) { |
| 1401 | (_, true) => HW_LABEL, |
| 1402 | (Format::Hevc | Format::HevcMp4, false) if intra => "SW encode (ec-h265 intra)", |
| 1403 | (Format::Hevc | Format::HevcMp4, false) => "SW encode (ec-h265 GOP)", |
| 1404 | (Format::Av1 | Format::Av1Mp4 | Format::Webm, false) => "SW encode (rav1e)", |
| 1405 | (Format::ProRes, false) => "SW encode (ec-prores)", |
| 1406 | (_, false) => "SW encode (ec-h264)", |
| 1407 | } |
| 1408 | } |
| 1409 | |
| 1410 | /// Whether the *edit* has touched the samples a copy would carry out: the one |
| 1411 | /// predicate both copy-or-encode decisions ask, with `lanes` the sound's own |
| 1412 | /// list as the caller has it -- every audio lane for the question a card asks |
| 1413 | /// before the button ([`forces_encode`]), and the single lane the segments have |
| 1414 | /// already narrowed a copy to ([`copy_audio`]). |
| 1415 | /// |
| 1416 | /// One function and not two lists of the same conditions, which is what they |
| 1417 | /// were: `faded` reached [`forces_encode`] and not [`copy_audio`]'s gate, so an |
| 1418 | /// mp4 whose lane carried a fade wrote the source's own packets with the fade |
| 1419 | /// nowhere, while the card had promised a re-encode -- and the WAV, FLAC and |
| 1420 | /// MP3 exports of the same project applied it. Two gates that cannot be given |
| 1421 | /// two answers is the fix; the drift was the defect. |
| 1422 | fn sample_altered(project: &Project, lanes: &[Lane]) -> bool { |
| 1423 | // Two lanes are a mix and a mix is not a copy; a speeded lane is resampled; |
| 1424 | // an equalizer, a fade and the mix itself are gain math on decoded samples |
| 1425 | // ([`equalized`], [`faded`], [`mastered`]). None of them is inside a packet. |
| 1426 | lanes.len() > 1 |
| 1427 | || lanes |
| 1428 | .iter() |
| 1429 | .any(|&lane| project.lane(lane).iter().any(|c| !c.speed.is_normal() || !c.speed_keys.is_empty() || c.reversed)) |
| 1430 | || equalized(project) |
| 1431 | || mastered(project) |
| 1432 | || faded(project) |
| 1433 | } |
| 1434 | |
| 1435 | /// The cheap half of "does this timeline's sound have to be re-encoded": what |
| 1436 | /// the *edit* says, with no file opened ([`sample_altered`], asked of every |
| 1437 | /// audio lane). The other half -- whether the sources can be copied out of at |
| 1438 | /// all -- costs a file open each and belongs to [`copy_audio`], which may |
| 1439 | /// re-encode where this says copy. |
| 1440 | fn forces_encode(project: &Project, ranged: bool) -> bool { |
| 1441 | // A ranged export needs an exact offset and an exact length, which a copy |
| 1442 | // of the source's own packets cannot give it ([`copy_audio`]) -- so a |
| 1443 | // range marked at all always encodes, whatever the lanes look like. |
| 1444 | ranged || sample_altered(project, &project.audio_lanes()) |
| 1445 | } |
| 1446 | |
| 1447 | /// What the sound is written by. Every audio encoder here is software -- there |
| 1448 | /// is no hardware AAC, PCM, FLAC or MP3 seat -- so this names *which* one, and |
| 1449 | /// whether a container escapes encoding altogether by copying the packets it was |
| 1450 | /// given. Both AV1 formats are in it like the mp4: an AV1 export carries the |
| 1451 | /// timeline's sound too, so leaving it unnamed would be the old lie. |
| 1452 | /// |
| 1453 | /// A prediction, and it says so: `copied` is what [`copy_audio`] *did*, which a |
| 1454 | /// card asking before the export has no way to know (a source that cannot be |
| 1455 | /// copied out of is only found by opening it). `None` predicts from the edit |
| 1456 | /// alone. |
| 1457 | fn audio_label( |
| 1458 | project: &Project, |
| 1459 | format: Format, |
| 1460 | sound: bool, |
| 1461 | copied: Option<bool>, |
| 1462 | ranged: bool, |
| 1463 | reencode: bool, |
| 1464 | ) -> &'static str { |
| 1465 | if !sound { |
| 1466 | return "no sound to write"; |
| 1467 | } |
| 1468 | match format { |
| 1469 | Format::Wav => "PCM · SW (ec-riff)", |
| 1470 | Format::Flac => "FLAC · SW (ec-flac)", |
| 1471 | Format::Mp3 => "MP3 · SW (ec-mp3)", |
| 1472 | Format::Ogg => "Vorbis · SW (ec-vorbis)", |
| 1473 | Format::Opus => "Opus · SW (ec-opus)", |
| 1474 | Format::ProRes => "PCM · SW (16-bit, mov)", |
| 1475 | // Never a copy: WebM carries Opus, and the sound is mixed and encoded |
| 1476 | // for it at 48 kHz ([`start`], [`encode_audio`]). |
| 1477 | Format::Webm => "Opus · SW encode (ec-opus)", |
| 1478 | _ => match copied.unwrap_or(!(reencode || forces_encode(project, ranged))) { |
| 1479 | true => "AAC copy", |
| 1480 | // A Matroska file gets Opus where the mix allows it -- 48 kHz and |
| 1481 | // stereo, which is every Opus source and most of everything else -- |
| 1482 | // and AAC where it does not ([`encode_audio`]). Which of the two it |
| 1483 | // will be cannot be known here: both answers need a source opened, |
| 1484 | // and this function may be asked per repaint. So the card names the |
| 1485 | // codec it will nearly always be, as a prediction like the copy above |
| 1486 | // it, and the line the export publishes while it runs is the measured |
| 1487 | // one ([`run`]) -- it says AAC when the fallback took it, so the |
| 1488 | // fallback is visible rather than silent. |
| 1489 | // |
| 1490 | // It is one line and 76 characters wide (`summary_head` in the app |
| 1491 | // has the test), which is why the condition is in this comment |
| 1492 | // instead of in the string. |
| 1493 | false if format.is_mkv() => "Opus · SW encode (ec-opus)", |
| 1494 | false => "AAC · SW encode (ec-aac)", |
| 1495 | }, |
| 1496 | } |
| 1497 | } |
| 1498 | |
| 1499 | /// What the export *did* to the sound, for the line it publishes while it runs: |
| 1500 | /// [`audio_label`]'s words with the one thing no prediction can know filled in |
| 1501 | /// -- whether the Opus seat took the track or handed it back |
| 1502 | /// ([`encode_opus`]'s gate). |
| 1503 | /// |
| 1504 | /// `sound` is `Some(copied)` for a track and `None` for a file with no sound. |
| 1505 | /// Naming Opus for *every* Matroska encode is what made that fallback |
| 1506 | /// invisible: a track the gate refused was written as AAC and the line still |
| 1507 | /// said Opus, on the one path where the difference is audible. |
| 1508 | fn measured_audio_label( |
| 1509 | project: &Project, |
| 1510 | format: Format, |
| 1511 | sound: Option<bool>, |
| 1512 | opus: bool, |
| 1513 | ) -> &'static str { |
| 1514 | match (sound, opus) { |
| 1515 | (_, true) => "Opus · SW encode (ec-opus)", |
| 1516 | // Encoded, into a container that would have carried Opus, and it is not |
| 1517 | // Opus: the fidelity gate sent it to AAC ([`OPUS_MIN_FIDELITY`]), or |
| 1518 | // the mix was not 48 kHz at a width the seat is measured in. |
| 1519 | (Some(false), false) if format.is_mkv() => "AAC · SW encode (ec-aac)", |
| 1520 | // `sound` is already what happened, not a prediction, so `copied` is |
| 1521 | // filled in and `ranged` never reaches the branch that reads it. |
| 1522 | _ => audio_label(project, format, sound.is_some(), sound, false, false), |
| 1523 | } |
| 1524 | } |
| 1525 | |
| 1526 | /// What [`start`] would write this timeline's sound with, before one is |
| 1527 | /// started. Pure: no probe and no file opened, so a card may ask it per |
| 1528 | /// repaint. `ranged` is whether the export a card is describing is bounded to |
| 1529 | /// a marked range -- a copy needs the source's own packets to *be* the file, |
| 1530 | /// which a range's exact offset and length rule out ([`copy_audio`]). |
| 1531 | pub fn planned_audio(project: &Project, format: Format, ranged: bool) -> &'static str { |
| 1532 | audio_label(project, format, has_sound(project), None, ranged, false) |
| 1533 | } |
| 1534 | |
| 1535 | /// Why the sound's rate is nothing this timeline can be asked about in this |
| 1536 | /// format, or `None` where it is a real choice: there is no sound to write, the |
| 1537 | /// format codes the samples themselves, or the packets are the source's own and |
| 1538 | /// carry the rate *it* was coded at. Pure, like [`planned_audio`], and a |
| 1539 | /// prediction in the same way -- a copy that turns out impossible (a source no |
| 1540 | /// mp4 sample table holds) falls through to [`encode_audio`], which codes at |
| 1541 | /// [`ExportSettings::audio_kbps`] like every other encode. So the value travels |
| 1542 | /// even where this refuses; what it cannot do is silently write a rate nobody |
| 1543 | /// picked. |
| 1544 | pub fn audio_rate_refusal(project: &Project, format: Format, ranged: bool, reencode: bool) -> Option<&'static str> { |
| 1545 | match format { |
| 1546 | _ if !has_sound(project) => Some("no sound to write"), |
| 1547 | Format::Wav | Format::Flac | Format::ProRes => Some("lossless — the samples themselves, at no rate"), |
| 1548 | // Vorbis is written at one measured operating point ([`VORBIS_QUALITY`] |
| 1549 | // + [`VORBIS_TARGET_BPS`]), not at a rate a user may pick: its actual |
| 1550 | // landing moves with the content around that target (124-134 kbps |
| 1551 | // across this suite's bench inputs), so a live rate row would print a |
| 1552 | // figure the file does not hold -- the one thing this card is built |
| 1553 | // not to do. |
| 1554 | Format::Ogg => Some("quality-coded — Vorbis holds no rate to pick"), |
| 1555 | // The bitrate is the one choice WebM leaves: Opus at the rate picked. |
| 1556 | Format::Mp3 | Format::Webm | Format::Opus => None, |
| 1557 | _ if reencode || forces_encode(project, ranged) => None, |
| 1558 | _ => Some("the source's own packets are copied — at the rate they hold"), |
| 1559 | } |
| 1560 | } |
| 1561 | |
| 1562 | /// The soft subtitle tracks an export carries: the lanes the timeline places, each |
| 1563 | /// as its placement (the lanes a pick reaches), then every picked track no lane |
| 1564 | /// places, whole. Empty where it carries none: no pick and no placement, a pick |
| 1565 | /// nothing answers, a track that could not be read, one with no cue left on the |
| 1566 | /// exported timeline -- and every format that is the sound alone, which has |
| 1567 | /// nowhere to put them. Filtered *per track*, so one unusable pick costs its own |
| 1568 | /// row and not the others. |
| 1569 | /// |
| 1570 | /// Both containers, since the mp4 muxer gained its `tx3g` track: what the two |
| 1571 | /// do with the very same [`SubParams`] is theirs to say |
| 1572 | /// ([`crate::mux::Mp4Muxer::write_subtitles`], [`MkvMuxer`]), and nothing here |
| 1573 | /// asks which one is being written. |
| 1574 | fn export_subtitles( |
| 1575 | project: &Project, |
| 1576 | meta: &VideoMeta, |
| 1577 | settings: &ExportSettings, |
| 1578 | ) -> Vec<SubParams> { |
| 1579 | // WebM has no subtitle track this writer can state: [`planned_subtitles`] |
| 1580 | // says so on the card, and nothing is written. |
| 1581 | if !settings.format.has_video() || matches!(settings.format, Format::Webm | Format::ProRes) || !has_picture(project) { |
| 1582 | return Vec::new(); |
| 1583 | } |
| 1584 | // Burned captions are the only ones this file carries: a soft track of the |
| 1585 | // same words would show them twice. |
| 1586 | if settings.no_soft_subtitles { |
| 1587 | return Vec::new(); |
| 1588 | } |
| 1589 | // Words placed on a lane are written through the lanes, at their placement |
| 1590 | // (`lane_subtitle`; none when nothing is placed). A picked track that no lane |
| 1591 | // places is written whole beside them, as it always was: the palette's pick |
| 1592 | // is the only say it has in the file, so it must not be dropped for a lane |
| 1593 | // elsewhere. A placed track is never written twice. The tracks go in the |
| 1594 | // order the caller gave them ([`soft_order`]), placed or not. |
| 1595 | let lanes = placed_lanes(project); |
| 1596 | let mut subs = Vec::new(); |
| 1597 | for entry in soft_order(project, &lanes, &settings.subtitles) { |
| 1598 | match entry { |
| 1599 | SoftEntry::Lane(lane) => subs.extend(lane_subtitle( |
| 1600 | project, |
| 1601 | lane, |
| 1602 | meta.frame_rate, |
| 1603 | settings.range, |
| 1604 | &settings.subtitles, |
| 1605 | )), |
| 1606 | SoftEntry::Track(pick) => subs.extend(whole_track(project, meta, settings, pick)), |
| 1607 | } |
| 1608 | } |
| 1609 | subs |
| 1610 | } |
| 1611 | |
| 1612 | /// Whether a track has a cue the file would carry: any cue at all on the whole timeline, or one |
| 1613 | /// left inside `range` (on the clock the range is cut to, as [`written_cues`] cuts it). |
| 1614 | fn track_has_cues(project: &Project, track: &SubtitleTrack, range: Option<(u32, u32)>, fps: f64) -> bool { |
| 1615 | match range { |
| 1616 | None => !track.cues.is_empty(), |
| 1617 | Some(_) => !written_cues(timeline_cues(project, track, fps), range, fps, project.media_frames()).is_empty(), |
| 1618 | } |
| 1619 | } |
| 1620 | |
| 1621 | /// The reason a track with nothing to carry is dropped, in the card's words. |
| 1622 | fn no_cues_word(range: Option<(u32, u32)>) -> &'static str { |
| 1623 | if range.is_some() { "no cues in range" } else { "no cues" } |
| 1624 | } |
| 1625 | |
| 1626 | /// The labels of the written soft tracks whose styling the file drops: a standalone ASS or SSA |
| 1627 | /// script whose lines carry override blocks (`{\i1}`, `{\an8}`), which a cue's plain text does not |
| 1628 | /// keep. An embedded ASS track is not read here, so it is not named. Empty when none is. |
| 1629 | pub fn stripped_styling(project: &Project, picks: &[usize]) -> Vec<String> { |
| 1630 | let lanes = placed_lanes(project); |
| 1631 | let placed = placed_tracks(project); |
| 1632 | let mut used: std::collections::BTreeSet<usize> = picks.iter().copied().filter(|p| !placed.contains(p)).collect(); |
| 1633 | for &lane in &lanes { |
| 1634 | let on_lane = project.sub_lane(lane); |
| 1635 | if picked(on_lane, picks) { |
| 1636 | used.extend(on_lane.iter().map(|s| s.track)); |
| 1637 | } |
| 1638 | } |
| 1639 | used.into_iter() |
| 1640 | .filter_map(|i| project.subtitles().get(i)) |
| 1641 | .filter(|t| t.refused.is_none() && !t.is_bitmap() && t.track.is_none() && has_override_blocks(&t.path)) |
| 1642 | .map(|t| t.label.clone()) |
| 1643 | .collect() |
| 1644 | } |
| 1645 | |
| 1646 | /// Whether `path` is an ASS or SSA script with an override block in it. |
| 1647 | fn has_override_blocks(path: &Path) -> bool { |
| 1648 | let ass = path |
| 1649 | .extension() |
| 1650 | .and_then(|e| e.to_str()) |
| 1651 | .is_some_and(|e| e.eq_ignore_ascii_case("ass") || e.eq_ignore_ascii_case("ssa")); |
| 1652 | ass && std::fs::read_to_string(path).is_ok_and(|text| text.contains("{\\")) |
| 1653 | } |
| 1654 | |
| 1655 | /// One soft track of the file: a subtitle lane (written through its placements) or a picked |
| 1656 | /// track no lane places (written whole). |
| 1657 | #[derive(Clone, Copy, Debug, PartialEq)] |
| 1658 | enum SoftEntry { |
| 1659 | Lane(Lane), |
| 1660 | Track(usize), |
| 1661 | } |
| 1662 | |
| 1663 | /// The soft tracks the file writes, in the order the file declares them. With picks, that is |
| 1664 | /// the order the caller gave them: a lane goes where the first pick that reaches it sits, and a |
| 1665 | /// pick no lane places goes whole in its own place. Without picks, every placed lane in lane |
| 1666 | /// order and no whole track. |
| 1667 | fn soft_order(project: &Project, lanes: &[Lane], picks: &[usize]) -> Vec<SoftEntry> { |
| 1668 | if picks.is_empty() { |
| 1669 | return lanes.iter().map(|&l| SoftEntry::Lane(l)).collect(); |
| 1670 | } |
| 1671 | let placed = placed_tracks(project); |
| 1672 | let mut out: Vec<SoftEntry> = Vec::new(); |
| 1673 | for &pick in picks { |
| 1674 | let entry = if placed.contains(&pick) { |
| 1675 | match lanes.iter().find(|&&l| project.sub_lane(l).iter().any(|s| s.track == pick)) { |
| 1676 | Some(&lane) => SoftEntry::Lane(lane), |
| 1677 | None => continue, |
| 1678 | } |
| 1679 | } else { |
| 1680 | SoftEntry::Track(pick) |
| 1681 | }; |
| 1682 | if !out.contains(&entry) { |
| 1683 | out.push(entry); |
| 1684 | } |
| 1685 | } |
| 1686 | out |
| 1687 | } |
| 1688 | |
| 1689 | /// One picked track written whole, on the timeline's clock and clipped to the range |
| 1690 | /// and the picture. `None` for a track that writes nothing: no row for the pick, a |
| 1691 | /// track that could not be read, a picture track (the muxer writes words), or no cue |
| 1692 | /// left in the file. |
| 1693 | fn whole_track( |
| 1694 | project: &Project, |
| 1695 | meta: &VideoMeta, |
| 1696 | settings: &ExportSettings, |
| 1697 | pick: usize, |
| 1698 | ) -> Option<SubParams> { |
| 1699 | let track = project.subtitles().get(pick)?; |
| 1700 | // A picture is not a line: the muxer writes an `S_TEXT/UTF8` track and a PGS cue |
| 1701 | // has no words to put in one. `planned_subtitles` says so before the button is |
| 1702 | // pressed rather than the file coming out short. |
| 1703 | if track.refused.is_some() || track.is_bitmap() { |
| 1704 | return None; |
| 1705 | } |
| 1706 | let cues = written_cues( |
| 1707 | timeline_cues(project, track, meta.frame_rate), |
| 1708 | settings.range, |
| 1709 | meta.frame_rate, |
| 1710 | project.media_frames(), |
| 1711 | ); |
| 1712 | // The container's own two fields, carried as two |
| 1713 | // ([`SubtitleTrack::language`]): a `TrackEntry` with no `Language` means `eng` |
| 1714 | // by spec, so a French track that arrives here as one flattened string leaves |
| 1715 | // as an English one. |
| 1716 | (!cues.is_empty()).then(|| SubParams { |
| 1717 | language: track.language.clone(), |
| 1718 | name: subtitle_title(track), |
| 1719 | cues, |
| 1720 | }) |
| 1721 | } |
| 1722 | |
| 1723 | /// The title a soft subtitle track is written under. An embedded track keeps the |
| 1724 | /// title its container gave it; a standalone file has none of its own, so it is |
| 1725 | /// titled with its language's name (`French`) or left untitled -- never with its |
| 1726 | /// file name. |
| 1727 | fn subtitle_title(track: &SubtitleTrack) -> String { |
| 1728 | match track.track { |
| 1729 | Some(_) => track.name.clone(), |
| 1730 | None => crate::subtitle::language_name(&track.language).unwrap_or_default().to_string(), |
| 1731 | } |
| 1732 | } |
| 1733 | |
| 1734 | /// The indices of the tracks some placement on a subtitle lane names. Those tracks |
| 1735 | /// are written through their lanes, so a pick of one of them is not written whole. |
| 1736 | fn placed_tracks(project: &Project) -> std::collections::BTreeSet<usize> { |
| 1737 | project |
| 1738 | .subtitle_lanes() |
| 1739 | .into_iter() |
| 1740 | .flat_map(|lane| project.sub_lane(lane).iter().map(|s| s.track)) |
| 1741 | .collect() |
| 1742 | } |
| 1743 | |
| 1744 | /// The labels of the soft subtitle tracks this export writes whose cues overlap. An mp4 |
| 1745 | /// writes an overlap as one stretch with both lines in it (`mux`'s `timed_text`), so the |
| 1746 | /// cue times the timeline holds are not the file's; an mkv keeps every cue. Empty when |
| 1747 | /// nothing is written or no two cues of a written track overlap. |
| 1748 | pub fn overlapping_subtitles(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Vec<String> { |
| 1749 | export_subtitles(project, meta, settings) |
| 1750 | .into_iter() |
| 1751 | .filter(|t| { |
| 1752 | let mut spans: Vec<(i64, i64)> = t.cues.iter().map(|c| (c.start_us, c.end_us)).collect(); |
| 1753 | spans.sort_unstable(); |
| 1754 | let mut reach = i64::MIN; |
| 1755 | spans.iter().any(|&(start, end)| { |
| 1756 | let overlap = start < reach; |
| 1757 | reach = reach.max(end); |
| 1758 | overlap |
| 1759 | }) |
| 1760 | }) |
| 1761 | .map(|t| match (t.name.is_empty(), t.language.is_empty()) { |
| 1762 | (false, _) => t.name, |
| 1763 | (true, false) => t.language, |
| 1764 | (true, true) => "an unnamed track".to_string(), |
| 1765 | }) |
| 1766 | .collect() |
| 1767 | } |
| 1768 | |
| 1769 | /// Whether a lane with these placements is in the file: an empty pick list is |
| 1770 | /// every lane, otherwise the lane must hold at least one placement of a picked |
| 1771 | /// track ([`Project::subtitles`] index, as [`ExportSettings::subtitles`] gives). |
| 1772 | fn picked(placed: &[crate::project::SubClip], picks: &[usize]) -> bool { |
| 1773 | picks.is_empty() || placed.iter().any(|s| picks.contains(&s.track)) |
| 1774 | } |
| 1775 | |
| 1776 | /// The project's subtitle lanes in display order, and empty where **nothing is |
| 1777 | /// placed on any of them** -- an empty list is what the export and the card both |
| 1778 | /// read as "this project does not use lanes yet", so a project holding a bare |
| 1779 | /// `S1` nobody dropped a caption on still exports by the pick list. |
| 1780 | fn placed_lanes(project: &Project) -> Vec<Lane> { |
| 1781 | let lanes = project.subtitle_lanes(); |
| 1782 | match lanes.iter().any(|&l| !project.sub_lane(l).is_empty()) { |
| 1783 | true => lanes, |
| 1784 | false => Vec::new(), |
| 1785 | } |
| 1786 | } |
| 1787 | |
| 1788 | /// One track per subtitle *lane*, in lane order -- so the file declares them |
| 1789 | /// top-down as the timeline shows them and a player's subtitle menu lists them |
| 1790 | /// in that order. |
| 1791 | /// |
| 1792 | /// The cues are [`Project::sub_lane_cues`]: each placement's window of its |
| 1793 | /// palette track, on the timeline's own clock. Clipped again here to what the |
| 1794 | /// export *writes*, which ends with the last picture or sound |
| 1795 | /// ([`Project::media_frames`]) -- a caption hanging past both holds the |
| 1796 | /// timeline open ([`Project::timeline_frames`]) but there is no picture under |
| 1797 | /// it to write, so a cue out there is dropped and one straddling the end keeps |
| 1798 | /// the half that is inside. [`planned_subtitles`] says so before the button is |
| 1799 | /// pressed. |
| 1800 | /// |
| 1801 | /// A lane is dropped whole -- no track at all in the file -- where any |
| 1802 | /// placement on it is a picture ([`SubtitleTrack::is_bitmap`]), a track that |
| 1803 | /// could not be read, or a palette row that has since gone: the muxers write |
| 1804 | /// words, and half a lane's cues under the other half's name would be worse |
| 1805 | /// than none. Its language and title are the lane's *first* placement's track, |
| 1806 | /// which is the one thing the whole lane is named by. |
| 1807 | /// |
| 1808 | /// `picks` narrows the lanes the same way [`ExportSettings::subtitles`] does: a |
| 1809 | /// lane is kept when it holds a placement of a picked track ([`picked`]), and an |
| 1810 | /// empty list keeps every lane. |
| 1811 | #[cfg(test)] |
| 1812 | fn lane_subtitles( |
| 1813 | project: &Project, |
| 1814 | fps: f64, |
| 1815 | range: Option<(u32, u32)>, |
| 1816 | picks: &[usize], |
| 1817 | ) -> Vec<SubParams> { |
| 1818 | placed_lanes(project) |
| 1819 | .into_iter() |
| 1820 | .filter_map(|lane| lane_subtitle(project, lane, fps, range, picks)) |
| 1821 | .collect() |
| 1822 | } |
| 1823 | |
| 1824 | /// One lane written as its track ([`lane_subtitles`] for a single lane); `None` where the |
| 1825 | /// lane is not in the file (see there for the reasons). |
| 1826 | fn lane_subtitle( |
| 1827 | project: &Project, |
| 1828 | lane: Lane, |
| 1829 | fps: f64, |
| 1830 | range: Option<(u32, u32)>, |
| 1831 | picks: &[usize], |
| 1832 | ) -> Option<SubParams> { |
| 1833 | let end = (f64::from(project.media_frames()) / fps * 1e6).round() as i64; |
| 1834 | let placed = project.sub_lane(lane); |
| 1835 | if !picked(placed, picks) { |
| 1836 | return None; |
| 1837 | } |
| 1838 | let first = placed.first()?; |
| 1839 | let writable = |track: usize| { |
| 1840 | project |
| 1841 | .subtitles() |
| 1842 | .get(track) |
| 1843 | .filter(|t| t.refused.is_none() && !t.is_bitmap()) |
| 1844 | }; |
| 1845 | let named = writable(first.track)?; |
| 1846 | if placed.iter().any(|s| writable(s.track).is_none()) { |
| 1847 | return None; |
| 1848 | } |
| 1849 | let cues: Vec<Cue> = written_cues( |
| 1850 | project |
| 1851 | .sub_lane_cues(lane, fps) |
| 1852 | .into_iter() |
| 1853 | .filter_map(|cue| { |
| 1854 | let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end)); |
| 1855 | (end_us > start_us).then_some(Cue { |
| 1856 | start_us, |
| 1857 | end_us, |
| 1858 | text: cue.text, |
| 1859 | image: cue.image, |
| 1860 | words: Vec::new(), |
| 1861 | karaoke: Vec::new(), |
| 1862 | }) |
| 1863 | }) |
| 1864 | .collect(), |
| 1865 | range, |
| 1866 | fps, |
| 1867 | project.media_frames(), |
| 1868 | ); |
| 1869 | (!cues.is_empty()).then(|| SubParams { |
| 1870 | language: named.language.clone(), |
| 1871 | name: subtitle_title(named), |
| 1872 | cues, |
| 1873 | }) |
| 1874 | } |
| 1875 | |
| 1876 | /// `cues` on the clock the export *writes*, for a range-relative file. |
| 1877 | /// |
| 1878 | /// A cue is timed on the timeline; a ranged export's file starts its own clock |
| 1879 | /// at zero where the range starts, so every cue moves back by the range's start. |
| 1880 | /// What falls before the range is dropped, what falls after it is dropped, and a |
| 1881 | /// cue straddling either edge keeps the half inside. The window is the range |
| 1882 | /// clamped to the media, the same clamp [`export_spans`] makes, so the cues stop |
| 1883 | /// where the pictures do. Both ends are whole microseconds of the same |
| 1884 | /// frame-to-time mapping the cues were timed with, so the only rounding left is |
| 1885 | /// the container's own tick. |
| 1886 | /// |
| 1887 | /// Unranged, the cues come back as they were. |
| 1888 | fn written_cues( |
| 1889 | cues: Vec<Cue>, |
| 1890 | range: Option<(u32, u32)>, |
| 1891 | fps: f64, |
| 1892 | media_frames: u32, |
| 1893 | ) -> Vec<Cue> { |
| 1894 | let Some((r_start, r_end)) = range else { |
| 1895 | return cues; |
| 1896 | }; |
| 1897 | let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64; |
| 1898 | let from = us(r_start); |
| 1899 | let to = us(r_end.min(media_frames).max(r_start)); |
| 1900 | cues.into_iter() |
| 1901 | .filter_map(|cue| { |
| 1902 | let start_us = cue.start_us.max(from); |
| 1903 | let end_us = cue.end_us.min(to); |
| 1904 | (end_us > start_us).then_some(Cue { |
| 1905 | start_us: start_us - from, |
| 1906 | end_us: end_us - from, |
| 1907 | text: cue.text, |
| 1908 | image: cue.image, |
| 1909 | words: Vec::new(), |
| 1910 | karaoke: Vec::new(), |
| 1911 | }) |
| 1912 | }) |
| 1913 | .collect() |
| 1914 | } |
| 1915 | |
| 1916 | /// The composite spans an export *writes*: [`Project::composite_spans_from`] |
| 1917 | /// cut to where the media runs out ([`Project::media_frames`]), and, with |
| 1918 | /// `range` set, to that window too. |
| 1919 | /// |
| 1920 | /// The walk itself is the timeline's ([`Project::timeline_frames`]), because a |
| 1921 | /// caption placed past the last picture holds the timeline open under it and |
| 1922 | /// playback parks on that tail -- but there is nothing to *write* out there, so |
| 1923 | /// an unbounded walk encoded and muxed black frames past the end of the media |
| 1924 | /// and padded the sound to match. This is the one place that end is decided: |
| 1925 | /// the frame count [`run`] publishes, the cues [`lane_subtitles`] clips and the |
| 1926 | /// blocks [`CopyPlan`] copies are then the same number by construction, which |
| 1927 | /// is what makes [`planned_lanes`]' "cut off there" true of the file. |
| 1928 | /// |
| 1929 | /// `span.start` stays the *project's* own timeline coordinate throughout -- |
| 1930 | /// what [`Project::composite_color_at`] and its fit sibling are keyed on -- so |
| 1931 | /// a caller writing a range-relative output shifts it at the one place that |
| 1932 | /// actually emits a position (`CopyPlan`'s own region, since the encode loop |
| 1933 | /// counts pictures rather than reading `span.start` for its output clock). |
| 1934 | /// Trimming the left edge mid-span moves `from`'s source frame by |
| 1935 | /// [`Speed::source_at`], the same mapping a legal cut is placed by. |
| 1936 | fn export_spans(project: &Project, range: Option<(u32, u32)>) -> Vec<crate::project::Span> { |
| 1937 | let end = project.media_frames(); |
| 1938 | let mut spans = stack_spans_from(project, 0); |
| 1939 | spans.retain(|span| span.start < end); |
| 1940 | for span in &mut spans { |
| 1941 | span.len = span.len.min(end - span.start); |
| 1942 | } |
| 1943 | // A title past the last clip is picture: the frames up to its end are black |
| 1944 | // under it, a gap like any other. Only titles extend the picture here; a |
| 1945 | // sound that runs on still does not, as it never did. |
| 1946 | let title_end = project |
| 1947 | .titles() |
| 1948 | .iter() |
| 1949 | .map(Title::end) |
| 1950 | .max() |
| 1951 | .unwrap_or(0) |
| 1952 | .min(end); |
| 1953 | let covered = spans.last().map_or(0, crate::project::Span::end); |
| 1954 | if covered < title_end { |
| 1955 | spans.push(crate::project::Span { |
| 1956 | ramp: None, |
| 1957 | start: covered, |
| 1958 | len: title_end - covered, |
| 1959 | from: None, |
| 1960 | speed: Speed::NORMAL, |
| 1961 | reverse: false, |
| 1962 | pitch: 0.0, |
| 1963 | }); |
| 1964 | } |
| 1965 | let Some((r_start, r_end)) = range else { |
| 1966 | return spans; |
| 1967 | }; |
| 1968 | let r_end = r_end.min(end).max(r_start); |
| 1969 | spans.retain(|span| span.start < r_end && span.start + span.len > r_start); |
| 1970 | for span in &mut spans { |
| 1971 | if span.start < r_start { |
| 1972 | let cut = r_start - span.start; |
| 1973 | if let Some((source, in_frame)) = span.from { |
| 1974 | span.from = Some((source, span.source_at(in_frame, cut))); |
| 1975 | } |
| 1976 | // A ramp's offsets are counted from the span's start, which has moved. |
| 1977 | span.ramp = span.ramp.map(|r| r.advanced(cut)); |
| 1978 | span.len -= cut; |
| 1979 | span.start = r_start; |
| 1980 | } |
| 1981 | span.len = span.len.min(r_end - span.start); |
| 1982 | } |
| 1983 | spans |
| 1984 | } |
| 1985 | |
| 1986 | /// The visible video lanes, bottom first: the last one is the topmost, the order |
| 1987 | /// [`Project::composite_clip_at`] counts in. |
| 1988 | fn visible_video_lanes(project: &Project) -> Vec<Lane> { |
| 1989 | project |
| 1990 | .lanes() |
| 1991 | .into_iter() |
| 1992 | .filter(|lane| lane.kind == LaneKind::Video && !project.lane_hidden(*lane)) |
| 1993 | .collect() |
| 1994 | } |
| 1995 | |
| 1996 | /// Every visible video clip covering `frame`, bottom first: the stack the |
| 1997 | /// picture is composed from. One entry is the single-clip picture every path |
| 1998 | /// has always drawn; two or more are a layered picture ([`layered_at`]), where |
| 1999 | /// each clip is drawn over the ones beneath it. |
| 2000 | pub(crate) fn stack_at(project: &Project, frame: u32) -> Vec<(Lane, usize)> { |
| 2001 | visible_video_lanes(project) |
| 2002 | .into_iter() |
| 2003 | .filter_map(|lane| Some((lane, project.lane_clip_at(lane, frame)?))) |
| 2004 | .collect() |
| 2005 | } |
| 2006 | |
| 2007 | /// Whether `frame` is a layered picture: more than one visible clip covers it. |
| 2008 | pub(crate) fn layered_at(project: &Project, frame: u32) -> bool { |
| 2009 | let stack = stack_at(project, frame); |
| 2010 | stack.len() >= 2 || animated_at(project, frame) || generated_at(project, &stack) |
| 2011 | } |
| 2012 | |
| 2013 | /// Whether a clip covering `frame` is an adjustment layer or an animated generator |
| 2014 | /// ([`crate::generate`]): neither is a picture the single-clip path draws. |
| 2015 | fn generated_at(project: &Project, stack: &[(Lane, usize)]) -> bool { |
| 2016 | stack.iter().any(|&(lane, idx)| { |
| 2017 | let src = project.sources().get(project.lane(lane)[idx].source); |
| 2018 | src.and_then(|s| crate::generate::Gen::parse(&s.path)).is_some_and(|g| g.animated() || g.is_adjust() || g.has_alpha()) |
| 2019 | }) |
| 2020 | } |
| 2021 | |
| 2022 | /// The one clip covering `frame` when its only animation is colour keys or an |
| 2023 | /// effects stack and nothing dissolves out of it: a 10-bit export keeps such a |
| 2024 | /// clip on the single-clip path, grading each picture by [`clip_color_at`] and |
| 2025 | /// drawing its effects at 10 bits ([`crate::effects`]), rather than composing it |
| 2026 | /// layered at 8 bits. |
| 2027 | fn color_keyed_alone_at(project: &Project, frame: u32) -> Option<&crate::project::Clip> { |
| 2028 | let [(lane, idx)] = stack_at(project, frame)[..] else { |
| 2029 | return None; |
| 2030 | }; |
| 2031 | let clip = &project.lane(lane)[idx]; |
| 2032 | ((!clip.color_keys.is_empty() || crate::effects::active(&clip.effects)) |
| 2033 | && clip.transform_keys.is_empty() |
| 2034 | && clip.opacity_keys.is_empty() |
| 2035 | && cross_window(project, lane, idx).is_none()) |
| 2036 | .then_some(clip) |
| 2037 | } |
| 2038 | |
| 2039 | /// Whether the picture at `frame` is one a single clip cannot show: the clip on |
| 2040 | /// top has placement keys, or its dissolve partner does. A keyed picture is |
| 2041 | /// composed as a layered one, which places each frame's own placement |
| 2042 | /// ([`LayerFeed::advance`]), so a single clip's span-long transform never has |
| 2043 | /// to stand in for a moving one. |
| 2044 | fn animated_at(project: &Project, frame: u32) -> bool { |
| 2045 | visible_video_lanes(project).into_iter().any(|lane| { |
| 2046 | let Some(idx) = project.lane_clip_at(lane, frame) else { |
| 2047 | return false; |
| 2048 | }; |
| 2049 | if crate::project::clip_animated(&project.lane(lane)[idx]) { |
| 2050 | return true; |
| 2051 | } |
| 2052 | matches!( |
| 2053 | cross_window(project, lane, idx), |
| 2054 | Some((window, start)) if frame >= start && frame - start < window |
| 2055 | ) && project.lane(lane).get(idx + 1).is_some_and(crate::project::clip_animated) |
| 2056 | }) |
| 2057 | } |
| 2058 | |
| 2059 | /// [`Project::composite_span_at`] over the stack. The topmost covering clip |
| 2060 | /// supplies `from` and `speed`, and the span runs until any visible video lane |
| 2061 | /// changes what covers the frame -- a clip there starts or ends. With one |
| 2062 | /// covering clip that is exactly the composite's own span; across a stack it |
| 2063 | /// also cuts where a lower lane changes beneath the picture on top, since the |
| 2064 | /// picture under it is then a different one. |
| 2065 | pub(crate) fn stack_span_at(project: &Project, frame: u32) -> Option<crate::project::Span> { |
| 2066 | let total = project.timeline_frames(); |
| 2067 | if frame >= total { |
| 2068 | return None; |
| 2069 | } |
| 2070 | let mut until = total; |
| 2071 | for lane in visible_video_lanes(project) { |
| 2072 | let clips = project.lane(lane); |
| 2073 | match project.lane_clip_at(lane, frame) { |
| 2074 | Some(idx) => until = until.min(clips[idx].end()), |
| 2075 | None => { |
| 2076 | if let Some(next) = clips.iter().find(|c| c.start > frame) { |
| 2077 | until = until.min(next.start); |
| 2078 | } |
| 2079 | } |
| 2080 | } |
| 2081 | } |
| 2082 | let (from, speed, ramp, reverse) = match stack_at(project, frame).pop() { |
| 2083 | Some((lane, idx)) => { |
| 2084 | let clip = &project.lane(lane)[idx]; |
| 2085 | let (speed, ramp) = crate::project::span_speed_of(clip, frame); |
| 2086 | ( |
| 2087 | Some((clip.source, clip_source_frame(clip, frame))), |
| 2088 | speed, |
| 2089 | ramp, |
| 2090 | clip.reversed, |
| 2091 | ) |
| 2092 | } |
| 2093 | None => (None, Speed::NORMAL, None, false), |
| 2094 | }; |
| 2095 | Some(crate::project::Span { |
| 2096 | start: frame, |
| 2097 | len: until - frame, |
| 2098 | from, |
| 2099 | speed, |
| 2100 | ramp, |
| 2101 | reverse, |
| 2102 | pitch: 0.0, |
| 2103 | }) |
| 2104 | } |
| 2105 | |
| 2106 | /// [`Project::composite_spans_from`] over the stack: every span from `frame` on. |
| 2107 | pub(crate) fn stack_spans_from(project: &Project, frame: u32) -> Vec<crate::project::Span> { |
| 2108 | let mut out = Vec::new(); |
| 2109 | let mut t = frame; |
| 2110 | while let Some(span) = stack_span_at(project, t) { |
| 2111 | t = span.end(); |
| 2112 | out.push(span); |
| 2113 | } |
| 2114 | out |
| 2115 | } |
| 2116 | |
| 2117 | /// Which source frame a clip plays at timeline `frame` -- the project's own |
| 2118 | /// rule, clamped inside the clip's range. |
| 2119 | fn clip_source_frame(clip: &crate::project::Clip, frame: u32) -> u32 { |
| 2120 | (crate::project::source_pos(clip, frame - clip.start).floor() as u32).min(clip.out_frame - 1) |
| 2121 | } |
| 2122 | |
| 2123 | /// One clip of a layered picture, open for the span: its decoder, read forward |
| 2124 | /// as the picture advances, and the canvas its picture lands on -- the same |
| 2125 | /// placement a single clip gets ([`place_picture`]). |
| 2126 | struct LayerFeed { |
| 2127 | clip: crate::project::Clip, |
| 2128 | info: Placed, |
| 2129 | meta: VideoMeta, |
| 2130 | grade: Option<crate::color::ColorParams>, |
| 2131 | /// The grade the current picture was graded with, so a colour-keyed clip is |
| 2132 | /// graded again the frame its grade moves, even on the same source frame. |
| 2133 | graded_with: Option<crate::color::ColorParams>, |
| 2134 | /// The clip's base placement ([`Clip::transform`] resolved); its keys, when |
| 2135 | /// it has any, are read from `clip` at each frame ([`clip_transform_at`]). |
| 2136 | transform: TransformParams, |
| 2137 | /// The placement the current picture was placed with, so a keyed clip is |
| 2138 | /// placed again the frame its placement moves, even on the same source frame. |
| 2139 | placed_with: TransformParams, |
| 2140 | /// The clip's own opacity ([`TransformParams::opacity`]), applied as its |
| 2141 | /// coverage over the layers beneath rather than in its placement. |
| 2142 | opacity: f32, |
| 2143 | fit_canvas: Composer, |
| 2144 | rotated: Planes, |
| 2145 | stretched: Planes, |
| 2146 | graded: Planes, |
| 2147 | transformed: Planes, |
| 2148 | /// The decoder, and the file frame its next picture is. |
| 2149 | decoder: Option<(ClipDecoder, u32)>, |
| 2150 | /// The placed picture, and the file frame it is of. |
| 2151 | current: Option<(u32, Planes)>, |
| 2152 | /// The same picture composed at 10 bits ([`LayerStack::picture16`]), and the |
| 2153 | /// scratch only that path uses. |
| 2154 | current16: Option<(u32, Planes16)>, |
| 2155 | scratch16: Scratch16, |
| 2156 | widened: Planes16, |
| 2157 | steadied16: Planes16, |
| 2158 | adjusted16: Planes16, |
| 2159 | fx16: crate::effects::Scratch<u16>, |
| 2160 | /// Luma-sized coverage of the placed picture on the canvas: 255 where the |
| 2161 | /// clip's own pixels are, 0 in the letterbox bars and off the canvas. A |
| 2162 | /// layer above lets the one beneath show wherever this is 0. |
| 2163 | cover: Option<Vec<u8>>, |
| 2164 | matrix: Matrix, |
| 2165 | /// The dissolve this clip's tail owes the clip after it on its lane, when |
| 2166 | /// one is set and adjacent ([`cross_window`]). |
| 2167 | cross: Option<Box<LayerCross>>, |
| 2168 | /// The effects stack's scratch, and what it made of the current picture: its |
| 2169 | /// coverage (the placed footprint times the keys and masks) where it has any, |
| 2170 | /// and the mode it is laid down in ([`crate::effects`]). |
| 2171 | fx: crate::effects::Scratch<u8>, |
| 2172 | fx_cover: Option<Vec<u8>>, |
| 2173 | fx_mode: crate::effects::BlendMode, |
| 2174 | /// The clip's stabilisation, once its analysis is cached |
| 2175 | /// ([`crate::stabilise::correction`]): applied to the decoded picture, by its |
| 2176 | /// file frame, before anything else is. |
| 2177 | steady: Option<std::sync::Arc<crate::stabilise::Correction>>, |
| 2178 | steadied: Planes, |
| 2179 | /// The clip's deinterlace setting as it applies to its file. `Field` makes |
| 2180 | /// `info.rate` count fields; stabilisation is measured per file frame, so a |
| 2181 | /// field takes its frame's correction. |
| 2182 | deint: Deinterlace, |
| 2183 | /// An adjustment layer ([`crate::generate`]): no picture, its grade and effects act on the |
| 2184 | /// layers beneath ([`LayerFeed::adjust_over`]). |
| 2185 | adjust: bool, |
| 2186 | /// An adjustment layer's scratch, kept between frames like `steadied`: the placed and |
| 2187 | /// effected copy of the layers beneath, and its coverage. |
| 2188 | adjusted: Planes, |
| 2189 | adjust_cover: Vec<u8>, |
| 2190 | /// A generator with a transparent background ([`crate::generate::Gen::has_alpha`]) and its |
| 2191 | /// alpha at the size last asked for, kept so the mask is drawn once, not per coverage. |
| 2192 | alpha_gen: Option<crate::generate::Gen>, |
| 2193 | alpha_mask: Option<(u32, u32, Vec<u8>)>, |
| 2194 | } |
| 2195 | |
| 2196 | /// The clip a layer's tail dissolves into: its own feed, and the window of |
| 2197 | /// timeline frames the blend runs over, from `start` for `window` frames. |
| 2198 | struct LayerCross { |
| 2199 | next: LayerFeed, |
| 2200 | window: u32, |
| 2201 | start: u32, |
| 2202 | } |
| 2203 | |
| 2204 | /// The dissolve window a clip's tail owes its successor, as [`dissolve_window`] |
| 2205 | /// reads it -- without the span rules, which a layered picture does not have: |
| 2206 | /// it blends wherever its lane is on the clip, whatever is above it. `None` for |
| 2207 | /// a hard cut, a stale transition out (the clips are no longer adjacent), or an |
| 2208 | /// empty window. `(window, start)` in timeline frames. |
| 2209 | fn cross_window(project: &Project, lane: Lane, idx: usize) -> Option<(u32, u32)> { |
| 2210 | let clips = project.lane(lane); |
| 2211 | let a = clips.get(idx)?; |
| 2212 | if a.transition_out == 0 { |
| 2213 | return None; |
| 2214 | } |
| 2215 | let b = clips.get(idx + 1)?; |
| 2216 | if a.end() != b.start { |
| 2217 | return None; |
| 2218 | } |
| 2219 | let window = a.transition_out.min(a.frames()).min(b.frames()); |
| 2220 | (window > 0).then_some((window, a.end() - window)) |
| 2221 | } |
| 2222 | |
| 2223 | impl LayerFeed { |
| 2224 | /// The feed for clip `idx` of `lane`, with the dissolve it owes its |
| 2225 | /// successor opened beside it. `paths`, when given, is the file each source |
| 2226 | /// is decoded from in place of its own (a proxy stand-in), by source index. |
| 2227 | /// `measure`, when given, is the cancel flag a stabilised clip's missing |
| 2228 | /// analysis is run under before this returns ([`crate::stabilise::ensure`]) |
| 2229 | /// and the stage it reports to ([`Shared::measuring`]); `None` takes only a |
| 2230 | /// finished one (the viewer, which shows the analysis's progress and redraws |
| 2231 | /// when it lands). |
| 2232 | fn open( |
| 2233 | project: &Project, |
| 2234 | meta: &VideoMeta, |
| 2235 | lane: Lane, |
| 2236 | idx: usize, |
| 2237 | matrix: Matrix, |
| 2238 | paths: Option<&[PathBuf]>, |
| 2239 | measure: Option<Measure<'_>>, |
| 2240 | ) -> crate::Result<Self> { |
| 2241 | let mut feed = Self::plain(project, meta, lane, idx, matrix, paths, measure)?; |
| 2242 | if let Some((window, start)) = cross_window(project, lane, idx) { |
| 2243 | let next = Self::plain(project, meta, lane, idx + 1, matrix, paths, measure)?; |
| 2244 | feed.cross = Some(Box::new(LayerCross { |
| 2245 | next, |
| 2246 | window, |
| 2247 | start, |
| 2248 | })); |
| 2249 | } |
| 2250 | Ok(feed) |
| 2251 | } |
| 2252 | |
| 2253 | fn plain( |
| 2254 | project: &Project, |
| 2255 | meta: &VideoMeta, |
| 2256 | lane: Lane, |
| 2257 | idx: usize, |
| 2258 | matrix: Matrix, |
| 2259 | paths: Option<&[PathBuf]>, |
| 2260 | measure: Option<Measure<'_>>, |
| 2261 | ) -> crate::Result<Self> { |
| 2262 | let Some(clip) = project.lane(lane).get(idx).cloned() else { |
| 2263 | return Err("a layer names a clip that is not there".into()); |
| 2264 | }; |
| 2265 | let mut info = placed_info(project, meta, clip.source)?; |
| 2266 | if let Some(path) = paths.and_then(|paths| paths.get(clip.source)) { |
| 2267 | info.path = path.clone(); |
| 2268 | } |
| 2269 | // Smoothed at the timeline's rate, as the viewer smooths it, over every |
| 2270 | // file frame the clip plays: an export measures what is missing rather |
| 2271 | // than write the clip unstabilised. |
| 2272 | let steady = match (clip.stabilise, project.sources().get(clip.source)) { |
| 2273 | (Some(st), Some(source)) => { |
| 2274 | let (lo, hi) = crate::stabilise::file_range(&clip, info.rate); |
| 2275 | match measure { |
| 2276 | Some((cancel, stage)) => { |
| 2277 | let mut tell = |f: f32| stage.store(1 + (f.clamp(0.0, 1.0) * 1000.0) as u32, Ordering::Relaxed); |
| 2278 | let c = crate::stabilise::ensure(&source.path, lo, hi, st, meta.frame_rate, &mut tell, cancel); |
| 2279 | stage.store(0, Ordering::Relaxed); |
| 2280 | Some(c?) |
| 2281 | } |
| 2282 | None => crate::stabilise::correction_or_start(&source.path, lo, hi, st, meta.frame_rate), |
| 2283 | } |
| 2284 | } |
| 2285 | _ => None, |
| 2286 | }; |
| 2287 | let deint = crate::deinterlace::effective(clip.deinterlace, &info.path); |
| 2288 | info.rate = crate::deinterlace::counted_rate(deint, info.rate); |
| 2289 | Ok(Self { |
| 2290 | steady, |
| 2291 | steadied: Default::default(), |
| 2292 | deint, |
| 2293 | adjust: crate::generate::is_adjust(&info.path), |
| 2294 | adjusted: Default::default(), |
| 2295 | adjust_cover: Vec::new(), |
| 2296 | alpha_gen: crate::generate::Gen::parse(&info.path).filter(|g| g.has_alpha()), |
| 2297 | alpha_mask: None, |
| 2298 | info, |
| 2299 | meta: *meta, |
| 2300 | grade: project.color_of(lane, idx).copied(), |
| 2301 | graded_with: None, |
| 2302 | // The layer's opacity is its coverage in [`LayerStack::picture`], so |
| 2303 | // the placement below runs at opacity 1: a placed mask at opacity |
| 2304 | // below 1 would fade the coverage it is read for. |
| 2305 | transform: { |
| 2306 | let whole = project.transform_of(lane, idx).copied().unwrap_or_default(); |
| 2307 | TransformParams { |
| 2308 | opacity: 1.0, |
| 2309 | ..whole |
| 2310 | } |
| 2311 | }, |
| 2312 | opacity: project |
| 2313 | .transform_of(lane, idx) |
| 2314 | .map_or(1.0, |t| t.opacity), |
| 2315 | fit_canvas: Composer::new(meta.width, meta.height, project.fit_of(lane, idx)), |
| 2316 | clip, |
| 2317 | rotated: Default::default(), |
| 2318 | stretched: Default::default(), |
| 2319 | graded: Default::default(), |
| 2320 | transformed: Default::default(), |
| 2321 | decoder: None, |
| 2322 | current: None, |
| 2323 | current16: None, |
| 2324 | scratch16: Default::default(), |
| 2325 | widened: Default::default(), |
| 2326 | steadied16: Default::default(), |
| 2327 | adjusted16: Default::default(), |
| 2328 | fx16: Default::default(), |
| 2329 | cover: None, |
| 2330 | placed_with: TransformParams::default(), |
| 2331 | matrix, |
| 2332 | cross: None, |
| 2333 | fx: Default::default(), |
| 2334 | fx_cover: None, |
| 2335 | fx_mode: Default::default(), |
| 2336 | }) |
| 2337 | } |
| 2338 | |
| 2339 | /// The dissolve picture this clip shows at timeline `frame` while its tail |
| 2340 | /// blends into the next clip on its lane: the two placed pictures mixed by |
| 2341 | /// [`dissolve_weight`], and the coverage between the two clips' footprints |
| 2342 | /// mixed the same way. `None` outside the window, and where the next clip's |
| 2343 | /// file ends first -- then this clip's own picture stands, as a single |
| 2344 | /// clip's does. The next clip is read forward as this one is. |
| 2345 | fn cross_at(&mut self, frame: u32) -> crate::Result<Option<(Planes, Vec<u8>)>> { |
| 2346 | let Some(cross) = self.cross.as_mut() else { |
| 2347 | return Ok(None); |
| 2348 | }; |
| 2349 | if frame < cross.start || frame - cross.start >= cross.window { |
| 2350 | return Ok(None); |
| 2351 | } |
| 2352 | // The next clip shows its own picture from its first frame on, as the |
| 2353 | // single clip's dissolve reads it ([`compose_at_with`]): window frame k |
| 2354 | // is its frame k, not the timeline frame, which is before its start. |
| 2355 | let k = frame - cross.start; |
| 2356 | if !cross.next.advance(cross.next.clip.start + k)? { |
| 2357 | return Ok(None); |
| 2358 | } |
| 2359 | let t = dissolve_weight(k, cross.window); |
| 2360 | let a_cover = self.fx_cover.as_deref().or(self.cover.as_deref()); |
| 2361 | let (Some((_, a)), Some(a_cover)) = (self.current.as_ref(), a_cover) else { |
| 2362 | return Ok(None); |
| 2363 | }; |
| 2364 | let b_cover = cross.next.fx_cover.as_deref().or(cross.next.cover.as_deref()); |
| 2365 | let (Some((_, b)), Some(b_cover)) = (cross.next.current.as_ref(), b_cover) |
| 2366 | 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 | /// [`LayerFeed::cross_at`] at 10 bits. |
| 2386 | fn cross_at16(&mut self, frame: u32) -> crate::Result<Option<(Planes16, Vec<u8>)>> { |
| 2387 | let Some(cross) = self.cross.as_mut() else { |
| 2388 | return Ok(None); |
| 2389 | }; |
| 2390 | if frame < cross.start || frame - cross.start >= cross.window { |
| 2391 | return Ok(None); |
| 2392 | } |
| 2393 | let k = frame - cross.start; |
| 2394 | if !cross.next.advance16(cross.next.clip.start + k)? { |
| 2395 | return Ok(None); |
| 2396 | } |
| 2397 | let t = dissolve_weight(k, cross.window); |
| 2398 | let a_cover = self.fx_cover.as_deref().or(self.cover.as_deref()); |
| 2399 | let (Some((_, a)), Some(a_cover)) = (self.current16.as_ref(), a_cover) else { |
| 2400 | return Ok(None); |
| 2401 | }; |
| 2402 | let b_cover = cross.next.fx_cover.as_deref().or(cross.next.cover.as_deref()); |
| 2403 | let (Some((_, b)), Some(b_cover)) = (cross.next.current16.as_ref(), b_cover) else { |
| 2404 | return Ok(None); |
| 2405 | }; |
| 2406 | let planes = crate::transitions::blend_planes( |
| 2407 | self.clip.transition_kind, |
| 2408 | (&a.0, &a.1, &a.2), |
| 2409 | (&b.0, &b.1, &b.2), |
| 2410 | t, |
| 2411 | self.meta.width as usize, |
| 2412 | self.meta.height as usize, |
| 2413 | ); |
| 2414 | let cover = a_cover |
| 2415 | .iter() |
| 2416 | .zip(b_cover) |
| 2417 | .map(|(&x, &y)| (f32::from(x) + (f32::from(y) - f32::from(x)) * t).round() as u8) |
| 2418 | .collect(); |
| 2419 | Ok(Some((planes, cover))) |
| 2420 | } |
| 2421 | |
| 2422 | /// Makes the placed picture for timeline `frame` the current one, reading |
| 2423 | /// the decoder forward to it. `false` when the file ends first. |
| 2424 | fn advance(&mut self, frame: u32) -> crate::Result<bool> { |
| 2425 | self.advance_as(frame, false) |
| 2426 | } |
| 2427 | |
| 2428 | /// [`LayerFeed::advance`] at 10 bits: the placed picture lands in `current16`. |
| 2429 | fn advance16(&mut self, frame: u32) -> crate::Result<bool> { |
| 2430 | self.advance_as(frame, true) |
| 2431 | } |
| 2432 | |
| 2433 | fn advance_as(&mut self, frame: u32, wide: bool) -> crate::Result<bool> { |
| 2434 | let want = self.info.rate.source_at(clip_source_frame(&self.clip, frame)); |
| 2435 | // Coverage is the layer's own (see `LayerFeed::picture`), so the placement |
| 2436 | // runs at opacity 1 whatever the keys say. |
| 2437 | let tf = TransformParams { |
| 2438 | opacity: 1.0, |
| 2439 | ..crate::project::clip_transform_at(&self.clip, self.transform, frame) |
| 2440 | }; |
| 2441 | // A colour-keyed clip's grade moves with the frame ([`clip_color_at`]). |
| 2442 | let grade = match self.clip.color_keys.is_empty() { |
| 2443 | true => self.grade, |
| 2444 | false => Some(crate::project::clip_color_at( |
| 2445 | &self.clip, |
| 2446 | self.grade.unwrap_or_default(), |
| 2447 | frame, |
| 2448 | )), |
| 2449 | }; |
| 2450 | let have = match wide { |
| 2451 | true => self.current16.as_ref().map(|(at, _)| *at), |
| 2452 | false => self.current.as_ref().map(|(at, _)| *at), |
| 2453 | }; |
| 2454 | if have == Some(want) |
| 2455 | && self.placed_with == tf |
| 2456 | && self.graded_with == grade |
| 2457 | && !crate::effects::animated(&self.clip.effects) |
| 2458 | { |
| 2459 | return Ok(true); |
| 2460 | } |
| 2461 | // A decoder that has read past the picture wanted is reopened at it; |
| 2462 | // playback and export only ever move forward through a span -- down it, |
| 2463 | // for a reversed clip, whose decoder counts the file frame it is on |
| 2464 | // downwards. |
| 2465 | let backwards = self.clip.reversed; |
| 2466 | let behind = matches!(&self.decoder, Some((_, pos)) if match backwards { |
| 2467 | true => *pos < want, |
| 2468 | false => *pos > want, |
| 2469 | }); |
| 2470 | if self.decoder.is_none() || behind { |
| 2471 | let path = self.info.path.clone(); |
| 2472 | let flags = self.clip.visualizer; |
| 2473 | let decoder = if crate::is_audio(&path) || flags & 1 != 0 { |
| 2474 | ClipDecoder::visualizer( |
| 2475 | &path, |
| 2476 | self.info.stream, |
| 2477 | want, |
| 2478 | (self.meta.width, self.meta.height), |
| 2479 | self.meta.frame_rate, |
| 2480 | flags, |
| 2481 | self.clip.viz_paint, |
| 2482 | )? |
| 2483 | } else if backwards && !crate::is_image(&path) { |
| 2484 | ClipDecoder::reversed(&path, want, self.info.rate.source_at(self.clip.in_frame), self.deint) |
| 2485 | } else { |
| 2486 | ClipDecoder::open_with(&path, want, None, None, wide, self.deint)? |
| 2487 | }; |
| 2488 | self.decoder = Some((decoder, want)); |
| 2489 | } |
| 2490 | let (decoder, pos) = self.decoder.as_mut().expect("opened above"); |
| 2491 | while match backwards { |
| 2492 | true => *pos > want, |
| 2493 | false => *pos < want, |
| 2494 | } { |
| 2495 | if decoder.next()?.is_none() { |
| 2496 | return Ok(false); |
| 2497 | } |
| 2498 | *pos = if backwards { *pos - 1 } else { *pos + 1 }; |
| 2499 | } |
| 2500 | let Some(picture) = decoder.next()? else { |
| 2501 | return Ok(false); |
| 2502 | }; |
| 2503 | *pos = if backwards { pos.saturating_sub(1) } else { *pos + 1 }; |
| 2504 | if wide { |
| 2505 | let (y, u, v, w, h): (&[u16], &[u16], &[u16], u32, u32) = match picture { |
| 2506 | Frame::Wide(y, u, v, w, h) => (y, u, v, w, h), |
| 2507 | Frame::Pixels(y, u, v, w, h) => { |
| 2508 | widen_into(y, &mut self.widened.0); |
| 2509 | widen_into(u, &mut self.widened.1); |
| 2510 | widen_into(v, &mut self.widened.2); |
| 2511 | (&self.widened.0[..], &self.widened.1[..], &self.widened.2[..], w, h) |
| 2512 | } |
| 2513 | Frame::Dma(_) => return Err("a layer's decoder produced no pixels".into()), |
| 2514 | }; |
| 2515 | let (y, u, v) = match &self.steady { |
| 2516 | Some(c) => { |
| 2517 | let m = c.at(crate::deinterlace::file_frame(self.deint, &self.info.path, want), w).ok_or_else(|| -> crate::Error { |
| 2518 | format!("stabilise: file frame {want} lies before the measured range").into() |
| 2519 | })?; |
| 2520 | crate::stabilise::warp_i420(y, u, v, w, h, m, &mut self.steadied16); |
| 2521 | (&self.steadied16.0[..], &self.steadied16.1[..], &self.steadied16.2[..]) |
| 2522 | } |
| 2523 | None => (y, u, v), |
| 2524 | }; |
| 2525 | let remap = remap_into(Some(self.info.color), self.info.mapper.is_some(), self.matrix); |
| 2526 | let (py, pu, pv, pw, ph) = place_picture16( |
| 2527 | y, |
| 2528 | u, |
| 2529 | v, |
| 2530 | w, |
| 2531 | h, |
| 2532 | self.info.rotation, |
| 2533 | self.info.pixel_aspect, |
| 2534 | grade, |
| 2535 | tf, |
| 2536 | remap, |
| 2537 | self.info.mapper.as_ref(), |
| 2538 | &mut self.scratch16, |
| 2539 | &mut self.fit_canvas, |
| 2540 | ); |
| 2541 | let mut planes = (py.to_vec(), pu.to_vec(), pv.to_vec()); |
| 2542 | if self.cover.is_none() || self.placed_with != tf { |
| 2543 | self.cover = Some(self.coverage(w, h, tf)); |
| 2544 | } |
| 2545 | debug_assert_eq!((pw, ph), (self.meta.width, self.meta.height), "a placed layer is canvas-sized"); |
| 2546 | let secs = f64::from(frame) / self.meta.frame_rate; |
| 2547 | let src = crate::project::key_sample_pos(&self.clip, frame); |
| 2548 | let (mode, fx_cover) = layer_effects( |
| 2549 | &self.clip.effects, |
| 2550 | &mut planes, |
| 2551 | (pw, ph), |
| 2552 | secs, |
| 2553 | src, |
| 2554 | self.matrix, |
| 2555 | &mut self.fx16, |
| 2556 | self.cover.as_deref().expect("set above"), |
| 2557 | ); |
| 2558 | self.fx_mode = mode; |
| 2559 | self.fx_cover = fx_cover; |
| 2560 | self.placed_with = tf; |
| 2561 | self.graded_with = grade; |
| 2562 | self.current16 = Some((want, planes)); |
| 2563 | return Ok(true); |
| 2564 | } |
| 2565 | let Frame::Pixels(y, u, v, w, h) = picture else { |
| 2566 | return Err("a layer's decoder produced no pixels".into()); |
| 2567 | }; |
| 2568 | let (y, u, v) = match &self.steady { |
| 2569 | Some(c) => { |
| 2570 | let m = c.at(crate::deinterlace::file_frame(self.deint, &self.info.path, want), w).ok_or_else(|| -> crate::Error { |
| 2571 | format!("stabilise: file frame {want} lies before the measured range").into() |
| 2572 | })?; |
| 2573 | crate::stabilise::warp_i420(y, u, v, w, h, m, &mut self.steadied); |
| 2574 | (&self.steadied.0[..], &self.steadied.1[..], &self.steadied.2[..]) |
| 2575 | } |
| 2576 | None => (y, u, v), |
| 2577 | }; |
| 2578 | let remap = remap_into( |
| 2579 | Some(self.info.color), |
| 2580 | self.info.mapper.is_some(), |
| 2581 | self.matrix, |
| 2582 | ); |
| 2583 | let (py, pu, pv, pw, ph) = place_picture( |
| 2584 | y, |
| 2585 | u, |
| 2586 | v, |
| 2587 | w, |
| 2588 | h, |
| 2589 | self.info.rotation, |
| 2590 | self.info.pixel_aspect, |
| 2591 | grade, |
| 2592 | tf, |
| 2593 | remap, |
| 2594 | self.info.mapper.as_ref(), |
| 2595 | &mut self.rotated, |
| 2596 | &mut self.stretched, |
| 2597 | &mut self.graded, |
| 2598 | &mut self.transformed, |
| 2599 | &mut self.fit_canvas, |
| 2600 | ); |
| 2601 | let mut planes = (py.to_vec(), pu.to_vec(), pv.to_vec()); |
| 2602 | if self.cover.is_none() || self.placed_with != tf { |
| 2603 | self.cover = Some(self.coverage(w, h, tf)); |
| 2604 | } |
| 2605 | // The effects stack, on the placed picture: its filters rewrite the |
| 2606 | // samples, and its keys and masks narrow the footprint it lands with. |
| 2607 | debug_assert_eq!((pw, ph), (self.meta.width, self.meta.height), "a placed layer is canvas-sized"); |
| 2608 | let secs = f64::from(frame) / self.meta.frame_rate; |
| 2609 | let src = crate::project::key_sample_pos(&self.clip, frame); |
| 2610 | let (mode, fx_cover) = layer_effects( |
| 2611 | &self.clip.effects, |
| 2612 | &mut planes, |
| 2613 | (pw, ph), |
| 2614 | secs, |
| 2615 | src, |
| 2616 | self.matrix, |
| 2617 | &mut self.fx, |
| 2618 | self.cover.as_deref().expect("set above"), |
| 2619 | ); |
| 2620 | self.fx_mode = mode; |
| 2621 | self.fx_cover = fx_cover; |
| 2622 | self.placed_with = tf; |
| 2623 | self.graded_with = grade; |
| 2624 | self.current = Some((want, planes)); |
| 2625 | Ok(true) |
| 2626 | } |
| 2627 | |
| 2628 | /// The layers composed so far, `base`, with this adjustment layer's grade, placement and |
| 2629 | /// effects applied to them, at strength `k` (its fade times its opacity). |
| 2630 | /// |
| 2631 | /// The clip's transform moves the composite below it (as Motion on an adjustment layer does |
| 2632 | /// in Premiere), so what the placement uncovers -- a shrunk, shifted or rotated composite -- |
| 2633 | /// goes black. Crop is different: the layer only reaches where its crop footprint |
| 2634 | /// ([`LayerFeed::coverage`], placement left out) is, so a cropped-away region keeps the base. |
| 2635 | fn adjust_over(&mut self, base: Planes, k: f32, frame: u32) -> Planes { |
| 2636 | let (w, h) = (self.meta.width, self.meta.height); |
| 2637 | let grade = match self.clip.color_keys.is_empty() { |
| 2638 | true => self.grade, |
| 2639 | false => Some(crate::project::clip_color_at(&self.clip, self.grade.unwrap_or_default(), frame)), |
| 2640 | }; |
| 2641 | let tf = TransformParams { opacity: 1.0, ..crate::project::clip_transform_at(&self.clip, self.transform, frame) }; |
| 2642 | let (py, pu, pv, _, _) = place_picture( |
| 2643 | &base.0, &base.1, &base.2, w, h, Rotation::None, crate::demux::PixelAspect::SQUARE, grade, tf, None, None, |
| 2644 | &mut self.rotated, &mut self.stretched, &mut self.graded, &mut self.transformed, &mut self.fit_canvas, |
| 2645 | ); |
| 2646 | let mut adjusted = std::mem::take(&mut self.adjusted); |
| 2647 | for (dst, src) in [(&mut adjusted.0, py), (&mut adjusted.1, pu), (&mut adjusted.2, pv)] { |
| 2648 | dst.clear(); |
| 2649 | dst.extend_from_slice(src); |
| 2650 | } |
| 2651 | let mut cover = std::mem::take(&mut self.adjust_cover); |
| 2652 | cover.clear(); |
| 2653 | // Only the crop limits the layer: the placement moved the composite itself, and |
| 2654 | // what it uncovers is the black of its own fit bars. |
| 2655 | // With crop and a transform together the crop footprint stays at the identity |
| 2656 | // position while the picture moves: the crop limits where the layer acts, not what moves. |
| 2657 | 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() }; |
| 2658 | match crop == TransformParams::default() { |
| 2659 | true => cover.resize(w as usize * h as usize, 255), |
| 2660 | false => cover.extend(self.coverage(w, h, crop)), |
| 2661 | } |
| 2662 | if crate::effects::active(&self.clip.effects) { |
| 2663 | let out = crate::effects::apply( |
| 2664 | &self.clip.effects, |
| 2665 | (&mut adjusted.0, &mut adjusted.1, &mut adjusted.2), |
| 2666 | w as usize, |
| 2667 | h as usize, |
| 2668 | f64::from(frame) / self.meta.frame_rate, |
| 2669 | crate::project::key_sample_pos(&self.clip, frame), |
| 2670 | self.matrix, |
| 2671 | &mut self.fx, |
| 2672 | ); |
| 2673 | if let Some(alpha) = out.alpha { |
| 2674 | for (c, a) in cover.iter_mut().zip(alpha) { |
| 2675 | *c = ((u32::from(*c) * u32::from(a) + 127) / 255) as u8; |
| 2676 | } |
| 2677 | } |
| 2678 | } |
| 2679 | let mut result = base; |
| 2680 | layer_over(&mut result, &adjusted, &cover, k, w as usize, h as usize); |
| 2681 | self.adjusted = adjusted; |
| 2682 | self.adjust_cover = cover; |
| 2683 | result |
| 2684 | } |
| 2685 | |
| 2686 | /// [`LayerFeed::adjust_over`] at 10 bits. |
| 2687 | fn adjust_over16(&mut self, base: Planes16, k: f32, frame: u32) -> Planes16 { |
| 2688 | let (w, h) = (self.meta.width, self.meta.height); |
| 2689 | let grade = match self.clip.color_keys.is_empty() { |
| 2690 | true => self.grade, |
| 2691 | false => Some(crate::project::clip_color_at(&self.clip, self.grade.unwrap_or_default(), frame)), |
| 2692 | }; |
| 2693 | let tf = TransformParams { opacity: 1.0, ..crate::project::clip_transform_at(&self.clip, self.transform, frame) }; |
| 2694 | let (py, pu, pv, _, _) = place_picture16( |
| 2695 | &base.0, &base.1, &base.2, w, h, Rotation::None, crate::demux::PixelAspect::SQUARE, grade, tf, None, None, |
| 2696 | &mut self.scratch16, &mut self.fit_canvas, |
| 2697 | ); |
| 2698 | let mut adjusted = std::mem::take(&mut self.adjusted16); |
| 2699 | for (dst, src) in [(&mut adjusted.0, py), (&mut adjusted.1, pu), (&mut adjusted.2, pv)] { |
| 2700 | dst.clear(); |
| 2701 | dst.extend_from_slice(src); |
| 2702 | } |
| 2703 | let mut cover = std::mem::take(&mut self.adjust_cover); |
| 2704 | cover.clear(); |
| 2705 | 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() }; |
| 2706 | match crop == TransformParams::default() { |
| 2707 | true => cover.resize(w as usize * h as usize, 255), |
| 2708 | false => cover.extend(self.coverage(w, h, crop)), |
| 2709 | } |
| 2710 | if crate::effects::active(&self.clip.effects) { |
| 2711 | let out = crate::effects::apply( |
| 2712 | &self.clip.effects, |
| 2713 | (&mut adjusted.0, &mut adjusted.1, &mut adjusted.2), |
| 2714 | w as usize, |
| 2715 | h as usize, |
| 2716 | f64::from(frame) / self.meta.frame_rate, |
| 2717 | crate::project::key_sample_pos(&self.clip, frame), |
| 2718 | self.matrix, |
| 2719 | &mut self.fx16, |
| 2720 | ); |
| 2721 | if let Some(alpha) = out.alpha { |
| 2722 | for (c, a) in cover.iter_mut().zip(alpha) { |
| 2723 | *c = ((u32::from(*c) * u32::from(a) + 127) / 255) as u8; |
| 2724 | } |
| 2725 | } |
| 2726 | } |
| 2727 | let mut result = base; |
| 2728 | layer_over(&mut result, &adjusted, &cover, k, w as usize, h as usize); |
| 2729 | self.adjusted16 = adjusted; |
| 2730 | self.adjust_cover = cover; |
| 2731 | result |
| 2732 | } |
| 2733 | |
| 2734 | /// Where a `w` x `h` picture of this clip lands on the canvas, as luma: the |
| 2735 | /// same placement, run on a picture that is white everywhere, so the cover |
| 2736 | /// is exactly the placed picture's footprint -- transform, crop, fit bars |
| 2737 | /// and all -- without a second copy of that geometry to keep in step. |
| 2738 | fn coverage(&mut self, w: u32, h: u32, transform: TransformParams) -> Vec<u8> { |
| 2739 | // A generator with a transparent background ([`crate::generate::Gen::has_alpha`]) places |
| 2740 | // its alpha as the luma (limited range, so the fit bars are 0) and is covered by degree. |
| 2741 | // The mask is drawn at the picture's own size, so a canvas that is not the generator's |
| 2742 | // still gets a shape, not the full frame. It reaches `place_picture` as plain luma with |
| 2743 | // no grade, remap or tonemap (all `None` below): only geometry and resampling touch it. |
| 2744 | if let Some(g) = self.alpha_gen |
| 2745 | && !matches!(&self.alpha_mask, Some((mw, mh, _)) if (*mw, *mh) == (w, h)) |
| 2746 | { |
| 2747 | let mask = crate::generate::Gen::new(g.kind, w, h).alpha().expect("an alpha generator has a mask"); |
| 2748 | self.alpha_mask = Some((w, h, mask)); |
| 2749 | } |
| 2750 | let alpha = self.alpha_gen.and(self.alpha_mask.as_ref()).map(|(_, _, m)| m); |
| 2751 | let ones: Vec<u8> = match alpha { |
| 2752 | Some(a) => a.iter().map(|&v| 16 + (u32::from(v) * 219 / 255) as u8).collect(), |
| 2753 | None => vec![255u8; w as usize * h as usize], |
| 2754 | }; |
| 2755 | let chroma = vec![128u8; w.div_ceil(2) as usize * h.div_ceil(2) as usize]; |
| 2756 | let (cy, _, _, _, _) = place_picture( |
| 2757 | &ones, |
| 2758 | &chroma, |
| 2759 | &chroma, |
| 2760 | w, |
| 2761 | h, |
| 2762 | self.info.rotation, |
| 2763 | self.info.pixel_aspect, |
| 2764 | None, |
| 2765 | transform, |
| 2766 | None, |
| 2767 | None, |
| 2768 | &mut self.rotated, |
| 2769 | &mut self.stretched, |
| 2770 | &mut self.graded, |
| 2771 | &mut self.transformed, |
| 2772 | &mut self.fit_canvas, |
| 2773 | ); |
| 2774 | match alpha.is_some() { |
| 2775 | true => cy.iter().map(|&p| ((u32::from(p.clamp(16, 235)) - 16) * 255 / 219) as u8).collect(), |
| 2776 | false => cy.iter().map(|&p| if p >= 128 { 255 } else { 0 }).collect(), |
| 2777 | } |
| 2778 | } |
| 2779 | } |
| 2780 | |
| 2781 | /// A layer's effects stack drawn on its placed picture `planes` (a canvas of `size`): the |
| 2782 | /// blend mode it lands in and the coverage its keys and masks leave of `cover`, `None` where |
| 2783 | /// it has no effects (or none that cut the footprint). Generic over the sample so the 8-bit |
| 2784 | /// and the 10-bit layer paths draw one stack the same way. |
| 2785 | #[allow(clippy::too_many_arguments)] |
| 2786 | fn layer_effects<T: crate::scale::Sample>( |
| 2787 | effects: &[crate::effects::Effect], |
| 2788 | planes: &mut Planes<T>, |
| 2789 | size: (u32, u32), |
| 2790 | secs: f64, |
| 2791 | src: f64, |
| 2792 | matrix: Matrix, |
| 2793 | scratch: &mut crate::effects::Scratch<T>, |
| 2794 | cover: &[u8], |
| 2795 | ) -> (crate::effects::BlendMode, Option<Vec<u8>>) { |
| 2796 | if !crate::effects::active(effects) { |
| 2797 | return (Default::default(), None); |
| 2798 | } |
| 2799 | let out = crate::effects::apply( |
| 2800 | effects, |
| 2801 | (&mut planes.0, &mut planes.1, &mut planes.2), |
| 2802 | size.0 as usize, |
| 2803 | size.1 as usize, |
| 2804 | secs, |
| 2805 | src, |
| 2806 | matrix, |
| 2807 | scratch, |
| 2808 | ); |
| 2809 | let fx_cover = out.alpha.map(|alpha| { |
| 2810 | debug_assert_eq!(cover.len(), alpha.len(), "the cover and the effects' alpha are one size"); |
| 2811 | cover |
| 2812 | .iter() |
| 2813 | .zip(alpha) |
| 2814 | .map(|(&c, a)| ((u32::from(c) * u32::from(a) + 127) / 255) as u8) |
| 2815 | .collect() |
| 2816 | }); |
| 2817 | (out.mode, fx_cover) |
| 2818 | } |
| 2819 | |
| 2820 | /// A layered picture's clips, open together: read forward by timeline frame and |
| 2821 | /// composed bottom to top ([`LayerStack::picture`]). |
| 2822 | pub(crate) struct LayerStack { |
| 2823 | feeds: Vec<LayerFeed>, |
| 2824 | width: usize, |
| 2825 | height: usize, |
| 2826 | } |
| 2827 | |
| 2828 | impl LayerStack { |
| 2829 | /// The clips of `stack` ([`stack_at`]) on a `meta`-sized canvas, colour |
| 2830 | /// converted with `matrix`, decoded from `paths` where given (see |
| 2831 | /// [`LayerFeed::open`]). Nothing is decoded until a frame is asked for. |
| 2832 | pub(crate) fn open( |
| 2833 | project: &Project, |
| 2834 | meta: &VideoMeta, |
| 2835 | stack: &[(Lane, usize)], |
| 2836 | matrix: Matrix, |
| 2837 | paths: Option<&[PathBuf]>, |
| 2838 | measure: Option<Measure<'_>>, |
| 2839 | ) -> crate::Result<Self> { |
| 2840 | let feeds = stack |
| 2841 | .iter() |
| 2842 | .map(|&(lane, idx)| LayerFeed::open(project, meta, lane, idx, matrix, paths, measure)) |
| 2843 | .collect::<crate::Result<Vec<_>>>()?; |
| 2844 | Ok(Self { |
| 2845 | feeds, |
| 2846 | width: meta.width as usize, |
| 2847 | height: meta.height as usize, |
| 2848 | }) |
| 2849 | } |
| 2850 | |
| 2851 | /// The composed I420 picture at timeline `frame`, or `None` once a clip's |
| 2852 | /// file ends before it. The bottom clip is drawn exactly as a single clip |
| 2853 | /// is (its bars black); each clip above lands on it where its own picture |
| 2854 | /// covers, at its own fade -- so a fade on a picture on top shows the one |
| 2855 | /// beneath through it, rather than fading the whole frame. A clip whose |
| 2856 | /// tail is dissolving into the next clip on its lane shows the blend of the |
| 2857 | /// two over the window ([`LayerFeed::cross_at`]), and the layers above |
| 2858 | /// composite over that -- so a dissolve under a picture-in-picture blends |
| 2859 | /// the same as one without it. |
| 2860 | pub(crate) fn picture(&mut self, frame: u32) -> crate::Result<Option<Planes>> { |
| 2861 | let (w, h) = (self.width, self.height); |
| 2862 | let mut out: Option<Planes> = None; |
| 2863 | for feed in &mut self.feeds { |
| 2864 | if !feed.adjust && !feed.advance(frame)? { |
| 2865 | return Ok(None); |
| 2866 | } |
| 2867 | // The fade and the opacity both scale this layer's coverage. |
| 2868 | let opacity = crate::project::clip_transform_at( |
| 2869 | &feed.clip, |
| 2870 | TransformParams { |
| 2871 | opacity: feed.opacity, |
| 2872 | ..TransformParams::default() |
| 2873 | }, |
| 2874 | frame, |
| 2875 | ) |
| 2876 | .opacity; |
| 2877 | let opacity = crate::project::clip_opacity_at(&feed.clip, opacity, frame); |
| 2878 | let k = clip_fade(&feed.clip, frame).unwrap_or(1.0) * opacity; |
| 2879 | // An adjustment layer with nothing beneath it is a no-op. Adjacent adjustment clips |
| 2880 | // hard-cut: `cross_at` is skipped for them, so a dissolve between two does nothing. |
| 2881 | if feed.adjust { |
| 2882 | out = out.take().map(|base| feed.adjust_over(base, k, frame)); |
| 2883 | continue; |
| 2884 | } |
| 2885 | let blended = feed.cross_at(frame)?; |
| 2886 | let (planes, cover): (&Planes, &[u8]) = match blended.as_ref() { |
| 2887 | Some((planes, cover)) => (planes, cover.as_slice()), |
| 2888 | None => { |
| 2889 | let Some((_, planes)) = feed.current.as_ref() else { |
| 2890 | return Ok(None); |
| 2891 | }; |
| 2892 | let cover = feed.fx_cover.as_deref().or(feed.cover.as_deref()); |
| 2893 | (planes, cover.expect("set with the picture")) |
| 2894 | } |
| 2895 | }; |
| 2896 | // A clip whose effects key, mask or blend it is laid over what is |
| 2897 | // beneath -- black, at the bottom -- by [`crate::effects::blend_over`]. |
| 2898 | let mode = feed.fx_mode; |
| 2899 | if feed.fx_cover.is_some() || mode != crate::effects::BlendMode::Normal { |
| 2900 | let base = out.get_or_insert_with(|| crate::scale::black_i420(w, h)); |
| 2901 | crate::effects::blend_over( |
| 2902 | (&mut base.0, &mut base.1, &mut base.2), |
| 2903 | borrow_planes(planes), |
| 2904 | cover, |
| 2905 | k, |
| 2906 | mode, |
| 2907 | feed.matrix, |
| 2908 | w, |
| 2909 | h, |
| 2910 | ); |
| 2911 | continue; |
| 2912 | } |
| 2913 | // A picture with a transparent background lands on black, as the bottom layer does. |
| 2914 | if out.is_none() && feed.alpha_gen.is_some() { |
| 2915 | out = Some(crate::scale::black_i420(w, h)); |
| 2916 | } |
| 2917 | match out.as_mut() { |
| 2918 | // The bottom layer sits on black, as a single clip does. |
| 2919 | None => { |
| 2920 | out = Some(match k < 1.0 { |
| 2921 | true => fade_planes(borrow_planes(planes), k), |
| 2922 | false => planes.clone(), |
| 2923 | }); |
| 2924 | } |
| 2925 | Some(base) => layer_over(base, planes, cover, k, w, h), |
| 2926 | } |
| 2927 | } |
| 2928 | // Nothing drew (a stack of adjustment layers alone) is a gap: black. |
| 2929 | Ok(Some(out.unwrap_or_else(|| crate::scale::black_i420(w, h)))) |
| 2930 | } |
| 2931 | |
| 2932 | /// [`LayerStack::picture`] at 10 bits: 10-bit layers keep every sample, 8-bit ones are |
| 2933 | /// widened where they meet, and the grade, the placement, the blends and the effects all |
| 2934 | /// run on 10-bit codes. |
| 2935 | pub(crate) fn picture16(&mut self, frame: u32) -> crate::Result<Option<Planes16>> { |
| 2936 | let (w, h) = (self.width, self.height); |
| 2937 | let mut out: Option<Planes16> = None; |
| 2938 | for feed in &mut self.feeds { |
| 2939 | if !feed.adjust && !feed.advance16(frame)? { |
| 2940 | return Ok(None); |
| 2941 | } |
| 2942 | let opacity = crate::project::clip_transform_at( |
| 2943 | &feed.clip, |
| 2944 | TransformParams { |
| 2945 | opacity: feed.opacity, |
| 2946 | ..TransformParams::default() |
| 2947 | }, |
| 2948 | frame, |
| 2949 | ) |
| 2950 | .opacity; |
| 2951 | let opacity = crate::project::clip_opacity_at(&feed.clip, opacity, frame); |
| 2952 | let k = clip_fade(&feed.clip, frame).unwrap_or(1.0) * opacity; |
| 2953 | if feed.adjust { |
| 2954 | out = out.take().map(|base| feed.adjust_over16(base, k, frame)); |
| 2955 | continue; |
| 2956 | } |
| 2957 | let blended = feed.cross_at16(frame)?; |
| 2958 | let (planes, cover): (&Planes16, &[u8]) = match blended.as_ref() { |
| 2959 | Some((planes, cover)) => (planes, cover.as_slice()), |
| 2960 | None => { |
| 2961 | let Some((_, planes)) = feed.current16.as_ref() else { |
| 2962 | return Ok(None); |
| 2963 | }; |
| 2964 | let cover = feed.fx_cover.as_deref().or(feed.cover.as_deref()); |
| 2965 | (planes, cover.expect("set with the picture")) |
| 2966 | } |
| 2967 | }; |
| 2968 | let mode = feed.fx_mode; |
| 2969 | if feed.fx_cover.is_some() || mode != crate::effects::BlendMode::Normal { |
| 2970 | let base = out.get_or_insert_with(|| crate::scale::black_i420_wide(w, h)); |
| 2971 | crate::effects::blend_over( |
| 2972 | (&mut base.0, &mut base.1, &mut base.2), |
| 2973 | borrow_planes(planes), |
| 2974 | cover, |
| 2975 | k, |
| 2976 | mode, |
| 2977 | feed.matrix, |
| 2978 | w, |
| 2979 | h, |
| 2980 | ); |
| 2981 | continue; |
| 2982 | } |
| 2983 | if out.is_none() && feed.alpha_gen.is_some() { |
| 2984 | out = Some(crate::scale::black_i420_wide(w, h)); |
| 2985 | } |
| 2986 | match out.as_mut() { |
| 2987 | None => { |
| 2988 | out = Some(match k < 1.0 { |
| 2989 | true => fade_planes(borrow_planes(planes), k), |
| 2990 | false => planes.clone(), |
| 2991 | }); |
| 2992 | } |
| 2993 | Some(base) => layer_over(base, planes, cover, k, w, h), |
| 2994 | } |
| 2995 | } |
| 2996 | Ok(Some(out.unwrap_or_else(|| crate::scale::black_i420_wide(w, h)))) |
| 2997 | } |
| 2998 | } |
| 2999 | |
| 3000 | /// `top` laid over `base` where `cover` says the picture is, at strength `k` |
| 3001 | /// (its fade times 1). Luma takes each sample's own coverage; chroma takes the |
| 3002 | /// coverage of the luma sample at its block's top left. |
| 3003 | fn layer_over<T: crate::scale::Sample>(base: &mut Planes<T>, top: &Planes<T>, cover: &[u8], k: f32, w: usize, h: usize) { |
| 3004 | let mix = |b: T, t: T, a: f32| { |
| 3005 | let (b, t) = (b.code() as f32, t.code() as f32); |
| 3006 | T::from_f32(b + (t - b) * a) |
| 3007 | }; |
| 3008 | for (i, (b, &t)) in base.0.iter_mut().zip(&top.0).enumerate() { |
| 3009 | let a = f32::from(cover[i]) / 255.0 * k; |
| 3010 | if a > 0.0 { |
| 3011 | *b = mix(*b, t, a); |
| 3012 | } |
| 3013 | } |
| 3014 | let cw = w.div_ceil(2); |
| 3015 | for i in 0..cw * h.div_ceil(2) { |
| 3016 | let (cx, cy) = (i % cw, i / cw); |
| 3017 | let a = f32::from(cover[2 * cy * w + 2 * cx]) / 255.0 * k; |
| 3018 | if a > 0.0 { |
| 3019 | base.1[i] = mix(base.1[i], top.1[i], a); |
| 3020 | base.2[i] = mix(base.2[i], top.2[i], a); |
| 3021 | } |
| 3022 | } |
| 3023 | } |
| 3024 | |
| 3025 | /// A layered span as a playback stream: its composed frames, one per picture |
| 3026 | /// change, decoded on a thread of their own. Each is `view`-sized and numbered |
| 3027 | /// the way a decoder numbers its pictures -- the span's first source frame plus |
| 3028 | /// the speed's step -- so the playback clock maps it like any other clip. |
| 3029 | pub(crate) fn layered_stream( |
| 3030 | project: Project, |
| 3031 | view: VideoMeta, |
| 3032 | out_color: ColorDescription, |
| 3033 | span: crate::project::Span, |
| 3034 | paths: Option<Vec<PathBuf>>, |
| 3035 | ) -> crate::decode::FrameStream { |
| 3036 | let stack = stack_at(&project, span.start); |
| 3037 | let base = span.from.map_or(0, |(_, in_frame)| in_frame); |
| 3038 | crate::decode::DecodeSession::spawn_stream( |
| 3039 | "layers", |
| 3040 | crate::decode::Backend::Software, |
| 3041 | move |tx, cancel| { |
| 3042 | let Ok(mut layers) = |
| 3043 | LayerStack::open(&project, &view, &stack, out_color.matrix, paths.as_deref(), None) |
| 3044 | else { |
| 3045 | return; |
| 3046 | }; |
| 3047 | let mut last = None; |
| 3048 | for offset in 0..span.len { |
| 3049 | if cancel.load(Ordering::Relaxed) { |
| 3050 | return; |
| 3051 | } |
| 3052 | // One picture per source step, as a decoder yields one per frame: |
| 3053 | // a slowed clip's repeats are held by the clock, not decoded again. |
| 3054 | let step = span.source_offset(offset); |
| 3055 | if last == Some(step) { |
| 3056 | continue; |
| 3057 | } |
| 3058 | last = Some(step); |
| 3059 | let Ok(Some((y, u, v))) = layers.picture(span.start + offset) else { |
| 3060 | return; |
| 3061 | }; |
| 3062 | let bgra = crate::convert::i420_to_bgra( |
| 3063 | &out_color, |
| 3064 | &y, |
| 3065 | &u, |
| 3066 | &v, |
| 3067 | view.width as usize, |
| 3068 | view.height as usize, |
| 3069 | ); |
| 3070 | let frame = crate::decode::Frame { |
| 3071 | index: base + step, |
| 3072 | width: view.width, |
| 3073 | height: view.height, |
| 3074 | bgra, |
| 3075 | }; |
| 3076 | if tx.send(frame).is_err() { |
| 3077 | return; |
| 3078 | } |
| 3079 | } |
| 3080 | }, |
| 3081 | ) |
| 3082 | } |
| 3083 | |
| 3084 | /// The cross-dissolve this span's tail owes its successor, or `None` for a |
| 3085 | /// hard cut. `(b_source, b_in_frame, window, b_start)`: which source and |
| 3086 | /// source frame the dissolve's B side starts reading, how many *output* |
| 3087 | /// frames the blend ramps across, and where B sits on the timeline (which is |
| 3088 | /// what its own grade and fit are keyed on, [`Project::composite_color_at`] |
| 3089 | /// and [`Project::composite_fit_at`]). |
| 3090 | /// |
| 3091 | /// [`Clip::transition_out`] is trusted only after adjacency is checked again |
| 3092 | /// here: a trim or a split since it was set leaves the stored number in |
| 3093 | /// place but not its meaning, so a stale one plays as the hard cut it now |
| 3094 | /// is rather than as a dissolve into a clip that no longer follows. |
| 3095 | pub(crate) fn dissolve_window( |
| 3096 | project: &Project, |
| 3097 | span: &crate::project::Span, |
| 3098 | ) -> Option<(usize, u32, u32, u32)> { |
| 3099 | // A layered picture is composed beneath its top clip, and a dissolve of that |
| 3100 | // clip would blend a picture of one clip alone -- the layers are not blended. |
| 3101 | if layered_at(project, span.start) { |
| 3102 | return None; |
| 3103 | } |
| 3104 | let (source, _) = span.from?; |
| 3105 | let (lane, idx) = project.composite_clip_at(span.start)?; |
| 3106 | let clips = project.lane(lane); |
| 3107 | let a = clips.get(idx)?; |
| 3108 | if a.source != source || a.transition_out == 0 { |
| 3109 | return None; |
| 3110 | } |
| 3111 | let b = clips.get(idx + 1)?; |
| 3112 | if a.end() != b.start { |
| 3113 | return None; // trimmed or split apart since the dissolve was set |
| 3114 | } |
| 3115 | // The span must run uninterrupted all the way to A's own end: a higher |
| 3116 | // video lane taking over before that means there is no tail of A left |
| 3117 | // here to blend into anything. |
| 3118 | if span.start + span.len != a.end() { |
| 3119 | return None; |
| 3120 | } |
| 3121 | let window = a |
| 3122 | .transition_out |
| 3123 | .min(a.frames()) |
| 3124 | .min(b.frames()) |
| 3125 | .min(span.len); |
| 3126 | (window > 0).then_some((b.source, b.in_frame, window, b.start)) |
| 3127 | } |
| 3128 | |
| 3129 | /// `B`'s weight in [`crate::scale::blend_i420`] at output frame `idx_in_window` of `window` |
| 3130 | /// (`idx_in_window < window`): a ramp from just above 0 to just below 1 that |
| 3131 | /// never actually reaches either end, so the first blended frame still shows |
| 3132 | /// a trace of A and the last still a trace of B -- the cut a hard transition |
| 3133 | /// would have made lands one frame *after* the window, at full B, rather than |
| 3134 | /// inside it. |
| 3135 | pub(crate) fn dissolve_weight(idx_in_window: u32, window: u32) -> f32 { |
| 3136 | (idx_in_window + 1) as f32 / (window + 1) as f32 |
| 3137 | } |
| 3138 | |
| 3139 | /// The picture's black fade at timeline `frame`: the share of the picture that |
| 3140 | /// survives, `None` where no fade reaches it. The clip on screen |
| 3141 | /// ([`Project::composite_clip_at`]) owns its own fades -- [`Clip::fade_in`] ramps |
| 3142 | /// from black on its first frame to the whole picture at `fade_in`, and |
| 3143 | /// [`Clip::fade_out`] ramps back to black over its last `fade_out` frames, the |
| 3144 | /// same edges [`crate::project::Fade`] ramps the sound on. A linear ramp: the |
| 3145 | /// first frame of a fade-in is pure black and the frame a fade-out ends on is |
| 3146 | /// one step short of it, so nothing shows the picture at full strength while |
| 3147 | /// the ramp is still running. |
| 3148 | pub(crate) fn picture_fade_at(project: &Project, frame: u32) -> Option<f32> { |
| 3149 | let (lane, idx) = project.composite_clip_at(frame)?; |
| 3150 | clip_fade(project.lane(lane).get(idx)?, frame) |
| 3151 | } |
| 3152 | |
| 3153 | /// [`picture_fade_at`] for one clip: the share of its picture that survives at |
| 3154 | /// `frame`. A layered picture asks it of each clip, so a fade belongs to the |
| 3155 | /// clip it is on. |
| 3156 | fn clip_fade(clip: &crate::project::Clip, frame: u32) -> Option<f32> { |
| 3157 | if clip.fade_in == 0 && clip.fade_out == 0 { |
| 3158 | return None; |
| 3159 | } |
| 3160 | let pos = frame.checked_sub(clip.start)?; |
| 3161 | let total = clip.frames(); |
| 3162 | let mut k = 1.0f32; |
| 3163 | if clip.fade_in > 0 && pos < clip.fade_in { |
| 3164 | k = pos as f32 / clip.fade_in as f32; |
| 3165 | } |
| 3166 | if clip.fade_out > 0 && pos >= total.saturating_sub(clip.fade_out) { |
| 3167 | k = k.min((total - pos) as f32 / clip.fade_out as f32); |
| 3168 | } |
| 3169 | (k < 1.0).then_some(k) |
| 3170 | } |
| 3171 | |
| 3172 | /// Whether any frame of `span` is inside a picture fade ([`picture_fade_at`]): |
| 3173 | /// the span's pixels then have to be touched, which a zero-copy span never is. |
| 3174 | fn picture_faded_in(project: &Project, span: &crate::project::Span) -> bool { |
| 3175 | (span.start..span.start.saturating_add(span.len)) |
| 3176 | .any(|frame| picture_fade_at(project, frame).is_some()) |
| 3177 | } |
| 3178 | |
| 3179 | /// Whether any video clip on the timeline has a picture fade -- the |
| 3180 | /// picture-side twin of [`faded`], which asks the same of sound: a fade is |
| 3181 | /// pixel math, so a stream copy cannot carry one. |
| 3182 | fn picture_faded(project: &Project) -> bool { |
| 3183 | project |
| 3184 | .lanes() |
| 3185 | .into_iter() |
| 3186 | .filter(|lane| lane.kind == LaneKind::Video) |
| 3187 | .any(|lane| { |
| 3188 | project |
| 3189 | .lane(lane) |
| 3190 | .iter() |
| 3191 | .any(|c| c.fade_in > 0 || c.fade_out > 0) |
| 3192 | }) |
| 3193 | } |
| 3194 | |
| 3195 | /// `planes` drawn toward black by `k` ([`picture_fade_at`]): luma moves toward |
| 3196 | /// 16 and chroma toward 128, the black a gap is composed as, so a faded frame |
| 3197 | /// and a gap agree on what black is. |
| 3198 | fn fade_planes<T: Sample>(planes: (&[T], &[T], &[T]), k: f32) -> Planes<T> { |
| 3199 | let toward = |s: &[T], black: T| -> Vec<T> { |
| 3200 | s.iter() |
| 3201 | .map(|&p| { |
| 3202 | let (black, p) = (black.code() as f32, p.code() as f32); |
| 3203 | T::from_f32(black + (p - black) * k) |
| 3204 | }) |
| 3205 | .collect() |
| 3206 | }; |
| 3207 | ( |
| 3208 | toward(planes.0, T::BLACK), |
| 3209 | toward(planes.1, T::NEUTRAL), |
| 3210 | toward(planes.2, T::NEUTRAL), |
| 3211 | ) |
| 3212 | } |
| 3213 | |
| 3214 | /// A dissolve's B side, open beside A's own decoder for this span's tail: |
| 3215 | /// its own decoder, and everything [`place_picture`] needs to put its frames |
| 3216 | /// on the same canvas, in the same space, graded the way B is graded rather |
| 3217 | /// than the way A is -- [`Project::composite_color_at`]/`composite_fit_at` |
| 3218 | /// asked at B's own start, not at the timeline position the blend writes to, |
| 3219 | /// which is still inside A's span. |
| 3220 | struct Dissolve<'a> { |
| 3221 | /// How many output frames the blend ramps across. |
| 3222 | window: u32, |
| 3223 | kind: crate::transitions::TransitionKind, |
| 3224 | /// The first output frame of this span's tail that is inside the window. |
| 3225 | tail_start: u32, |
| 3226 | decoder: ClipDecoder, |
| 3227 | mapper: Option<&'a ToneMapper>, |
| 3228 | remap: Option<Remap>, |
| 3229 | grade: Option<crate::color::ColorParams>, |
| 3230 | transform: TransformParams, |
| 3231 | /// B's own file's display-matrix turn, [`place_picture`]'s first stage; |
| 3232 | /// B is a different file and may be turned differently from A. |
| 3233 | rotation: Rotation, |
| 3234 | /// B's own file's sample aspect, [`place_picture`]'s second stage, for |
| 3235 | /// the same reason the turn is per file. |
| 3236 | pixel_aspect: crate::demux::PixelAspect, |
| 3237 | canvas: Composer, |
| 3238 | /// The turn's, the grade's and the transform's scratch, exactly as A's |
| 3239 | /// span keeps them: refilled per picture, allocated once. |
| 3240 | rotated: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3241 | /// The stretch's own scratch, [`place_picture`]'s second stage -- the |
| 3242 | /// pixel aspect's, beside the turn's. |
| 3243 | stretched: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3244 | graded: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3245 | transformed: (Vec<u8>, Vec<u8>, Vec<u8>), |
| 3246 | /// The 10-bit scratch of B's placement, for a 10-bit export. |
| 3247 | scratch16: Scratch16, |
| 3248 | } |
| 3249 | |
| 3250 | /// The Videos folder a default export lands in: the user's own (`XDG_VIDEOS_DIR`, |
| 3251 | /// else the one `~/.config/user-dirs.dirs` names, else `~/Videos`), then the |
| 3252 | /// project's folder, never the media's own folder by default. |
| 3253 | pub fn default_export_folder(project: &Path) -> PathBuf { |
| 3254 | let home = std::env::var_os("HOME").map(PathBuf::from); |
| 3255 | let xdg = std::env::var_os("XDG_VIDEOS_DIR").map(PathBuf::from).or_else(|| { |
| 3256 | let home = home.as_ref()?; |
| 3257 | let text = std::fs::read_to_string(home.join(".config/user-dirs.dirs")).ok()?; |
| 3258 | let line = text.lines().find_map(|l| l.trim().strip_prefix("XDG_VIDEOS_DIR="))?; |
| 3259 | let value = line.trim().trim_matches('"'); |
| 3260 | Some(PathBuf::from(value.replace("$HOME", &home.to_string_lossy()))) |
| 3261 | }); |
| 3262 | let videos = xdg.filter(|d| d.is_dir()).or_else(|| home.map(|h| h.join("Videos")).filter(|d| d.is_dir())); |
| 3263 | videos |
| 3264 | .or_else(|| project.parent().filter(|p| !p.as_os_str().is_empty()).map(Path::to_path_buf)) |
| 3265 | .unwrap_or_else(|| PathBuf::from(".")) |
| 3266 | } |
| 3267 | |
| 3268 | /// The track's cues where the *exported* timeline puts them, which is the only |
| 3269 | /// clock the file has: the export writes timeline frame 0 onwards and nothing |
| 3270 | /// else, exactly as the sound is mixed from frame 0 and resized to the |
| 3271 | /// timeline's own length ([`encode_audio`]). |
| 3272 | /// |
| 3273 | /// Which clock the cues arrive in is what the track itself says: |
| 3274 | /// |
| 3275 | /// * a track out of a *file* (`SubtitleTrack::track`) is timed against that |
| 3276 | /// file, so each cue is carried through the spans that play it -- a cue over |
| 3277 | /// a stretch that was cut out is gone, one straddling a cut keeps the half |
| 3278 | /// that is still there, and one after a rippled delete moves back with the |
| 3279 | /// picture it belongs to. The *edges* a cut clips to are frames -- that is |
| 3280 | /// what a cut is -- but a cue nothing clipped keeps its own microseconds, so |
| 3281 | /// an untouched timeline exports the times the source states. |
| 3282 | /// * a *standalone* file (`subs.srt`) is timed against nothing else -- there is |
| 3283 | /// no clip to hang it on and no offset in the project to shift it by -- so it |
| 3284 | /// is the timeline's own clock, which is where it was drawn while editing |
| 3285 | /// (`Player::subtitle_overlay`). Clipped to the exported length and no more. |
| 3286 | /// |
| 3287 | /// This is also what the *preview* draws: the plate over the picture and the |
| 3288 | /// timeline strip both ask it through |
| 3289 | /// [`PlaybackSession::timeline_cues`](crate::PlaybackSession::timeline_cues), so |
| 3290 | /// what a rippled timeline shows and what its export writes are one answer by |
| 3291 | /// construction rather than two maps kept in step by hand. |
| 3292 | /// |
| 3293 | /// Pure and cheap enough to ask per repaint (a walk of the spans and of the |
| 3294 | /// cues, no file opened), which is how a front-end asks it. |
| 3295 | pub fn timeline_cues(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<Cue> { |
| 3296 | timeline_cues_indexed(project, track, fps).into_iter().map(|(_, cue)| cue).collect() |
| 3297 | } |
| 3298 | |
| 3299 | fn timeline_cues_indexed(project: &Project, track: &SubtitleTrack, fps: f64) -> Vec<(usize, Cue)> { |
| 3300 | let frames = project.timeline_frames(); |
| 3301 | let us = |frame: u32| (f64::from(frame) / fps * 1e6).round() as i64; |
| 3302 | let end = us(frames); |
| 3303 | // The file the cues are timed against, when there is one on this timeline. |
| 3304 | // A track whose media has since been dropped from the project has no span |
| 3305 | // to be carried through and falls back to the timeline's clock, which is |
| 3306 | // what it was drawn on. |
| 3307 | // |
| 3308 | // Through the same `canonical` a source is indexed by, or the two spellings |
| 3309 | // of one file (an argv `../assets/film.mkv`, a symlinked folder) would read |
| 3310 | // as two files and the cues would quietly fall back to the timeline's clock. |
| 3311 | let source = track.track.and_then(|_| { |
| 3312 | let path = crate::project::canonical(&track.path); |
| 3313 | project.sources().iter().position(|s| s.path == path) |
| 3314 | }); |
| 3315 | let Some(source) = source else { |
| 3316 | return track |
| 3317 | .cues |
| 3318 | .iter() |
| 3319 | .enumerate() |
| 3320 | .filter_map(|(i, cue)| { |
| 3321 | let (start_us, end_us) = (cue.start_us.max(0), cue.end_us.min(end)); |
| 3322 | (end_us > start_us).then_some((i, Cue { |
| 3323 | start_us, |
| 3324 | end_us, |
| 3325 | text: cue.text.clone(), |
| 3326 | image: cue.image.clone(), |
| 3327 | words: crate::subtitle::map_words(&cue.words, (start_us, end_us), (start_us, end_us)), |
| 3328 | karaoke: crate::subtitle::map_karaoke(&cue.karaoke, (start_us, end_us), (start_us, end_us)), |
| 3329 | })) |
| 3330 | }) |
| 3331 | .collect(); |
| 3332 | }; |
| 3333 | let mut out = Vec::new(); |
| 3334 | for span in stack_spans_from(project, 0) { |
| 3335 | let Some((_, in_frame)) = span.from.filter(|&(from, _)| from == source) else { |
| 3336 | continue; |
| 3337 | }; |
| 3338 | // What of the file this span plays, as *time in the file*: a clip counts |
| 3339 | // the timeline's frames whatever its file was shot at ([`Rate`]), which |
| 3340 | // is what makes those frames the same seconds a cue is timed in. |
| 3341 | let (first, last) = match span.source_window() { |
| 3342 | Some((_, lo, hi)) => (us(lo), us(hi)), |
| 3343 | None => (us(in_frame), us(in_frame + span.source_len())), |
| 3344 | }; |
| 3345 | // Where that lands, and how fast: a cue is carried by the same factor |
| 3346 | // the pictures under it are, so a slowed clip stretches its subtitles |
| 3347 | // with it instead of leaving them behind. |
| 3348 | let start = us(span.start); |
| 3349 | // `rel` is the time since the span's head in the file's own direction of play: |
| 3350 | // forwards from `first`, and for a reversed clip back from `last` (the cue |
| 3351 | // [s, e] is mirrored to [last - e, last - s]). |
| 3352 | let onto = |rel: i64| { |
| 3353 | let Some(_) = span.ramp else { |
| 3354 | return start + (rel as f64 / span.speed.as_f64()).round() as i64; |
| 3355 | }; |
| 3356 | // A ramp has no one factor: carry the cue through the ramp's own |
| 3357 | // inverse (`Span::timeline_at`), interpolating between whole frames. |
| 3358 | let f = (rel as f64 / 1e6 * fps).max(0.0); |
| 3359 | let (lo, hi) = (f.floor() as u32, f.ceil() as u32); |
| 3360 | let at = |s: u32| f64::from(span.timeline_at(in_frame + s).min(span.start + span.len) - span.start); |
| 3361 | let (a, b) = (at(lo), at(hi)); |
| 3362 | let frames = if hi == lo { b } else { a + (b - a) * (f - f64::from(lo)) }; |
| 3363 | start + (frames / fps * 1e6).round() as i64 |
| 3364 | }; |
| 3365 | for (i, cue) in track.cues.iter().enumerate() { |
| 3366 | let (a, b) = (cue.start_us.max(first), cue.end_us.min(last)); |
| 3367 | if b <= a { |
| 3368 | continue; // wholly outside what this span kept |
| 3369 | } |
| 3370 | let (from, to) = if span.reverse { (last - b, last - a) } else { (a - first, b - first) }; |
| 3371 | out.push((i, Cue { |
| 3372 | start_us: onto(from), |
| 3373 | end_us: onto(to).min(end), |
| 3374 | text: cue.text.clone(), |
| 3375 | image: cue.image.clone(), |
| 3376 | // Each word through the same mapping as the cue, so a ramp places it where |
| 3377 | // its own sound plays; a reversed clip keeps none, its cue shown whole. |
| 3378 | words: if span.reverse { |
| 3379 | Vec::new() |
| 3380 | } else { |
| 3381 | cue.words |
| 3382 | .iter() |
| 3383 | .filter(|(s, _, _)| *s < b) |
| 3384 | .map(|(s, e, w)| { |
| 3385 | let at = |t: i64| onto(t.clamp(a, b) - first).min(end); |
| 3386 | (at(*s), at(*e), w.clone()) |
| 3387 | }) |
| 3388 | .collect() |
| 3389 | }, |
| 3390 | karaoke: if span.reverse { |
| 3391 | Vec::new() |
| 3392 | } else { |
| 3393 | cue.karaoke |
| 3394 | .iter() |
| 3395 | .filter(|k| k.start_us < b) |
| 3396 | .map(|k| { |
| 3397 | let at = |t: i64| onto(t.clamp(a, b) - first).min(end); |
| 3398 | crate::subtitle::Syllable { start_us: at(k.start_us), end_us: at(k.end_us), ..k.clone() } |
| 3399 | }) |
| 3400 | .collect() |
| 3401 | }, |
| 3402 | })); |
| 3403 | } |
| 3404 | } |
| 3405 | // The spans come in timeline order but a cue's *own* order across them does |
| 3406 | // not: a Matroska muxer writes blocks as they come up. |
| 3407 | out.sort_by_key(|(_, cue)| cue.start_us); |
| 3408 | out |
| 3409 | } |
| 3410 | |
| 3411 | /// What [`start`] would do about the subtitles, in the words a card shows: what |
| 3412 | /// travels, and the reason beside every pick that does not. Pure, like |
| 3413 | /// [`planned_audio`]: no file is opened, so it may be asked per repaint. |
| 3414 | /// |
| 3415 | /// `picks` is any run of indices into [`Project::subtitles`] -- an |
| 3416 | /// [`ExportSettings::subtitles`] list (`picks.iter().copied()`) as much as a |
| 3417 | /// single `Some(row)`, which is what a front-end holding one row still hands it. |
| 3418 | pub fn planned_subtitles( |
| 3419 | project: &Project, |
| 3420 | format: Format, |
| 3421 | picks: impl IntoIterator<Item = usize>, |
| 3422 | ) -> String { |
| 3423 | planned_subtitles_in(project, format, picks, None, 0.0) |
| 3424 | } |
| 3425 | |
| 3426 | /// [`planned_subtitles`] for an export of `range` (the frames a ranged file keeps) at `fps`: a |
| 3427 | /// track or lane with no cue left in the range is named as dropped for that reason, since the |
| 3428 | /// file would carry it empty. `None` is the whole timeline, and `fps` is then not read. |
| 3429 | pub fn planned_subtitles_in( |
| 3430 | project: &Project, |
| 3431 | format: Format, |
| 3432 | picks: impl IntoIterator<Item = usize>, |
| 3433 | range: Option<(u32, u32)>, |
| 3434 | fps: f64, |
| 3435 | ) -> String { |
| 3436 | let picks: Vec<usize> = picks.into_iter().collect(); |
| 3437 | let lanes = placed_lanes(project); |
| 3438 | // WebM is the one container that names no subtitle track here, placed or |
| 3439 | // picked: said first and once, as the reason nothing travels. |
| 3440 | if format == Format::Webm && (!picks.is_empty() || !lanes.is_empty()) { |
| 3441 | return "none — a WebM file carries no subtitles".into(); |
| 3442 | } |
| 3443 | if format == Format::ProRes && (!picks.is_empty() || !lanes.is_empty()) { |
| 3444 | return "none — a ProRes QuickTime file carries no subtitles".into(); |
| 3445 | } |
| 3446 | // An mp4 of a timeline with no picture is the sound alone too: no track of |
| 3447 | // either kind is written, placed or picked ([`export_subtitles`]). |
| 3448 | if format.ext() == "mp4" && !has_picture(project) { |
| 3449 | return "none — a timeline with no picture is the sound alone".into(); |
| 3450 | } |
| 3451 | // One statement about the *file*, said before any about a track: a format |
| 3452 | // that is the sound alone has nowhere to put a single one of them, and the |
| 3453 | // reason a pick would not have travelled anyway (a picture track, no cues) |
| 3454 | // is not the reason it does not travel here. Nothing picked is "none" -- |
| 3455 | // there is nothing to say a container cannot carry. |
| 3456 | if !format.has_video() && (!picks.is_empty() || !lanes.is_empty()) { |
| 3457 | return "none — this format is the sound alone".into(); |
| 3458 | } |
| 3459 | // The lanes are the words placed on the timeline and go as they are placed |
| 3460 | // ([`export_subtitles`]); each picked track no lane places is written whole, |
| 3461 | // beside them. The clauses go in the order the file writes the tracks |
| 3462 | // ([`soft_order`]), which is the order the caller gave them. |
| 3463 | let (mut embedded, mut dropped) = (Vec::new(), Vec::new()); |
| 3464 | let (mut lane_count, mut trailing) = (0, false); |
| 3465 | for entry in soft_order(project, &lanes, &picks) { |
| 3466 | let pick = match entry { |
| 3467 | SoftEntry::Lane(lane) => { |
| 3468 | let (e, d, t) = planned_lanes(project, &[lane], &picks, range, fps); |
| 3469 | lane_count += e.len(); |
| 3470 | embedded.extend(e); |
| 3471 | dropped.extend(d); |
| 3472 | trailing |= t; |
| 3473 | continue; |
| 3474 | } |
| 3475 | SoftEntry::Track(pick) => pick, |
| 3476 | }; |
| 3477 | // A pick the project has no row for: a caller holding an index the list |
| 3478 | // no longer has (a removed row shifts every later one down). Every other |
| 3479 | // reason a pick does not travel is named on this card, so this one is |
| 3480 | // too -- a bug that says nothing is a bug found in the finished file. |
| 3481 | let Some(track) = project.subtitles().get(pick) else { |
| 3482 | dropped.push(format!("#{pick} — no such track")); |
| 3483 | continue; |
| 3484 | }; |
| 3485 | if let Some(why) = &track.refused { |
| 3486 | dropped.push(format!("{} — {why}", track.label)); |
| 3487 | } else if track.is_bitmap() { |
| 3488 | // Drawn over the picture, written into no file: the exported track |
| 3489 | // is text and these cues are bitmaps. Said whatever the format, |
| 3490 | // because it is the track and not the container that cannot be |
| 3491 | // carried. |
| 3492 | dropped.push(format!("{} — pictures; drawn, not written", track.label)); |
| 3493 | } else if !track_has_cues(project, track, range, fps) { |
| 3494 | dropped.push(format!("{} — {}", track.label, no_cues_word(range))); |
| 3495 | } else { |
| 3496 | // Whichever container: a Matroska carries the track as |
| 3497 | // `S_TEXT/UTF8` blocks and an mp4 as a `tx3g` timed-text track, and |
| 3498 | // a pick travels either way. There is no container refusal left on |
| 3499 | // this card -- the sound-alone one above is about the *file* and the |
| 3500 | // ones beside it about the *track*. |
| 3501 | embedded.push(track.label.clone()); |
| 3502 | } |
| 3503 | } |
| 3504 | // Lanes only are named as lanes; a picked track in the mix makes them tracks. |
| 3505 | let noun = if lane_count == embedded.len() { "lanes" } else { "tracks" }; |
| 3506 | // A Matroska block numbers its track in one byte, so a file carries at most |
| 3507 | // MAX_SUB_TRACKS of them, placed or picked; the muxer refuses more again. |
| 3508 | if format.is_mkv() && embedded.len() > crate::mux::MAX_SUB_TRACKS { |
| 3509 | return format!( |
| 3510 | "{} subtitle {noun}: a Matroska block writes its track number in one byte, so one file \ |
| 3511 | carries at most {}", |
| 3512 | embedded.len(), |
| 3513 | crate::mux::MAX_SUB_TRACKS |
| 3514 | ); |
| 3515 | } |
| 3516 | let mut parts = match embedded.len() { |
| 3517 | 0 => Vec::new(), |
| 3518 | 1 => vec![format!("{} → embedded", embedded[0])], |
| 3519 | n => vec![format!("{n} {noun} → embedded ({})", embedded.join(", "))], |
| 3520 | }; |
| 3521 | parts.extend(dropped); |
| 3522 | if trailing { |
| 3523 | parts.push("cues past the last picture are cut off there".into()); |
| 3524 | } |
| 3525 | match parts.is_empty() { |
| 3526 | true => "none".into(), |
| 3527 | false => parts.join("; "), |
| 3528 | } |
| 3529 | } |
| 3530 | |
| 3531 | /// [`planned_subtitles`] for a timeline that *places* its words: one clause per |
| 3532 | /// subtitle lane, named by the lane and by the palette row it shows, in the |
| 3533 | /// order the file will declare them ([`lane_subtitles`]). |
| 3534 | /// |
| 3535 | /// Every reason a lane does not travel is said here rather than found in the |
| 3536 | /// file: a picture track placed on it, a track that could not be read, a palette |
| 3537 | /// row that has since gone, a lane sitting entirely past the last picture, and |
| 3538 | /// -- before a byte is written -- more lanes than a Matroska block can number |
| 3539 | /// ([`crate::mux::MAX_SUB_TRACKS`], which the muxer refuses again). |
| 3540 | fn planned_lanes( |
| 3541 | project: &Project, |
| 3542 | lanes: &[Lane], |
| 3543 | picks: &[usize], |
| 3544 | range: Option<(u32, u32)>, |
| 3545 | fps: f64, |
| 3546 | ) -> (Vec<String>, Vec<String>, bool) { |
| 3547 | let end = project.media_frames(); |
| 3548 | let (mut embedded, mut dropped, mut trailing) = (Vec::new(), Vec::new(), false); |
| 3549 | for &lane in lanes { |
| 3550 | let placed = project.sub_lane(lane); |
| 3551 | // An empty lane is a lane nobody has used yet, not a refusal. A lane no |
| 3552 | // pick reaches is not in this file at all, so it is not named either. |
| 3553 | let Some(first) = placed.first() else { |
| 3554 | continue; |
| 3555 | }; |
| 3556 | if !picked(placed, picks) { |
| 3557 | continue; |
| 3558 | } |
| 3559 | let row = |s: &crate::project::SubClip| project.subtitles().get(s.track); |
| 3560 | let (label, head) = (lane.label(), row(first)); |
| 3561 | let name = head.map_or_else(String::new, |t| format!("{} ", t.label)); |
| 3562 | if let Some(gone) = placed.iter().find(|s| row(s).is_none()) { |
| 3563 | dropped.push(format!("{label} — #{} is no longer a track", gone.track)); |
| 3564 | } else if let Some((t, why)) = placed |
| 3565 | .iter() |
| 3566 | .find_map(|s| row(s).and_then(|t| t.refused.as_ref().map(|why| (t, why)))) |
| 3567 | { |
| 3568 | dropped.push(format!("{label} {} — {why}", t.label)); |
| 3569 | } else if let Some(t) = placed.iter().find_map(|s| row(s).filter(|t| t.is_bitmap())) { |
| 3570 | // Drawn over the picture, written into no file -- the same sentence |
| 3571 | // a picked track gets, because it is the track and not the lane that |
| 3572 | // cannot be carried. |
| 3573 | dropped.push(format!( |
| 3574 | "{label} {} — pictures; drawn, not written", |
| 3575 | t.label |
| 3576 | )); |
| 3577 | } else if first.start >= end { |
| 3578 | dropped.push(format!("{label} {name}— past the last picture")); |
| 3579 | } else if range.is_some() && lane_subtitle(project, lane, fps, range, picks).is_none() { |
| 3580 | dropped.push(format!("{label} {name}— {}", no_cues_word(range))); |
| 3581 | } else { |
| 3582 | embedded.push(format!("{label} {}", name.trim_end())); |
| 3583 | // Something on it hangs past the end of the media: the timeline is |
| 3584 | // held open under it ([`Project::timeline_frames`]) but the file |
| 3585 | // stops with the last picture, so those cues are cut off there. |
| 3586 | trailing |= placed.last().is_some_and(|s| s.end() > end); |
| 3587 | } |
| 3588 | } |
| 3589 | (embedded, dropped, trailing) |
| 3590 | } |
| 3591 | |
| 3592 | /// What [`start`] would encode the picture with, probed the way the export |
| 3593 | /// probes it -- the very encoder is opened and closed again -- so this is a |
| 3594 | /// measurement and not a promise. `None` for a format that carries no picture. |
| 3595 | /// |
| 3596 | /// Costs that open (~100 ms here): ask it off a render thread and keep the |
| 3597 | /// answer until the format, the resolution or the bitrate changes. |
| 3598 | pub fn planned_video(meta: &VideoMeta, settings: &ExportSettings) -> Option<&'static str> { |
| 3599 | settings |
| 3600 | .format |
| 3601 | .has_video() |
| 3602 | .then(|| match hw_seat(meta, settings) { |
| 3603 | Ok(hw) => video_label(settings.format, hw.is_some(), settings.intra_only), |
| 3604 | // The seat the settings demand and this machine has not: the very |
| 3605 | // refusal [`start`] would settle with, said on the card instead. |
| 3606 | Err(_) => NO_HW_SEAT, |
| 3607 | }) |
| 3608 | } |
| 3609 | |
| 3610 | /// What [`start`] would open for *this* timeline: the picture's seat -- or the |
| 3611 | /// copy that means there is no encoder at all -- and the sound's, asked of the |
| 3612 | /// very gates the export asks ([`CopyPlan::of`] and [`copy_audio`]'s) rather |
| 3613 | /// than of the format alone. |
| 3614 | /// |
| 3615 | /// This exists because the card and the running export used to disagree in both |
| 3616 | /// directions on the same file: the card named a software HEVC encode for a cut |
| 3617 | /// the engine copied, and named an AAC copy for a Matroska source whose sound |
| 3618 | /// no sample table holds and which therefore always re-encodes. A prediction |
| 3619 | /// that is not the decision is worse than no prediction, because a person plans |
| 3620 | /// their evening around it. |
| 3621 | /// |
| 3622 | /// Costs what [`planned_video`] costs (an encoder opened and closed) plus a |
| 3623 | /// header read per source and, once per file, its cluster walk: ask it off a |
| 3624 | /// render thread and keep the answer until the timeline or the settings change. |
| 3625 | pub fn planned_seats( |
| 3626 | project: &Project, |
| 3627 | meta: &VideoMeta, |
| 3628 | settings: &ExportSettings, |
| 3629 | ) -> (Option<&'static str>, &'static str) { |
| 3630 | // The canvas the file is drawn at, which is what the seat and the copy gate are about. |
| 3631 | let meta = &output_meta(meta, settings); |
| 3632 | let video = settings.format.has_video().then(|| { |
| 3633 | match CopyPlan::of(project, meta, settings).is_some() { |
| 3634 | true => "copy (source packets)", |
| 3635 | false => planned_video(meta, settings).unwrap_or(NO_HW_SEAT), |
| 3636 | } |
| 3637 | }); |
| 3638 | // The half [`audio_label`] cannot know from the format: a copy is a *sample |
| 3639 | // table's* packets ([`copy_audio`] hands them to `copy_multi_streams`), and |
| 3640 | // a Matroska file has none -- so every mkv source re-encodes, however |
| 3641 | // untouched its lane is. Extension only, which is what `is_matroska` |
| 3642 | // reads, so this costs nothing beyond what is already open. A standalone |
| 3643 | // audio file (mp3, wav, flac...) has no sample table either: its sound is |
| 3644 | // decoded and encoded again, as [`copy_multi_streams`] refusing it sends it. |
| 3645 | let copyable = !settings.reencode_audio |
| 3646 | && !forces_encode(project, settings.range.is_some()) |
| 3647 | && !project.sources().iter().any(|source| |
| 3648 | { |
| 3649 | crate::demux::is_matroska(&source.path) |
| 3650 | || crate::demux::is_mpeg_system(&source.path) |
| 3651 | || crate::is_audio(&source.path) |
| 3652 | }); |
| 3653 | let sound = match undecodable_sound(project) { |
| 3654 | Some(label) if has_sound(project) => label, |
| 3655 | // A Matroska file that is encoded (not copied) takes Opus or AAC as the mix decides, so |
| 3656 | // the card names the one this mix will get, read from the sources' headers. |
| 3657 | None if has_sound(project) |
| 3658 | && !copyable |
| 3659 | && settings.format.is_mkv() |
| 3660 | && settings.format != Format::Webm => |
| 3661 | { |
| 3662 | match mkv_mix_is_opus(project, meta.frame_rate) { |
| 3663 | true => "Opus · SW encode (ec-opus)", |
| 3664 | false => "AAC · SW encode (ec-aac)", |
| 3665 | } |
| 3666 | } |
| 3667 | _ => audio_label( |
| 3668 | project, |
| 3669 | settings.format, |
| 3670 | has_sound(project), |
| 3671 | Some(copyable), |
| 3672 | settings.range.is_some(), |
| 3673 | settings.reencode_audio, |
| 3674 | ), |
| 3675 | }; |
| 3676 | (video, sound) |
| 3677 | } |
| 3678 | |
| 3679 | /// Whether the mix a Matroska export encodes would be written as Opus: the rule |
| 3680 | /// [`encode_audio`] applies after the mix is open -- 48 kHz, mono or stereo -- worked |
| 3681 | /// out from the lanes' sources' headers instead ([`AudioSession::probe`]), since no mix |
| 3682 | /// is opened to ask. The mix runs at the highest source rate, 48 kHz when every source |
| 3683 | /// is below 44.1 kHz ([`crate::audio`]'s `mix_rate`), and as wide as the widest source. |
| 3684 | /// The fidelity gate that can still hand the track back to AAC is measured only once |
| 3685 | /// the encode has run, so this is the prediction the export's own line corrects. |
| 3686 | fn mkv_mix_is_opus(project: &Project, fps: f64) -> bool { |
| 3687 | let sources = project.audio_sources(); |
| 3688 | let mut rates = Vec::new(); |
| 3689 | let mut channels = 0u16; |
| 3690 | for lane in project.audio_segments_from(0, fps) { |
| 3691 | for (source, ..) in lane { |
| 3692 | let Some((path, stream)) = source.and_then(|i| sources.get(i)) else { |
| 3693 | continue; |
| 3694 | }; |
| 3695 | if crate::is_image(path) { |
| 3696 | continue; |
| 3697 | } |
| 3698 | if let Ok(Some(probe)) = AudioSession::probe(path, *stream) { |
| 3699 | rates.push(probe.sample_rate); |
| 3700 | channels = channels.max(probe.channels); |
| 3701 | } |
| 3702 | } |
| 3703 | } |
| 3704 | let rate = rates.into_iter().max().map(|r| if r < 44_100 { OPUS_RATE } else { r }); |
| 3705 | rate == Some(OPUS_RATE) && (1..=2).contains(&channels) |
| 3706 | } |
| 3707 | |
| 3708 | /// The sound a timeline's sources cannot give: `Some(label)` when every source |
| 3709 | /// on the audio lanes is one [`AudioSession::unsupported`] names as undecodable, |
| 3710 | /// which is what the export's own open answers with no sound at all ("no audio |
| 3711 | /// to write"). `None` when any source decodes, or when a source has no sound |
| 3712 | /// this question can name. |
| 3713 | fn undecodable_sound(project: &Project) -> Option<&'static str> { |
| 3714 | let reasons: Vec<Option<String>> = project |
| 3715 | .audio_sources() |
| 3716 | .iter() |
| 3717 | .map(|(path, _)| AudioSession::unsupported(path).ok().flatten()) |
| 3718 | .collect(); |
| 3719 | if reasons.is_empty() || reasons.iter().any(Option::is_none) { |
| 3720 | return None; |
| 3721 | } |
| 3722 | // The reason's first words name the codec: a Matroska file by its codec id |
| 3723 | // ("the A_DTS track ..."), an mp4 by its media type ("the dts audio track |
| 3724 | // ..."). Only DTS is named by name; any other codec this engine cannot decode |
| 3725 | // gets the general words. |
| 3726 | let dts = reasons.iter().flatten().all(|reason| { |
| 3727 | let reason = reason.to_ascii_lowercase(); |
| 3728 | reason.starts_with("the a_dts ") || reason.starts_with("the dts ") |
| 3729 | }); |
| 3730 | Some(match dts { |
| 3731 | true => "none — DTS can't be decoded", |
| 3732 | false => "none — this codec can't be decoded", |
| 3733 | }) |
| 3734 | } |
| 3735 | |
| 3736 | /// The tone map a picture export puts on its HDR sources, as a sentence for the |
| 3737 | /// start line and the plan: the picture is written 8-bit BT.709 SDR, so a PQ or |
| 3738 | /// HLG source is tone-mapped down silently otherwise. `None` where no picture |
| 3739 | /// is tone-mapped -- a sound-only format, a preview that keeps its source's |
| 3740 | /// curve ([`ExportSettings::keep_source_colour`]), or no HDR source in the |
| 3741 | /// project. Asked of every source, as [`planned_seats`] asks its sound. |
| 3742 | /// |
| 3743 | /// Header reads only, one per source, the same colour the export's own tone map |
| 3744 | /// is built from ([`source_rate`]). |
| 3745 | pub fn planned_tone(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<String> { |
| 3746 | if !settings.format.has_video() || settings.keep_source_colour { |
| 3747 | return None; |
| 3748 | } |
| 3749 | // The matrix the file is tagged with: the one [`start`] writes for this canvas |
| 3750 | // ([`ColorDescription::output_sized`]), so the words name what the file says. |
| 3751 | let out = output_meta(meta, settings); |
| 3752 | let matrix = match ColorDescription::output_sized(out.width, out.height).matrix { |
| 3753 | Matrix::Bt601 => "BT.601", |
| 3754 | _ => "BT.709", |
| 3755 | }; |
| 3756 | let mut transfers = project.sources().iter().filter_map(|source| { |
| 3757 | if crate::is_image(&source.path) || crate::is_audio(&source.path) { |
| 3758 | return None; |
| 3759 | } |
| 3760 | Demuxer::open(&source.path).ok().map(|(meta, _)| meta.color.transfer) |
| 3761 | }); |
| 3762 | transfers.find_map(|transfer| match transfer { |
| 3763 | Transfer::Pq => Some(format!("HDR (PQ) source tone-mapped to SDR {matrix}")), |
| 3764 | Transfer::Hlg => Some(format!("HDR (HLG) source tone-mapped to SDR {matrix}")), |
| 3765 | Transfer::Sdr => None, |
| 3766 | }) |
| 3767 | } |
| 3768 | |
| 3769 | fn settle(shared: &Shared, result: crate::Result<()>) { |
| 3770 | *shared.outcome.lock().unwrap() = Some(result); |
| 3771 | // Published last: a caller that sees the flag is guaranteed the outcome. |
| 3772 | shared.finished.store(true, Ordering::Release); |
| 3773 | } |
| 3774 | |
| 3775 | /// The audio track an export writes, and how it was made -- a copy is the |
| 3776 | /// source's own packets, bit for bit, and anything else is this project's |
| 3777 | /// encoder over the decoded mix. [`run`] publishes which of the two really |
| 3778 | /// happened, so the encoder line a user reads is measured and not promised. |
| 3779 | pub(crate) struct ExportAudio { |
| 3780 | pub params: crate::AacTrackParams, |
| 3781 | pub packets: Vec<crate::AacPacket>, |
| 3782 | /// Whether those packets are the source's, untouched. |
| 3783 | pub copied: bool, |
| 3784 | /// The track's pre-skip in samples where those packets are **Opus** and not |
| 3785 | /// AAC ([`encode_opus`]), which is what the Matroska track entry states in |
| 3786 | /// its `OpusHead` and its `CodecDelay`. `None` is an AAC track, which is |
| 3787 | /// every copy and every mp4. |
| 3788 | pub opus_pre_skip: Option<u16>, |
| 3789 | /// The language the track is tagged with ([`audio_language`]), `None` for |
| 3790 | /// `und`. Set once where the track is made, from the project it came from. |
| 3791 | pub language: Option<String>, |
| 3792 | /// The sound's length in PCM frames per channel, where the packets were |
| 3793 | /// encoded from a mix of exactly that many: the count the encoder was fed, |
| 3794 | /// not the packets' sum, which runs on past it by the encoder's priming and |
| 3795 | /// the last frame's padding. `None` for a copy, whose length is the |
| 3796 | /// source's own packets. |
| 3797 | pub pcm_frames: Option<u64>, |
| 3798 | } |
| 3799 | |
| 3800 | /// The timeline's audio track for a file that carries picture: copied packet for |
| 3801 | /// packet where a copy says exactly what the timeline says, and decoded, mixed |
| 3802 | /// and encoded again ([`encode_audio`]) where it cannot -- a second audio lane, |
| 3803 | /// a speeded clip, an equalizer, a source that is not AAC inside an mp4 sample |
| 3804 | /// table. Nothing is refused for being uncopyable any more; the only refusals |
| 3805 | /// left below the copy are about sound this engine cannot *decode* either, and |
| 3806 | /// those come out of the decode path by name. |
| 3807 | /// |
| 3808 | /// The copy is still the default and still bit-exact: a timeline nobody has |
| 3809 | /// touched leaves as the very packets its source holds. |
| 3810 | /// |
| 3811 | /// corner-cut: this holds the whole exported AAC track in memory (~3 kB per |
| 3812 | /// 23 ms packet, so ~500 MB for an hour). Upgrade path is a streaming |
| 3813 | /// `copy_segments` that yields packets instead of collecting them. |
| 3814 | #[allow(clippy::too_many_arguments)] |
| 3815 | fn copy_audio( |
| 3816 | project: &Project, |
| 3817 | meta: &VideoMeta, |
| 3818 | kbps: u32, |
| 3819 | mkv: bool, |
| 3820 | webm: bool, |
| 3821 | reencode: bool, |
| 3822 | shared: &Shared, |
| 3823 | sample_rate: Option<u32>, |
| 3824 | range: Option<(u32, u32)>, |
| 3825 | ) -> crate::Result<Option<ExportAudio>> { |
| 3826 | // WebM's sound is Opus, which no source's packets are: always the mix. A loudness target is a |
| 3827 | // gain over the mix, which a copied packet cannot carry. A rate the caller chose is a re-encode. |
| 3828 | if webm || reencode || shared.loudness.is_some() { |
| 3829 | return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, range); |
| 3830 | } |
| 3831 | // A ranged export needs an exact offset and an exact length, which a |
| 3832 | // packet copy cannot give -- it carries whole segments named by |
| 3833 | // `audio_segments_from(0, ..)`, not an arbitrary window into them. The |
| 3834 | // decoded path already resamples per segment, so it is the one that can |
| 3835 | // start and stop anywhere; this falls to it exactly as a speeded or |
| 3836 | // equalized lane already does. |
| 3837 | if range.is_some() { |
| 3838 | return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, range); |
| 3839 | } |
| 3840 | // The segments name their source, and the copy carries its packet-rounding |
| 3841 | // debt across a source join exactly as across a cut, so a timeline spanning |
| 3842 | // files stays in sync. A source whose AAC parameters disagree with the |
| 3843 | // first one is an `Err` from there -- import refuses those up front, this |
| 3844 | // is the backstop -- and the caller deletes the `.part`. |
| 3845 | // |
| 3846 | // The stream each source is copied from is the one it plays: `audio_sources` |
| 3847 | // is the same list `PlaybackSession::seek` hands the decoder, so an export |
| 3848 | // of a timeline playing a file's second audio track carries *that* track. |
| 3849 | // |
| 3850 | // One lane is the only shape a *copy* has: summing two means decoding both, |
| 3851 | // and a sum is not a copy. Two or more go to [`encode_audio`], which is the |
| 3852 | // very mix the WAV path writes -- it used to be a refusal, and a refusal is |
| 3853 | // what a file missing half its sound deserves, not what a mix does. |
| 3854 | // |
| 3855 | // *Which* lane is the same question `audio_segments_from` answers for |
| 3856 | // playback, and it is asked here rather than assumed: the lane that holds |
| 3857 | // the sound need not be `A1` (a project may leave `A1` empty and place |
| 3858 | // everything on `A2`), and copying `A1`'s list in that case would write a |
| 3859 | // file with no audio track at all -- silently, which is the failure this |
| 3860 | // whole comment is about. |
| 3861 | let mut lanes = project.audio_segments_from(0, meta.frame_rate); |
| 3862 | // ...cut to what the picture writes ([`export_spans`]). The play list is |
| 3863 | // the *timeline's* ([`Project::timeline_frames`]), so a caption hanging past |
| 3864 | // the last picture ends every audio lane with a trailing gap -- silence this |
| 3865 | // path would copy out past the last frame, three seconds of it on the film |
| 3866 | // this was found on. Only a gap can be out there (`media_frames` is the last |
| 3867 | // clip's own end), and the mixed paths already resize to the same length |
| 3868 | // ([`encode_audio`]); a copy carries source packets and has no resize. |
| 3869 | let over = f64::from(project.timeline_frames() - project.media_frames()) / meta.frame_rate; |
| 3870 | for lane in &mut lanes { |
| 3871 | match lane.last_mut() { |
| 3872 | Some((None, _, len)) if *len > over => *len -= over, |
| 3873 | Some((None, _, _)) if over > 0.0 => { |
| 3874 | lane.pop(); |
| 3875 | } |
| 3876 | _ => {} |
| 3877 | } |
| 3878 | } |
| 3879 | let [segments] = &lanes[..] else { |
| 3880 | return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None); |
| 3881 | }; |
| 3882 | // ...and the same list names *which* lane those clips sit on, which is the |
| 3883 | // only way to ask what has been done to them. |
| 3884 | let lane = project.audio_lanes()[0]; |
| 3885 | // ...and the same list decides whether any clip this would copy plays at a |
| 3886 | // rate other than the one it was recorded at. A copy hands the muxer the |
| 3887 | // very AAC packets the source holds and there is no rate inside a packet to |
| 3888 | // change: the picture would come out re-timed (the walk in [`run`] honours |
| 3889 | // it) over sound at 1.00x, which is the drift a person finds only after the |
| 3890 | // file has gone somewhere. Decoded and resampled instead, by the same worker |
| 3891 | // playback feeds from. |
| 3892 | // |
| 3893 | // ...and whether any clip on it carries an equalizer, which is sample math a |
| 3894 | // copy never reaches: copying such a lane would write the clip *flat*, |
| 3895 | // silently. |
| 3896 | // |
| 3897 | // A frame *rate* of its own is not one of those, and that is deliberate: do |
| 3898 | // not "fix" this into a re-encode. A clip counts the **timeline's** frames |
| 3899 | // whatever its file was shot at ([`crate::project::Rate`]), so the window |
| 3900 | // this copy trims a source's sound to is `start..end` in whole timeline |
| 3901 | // frames -- exactly the seconds the picture covers -- and the file is read |
| 3902 | // at the pitch it was recorded at, which is what playing at the rate it was |
| 3903 | // shot at means. There is no per-clip stretch to express, so the packets are |
| 3904 | // already the right sound in the right place; re-encoding a conformed lane |
| 3905 | // would buy nothing and cost a generation of loss on every mixed-rate export |
| 3906 | // (`tests/mixed_fps.rs`, `an_export_of_two_rates_runs_at_the_speed_it_was_shot` |
| 3907 | // measures the copied sound against the picture). A *speed* is different |
| 3908 | // because it resamples, which is why it leaves through the re-encode above. |
| 3909 | // |
| 3910 | // Only these: a timeline nobody has touched still leaves through the copy |
| 3911 | // below, packet for packet, so no passthrough quietly becomes a generation |
| 3912 | // of loss. |
| 3913 | // ...and whether the mix itself does anything a packet never went through: |
| 3914 | // a lane volume is applied at the sum and a limiter over it, so copying |
| 3915 | // such a lane would write it at unity and unlimited, silently. |
| 3916 | // ...asked as the very predicate [`forces_encode`] is, over the one lane |
| 3917 | // the segments came off, so what a card predicted and what this decides are |
| 3918 | // one answer. `lane` here is that lane, and not `A1` by assumption: |
| 3919 | // [`Project::audio_lanes`] is the list built for, and filtered by, these |
| 3920 | // very segments. |
| 3921 | if sample_altered(project, &[lane]) { |
| 3922 | return encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None); |
| 3923 | } |
| 3924 | // What is left is a copy the *sources* may still not be able to give: AAC |
| 3925 | // inside a Matroska file (readable, but not out of a sample table this walks |
| 3926 | // -- there is none), an mp3 or a wav on the timeline, an AC-3 track, two |
| 3927 | // sources whose AAC parameters disagree. Every one of them decodes, and what |
| 3928 | // decodes can be encoded again, so the copy's refusal is now a route: the |
| 3929 | // error a *decode* cannot get past -- Opus or AC-3 inside a Matroska file, |
| 3930 | // which symphonia has no decoder for at any version -- is the one that comes |
| 3931 | // back, by name, from [`encode_audio`]. |
| 3932 | match AudioSession::copy_multi_streams(&project.audio_sources(), segments) { |
| 3933 | Ok(copied) => Ok(copied.map(|(params, packets)| ExportAudio { |
| 3934 | params, |
| 3935 | packets, |
| 3936 | copied: true, |
| 3937 | // A copy is the source's own AAC packets: there is no Opus copy |
| 3938 | // path here, since the packets an mkv source holds never reach this |
| 3939 | // (they are not in a sample table) and every one of them re-encodes. |
| 3940 | opus_pre_skip: None, |
| 3941 | language: None, |
| 3942 | pcm_frames: None, |
| 3943 | })), |
| 3944 | Err(_) => encode_audio(project, meta, kbps, mkv, webm, shared, sample_rate, None), |
| 3945 | } |
| 3946 | } |
| 3947 | |
| 3948 | /// The picture's half of [`copy_audio`]: a Matroska export whose every span is |
| 3949 | /// its source's own coded blocks, written back out without a decoder or an |
| 3950 | /// encoder anywhere in the path. |
| 3951 | /// |
| 3952 | /// **When.** A copy is entered only where it says *exactly* what the timeline |
| 3953 | /// says, which is the audio gate's rule and not a looser one: the file this |
| 3954 | /// export writes is Matroska, the source's codec is the one that file would |
| 3955 | /// carry ([`Format::Hevc`] over HEVC, [`Format::Av1`] over AV1), and nothing on |
| 3956 | /// the way has touched a sample -- no grade, no speed, no rate conversion, no |
| 3957 | /// gap to fill with black, no source of another size to place on the canvas, |
| 3958 | /// no `ContentEncodings` packing to undo. Anything else re-encodes exactly as |
| 3959 | /// it always did; there is no half-copied file. |
| 3960 | /// |
| 3961 | /// **All or nothing, per export.** A copied span and an encoded one cannot |
| 3962 | /// share one track: this project's encoders write 8-bit SDR streams whose |
| 3963 | /// parameter sets are their own, so splicing them into (say) a Main 10 HDR |
| 3964 | /// source would change bit depth and colour mid-track, and a container states |
| 3965 | /// its configuration record once. So the head and tail fragments of a cut that |
| 3966 | /// lands mid-GOP are *not* re-encoded into the copy -- they are what makes the |
| 3967 | /// whole export fall back to the encoder. What a copy needs instead is that |
| 3968 | /// every span begins on a sync point and ends where the next one begins, which |
| 3969 | /// is what a cut placed on a keyframe gives it. |
| 3970 | /// |
| 3971 | /// **What a cut costs.** An open-GOP source (x265's default) writes leading |
| 3972 | /// pictures after a sync point that are shown *before* it and reference the |
| 3973 | /// group before it. At the start of a copied region those references are not in |
| 3974 | /// the file, so they are dropped -- the picture before the cut is held for those |
| 3975 | /// few frames (four at this film's B-depth, a sixth of a second) rather than |
| 3976 | /// being written as pictures that cannot decode. The region still starts at the |
| 3977 | /// timeline frame it owns, so the sound never drifts. |
| 3978 | /// |
| 3979 | /// corner-cut: mp4 is not copied (its `hvc1` sample entry forbids in-band |
| 3980 | /// parameter sets, and the mp4 muxer here writes its sample table from a frame |
| 3981 | /// counter), and neither is H.264, which this project only writes into mp4. The |
| 3982 | /// upgrade path for both is a sample-table writer that takes explicit |
| 3983 | /// timestamps, which is what [`MkvMuxer::write_block`] already is for Matroska. |
| 3984 | struct CopyPlan { |
| 3985 | /// Every source a region reads, by the index the project names it with; |
| 3986 | /// `None` for a source no clip plays from. |
| 3987 | sources: Vec<Option<MkvDemuxer>>, |
| 3988 | regions: Vec<CopyRegion>, |
| 3989 | codec_id: &'static [u8], |
| 3990 | /// The `CodecPrivate` every region's source agrees on -- a track is declared |
| 3991 | /// once, so two sources that disagree about their parameter sets are not one |
| 3992 | /// copy. |
| 3993 | private: Vec<u8>, |
| 3994 | /// The picture's language as the first source states it ([`video_language`]), which the |
| 3995 | /// copied track declares. |
| 3996 | language: Option<String>, |
| 3997 | /// The container's colour tags exactly as the source wrote them, which the |
| 3998 | /// copied track declares: a field the source left out stays left out, and |
| 3999 | /// nothing is resolved in its place ([`MkvDemuxer::colour_tags`]). |
| 4000 | colour: Tags, |
| 4001 | /// The coded shape the copied track declares: the samples under it are the |
| 4002 | /// source's own, so the header names what they are stored at -- not the |
| 4003 | /// shape they are drawn at. |
| 4004 | width: u32, |
| 4005 | height: u32, |
| 4006 | /// The aspect the copied samples are drawn at, written into the file as |
| 4007 | /// display metadata ([`CopyParams::pixel_aspect`]): square for every |
| 4008 | /// ordinary source, so the header gains nothing. |
| 4009 | pixel_aspect: crate::demux::PixelAspect, |
| 4010 | } |
| 4011 | |
| 4012 | /// A run of source blocks copied in one piece: what a cut leaves behind, and |
| 4013 | /// what two spans that continue each other in the same file merge back into. |
| 4014 | struct CopyRegion { |
| 4015 | source: usize, |
| 4016 | /// Blocks of that source, in the file's own decode order. |
| 4017 | blocks: std::ops::Range<usize>, |
| 4018 | /// The *output* frame the region's first picture is shown at -- the |
| 4019 | /// project's own timeline frame less the range's own start, since a |
| 4020 | /// ranged export's file starts a fresh clock at zero. |
| 4021 | start: u32, |
| 4022 | } |
| 4023 | |
| 4024 | /// Why [`ExportSettings::exact`] cannot be honoured for this project right |
| 4025 | /// now, or `None` where [`CopyPlan`] already carries the whole file. A state |
| 4026 | /// report, not an instruction: it says what the file *is* rather than what to |
| 4027 | /// pick instead. |
| 4028 | /// |
| 4029 | /// Two shapes of reason, told apart because only one of them is permanent. |
| 4030 | /// **The container cannot carry the source's own codec at all** -- Exact was |
| 4031 | /// asked of an mp4, or of a Matroska file whose codec is not the source's own |
| 4032 | /// -- which is [`CopyPlan`]'s own corner-cut (mp4 copies nothing yet) and |
| 4033 | /// [`CopyPlan::of`]'s codec check, so it is checked here the same way rather |
| 4034 | /// than duplicated with different words. **The edit is what stops it** -- a |
| 4035 | /// cut off a sync point, a grade, a speed, a dissolve, a moved or scaled |
| 4036 | /// clip -- which the same format would carry exactly if the edit let it, so |
| 4037 | /// those six [`CopyPlan::of`] gates are named together rather than picked |
| 4038 | /// apart into six different sentences. |
| 4039 | pub fn exact_refusal( |
| 4040 | project: &Project, |
| 4041 | meta: &VideoMeta, |
| 4042 | settings: &ExportSettings, |
| 4043 | ) -> Option<String> { |
| 4044 | if !settings.exact || CopyPlan::of(project, meta, settings).is_some() { |
| 4045 | return None; |
| 4046 | } |
| 4047 | // An anamorphic source asked of a format that cannot state the aspect: the |
| 4048 | // blocks would copy, but the sample entry this writer produces has no |
| 4049 | // `pasp` box to carry it in, and a header that declares the coded pair |
| 4050 | // while the pixels are drawn 4/3 wide is a file that lies about its own |
| 4051 | // shape. Refused by name -- the sentence a reader is owed -- before the |
| 4052 | // container's codec question, because this is the *nearer* reason: a |
| 4053 | // Matroska copy needs no refusal at all (its track carries the aspect |
| 4054 | // beside the blocks, [`CopyParams::pixel_aspect`], which is ffmpeg's own |
| 4055 | // copy behaviour), so an anamorphic source's Exact row only ever dies on |
| 4056 | // this for an mp4. |
| 4057 | if settings.burn_subtitles.is_some() { |
| 4058 | return Some( |
| 4059 | "captions are drawn into the picture, so it is decoded and encoded again rather \ |
| 4060 | than copied byte for byte" |
| 4061 | .to_string(), |
| 4062 | ); |
| 4063 | } |
| 4064 | if !project.titles().is_empty() { |
| 4065 | return Some( |
| 4066 | "titles are drawn into the picture, so it is decoded and encoded again rather \ |
| 4067 | than copied byte for byte" |
| 4068 | .to_string(), |
| 4069 | ); |
| 4070 | } |
| 4071 | if picture_faded(project) { |
| 4072 | return Some( |
| 4073 | "a picture fade is pixel math, so it is decoded and encoded again rather than \ |
| 4074 | copied byte for byte" |
| 4075 | .to_string(), |
| 4076 | ); |
| 4077 | } |
| 4078 | if !settings.format.is_mkv() { |
| 4079 | let anamorphic = project.sources().iter().any(|source| { |
| 4080 | Demuxer::open(&source.path) |
| 4081 | .ok() |
| 4082 | .is_some_and(|(source_meta, _)| !source_meta.pixel_aspect.is_square()) |
| 4083 | }); |
| 4084 | if anamorphic { |
| 4085 | return Some( |
| 4086 | "a copy would lose the pixel aspect — this format cannot state it beside the \ |
| 4087 | coded picture, so the export re-encodes it into the square pixels it is drawn at" |
| 4088 | .to_string(), |
| 4089 | ); |
| 4090 | } |
| 4091 | } |
| 4092 | let codec = match settings.format { |
| 4093 | Format::Hevc => Codec::Hevc, |
| 4094 | Format::Av1 => Codec::Av1, |
| 4095 | _ => { |
| 4096 | return Some(format!( |
| 4097 | "{} cannot carry a source's own coded picture byte for byte — pick an HEVC or AV1 Matroska to copy it exactly", |
| 4098 | settings.format.name() |
| 4099 | )); |
| 4100 | } |
| 4101 | }; |
| 4102 | // The turn-baking corner-cut (a copied packet is the source's own coded |
| 4103 | // picture; this export bakes a display-matrix turn into the pixels) and |
| 4104 | // the rest of the reasons a copy says something other than what the |
| 4105 | // timeline says are [`CopyPlan::of`]'s own gates, so the container and |
| 4106 | // edit sentences below are checked the same way rather than duplicated |
| 4107 | // with different words. |
| 4108 | let carries = project.sources().iter().all(|source| { |
| 4109 | crate::demux::is_matroska(&source.path) |
| 4110 | && Demuxer::open(&source.path) |
| 4111 | .ok() |
| 4112 | .is_some_and(|(source_meta, _)| source_meta.codec == codec) |
| 4113 | }); |
| 4114 | Some(match carries { |
| 4115 | false => format!( |
| 4116 | "{} cannot carry the source's own codec byte for byte", |
| 4117 | settings.format.name() |
| 4118 | ), |
| 4119 | true => "the edit does not let this file copy the source exactly — a cut off a sync \ |
| 4120 | point, a grade, a speed, a transform or a canvas the source is not forces a \ |
| 4121 | re-encode" |
| 4122 | .to_string(), |
| 4123 | }) |
| 4124 | } |
| 4125 | |
| 4126 | impl CopyPlan { |
| 4127 | /// The plan for this timeline, or `None` where anything at all makes a copy |
| 4128 | /// say something other than what the timeline says -- in which case the |
| 4129 | /// caller encodes, which is what it always did. |
| 4130 | fn of(project: &Project, meta: &VideoMeta, settings: &ExportSettings) -> Option<Self> { |
| 4131 | // Burned-in captions and titles are drawn into pixels, which a copy |
| 4132 | // never has. |
| 4133 | if settings.burn_subtitles.is_some() |
| 4134 | || !project.titles().is_empty() |
| 4135 | || picture_faded(project) |
| 4136 | { |
| 4137 | return None; |
| 4138 | } |
| 4139 | // An explicit picture depth is a request for samples the source may not |
| 4140 | // have (8 bits from a 10-bit HEVC, say), which a copy would silently |
| 4141 | // keep: the picture is re-encoded at the depth asked for. |
| 4142 | if settings.video_bit_depth.is_some() { |
| 4143 | return None; |
| 4144 | } |
| 4145 | // An HDR transfer is a statement the encoder writes into its own stream |
| 4146 | // (VUI, SEIs); a copy carries the source's. |
| 4147 | if settings.hdr.transfer != HdrTransfer::Sdr { |
| 4148 | return None; |
| 4149 | } |
| 4150 | let (codec_id, codec): (&'static [u8], Codec) = match settings.format { |
| 4151 | Format::Hevc => (b"V_MPEGH/ISO/HEVC", Codec::Hevc), |
| 4152 | Format::Av1 => (b"V_AV1", Codec::Av1), |
| 4153 | _ => return None, |
| 4154 | }; |
| 4155 | let entries = project.sources(); |
| 4156 | let mut sources: Vec<Option<MkvDemuxer>> = (0..entries.len()).map(|_| None).collect(); |
| 4157 | // The DRAWN pair each source is displayed at, kept beside its demuxer: |
| 4158 | // the fit gate below asks what a clip's policy does with this source's |
| 4159 | // picture on this canvas, and the picture the encoder places is the |
| 4160 | // drawn one ([`VideoMeta::width`]/`height`] -- the coded one with the |
| 4161 | // file's turn and its pixel aspect already applied), not the pair the |
| 4162 | // samples are stored at. A non-square source at its own displayed size |
| 4163 | // is therefore the identity again, which is what a copy of one is: the |
| 4164 | // aspect travels beside the track in the `Display*` elements rather |
| 4165 | // than being resampled into it. |
| 4166 | let mut drawn: Vec<Option<(u32, u32)>> = (0..entries.len()).map(|_| None).collect(); |
| 4167 | let mut declared: Option<(Vec<u8>, Tags, crate::demux::PixelAspect)> = None; |
| 4168 | let mut regions: Vec<CopyRegion> = Vec::new(); |
| 4169 | let r_start = settings.range.map_or(0, |(s, _)| s); |
| 4170 | for span in export_spans(project, settings.range) { |
| 4171 | let out_start = span.start - r_start; |
| 4172 | // A gap is black frames, which only an encoder makes. |
| 4173 | let (source, in_frame) = span.from?; |
| 4174 | if !span.speed.is_normal() || span.ramp.is_some() || span.reverse { |
| 4175 | return None; |
| 4176 | } |
| 4177 | // A layered picture is composed from more than one clip; no packet |
| 4178 | // of one of them is the picture. |
| 4179 | if layered_at(project, span.start) { |
| 4180 | return None; |
| 4181 | } |
| 4182 | // A copied packet is the source's own picture, never a blend: a |
| 4183 | // live dissolve on this span's tail forces the whole video track |
| 4184 | // through the encoder, exactly as a grade or a speed does below. |
| 4185 | // |
| 4186 | // corner-cut: the whole file falls back rather than only the |
| 4187 | // clips either side of the dissolve -- [`CopyPlan`] is already |
| 4188 | // all-or-nothing per export ([`CopyPlan`]'s own doc comment |
| 4189 | // states why), so one dissolve on a two-hour film re-encodes all |
| 4190 | // of it. Upgrade path: splice a re-encoded region between two |
| 4191 | // copied ones, which needs the sample-table writer that doc |
| 4192 | // comment already names as the cost of a finer copy. |
| 4193 | if dissolve_window(project, &span).is_some() { |
| 4194 | return None; |
| 4195 | } |
| 4196 | // The grade playback shows, which a copied packet never went |
| 4197 | // through. `None` and the identity are the same untouched picture. |
| 4198 | if project |
| 4199 | .composite_color_at(span.start) |
| 4200 | .is_some_and(|params| !params.is_identity()) |
| 4201 | { |
| 4202 | return None; |
| 4203 | } |
| 4204 | // A moved, scaled, rotated or cropped clip is a different picture |
| 4205 | // than the source's own packets, exactly as a grade is. |
| 4206 | if project |
| 4207 | .composite_transform_at(span.start) |
| 4208 | .is_some_and(|params| !params.is_identity()) |
| 4209 | { |
| 4210 | return None; |
| 4211 | } |
| 4212 | let path = &entries.get(source)?.path; |
| 4213 | if sources.get(source)?.is_none() { |
| 4214 | if !crate::demux::is_matroska(path) { |
| 4215 | return None; |
| 4216 | } |
| 4217 | let (source_meta, demuxer) = Demuxer::open(path).ok()?; |
| 4218 | let Demuxer::Mkv(demuxer) = demuxer else { |
| 4219 | return None; |
| 4220 | }; |
| 4221 | // The stream this file would carry, at the size and the rate the |
| 4222 | // timeline is in: anything else is a picture that has to be |
| 4223 | // coded again to become this file's. |
| 4224 | // |
| 4225 | // A source whose display matrix asks for a turn is one of |
| 4226 | // those: a copied packet is the source's own coded picture, and |
| 4227 | // this export bakes the turn into the pixels -- so a copy would |
| 4228 | // ship the file sideways. Re-encoding is the only honest |
| 4229 | // answer here. |
| 4230 | // |
| 4231 | // The size the copy declares is the source's *coded* pair, so |
| 4232 | // that is what the comparison asks: coded to coded. A display |
| 4233 | // comparison would refuse every anamorphic source that happens |
| 4234 | // to sit at the project's displayed shape and then write a |
| 4235 | // track that lies about its own samples -- and a square |
| 4236 | // source's coded pair is its display pair, so this asks nothing |
| 4237 | // new of the ordinary file. |
| 4238 | // |
| 4239 | // A source whose samples are not square is the *other* kind of |
| 4240 | // picture a copy cannot carry here: the blocks are its own |
| 4241 | // coded pixels and this engine's Matroska writer can now state |
| 4242 | // the aspect beside them -- but only this engine's |
| 4243 | // ([`MkvMuxer::create_copy`] writes the `Display*` elements), |
| 4244 | // and the copy's declared shape must stay the coded one. The |
| 4245 | // aspect travels with the track instead of being baked in, |
| 4246 | // which is ffmpeg's own copy behaviour, so an anamorphic |
| 4247 | // source is copyable *into Matroska* and nowhere else. |
| 4248 | if !source_meta.rotation.is_none() |
| 4249 | || source_meta.codec != codec |
| 4250 | || source_meta.coded_width != meta.coded_width |
| 4251 | || source_meta.coded_height != meta.coded_height |
| 4252 | || Rate::from_fps(source_meta.frame_rate, meta.frame_rate).ok()? |
| 4253 | != Rate::REAL_TIME |
| 4254 | || !demuxer.plain_blocks() |
| 4255 | { |
| 4256 | return None; |
| 4257 | } |
| 4258 | // Two sources that disagree about their pixel aspect are two |
| 4259 | // displayed pictures under one track; the copy declares one |
| 4260 | // aspect or none. |
| 4261 | let declares = ( |
| 4262 | demuxer.codec_private().to_vec(), |
| 4263 | demuxer.colour_tags(), |
| 4264 | source_meta.pixel_aspect, |
| 4265 | ); |
| 4266 | if declared.get_or_insert(declares.clone()) != &declares { |
| 4267 | return None; |
| 4268 | } |
| 4269 | sources[source] = Some(*demuxer); |
| 4270 | drawn[source] = Some((source_meta.width, source_meta.height)); |
| 4271 | } |
| 4272 | let demuxer = sources.get_mut(source)?.as_mut()?; |
| 4273 | // **The canvas gate** -- the condition this path was missing, and |
| 4274 | // the one that decides whether a copy can state the project's size. |
| 4275 | // |
| 4276 | // A copied packet is the source's own coded picture; the file this |
| 4277 | // export writes has to be the size the *project* is, and those are |
| 4278 | // two different pairs held in two different fields: |
| 4279 | // |
| 4280 | // * `meta.coded_width`/`coded_height` is the pair a *copied* track |
| 4281 | // declares -- what the samples are stored at, and what the check |
| 4282 | // above compares every source against. Only a *source* ever moves |
| 4283 | // it. |
| 4284 | // * `meta.width`/`meta.height` is the canvas -- what a person chose |
| 4285 | // with [`crate::playback::PlaybackSession::set_resolution`], |
| 4286 | // which writes those two and leaves the coded pair exactly where |
| 4287 | // it was. The encode door sizes everything from it |
| 4288 | // ([`Composer`]), so this is the size the file must have. |
| 4289 | // |
| 4290 | // ...and the two meet in the *drawn* pair: what this span is |
| 4291 | // composed from is the source's picture as a decoder delivers it, |
| 4292 | // turn and pixel aspect already applied |
| 4293 | // ([`VideoMeta::width`]/`height`]), which is what the check below is |
| 4294 | // asked about. |
| 4295 | // |
| 4296 | // A canvas that differs from the source's drawn pair means every |
| 4297 | // span is a picture the export has to *place onto* that canvas, and |
| 4298 | // there is no resampler on this path at all -- so a copy would ship |
| 4299 | // the source's frame size under the project's name, with the seat |
| 4300 | // line reading "copy · …" all the way out. That is the defect: not |
| 4301 | // a wrong rate or a wrong codec but the wrong geometry, silently, |
| 4302 | // on the one door that is supposed to be exact. |
| 4303 | // |
| 4304 | // Asked as a *placement* rather than as two separate conditions -- |
| 4305 | // is this clip's policy the identity for this source on this canvas |
| 4306 | // -- because that is the one thing a condition has to mean here: |
| 4307 | // [`fit_is_identity`] computes it from [`scale::fit_rect`] itself, |
| 4308 | // so it holds for `Fill` on a canvas the size of the picture the |
| 4309 | // source draws at (there is nothing to crop there) and refuses a |
| 4310 | // canvas of another size under *every* policy, and a |
| 4311 | // [`crate::scale::FitPolicy`] added later is judged by what it |
| 4312 | // places rather than by being absent from a list here. |
| 4313 | if !fit_is_identity( |
| 4314 | drawn.get(source).copied().flatten()?, |
| 4315 | (meta.width, meta.height), |
| 4316 | project.composite_fit_at(span.start), |
| 4317 | ) { |
| 4318 | return None; |
| 4319 | } |
| 4320 | // The window this span reads, in the blocks the whole engine counts |
| 4321 | // a source's frames in. It has to *be* whole groups of pictures: a |
| 4322 | // copy that began between two sync points would hand a decoder |
| 4323 | // pictures whose references are not in the file, and one that ended |
| 4324 | // between them would drop a reference the pictures before it need. |
| 4325 | let (start, end) = (in_frame as usize, in_frame as usize + span.len as usize); |
| 4326 | if end > demuxer.block_count() |
| 4327 | || !demuxer.is_sync(start) |
| 4328 | || (end < demuxer.block_count() && !demuxer.is_sync(end)) |
| 4329 | { |
| 4330 | return None; |
| 4331 | } |
| 4332 | // Two spans that continue each other in one file are one region: |
| 4333 | // nothing was cut between them, so the leading pictures across that |
| 4334 | // boundary still have every reference they need. |
| 4335 | match regions.last_mut() { |
| 4336 | Some(last) |
| 4337 | if last.source == source |
| 4338 | && last.blocks.end == start |
| 4339 | && last.start + (last.blocks.end - last.blocks.start) as u32 |
| 4340 | == out_start => |
| 4341 | { |
| 4342 | last.blocks.end = end; |
| 4343 | } |
| 4344 | _ => regions.push(CopyRegion { |
| 4345 | source, |
| 4346 | blocks: start..end, |
| 4347 | start: out_start, |
| 4348 | }), |
| 4349 | } |
| 4350 | } |
| 4351 | let (private, colour, pixel_aspect) = declared?; |
| 4352 | Some(Self { |
| 4353 | sources, |
| 4354 | regions, |
| 4355 | codec_id, |
| 4356 | private, |
| 4357 | language: video_language(project), |
| 4358 | colour, |
| 4359 | // The track the copy declares is the source's coded shape -- the |
| 4360 | // samples under it are the source's own -- with the aspect beside |
| 4361 | // it as the display metadata ([`CopyParams::pixel_aspect`]). |
| 4362 | width: meta.coded_width, |
| 4363 | height: meta.coded_height, |
| 4364 | pixel_aspect, |
| 4365 | }) |
| 4366 | } |
| 4367 | |
| 4368 | /// The file itself: one Matroska muxer, every region's blocks through it in |
| 4369 | /// the order and at the timing their source states. |
| 4370 | #[allow( |
| 4371 | clippy::too_many_arguments, |
| 4372 | reason = "the copy's one run: its inputs are passed positionally at its one call site, and a struct would only rename them" |
| 4373 | )] |
| 4374 | fn run( |
| 4375 | mut self, |
| 4376 | out: &Path, |
| 4377 | meta: &VideoMeta, |
| 4378 | shared: &Shared, |
| 4379 | audio: Option<(&AudioParams, Vec<crate::AacPacket>)>, |
| 4380 | subs: Vec<SubParams>, |
| 4381 | total: u32, |
| 4382 | chapters: &[(u64, String)], |
| 4383 | ) -> crate::Result<()> { |
| 4384 | let mut muxer = MkvMuxer::create_copy( |
| 4385 | out, |
| 4386 | &CopyParams { |
| 4387 | width: self.width, |
| 4388 | height: self.height, |
| 4389 | frame_rate: meta.frame_rate, |
| 4390 | codec_id: self.codec_id, |
| 4391 | codec_private: &self.private, |
| 4392 | colour: self.colour, |
| 4393 | pixel_aspect: self.pixel_aspect, |
| 4394 | language: self.language.clone(), |
| 4395 | }, |
| 4396 | audio, |
| 4397 | subs, |
| 4398 | )?; |
| 4399 | muxer.set_chapters(chapters)?; |
| 4400 | // Nanoseconds a timeline frame lasts, which is what a region's own |
| 4401 | // position on the timeline is measured in. |
| 4402 | let frame_ns = 1e9 / meta.frame_rate; |
| 4403 | let mut done = 0u32; |
| 4404 | for region in &self.regions { |
| 4405 | let demuxer = self.sources[region.source] |
| 4406 | .as_mut() |
| 4407 | .ok_or("a copied region names a source that was never opened")?; |
| 4408 | let base = (f64::from(region.start) * frame_ns).round() as i64; |
| 4409 | // When the region's first picture is shown on its source's clock; |
| 4410 | // everything after it is written that far along from `base`. |
| 4411 | let mut origin: Option<i64> = None; |
| 4412 | for index in region.blocks.clone() { |
| 4413 | cancelled(shared)?; |
| 4414 | let Some(block) = demuxer.coded_block(index)? else { |
| 4415 | break; |
| 4416 | }; |
| 4417 | let origin = *origin.get_or_insert(block.ts_ns); |
| 4418 | // The leading pictures of the group this region opens on: shown |
| 4419 | // before it, coded against the group before it, and that group |
| 4420 | // is not in this file. Dropped rather than written as pictures |
| 4421 | // no decoder can put back together. |
| 4422 | if block.ts_ns < origin { |
| 4423 | continue; |
| 4424 | } |
| 4425 | muxer.write_block(block.bytes, block.key, base + block.ts_ns - origin)?; |
| 4426 | done += 1; |
| 4427 | shared |
| 4428 | .progress |
| 4429 | .fetch_max(picture_progress(done, total), Ordering::Relaxed); |
| 4430 | } |
| 4431 | } |
| 4432 | // Everything up to here is still cancellable, exactly as the encoded |
| 4433 | // path is up to its own `finish`. |
| 4434 | cancelled(shared)?; |
| 4435 | muxer.finish()?; |
| 4436 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); |
| 4437 | Ok(()) |
| 4438 | } |
| 4439 | } |
| 4440 | |
| 4441 | /// Whether `policy` places the picture `source` is DRAWN at onto this `canvas` |
| 4442 | /// without touching a sample: the whole picture, at the whole canvas, 1:1. |
| 4443 | /// |
| 4444 | /// The 1:1 is the half the rects cannot state: a source scaled onto a canvas |
| 4445 | /// of another aspect is placed whole and cropped nowhere, which is a resize |
| 4446 | /// and not an identity -- so the pairs themselves are compared first. |
| 4447 | /// |
| 4448 | /// The pair asked about is the **drawn** one ([`VideoMeta::width`]/`height`]), |
| 4449 | /// never the coded one: what the fit is composed against is what a decoder |
| 4450 | /// hands the canvas after the file's turn and its pixel aspect have been |
| 4451 | /// applied, so a 1440x1080 file with a 4:3 sample aspect is a 1920x1080 |
| 4452 | /// picture, and a project at 1920x1080 is copying it exactly. The coded pair |
| 4453 | /// has its own question -- what a copied track *declares* -- and the coded-to- |
| 4454 | /// coded check in [`CopyPlan::of`] already asks that one; asking it twice, in |
| 4455 | /// the geometry's stead, refuses a copy main performs byte for byte. |
| 4456 | /// |
| 4457 | /// Asked from [`scale::fit_rect`] -- the one function that *is* a fit policy's |
| 4458 | /// meaning -- rather than from the policy itself, which is what makes this |
| 4459 | /// canvas-aware twice over: `Fill` on a canvas the size of the source's own |
| 4460 | /// samples is the identity (nothing is cropped, because there is nothing to |
| 4461 | /// crop), while `Fit` on a canvas of another aspect is not (it bars or crops). |
| 4462 | /// A policy added to [`FitPolicy`] later is judged by what it places, not by |
| 4463 | /// being absent from a list here. |
| 4464 | fn fit_is_identity( |
| 4465 | source: (u32, u32), |
| 4466 | canvas: (u32, u32), |
| 4467 | policy: crate::scale::FitPolicy, |
| 4468 | ) -> bool { |
| 4469 | // The pairs themselves: a picture is the canvas only when it *is* the |
| 4470 | // canvas, and the rects below cannot say so -- a source scaled onto a |
| 4471 | // canvas of another aspect is still placed whole and still cropped |
| 4472 | // nowhere, which is a resize, and a resize is exactly what a copied packet |
| 4473 | // cannot be. |
| 4474 | if source != canvas { |
| 4475 | return false; |
| 4476 | } |
| 4477 | let (placed, cropped) = crate::scale::fit_rect(source.0, source.1, canvas.0, canvas.1, policy); |
| 4478 | placed |
| 4479 | == crate::scale::Rect { |
| 4480 | x: 0, |
| 4481 | y: 0, |
| 4482 | w: canvas.0, |
| 4483 | h: canvas.1, |
| 4484 | } |
| 4485 | && cropped |
| 4486 | == crate::scale::Rect { |
| 4487 | x: 0, |
| 4488 | y: 0, |
| 4489 | w: source.0, |
| 4490 | h: source.1, |
| 4491 | } |
| 4492 | } |
| 4493 | |
| 4494 | /// The same lane, *decoded*: what a packet copy cannot carry comes out here as |
| 4495 | /// AAC written by this project's own encoder. |
| 4496 | /// |
| 4497 | /// The samples are the very ones [`run_audio`] would put in a WAV -- the same |
| 4498 | /// opener with the same equalizers, the same rates and the same resize onto the |
| 4499 | /// timeline's own length -- so an mp4 and a WAV of one timeline are one mix, |
| 4500 | /// not two that could disagree. |
| 4501 | /// |
| 4502 | /// AAC-LC's encoder delay is one 1024-frame block, which is exactly the priming |
| 4503 | /// a reader drops when the file carries no edit list (`audio::DEFAULT_PRIMING`, |
| 4504 | /// and [`crate::mux::Mp4Muxer`] writes none): the first packet is that delay, so |
| 4505 | /// the sound starts at timeline frame 0 as a copied track's does. |
| 4506 | /// |
| 4507 | /// corner-cut: the mix sits in memory as f32 before it is encoded (~46 MB a |
| 4508 | /// minute of 48 kHz stereo), for [`run_audio`]'s reason -- sizing the track |
| 4509 | /// against the timeline, publishing the mix third of the bar as it goes and |
| 4510 | /// answering a cancel before the encode are whole-mix concerns here. The |
| 4511 | /// upgrade path is a chunked push: `ec_aac`'s encoder itself streams. |
| 4512 | #[allow(clippy::too_many_arguments)] |
| 4513 | fn encode_audio( |
| 4514 | project: &Project, |
| 4515 | meta: &VideoMeta, |
| 4516 | kbps: u32, |
| 4517 | mkv: bool, |
| 4518 | webm: bool, |
| 4519 | shared: &Shared, |
| 4520 | sample_rate: Option<u32>, |
| 4521 | range: Option<(u32, u32)>, |
| 4522 | ) -> crate::Result<Option<ExportAudio>> { |
| 4523 | let sources = project.audio_sources(); |
| 4524 | let range_start = range.map_or(0, |(s, _)| s); |
| 4525 | let pre = warm_up(project, range_start, meta.frame_rate); |
| 4526 | let offset = range_start - pre; |
| 4527 | let segs = project.audio_segments_from(offset, meta.frame_rate); |
| 4528 | let eqs = project.audio_eqs_from(offset, meta.frame_rate); |
| 4529 | let speeds = project.audio_speeds_from(offset, meta.frame_rate); |
| 4530 | let fades = project.audio_fades_from(offset, meta.frame_rate); |
| 4531 | // Coarse stage timers, in the same voice as `export video: copy` below: an |
| 4532 | // export of a feature film spends minutes in here before a byte of picture |
| 4533 | // is written, and which minutes went where is the first question asked of a |
| 4534 | // slow export. Three lines an export, so they stay on. |
| 4535 | let mixed = std::time::Instant::now(); |
| 4536 | let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade( |
| 4537 | &sources, |
| 4538 | &segs, |
| 4539 | &eqs, |
| 4540 | &speeds, |
| 4541 | &fades, |
| 4542 | meta.frame_rate, |
| 4543 | &project.audio_gains(), |
| 4544 | &project.audio_ducks(), |
| 4545 | &project.audio_voices(), |
| 4546 | project.limiter(), |
| 4547 | sample_rate, |
| 4548 | )? |
| 4549 | else { |
| 4550 | return Ok(None); // no audio to write, exactly as a copy of nothing is |
| 4551 | }; |
| 4552 | let freq_index = ec_aac::sf_index_for_rate(audio.sample_rate).ok_or_else(|| { |
| 4553 | format!( |
| 4554 | "{} Hz is not an AAC sample rate: export WAV, FLAC, MP3 or OGG, which write it as \ |
| 4555 | it is", |
| 4556 | audio.sample_rate |
| 4557 | ) |
| 4558 | })?; |
| 4559 | let channels = usize::from(audio.channels.max(1)); |
| 4560 | // The timeline's length, not the mix's: a segment resolves its window to |
| 4561 | // whole samples on its own, so the sum can miss by a sample or two and a |
| 4562 | // source that ran out early would leave the track short under a picture |
| 4563 | // that is not. One resize settles both, as [`run_audio`]'s does. |
| 4564 | let out_frames = range.map_or(project.media_frames(), |(s, e)| { |
| 4565 | e.min(project.media_frames()).saturating_sub(s) |
| 4566 | }); |
| 4567 | let total = (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() |
| 4568 | as usize |
| 4569 | * channels; |
| 4570 | let skip = warm_up_samples(range_start, pre, meta.frame_rate, audio.sample_rate, channels); |
| 4571 | let mut samples: Vec<f32> = Vec::with_capacity(total + skip); |
| 4572 | for chunk in chunks { |
| 4573 | // The only place a cancelled export can be answered before the whole |
| 4574 | // timeline has been mixed. This pass runs on a thread of its own now |
| 4575 | // ([`run`]), so without this a cancel left it mixing a feature film |
| 4576 | // for minutes behind a job nobody is waiting for any more, writing |
| 4577 | // into a `Shared` whose outcome was already settled. |
| 4578 | cancelled(shared)?; |
| 4579 | samples.extend(chunk.samples); |
| 4580 | // The bar's first third of [`AUDIO_BAND`]: the mix is the longest of |
| 4581 | // the three stages and the only one that can be counted as it goes. |
| 4582 | // |
| 4583 | // `fetch_max` and not `store`, for the reason [`Shared::progress`] |
| 4584 | // states: this runs on the audio thread while the picture publishes |
| 4585 | // numbers above [`AUDIO_BAND`] from the other, and a `store` of this |
| 4586 | // small one pulled the bar backwards 5,458 times over one film export. |
| 4587 | shared.progress.fetch_max( |
| 4588 | (samples.len().saturating_sub(skip).min(total) * (AUDIO_BAND / 3) as usize / total.max(1)) as u32, |
| 4589 | Ordering::Relaxed, |
| 4590 | ); |
| 4591 | // The range is in: the mix past its end would only be cut off below. |
| 4592 | if samples.len() >= skip + total { |
| 4593 | break; |
| 4594 | } |
| 4595 | } |
| 4596 | samples.drain(..skip.min(samples.len())); |
| 4597 | samples.resize(total, 0.0); |
| 4598 | if let Some(target) = shared.loudness { |
| 4599 | level_to_target(&mut samples, audio.sample_rate, audio.channels.max(1), target); |
| 4600 | } |
| 4601 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!( |
| 4602 | "export audio: mixed {:.1} s of sound in {:.1} s", |
| 4603 | total as f64 / f64::from(audio.sample_rate.max(1)) / channels as f64, |
| 4604 | mixed.elapsed().as_secs_f64() |
| 4605 | ); } |
| 4606 | |
| 4607 | // Opus where the container carries it and the mix is inside the envelope |
| 4608 | // this encoder is *measured* correct in ([`encode_opus`]): a Matroska file, |
| 4609 | // 48 kHz, mono or stereo. An Opus source edited into an mkv export |
| 4610 | // therefore leaves as Opus instead of being turned into AAC on the way |
| 4611 | // out, which is the one generation of loss an all-Opus timeline used to |
| 4612 | // pay for being cut. |
| 4613 | // |
| 4614 | // Everything else falls through to the AAC below and is unchanged by this: |
| 4615 | // every mp4, a 44.1 kHz timeline. The rate is the mix's own -- there is no |
| 4616 | // resampler on this path, and inventing one to reach 48 kHz would resample |
| 4617 | // a whole timeline to satisfy a codec, which is a bigger change to the |
| 4618 | // sound than the codec is. |
| 4619 | // ...and again before either encoder is entered: both of them run to the |
| 4620 | // end of the mix without a checkpoint of their own, so this is the last |
| 4621 | // moment a cancel costs seconds rather than the whole encode. |
| 4622 | cancelled(shared)?; |
| 4623 | if mkv |
| 4624 | && audio.sample_rate == OPUS_RATE |
| 4625 | && (1..=2).contains(&channels) |
| 4626 | && let Some((packets, pre_skip)) = encode_opus(&samples, kbps, channels)? |
| 4627 | { |
| 4628 | return Ok(Some(ExportAudio { |
| 4629 | params: crate::AacTrackParams { |
| 4630 | freq_index, |
| 4631 | chan_conf: channels as u8, |
| 4632 | sample_rate: OPUS_RATE, |
| 4633 | }, |
| 4634 | packets, |
| 4635 | copied: false, |
| 4636 | opus_pre_skip: Some(pre_skip), |
| 4637 | language: None, |
| 4638 | pcm_frames: Some(samples.len() as u64 / channels as u64), |
| 4639 | })); |
| 4640 | } |
| 4641 | |
| 4642 | // A WebM file carries Opus or nothing: a track the gate handed back is named |
| 4643 | // here rather than written as AAC into a file no WebM reader will open. |
| 4644 | if webm { |
| 4645 | return Err( |
| 4646 | "the sound could not be coded as Opus, the only sound a WebM file \ |
| 4647 | carries: export a Matroska instead" |
| 4648 | .into(), |
| 4649 | ); |
| 4650 | } |
| 4651 | // The caller's rate, never the encoder's own 128 default -- see |
| 4652 | // [`DEFAULT_AUDIO_KBPS`] for why the untouched figure is 256. |
| 4653 | let mut encoder = ec_aac::AacEncoder::new(ec_aac::AacEncoderConfig { |
| 4654 | bitrate_bps: kbps * 1_000, |
| 4655 | ..Default::default() |
| 4656 | }); |
| 4657 | encoder.push_pcm(&samples, audio.channels.max(1), audio.sample_rate)?; |
| 4658 | encoder.finish(); |
| 4659 | let mut packets = Vec::new(); |
| 4660 | // `next_packet` after `finish` yields packets until `Eof` and nothing else, |
| 4661 | // so the loop ends on the only error it can see. |
| 4662 | while let Ok(packet) = encoder.next_packet() { |
| 4663 | cancelled(shared)?; |
| 4664 | packets.push(crate::AacPacket { |
| 4665 | bytes: packet.data, |
| 4666 | samples: packet.duration, |
| 4667 | }); |
| 4668 | } |
| 4669 | Ok(Some(ExportAudio { |
| 4670 | params: crate::AacTrackParams { |
| 4671 | freq_index, |
| 4672 | // 1 and 2 are the ISO channel configurations for mono and stereo, |
| 4673 | // and what the opener hands the timeline is one of those whatever |
| 4674 | // the source carried ([`crate::audio::downmix`]). |
| 4675 | chan_conf: audio.channels.max(1) as u8, |
| 4676 | sample_rate: audio.sample_rate, |
| 4677 | }, |
| 4678 | packets, |
| 4679 | copied: false, |
| 4680 | opus_pre_skip: None, |
| 4681 | language: None, |
| 4682 | pcm_frames: Some(samples.len() as u64 / channels as u64), |
| 4683 | })) |
| 4684 | } |
| 4685 | |
| 4686 | /// The one rate Opus codes at. The container may state another one in its |
| 4687 | /// `OpusHead` and every decoder still runs at 48 kHz (RFC 7845 §5.1), so a |
| 4688 | /// timeline at any other rate is not "encoded at its own rate" here -- it is |
| 4689 | /// resampled or it is not Opus, and [`encode_audio`] picks the second. |
| 4690 | pub(crate) const OPUS_RATE: u32 = 48_000; |
| 4691 | |
| 4692 | /// 20 ms at [`OPUS_RATE`], the frame every Opus muxer in the wild writes: |
| 4693 | /// long enough that the per-packet overhead is nothing, short enough that a |
| 4694 | /// Matroska block timestamp in whole milliseconds is exact. |
| 4695 | const OPUS_FRAME: usize = 960; |
| 4696 | |
| 4697 | /// The most this project asks of the Opus encoder, in kbps, and why it is a cap |
| 4698 | /// rather than the four rates the Sound row offers. |
| 4699 | /// |
| 4700 | /// History, because the number moved once already and the reason it could is |
| 4701 | /// part of the record. Under `opus-rs 0.1.26` the ceiling was 128: that encoder |
| 4702 | /// fell off a cliff at a rate that depended on the *content*, and above it a |
| 4703 | /// conformant decoder got noise back. Measured on three one-second spans of a |
| 4704 | /// real 5.1 Opus film, encoded there and decoded with `ruopus` -- which was not |
| 4705 | /// the suspect, since it decoded ffmpeg's own libopus at 256 kbps to |
| 4706 | /// correlation 1.00000 on the same material: |
| 4707 | /// |
| 4708 | /// ```text |
| 4709 | /// kbps 120 128 136 144 152 160 |
| 4710 | /// span A 0.945 0.937 0.452 0.206 0.223 0.163 |
| 4711 | /// span B 0.986 0.989 0.697 0.153 0.114 0.149 |
| 4712 | /// span C 0.999 0.994 0.951 0.335 0.266 0.326 |
| 4713 | /// libopus 0.997 0.998 -- -- -- 0.996 (same spans, control) |
| 4714 | /// ``` |
| 4715 | /// |
| 4716 | /// So: usable to 128, ruined by 136 on real film sound -- and mono worse, at |
| 4717 | /// every rate, which is why a mono mix kept the AAC path entirely. `ec-opus` |
| 4718 | /// has no such cliff: its own suite holds every rate of the format's table to |
| 4719 | /// the reference decoders, mono, stereo and 5.1 alike, and this project |
| 4720 | /// re-measures the high band and the mono path where the old encoder failed |
| 4721 | /// (`the_opus_encoder_is_pinned_to_the_band_it_was_measured_in`). |
| 4722 | /// |
| 4723 | /// It is still not *trusted*: every track is decoded again and measured before |
| 4724 | /// it is written ([`opus_fidelity`]), because a rate nobody measured on *your* |
| 4725 | /// sound is not something a constant can be safe against on its own. |
| 4726 | /// The ceiling is the Sound row's ([`AUDIO_KBPS`]), not the format's 510 kbps: |
| 4727 | /// a rate nothing in the product can ask for is a rate nothing here measures. |
| 4728 | /// 320 covers the row honestly, including the 256 default |
| 4729 | /// ([`DEFAULT_AUDIO_KBPS`]) the old cap silently halved on a Matroska export. |
| 4730 | pub(crate) const OPUS_MAX_KBPS: u32 = 320; |
| 4731 | |
| 4732 | /// How well a track has to survive its own round trip to be written as Opus: |
| 4733 | /// the correlation between the mix and the decode of what was encoded from it. |
| 4734 | /// A good encoder scores 0.98-0.999 on this material (libopus, measured above); |
| 4735 | /// the failure mode is not subtle at all, scoring 0.1-0.7. 0.95 sits in the gap |
| 4736 | /// with room on both sides, and what fails it is written as AAC -- the export's |
| 4737 | /// own encoder line then says AAC, so the fallback is visible rather than |
| 4738 | /// silent. |
| 4739 | const OPUS_MIN_FIDELITY: f64 = 0.95; |
| 4740 | |
| 4741 | /// The encoder's lookahead at [`OPUS_RATE`] in the mode this envelope always |
| 4742 | /// selects (CELT-only: 2.5 ms). The pre-skip a file states is this *plus* the |
| 4743 | /// warm-up frame [`encode_opus`] throws away. Measured by |
| 4744 | /// cross-correlating the decode against the source, not taken from the crate -- |
| 4745 | /// it exposes no lookahead getter -- and asserted at both ends of the rate band |
| 4746 | /// in `tests/opus_export.rs`, which is what catches a version that changes it. |
| 4747 | const OPUS_PRE_SKIP: u16 = 120; |
| 4748 | |
| 4749 | /// The mix as Opus packets, one per [`OPUS_FRAME`], plus the pre-skip that has |
| 4750 | /// to be declared in front of them. Mono or stereo, at [`OPUS_RATE`] -- the |
| 4751 | /// caller checks all of it, because outside that envelope this encoder is not |
| 4752 | /// one this project is willing to write files with ([`OPUS_MAX_KBPS`]). |
| 4753 | /// |
| 4754 | /// The tail frame is padded with silence rather than dropped: Opus codes whole |
| 4755 | /// frames and a track a few milliseconds short under a picture that is not is |
| 4756 | /// the drift every other path here is written to avoid. The pre-skip trims the |
| 4757 | /// front; the container's duration trims the back. |
| 4758 | fn encode_opus( |
| 4759 | samples: &[f32], |
| 4760 | kbps: u32, |
| 4761 | channels: usize, |
| 4762 | ) -> crate::Result<Option<(Vec<crate::AacPacket>, u16)>> { |
| 4763 | let mut encoder = ec_opus::Encoder::new(OPUS_RATE, channels, ec_opus::Application::Audio) |
| 4764 | .map_err(|e| format!("the Opus encoder refused 48 kHz {channels}-channel sound: {e}"))?; |
| 4765 | // CBR, the crate's default: every packet exactly the rate's size. The old |
| 4766 | // seat ran opus-rs's VBR; the gate below measures either, and a fixed |
| 4767 | // packet size is the friendlier neighbour to a muxer's block budget. |
| 4768 | encoder.set_bitrate(kbps.min(OPUS_MAX_KBPS) * 1_000); |
| 4769 | // No complexity knob on this crate: the reference's default (9) is baked |
| 4770 | // into its rate arithmetic, one percent of equiv rate away from the 10 the |
| 4771 | // old encoder was asked for. |
| 4772 | let mut packets = Vec::new(); |
| 4773 | let mut frame = vec![0f32; OPUS_FRAME * channels]; |
| 4774 | // 1275 bytes is the most one Opus frame may weigh (RFC 6716 §3.2); this is |
| 4775 | // that with room for the TOC and a padded frame, so `encode_float` never |
| 4776 | // has to refuse for want of a buffer. |
| 4777 | let mut out = vec![0u8; 1500]; |
| 4778 | // The head, coded **twice**. An encoder's very first frame has no history |
| 4779 | // behind it and comes out ramped and out of phase -- measured on a 440 Hz |
| 4780 | // fixture, the first 20 ms of the export correlated 0.09 with the source |
| 4781 | // where every later window correlated 0.9997 -- and 20 ms of wrong sound at |
| 4782 | // the head of a file is the kind of thing nobody hears in a test and |
| 4783 | // everybody hears in the first frame of a cut. So the first frame is fed in |
| 4784 | // once to warm the encoder, and thrown away again by the pre-skip: exactly |
| 4785 | // what pre-skip is for (RFC 7845 §4.2), at the cost of one packet. |
| 4786 | let coded = std::time::Instant::now(); |
| 4787 | let warm = samples.len().min(OPUS_FRAME * channels); |
| 4788 | // ...and one silent frame after the sound, for the same delay seen from the |
| 4789 | // other end: the encoder is [`OPUS_PRE_SKIP`] samples behind its input, so |
| 4790 | // without a frame to push them out the last 2.5 ms of the timeline stay |
| 4791 | // inside it and the track ends short under a picture that does not. |
| 4792 | let blocks = std::iter::once(&samples[..warm]) |
| 4793 | .chain(samples.chunks(OPUS_FRAME * channels)) |
| 4794 | .chain(std::iter::once(&samples[..0])); |
| 4795 | for block in blocks { |
| 4796 | frame[..block.len()].copy_from_slice(block); |
| 4797 | frame[block.len()..].fill(0.0); |
| 4798 | let len = encoder |
| 4799 | .encode_float(&frame, OPUS_FRAME, &mut out) |
| 4800 | .map_err(|e| format!("Opus encode failed: {e}"))?; |
| 4801 | packets.push(crate::AacPacket { |
| 4802 | bytes: out[..len].to_vec(), |
| 4803 | samples: OPUS_FRAME as u32, |
| 4804 | }); |
| 4805 | } |
| 4806 | // ...and now the part that is not optimism: what was just written is |
| 4807 | // decoded again and measured against what went in, and a track that does |
| 4808 | // not come back is not written at all ([`OPUS_MIN_FIDELITY`]). The caller |
| 4809 | // falls through to AAC, which is exactly where it stood before this seat |
| 4810 | // existed -- a worse codec is a fair trade for a track that is the sound. |
| 4811 | // |
| 4812 | // corner-cut: this costs one Opus decode of the whole track (a minute of |
| 4813 | // sound in a few hundred milliseconds, against a video encode that is |
| 4814 | // minutes). Upgrade path is deleting it, the day this encoder can be |
| 4815 | // trusted at the rate it is asked for. |
| 4816 | let encoded = coded.elapsed().as_secs_f64(); |
| 4817 | let pre_skip = OPUS_PRE_SKIP + OPUS_FRAME as u16; |
| 4818 | let measured = std::time::Instant::now(); |
| 4819 | let fidelity = opus_fidelity(&packets, samples, usize::from(pre_skip), channels); |
| 4820 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!( |
| 4821 | "export audio: Opus encode {encoded:.1} s, fidelity {fidelity:.4} measured in {:.1} s", |
| 4822 | measured.elapsed().as_secs_f64() |
| 4823 | ); } |
| 4824 | Ok((fidelity >= OPUS_MIN_FIDELITY).then_some((packets, pre_skip))) |
| 4825 | } |
| 4826 | |
| 4827 | /// Packets one sampled window listens to: 5 s at [`OPUS_FRAME`]. |
| 4828 | const FIDELITY_WINDOW: usize = 250; |
| 4829 | |
| 4830 | /// How many of them a long track is judged on -- a minute of sound, wherever |
| 4831 | /// the track's length puts them, and a constant cost rather than one that grows |
| 4832 | /// with the film ([`opus_fidelity`]). |
| 4833 | const FIDELITY_WINDOWS: usize = 12; |
| 4834 | |
| 4835 | /// Packets decoded into a window and thrown away before it is measured. CELT |
| 4836 | /// predicts across frames, so a decoder started cold mid-stream is behind its |
| 4837 | /// own history for a few frames; 100 ms is far more than it needs and is not |
| 4838 | /// worth counting. |
| 4839 | const FIDELITY_WARMUP: usize = 5; |
| 4840 | |
| 4841 | /// How much sound a window must carry before its correlation means anything: |
| 4842 | /// mean square per sample. A window of digital silence -- the head of a film, |
| 4843 | /// the gap between a feature and its credits -- correlates with nothing, and |
| 4844 | /// failing a track for it would send perfectly good sound to AAC. |
| 4845 | const FIDELITY_FLOOR: f64 = 1e-9; |
| 4846 | |
| 4847 | /// The correlation between `samples` and the decode of `packets` with the first |
| 4848 | /// `pre_skip` frames dropped: 1.0 is the same waveform, and this codec's failure |
| 4849 | /// mode lands near 0.1. Streamed packet by packet -- the decode is never held, |
| 4850 | /// only three running sums -- because the mix behind it is already the biggest |
| 4851 | /// thing in an export ([`encode_audio`]'s corner-cut). |
| 4852 | /// |
| 4853 | /// A packet the decoder refuses is 0.0 and no argument: a track this project |
| 4854 | /// cannot read is exactly what this is here to catch. |
| 4855 | /// |
| 4856 | /// **Sampled above a minute of sound, and the median window is the answer.** |
| 4857 | /// This decode was the whole cost of exporting a feature film under the |
| 4858 | /// previous decoder: `ruopus` ran its inverse MDCT at 0.2x real time (measured, |
| 4859 | /// 24.2 s for 121.5 s of stereo; `ec-opus`, the decoder here now, is far |
| 4860 | /// quicker, and the sampling survives it because it costs almost nothing to |
| 4861 | /// keep), |
| 4862 | /// so judging every packet of a two-and-a-half-hour film costs half an hour |
| 4863 | /// before a byte of picture is written -- which is what it did, and what made a |
| 4864 | /// copy export that has no encoding to do at all sit at zero for twenty minutes. |
| 4865 | /// [`FIDELITY_WINDOWS`] windows spread evenly across the track cost the same |
| 4866 | /// minute of decode whatever the film's length, and what they are looking for |
| 4867 | /// survives sampling: [`OPUS_MAX_KBPS`]'s cliff is a *rate* the encoder falls |
| 4868 | /// off everywhere that rate is used, not a defect of one bar of music. |
| 4869 | /// |
| 4870 | /// The **median** and not the worst, and that is measured rather than cautious. |
| 4871 | /// Forty five-second windows of a real 5.1 film's mix, encoded here at 128 kbps |
| 4872 | /// and decoded back, in order: |
| 4873 | /// |
| 4874 | /// ```text |
| 4875 | /// 0.803 0.835 0.938 0.940 0.960 0.987 0.994 ... median 0.998 ... 0.999 |
| 4876 | /// ``` |
| 4877 | /// |
| 4878 | /// Five of the thirty-nine that carried sound sit under [`OPUS_MIN_FIDELITY`] on |
| 4879 | /// a track that is *good* -- which is the same thing the table in |
| 4880 | /// [`OPUS_MAX_KBPS`] shows, where a span scoring 0.937 at 128 kbps is inside the |
| 4881 | /// usable band. A worst-window rule at 0.95 therefore refuses films this encoder |
| 4882 | /// handles perfectly well, while the failure it exists for is the opposite |
| 4883 | /// shape: at 136 kbps the same three measured spans read 0.452, 0.697, 0.951, |
| 4884 | /// and at 256 kbps the whole track correlates 0.06. Half a track cannot be |
| 4885 | /// ruined without the middle of the list moving, so the median separates the two |
| 4886 | /// by a margin no single window can (0.998 against under 0.7) -- and a track |
| 4887 | /// under a minute is one window, where median and whole-track correlation are |
| 4888 | /// the same number the gate always used. |
| 4889 | fn opus_fidelity( |
| 4890 | packets: &[crate::AacPacket], |
| 4891 | samples: &[f32], |
| 4892 | pre_skip: usize, |
| 4893 | channels: usize, |
| 4894 | ) -> f64 { |
| 4895 | // Short enough to hear all of: every fixture, every unit test, and any |
| 4896 | // track under a minute. There is nothing to sample from. |
| 4897 | let all = FIDELITY_WINDOW * FIDELITY_WINDOWS; |
| 4898 | if packets.len() <= all { |
| 4899 | return window_fidelity(packets, samples, pre_skip, channels, 0, 0, packets.len()) |
| 4900 | .unwrap_or(1.0); |
| 4901 | } |
| 4902 | // Evenly spread, first window at the head: the head is where an encoder's |
| 4903 | // own warm-up would show, and the last starts a window short of the end so |
| 4904 | // no window runs past the packets. |
| 4905 | let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1); |
| 4906 | let mut scores: Vec<f64> = Vec::with_capacity(FIDELITY_WINDOWS); |
| 4907 | for w in 0..FIDELITY_WINDOWS { |
| 4908 | let at = w * step; |
| 4909 | let from = at.saturating_sub(FIDELITY_WARMUP); |
| 4910 | let Some(fidelity) = window_fidelity( |
| 4911 | packets, |
| 4912 | samples, |
| 4913 | pre_skip, |
| 4914 | channels, |
| 4915 | from, |
| 4916 | at, |
| 4917 | at + FIDELITY_WINDOW, |
| 4918 | ) else { |
| 4919 | continue; // silence: nothing to correlate, and not a failure |
| 4920 | }; |
| 4921 | scores.push(fidelity); |
| 4922 | } |
| 4923 | // Every window silent is a silent track, which this codec writes as silence. |
| 4924 | if scores.is_empty() { |
| 4925 | return 1.0; |
| 4926 | } |
| 4927 | scores.sort_by(f64::total_cmp); |
| 4928 | scores[scores.len() / 2] |
| 4929 | } |
| 4930 | |
| 4931 | /// [`opus_fidelity`] over `packets[measure..to]`, with `packets[from..measure]` |
| 4932 | /// -- the warm-up -- decoded for its state and thrown away. `None` where the |
| 4933 | /// source window carries no sound worth correlating ([`FIDELITY_FLOOR`]). |
| 4934 | fn window_fidelity( |
| 4935 | packets: &[crate::AacPacket], |
| 4936 | samples: &[f32], |
| 4937 | pre_skip: usize, |
| 4938 | channels: usize, |
| 4939 | from: usize, |
| 4940 | measure: usize, |
| 4941 | to: usize, |
| 4942 | ) -> Option<f64> { |
| 4943 | let (streams, coupled, mapping) = match channels { |
| 4944 | 1 => (1, 0, vec![0u8]), |
| 4945 | // One coupled stream: the stereo shape every fixture and every mix |
| 4946 | // here decodes back through. |
| 4947 | _ => (1, 1, vec![0, 1]), |
| 4948 | }; |
| 4949 | let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, streams, coupled, &mapping); |
| 4950 | let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); |
| 4951 | // Where in the mix this window's first decoded sample lands: every packet |
| 4952 | // is [`OPUS_FRAME`] long, and the pre-skip is what the front of the stream |
| 4953 | // owes before the first of them is the timeline's frame 0. |
| 4954 | let mut at = (from * OPUS_FRAME * channels).saturating_sub(pre_skip * channels); |
| 4955 | let mut drop = (pre_skip * channels).saturating_sub(from * OPUS_FRAME * channels); |
| 4956 | let mut counted = 0usize; |
| 4957 | for (index, packet) in packets.iter().enumerate().take(to).skip(from) { |
| 4958 | let Ok(pcm) = decoder.decode_packet(&packet.bytes) else { |
| 4959 | return Some(0.0); |
| 4960 | }; |
| 4961 | let pcm = &pcm[drop.min(pcm.len())..]; |
| 4962 | drop = drop.saturating_sub(packet.samples as usize * channels); |
| 4963 | // The warm-up is decoded for its state and not for its numbers. |
| 4964 | if index < measure { |
| 4965 | at += pcm.len(); |
| 4966 | continue; |
| 4967 | } |
| 4968 | for (want, got) in samples[at.min(samples.len())..].iter().zip(pcm) { |
| 4969 | let (x, y) = (f64::from(*want), f64::from(*got)); |
| 4970 | num += x * y; |
| 4971 | da += x * x; |
| 4972 | db += y * y; |
| 4973 | at += 1; |
| 4974 | counted += 1; |
| 4975 | } |
| 4976 | } |
| 4977 | (da / counted.max(1) as f64 > FIDELITY_FLOOR).then(|| num / (da.sqrt() * db.sqrt()).max(1e-12)) |
| 4978 | } |
| 4979 | |
| 4980 | /// The audio pass, running beside the picture: what [`run`] holds while it |
| 4981 | /// encodes and joins where the file it is writing needs the track. |
| 4982 | type AudioJob = thread::JoinHandle<crate::Result<Option<ExportAudio>>>; |
| 4983 | |
| 4984 | /// The pass while [`run`] holds it, joined however that function leaves -- |
| 4985 | /// including through a `?`. |
| 4986 | /// |
| 4987 | /// A [`JoinHandle`](thread::JoinHandle) that is merely dropped *detaches* its |
| 4988 | /// thread, and the one error that matters here is the hardware encoder's |
| 4989 | /// process dying ([`crate::hwproc`]): the whole export is then written again by |
| 4990 | /// [`start`], which starts an audio pass of its own. The abandoned one would go |
| 4991 | /// on mixing and encoding the same sound beside it -- two passes of a feature |
| 4992 | /// film's audio at once, on the machine that has just lost its GPU. Joined |
| 4993 | /// instead, so an export has one audio pass at a time and none outlives it. |
| 4994 | struct AudioPass(Option<AudioJob>); |
| 4995 | |
| 4996 | impl AudioPass { |
| 4997 | /// Whether the pass has landed, so the picture loop may collect it without |
| 4998 | /// waiting. |
| 4999 | fn is_finished(&self) -> bool { |
| 5000 | self.0.as_ref().is_some_and(thread::JoinHandle::is_finished) |
| 5001 | } |
| 5002 | |
| 5003 | /// Whether a pass is still to be collected -- which is what "the sound is |
| 5004 | /// still being worked out" means on the encoder line. |
| 5005 | fn running(&self) -> bool { |
| 5006 | self.0.is_some() |
| 5007 | } |
| 5008 | |
| 5009 | /// The handle, for the one caller that is about to join it itself. |
| 5010 | fn take(&mut self) -> Option<AudioJob> { |
| 5011 | self.0.take() |
| 5012 | } |
| 5013 | } |
| 5014 | |
| 5015 | impl Drop for AudioPass { |
| 5016 | fn drop(&mut self) { |
| 5017 | if let Some(job) = self.0.take() { |
| 5018 | let _ = job.join(); |
| 5019 | } |
| 5020 | } |
| 5021 | } |
| 5022 | |
| 5023 | /// The pass's answer, or the failure that is the export's failure. A panicked |
| 5024 | /// audio thread reads as an error rather than as silence: an export that wrote |
| 5025 | /// its picture and quietly no sound is the one outcome this must not have. |
| 5026 | fn join_audio(job: AudioJob) -> crate::Result<Option<ExportAudio>> { |
| 5027 | job.join() |
| 5028 | .map_err(|_| crate::Error::from("the audio pass stopped without a picture or a reason"))? |
| 5029 | } |
| 5030 | |
| 5031 | /// The encoder line a running export shows: the seat the picture is really |
| 5032 | /// being written by, and what the sound is -- or that the sound is still being |
| 5033 | /// worked out, which an overlapped audio pass is until it is collected. |
| 5034 | fn publish_seats( |
| 5035 | shared: &Shared, |
| 5036 | seat: &str, |
| 5037 | project: &Project, |
| 5038 | settings: &ExportSettings, |
| 5039 | sound: Option<bool>, |
| 5040 | opus: bool, |
| 5041 | waiting: bool, |
| 5042 | ) { |
| 5043 | let audio = match waiting { |
| 5044 | // Still mixing on the other thread. The same half-line the copied- |
| 5045 | // picture path has always shown, and for the same reason: what is |
| 5046 | // published is never a codec that did not run. |
| 5047 | true => "working out the sound…", |
| 5048 | false => measured_audio_label(project, settings.format, sound, opus), |
| 5049 | }; |
| 5050 | *shared.encoders.lock().unwrap() = Some(format!("{seat} · {audio}")); |
| 5051 | } |
| 5052 | |
| 5053 | /// Hands a mix that finished mixing early to the mp4 it belongs in, the |
| 5054 | /// moment both exist: `late` may land before the first coded picture has |
| 5055 | /// opened `muxer` at all, so this is tried both right where the mix lands |
| 5056 | /// and after every picture written afterwards, and does nothing once |
| 5057 | /// `*fed` says an earlier try already succeeded. Declaring the track and |
| 5058 | /// queuing its packets here is what lets [`crate::mux::Mp4Muxer`]'s own |
| 5059 | /// hold interleave them under the pictures still to come, rather than the |
| 5060 | /// track landing all at once after the picture is done. |
| 5061 | fn feed_late_audio( |
| 5062 | muxer: &mut Option<Muxer>, |
| 5063 | late: &Option<ExportAudio>, |
| 5064 | fed: &mut bool, |
| 5065 | ) -> crate::Result<()> { |
| 5066 | if *fed { |
| 5067 | return Ok(()); |
| 5068 | } |
| 5069 | let (Some(track), Some(Muxer::Mp4(mp4))) = (late.as_ref(), muxer.as_mut()) else { |
| 5070 | return Ok(()); |
| 5071 | }; |
| 5072 | mp4.add_audio_track(¶ms_of(track))?; |
| 5073 | for packet in &track.packets { |
| 5074 | mp4.write_audio_packet(&packet.bytes)?; |
| 5075 | } |
| 5076 | *fed = true; |
| 5077 | Ok(()) |
| 5078 | } |
| 5079 | |
| 5080 | /// The language the timeline's sound is in, for the export to tag its audio track with: the one |
| 5081 | /// language every audio clip's stream states. `None` when the clips disagree, when one of them |
| 5082 | /// states none (`und`), or when there are no audio clips, and the track stays `und`. |
| 5083 | pub(crate) fn audio_language(project: &Project) -> Option<String> { |
| 5084 | let sources = project.sources(); |
| 5085 | shared_language( |
| 5086 | project |
| 5087 | .audio_lanes() |
| 5088 | .into_iter() |
| 5089 | .flat_map(|lane| project.lane(lane).iter()) |
| 5090 | .map(|clip| sources.get(clip.source).and_then(|src| stream_language(&src.path, src.audio_stream))), |
| 5091 | ) |
| 5092 | } |
| 5093 | |
| 5094 | /// The one language every stream in `langs` states, or `None` when there are none, when one |
| 5095 | /// states none, or when they differ. |
| 5096 | fn shared_language(langs: impl IntoIterator<Item = Option<String>>) -> Option<String> { |
| 5097 | let mut shared: Option<String> = None; |
| 5098 | for lang in langs { |
| 5099 | let lang = lang?; |
| 5100 | match &shared { |
| 5101 | None => shared = Some(lang), |
| 5102 | Some(s) if *s == lang => {} |
| 5103 | Some(_) => return None, |
| 5104 | } |
| 5105 | } |
| 5106 | shared |
| 5107 | } |
| 5108 | |
| 5109 | /// The language audio stream `audio_stream` of `path` states in its header, with `und` (none |
| 5110 | /// stated) as `None`. Read from the header alone. |
| 5111 | fn stream_language(path: &Path, audio_stream: usize) -> Option<String> { |
| 5112 | crate::probe_media(path) |
| 5113 | .streams |
| 5114 | .into_iter() |
| 5115 | .find(|s| s.kind == crate::StreamKind::Audio && s.index == audio_stream)? |
| 5116 | .language |
| 5117 | .filter(|l| l != "und") |
| 5118 | } |
| 5119 | |
| 5120 | /// The language the picture is tagged with, for the Matroska video track to state: the first |
| 5121 | /// source's picture track, the one the export takes its picture from ([`source_colour_tags`]). |
| 5122 | /// `None` where that track states none (`und`), or no source can be read. |
| 5123 | fn video_language(project: &Project) -> Option<String> { |
| 5124 | let path = &project.sources().first()?.path; |
| 5125 | crate::probe_media(path) |
| 5126 | .streams |
| 5127 | .into_iter() |
| 5128 | .find(|s| s.kind == crate::StreamKind::Video && s.index == 0)? |
| 5129 | .language |
| 5130 | .filter(|l| l != "und") |
| 5131 | } |
| 5132 | |
| 5133 | /// The colour tags of the first source, exactly as its container states them: |
| 5134 | /// what a file that keeps its source's colour declares, unspecified fields left |
| 5135 | /// unspecified. Nothing when no source can be read, which declares nothing. |
| 5136 | fn source_colour_tags(project: &Project) -> Tags { |
| 5137 | project |
| 5138 | .sources() |
| 5139 | .first() |
| 5140 | .and_then(|source| crate::demux::Demuxer::open(&source.path).ok()) |
| 5141 | .map(|(_, demuxer)| demuxer.colour_tags()) |
| 5142 | .unwrap_or_default() |
| 5143 | } |
| 5144 | |
| 5145 | fn params_of(track: &ExportAudio) -> AudioParams { |
| 5146 | AudioParams { |
| 5147 | freq_index: track.params.freq_index, |
| 5148 | chan_conf: track.params.chan_conf, |
| 5149 | sample_rate: track.params.sample_rate, |
| 5150 | opus_pre_skip: track.opus_pre_skip, |
| 5151 | language: track.language.clone(), |
| 5152 | } |
| 5153 | } |
| 5154 | |
| 5155 | fn run( |
| 5156 | project: &Project, |
| 5157 | meta: &VideoMeta, |
| 5158 | out: &Path, |
| 5159 | shared: &Arc<Shared>, |
| 5160 | settings: &ExportSettings, |
| 5161 | sample_rate: Option<u32>, |
| 5162 | ) -> crate::Result<()> { |
| 5163 | // The media's length and not the timeline's: a caption placed past the last |
| 5164 | // picture holds the *timeline* open ([`Project::timeline_frames`]) and there |
| 5165 | // is nothing to write under it -- the picture loop walks the composite spans |
| 5166 | // and stops with them, so a file padded to the caption's end would be |
| 5167 | // trailing silence over a frozen last frame. The export ends with the last |
| 5168 | // picture or sound, the cues are cut off there ([`lane_subtitles`]), and |
| 5169 | // [`planned_subtitles`] says so before the button is pressed. |
| 5170 | // The range's own length where one is marked, the media's otherwise -- |
| 5171 | // `export_spans` walks the same window, so `done` ends on this `total` |
| 5172 | // exactly as it always did. |
| 5173 | let total = settings.range.map_or(project.media_frames(), |(s, e)| { |
| 5174 | e.min(project.media_frames()).saturating_sub(s) |
| 5175 | }); |
| 5176 | // The two preview switches are the H.264 mp4 pair's alone. Only that |
| 5177 | // container carries a colour of its own back out ([`write_video`] tags it |
| 5178 | // there), so asking any other for a source-space file would write pictures |
| 5179 | // in one space and a header in another; and only that codec's seats honour |
| 5180 | // `intra_only` -- the H.264 and HEVC pairs do, and an AV1 one would quietly |
| 5181 | // write the long-GOP file it always did. |
| 5182 | if settings.keep_source_colour && settings.format != Format::Mp4 { |
| 5183 | return Err(format!( |
| 5184 | "{} cannot be written in its source's colour space", |
| 5185 | settings.format.name() |
| 5186 | ) |
| 5187 | .into()); |
| 5188 | } |
| 5189 | if settings.intra_only && !matches!(settings.format, Format::Mp4 | Format::Hevc | Format::HevcMp4) { |
| 5190 | return Err(format!("{} cannot be written intra-only", settings.format.name()).into()); |
| 5191 | } |
| 5192 | if settings.keyframe_s.is_some() && settings.intra_only { |
| 5193 | return Err("keyframe_s sets the key frame interval, and intra_only codes every picture a key frame: pass one".into()); |
| 5194 | } |
| 5195 | if settings.faststart && !settings.format.is_mp4_family() { |
| 5196 | return Err(format!("faststart lays out an mp4 file, and {} is not one", settings.format.name()).into()); |
| 5197 | } |
| 5198 | if let Some(why) = exact_refusal(project, meta, settings) { |
| 5199 | return Err(why.into()); |
| 5200 | } |
| 5201 | let hdr_colour = hdr_colour_of(settings)?; |
| 5202 | let sources = project.sources(); |
| 5203 | // The picture's decision first, before a sample of sound is touched: it is |
| 5204 | // the answer that decides what the whole export *is*, it costs one header |
| 5205 | // read per source, and it is what the line on screen has been missing -- |
| 5206 | // an export that copies its picture used to say nothing at all for as long |
| 5207 | // as its sound took, which on a feature film was minutes. Half a line now, |
| 5208 | // completed by the measured codec once the sound is known below: what is |
| 5209 | // published is never a codec that did not run. |
| 5210 | let plan = CopyPlan::of(project, meta, settings); |
| 5211 | if plan.is_some() { |
| 5212 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export video: copy (source packets)"); } |
| 5213 | *shared.encoders.lock().unwrap() = Some("copy · working out the sound…".into()); |
| 5214 | } |
| 5215 | // ...then the audio, on a thread of its own, started before anything is |
| 5216 | // opened for the picture. |
| 5217 | // |
| 5218 | // Where it is *waited* for is the whole of this: a Matroska file interleaves |
| 5219 | // its audio into the clusters from the header on, so that path needs every |
| 5220 | // packet before the first coded picture and there is nothing to overlap. An |
| 5221 | // mp4 writes its audio track after the whole picture -- and now declares it |
| 5222 | // there too ([`MkvMuxer`]'s opposite, `Mp4Muxer::add_audio_track`) -- so the |
| 5223 | // picture's loop needs nothing at all from this until it has finished, and |
| 5224 | // the mix, its encode and the encode of every frame run at once. An export |
| 5225 | // used to cost the sound *plus* the picture; an mp4 one now costs the longer |
| 5226 | // of the two. On this project's own film that is 168 s of AC-3 that no |
| 5227 | // longer stands in front of 733 s of hardware H.264. |
| 5228 | // What a file keeping its source's colour declares, read once: the picture |
| 5229 | // is written in that space, so the tags are the source's own, not resolved. |
| 5230 | let source_colour = match settings.keep_source_colour { |
| 5231 | true => source_colour_tags(project), |
| 5232 | false => Tags::default(), |
| 5233 | }; |
| 5234 | // The picture's language, which the Matroska video track states (`und` where none). |
| 5235 | let source_language = video_language(project); |
| 5236 | // A ProRes file's sound is PCM (24-bit unless asked for 16) mixed on a thread of its own and written |
| 5237 | // after the picture ([`PcmPass`]); no AAC pass runs beside it. |
| 5238 | let bits = prores_audio_bits(settings); |
| 5239 | let pcm_job = match settings.format.is_prores() { |
| 5240 | true => { |
| 5241 | let (project, meta, settings, shared) = |
| 5242 | (project.clone(), *meta, settings.clone(), Arc::clone(shared)); |
| 5243 | PcmPass(Some( |
| 5244 | thread::Builder::new() |
| 5245 | .name("export-pcm".into()) |
| 5246 | .spawn(move || mix_pcm16(&project, &meta, &shared, &settings, sample_rate, bits))?, |
| 5247 | )) |
| 5248 | } |
| 5249 | false => PcmPass(None), |
| 5250 | }; |
| 5251 | let audio_job = if settings.format.is_prores() { None } else { Some({ |
| 5252 | let (project, meta, settings, shared) = |
| 5253 | (project.clone(), *meta, settings.clone(), Arc::clone(shared)); |
| 5254 | thread::Builder::new() |
| 5255 | .name("export-audio".into()) |
| 5256 | .spawn(move || { |
| 5257 | let track = copy_audio( |
| 5258 | &project, |
| 5259 | &meta, |
| 5260 | audio_kbps_of(&settings), |
| 5261 | settings.format.is_mkv(), |
| 5262 | settings.format == Format::Webm, |
| 5263 | settings.reencode_audio, |
| 5264 | &shared, |
| 5265 | // WebM's sound is mixed at the rate Opus codes at, so the |
| 5266 | // one encoder path it takes is the one that resamples. |
| 5267 | match settings.format { |
| 5268 | Format::Webm => Some(OPUS_RATE), |
| 5269 | _ => sample_rate, |
| 5270 | }, |
| 5271 | settings.range, |
| 5272 | )?; |
| 5273 | // The language the sound is in, on the copy and the mix alike: |
| 5274 | // the one tag the whole track carries. |
| 5275 | Ok(track.map(|track| ExportAudio { |
| 5276 | language: audio_language(&project), |
| 5277 | ..track |
| 5278 | })) |
| 5279 | })? |
| 5280 | }) }; |
| 5281 | // A Matroska file (and a copied one, whose muxer is the same) collects it |
| 5282 | // here; an mp4 leaves it running and collects it under the picture below. |
| 5283 | // Held in a guard from here on, so no way out of this function leaves the |
| 5284 | // pass running behind it ([`AudioPass`]). |
| 5285 | let mut audio_job = AudioPass(audio_job); |
| 5286 | // The condition is the *format*, and the copied-picture path below relies |
| 5287 | // on that covering it too: `plan` hands its packets straight to a Matroska |
| 5288 | // muxer, so it may only exist where this has already collected them -- |
| 5289 | // which holds because [`CopyPlan::of`] returns `None` for every format |
| 5290 | // that is not `Hevc` or `Av1`, both of which are `is_mkv`. Said out loud |
| 5291 | // because a copy plan for an mp4 would otherwise reach `plan.run` with the |
| 5292 | // sound still being mixed on the other thread. |
| 5293 | debug_assert!( |
| 5294 | settings.format.is_mkv() || plan.is_none(), |
| 5295 | "a copy plan outside Matroska would run before its sound is collected" |
| 5296 | ); |
| 5297 | let mut pcm_job = pcm_job; |
| 5298 | let audio = match settings.format.is_mkv() { |
| 5299 | true => join_audio(audio_job.take().expect("the job was just made"))?, |
| 5300 | false => None, |
| 5301 | }; |
| 5302 | let audio_params = audio.as_ref().map(params_of); |
| 5303 | // What the track *is*, kept before the packets are handed to a muxer: the |
| 5304 | // encoder line names a copy or an encode and only `copy_audio` knows which. |
| 5305 | // `None` on the mp4 path until the pass is collected -- the line says it is |
| 5306 | // still working the sound out, which is what it is doing. |
| 5307 | let mut sound = audio.as_ref().map(|track| track.copied); |
| 5308 | // ...and *which* encoder, for the same line: the card predicts Opus from the |
| 5309 | // format alone and cannot know the mix's rate or width ([`audio_label`]), |
| 5310 | // while this is after the mix was opened, so it is the measured answer. |
| 5311 | let mut opus = audio |
| 5312 | .as_ref() |
| 5313 | .is_some_and(|track| track.opus_pre_skip.is_some()); |
| 5314 | // Taken by the Matroska muxer at creation; the mp4 one writes its track |
| 5315 | // after the picture, so for that path this is filled in at the end. |
| 5316 | let mut packets = audio.map(|track| track.packets); |
| 5317 | // ...and the cues with them, for the same reason: the subtitle track is |
| 5318 | // declared in the header and its blocks are interleaved into the clusters, |
| 5319 | // so the muxer needs the lot before the first picture is written. |
| 5320 | let mut subs = export_subtitles(project, meta, settings); |
| 5321 | // Whatever the sound has reached, the picture's share starts here |
| 5322 | // ([`AUDIO_BAND`]) -- and the bar only ever moves forwards, which is what |
| 5323 | // `fetch_max` below keeps true while an audio pass is still publishing its |
| 5324 | // own third of that band from the other thread. |
| 5325 | shared.progress.fetch_max(AUDIO_BAND, Ordering::Relaxed); |
| 5326 | |
| 5327 | // Before an encoder is opened at all: a timeline nobody has touched, whose |
| 5328 | // sources this file can hold as they are, is written by copying their coded |
| 5329 | // blocks -- the picture's half of what `copy_audio` just did for the sound, |
| 5330 | // and the difference between an export bounded by the *edited* spans and one |
| 5331 | // that re-encodes a whole film to change a cut. [`CopyPlan`] states the |
| 5332 | // whole rule; anything at all outside it falls through to the walk below. |
| 5333 | if let Some(plan) = plan { |
| 5334 | *shared.encoders.lock().unwrap() = Some(format!( |
| 5335 | "copy · {}", |
| 5336 | // The measured codec, exactly as the encoder path below publishes |
| 5337 | // it: the mix has been opened by now, so a line that fell back to |
| 5338 | // AAC says AAC. Naming the prediction here would make the fallback |
| 5339 | // invisible on precisely the exports that are over in seconds. |
| 5340 | measured_audio_label(project, settings.format, sound, opus) |
| 5341 | )); |
| 5342 | return plan.run( |
| 5343 | out, |
| 5344 | meta, |
| 5345 | shared, |
| 5346 | audio_params.as_ref().zip(packets.take()), |
| 5347 | std::mem::take(&mut subs), |
| 5348 | total, |
| 5349 | &settings.chapters, |
| 5350 | ); |
| 5351 | } |
| 5352 | |
| 5353 | // One header parse per source, before any of them is decoded: what rate |
| 5354 | // each file was shot at against the timeline's ([`Rate`]), which is how the |
| 5355 | // clip's timeline frames below become frames of the file, and what its |
| 5356 | // samples *mean* ([`ColorDescription`]), which is what decides whether they |
| 5357 | // are remapped on the way in. Real time for a still, a song and a |
| 5358 | // single-rate project, where every conversion below is the identity. |
| 5359 | let rates: Vec<( |
| 5360 | Rate, |
| 5361 | ColorDescription, |
| 5362 | Option<f32>, |
| 5363 | Rotation, |
| 5364 | crate::demux::PixelAspect, |
| 5365 | )> = sources |
| 5366 | .iter() |
| 5367 | .map(|source| source_rate(&source.path, meta.frame_rate)) |
| 5368 | .collect(); |
| 5369 | // ...and, for a source on an HDR curve, the tone map that brings its samples |
| 5370 | // down to the SDR this file is written in ([`crate::tonemap`]). Once per |
| 5371 | // source stream: the table costs a couple of milliseconds to build and a |
| 5372 | // span reopens its file, so building it here rather than in the loop below |
| 5373 | // is the difference between paying that once and paying it per cut. An SDR |
| 5374 | // source -- the whole of an ordinary project -- builds no table at all. |
| 5375 | // |
| 5376 | // Through the project's own preset ([`tonemap::Preset`]) and each source's |
| 5377 | // own declared peak, which is the pair playback's decode funnel builds its |
| 5378 | // tables with: preview and export are the same rendition of the same film |
| 5379 | // because they are told the same two things, not because two numbers happen |
| 5380 | // to agree. |
| 5381 | let preset = project.tone(); |
| 5382 | let tone: Vec<Option<ToneMapper>> = rates |
| 5383 | .iter() |
| 5384 | .map(|(_, color, peak, _, _)| match color.transfer { |
| 5385 | // A preview file keeps the film's own curve and is tone-mapped when |
| 5386 | // it is *shown* ([`ExportSettings::keep_source_colour`]), which is |
| 5387 | // both cheaper and the only way the preset can still be changed |
| 5388 | // after the stand-in was made. |
| 5389 | _ if settings.keep_source_colour => None, |
| 5390 | // An HDR export keeps the HDR sources' own curve: no tone map to SDR |
| 5391 | // ([`ExportSettings::hdr`], [`hdr_colour_of`] refuses a curve change). |
| 5392 | _ if hdr_colour.is_some() => None, |
| 5393 | Transfer::Sdr => None, |
| 5394 | Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, *peak)), |
| 5395 | Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, *peak)), |
| 5396 | }) |
| 5397 | .collect(); |
| 5398 | // ...and the one space they are all written in, the same rule a reader with |
| 5399 | // no tags to read would apply to this file's height -- or, for a preview |
| 5400 | // file, the source's own, which is what makes every remap below the |
| 5401 | // identity and the file's `colr` box its film's. |
| 5402 | // The software seat's depth ([`wide_ten_bit`]): a 10-bit timeline is |
| 5403 | // decoded and encoded at 10 bits wherever its pictures pass through untouched. |
| 5404 | for (_, color, ..) in &rates { |
| 5405 | let clash = hdr_colour.is_some_and(|out| color.transfer != Transfer::Sdr && color.transfer != out.transfer); |
| 5406 | if clash { |
| 5407 | let out = hdr_colour.expect("a clash needs an HDR output"); |
| 5408 | return Err(format!( |
| 5409 | "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", |
| 5410 | transfer_name(color.transfer), |
| 5411 | transfer_name(out.transfer) |
| 5412 | ) |
| 5413 | .into()); |
| 5414 | } |
| 5415 | } |
| 5416 | let ten_bit = wide_ten_bit(settings, || { |
| 5417 | sources |
| 5418 | .iter() |
| 5419 | .any(|s| Demuxer::open(&s.path).is_ok_and(|(_, d)| d.bit_depth() >= 10)) |
| 5420 | })?; |
| 5421 | // The colour a 10-bit SDR export declares: its sources' own matrix, where every |
| 5422 | // clip is SDR in one matrix ([`source_sdr_colour`]). Every other export keeps the |
| 5423 | // output rule, and so does the encoder's declared colour when there is no such one. |
| 5424 | let source_sdr = match ten_bit && !settings.keep_source_colour { |
| 5425 | // An HDR export declares its own colour, whatever the sources are. |
| 5426 | true if hdr_colour.is_some() => hdr_colour, |
| 5427 | true => source_sdr_colour(&rates.iter().map(|(_, c, ..)| *c).collect::<Vec<_>>()), |
| 5428 | false => None, |
| 5429 | }; |
| 5430 | let rule = ColorDescription::output_sized(meta.width, meta.height); |
| 5431 | let out_color = match settings.keep_source_colour { |
| 5432 | true => meta.color, |
| 5433 | false => source_sdr.unwrap_or(rule), |
| 5434 | }; |
| 5435 | let container_colour = source_sdr.map_or(source_colour, Tags::of); |
| 5436 | |
| 5437 | // The captions drawn into each picture, if the export burns any in ([`Burn`]). |
| 5438 | let mut burn = Burn::new(project, settings, meta.frame_rate, out_color.full_range)?; |
| 5439 | let mut encoder = Enc::open(meta, settings, ten_bit, source_sdr.unwrap_or(rule))?; |
| 5440 | // What this file is really being written by, for a progress line to name. |
| 5441 | // Published *after* the seat is open, so a hardware encoder the driver |
| 5442 | // refused reads as the software one that took over rather than as the hope |
| 5443 | // it replaced -- and the sound says whether it was copied or encoded, which |
| 5444 | // only `copy_audio` knows and, on the overlapped path, does not know yet. |
| 5445 | let seat = encoder.label(); |
| 5446 | publish_seats( |
| 5447 | shared, |
| 5448 | seat, |
| 5449 | project, |
| 5450 | settings, |
| 5451 | sound, |
| 5452 | opus, |
| 5453 | audio_job.running(), |
| 5454 | ); |
| 5455 | // When the picture started, so the stage line below can say where under it |
| 5456 | // the sound landed -- the one number that says whether the two passes |
| 5457 | // really overlapped, in the same voice as `encode_audio`'s own timers. |
| 5458 | let picture_started = std::time::Instant::now(); |
| 5459 | // The sound, once the pass beside this one has finished with it: joined |
| 5460 | // here the moment it lands rather than only after the picture, so |
| 5461 | // `feed_late_audio` below can hand it to the muxer while pictures are |
| 5462 | // still being coded and let `Mp4Muxer`'s own hold interleave the two |
| 5463 | // ([`crate::mux::Mp4Muxer`]). |
| 5464 | let mut late: Option<ExportAudio> = None; |
| 5465 | // Set once `late`'s track has been handed to the muxer -- so the final |
| 5466 | // join below, which still exists for a mix that never lands mid-picture, |
| 5467 | // knows not to declare the track or write its packets a second time. |
| 5468 | let mut audio_fed = false; |
| 5469 | let mut muxer = None; |
| 5470 | // A ProRes file is declared up front: the encoder knows its own sample entry. |
| 5471 | if let Some(params) = encoder.prores_params() { |
| 5472 | muxer = Some(Muxer::Mov(crate::prores_out::MovWriter::create( |
| 5473 | out, |
| 5474 | params, |
| 5475 | crate::mux::frame_timing(meta.frame_rate)?, |
| 5476 | )?)); |
| 5477 | } |
| 5478 | let mut done = 0u32; |
| 5479 | // ...and how many of the edit's frames a file could not give, summed over |
| 5480 | // the spans that ran out under their clip ([`Shared::truncated`]). |
| 5481 | let mut skipped = 0u32; |
| 5482 | let black = Black::new(meta); |
| 5483 | // Software decoders that spans leave behind for the next span of the same |
| 5484 | // file to continue (see [`Parked`]). |
| 5485 | let parked = Arc::new(Parked::default()); |
| 5486 | // Spans, not clips: a gap in the video is part of the timeline and gets |
| 5487 | // encoded too, as black frames. The picture count is therefore |
| 5488 | // `media_frames` however the lanes are arranged -- [`export_spans`] is that |
| 5489 | // walk cut to it, so `done` ends on the `total` above instead of running |
| 5490 | // past it under a trailing caption -- and *which* lane a span comes from is |
| 5491 | // `composite_spans_from`'s answer, the same one playback shows, so an |
| 5492 | // export is what was watched. |
| 5493 | for span in export_spans(project, settings.range) { |
| 5494 | // Every clip reopens its own source file at its own in point; the |
| 5495 | // encoder is *not* reopened, so the export is one continuous stream |
| 5496 | // whose GOP boundaries need not line up with the cuts -- nor with the |
| 5497 | // file boundaries, which are just cuts that change the path. |
| 5498 | // Whether this span's tail dissolves into its successor -- decided |
| 5499 | // before A's own decoder is opened, because it is what decides |
| 5500 | // whether A may take the DMA fast path at all: the blend below needs |
| 5501 | // A's pixels on the CPU, so a dissolving span never asks for a GPU |
| 5502 | // buffer, not even outside its own window. |
| 5503 | // |
| 5504 | // A layered span (two or more clips on the stack, [`layered_at`]) takes |
| 5505 | // no decoder of its own: its pictures are composed by a [`LayerStack`] |
| 5506 | // opened beside it, placed and faded per clip, so it never dissolves, |
| 5507 | // never takes the DMA path and never runs the single-clip placement. |
| 5508 | let keyed_color = color_keyed_alone_at(project, span.start).filter(|_| ten_bit); |
| 5509 | let layered_here = layered_at(project, span.start) && keyed_color.is_none(); |
| 5510 | let dissolve = dissolve_window(project, &span); |
| 5511 | let (mut pictures, rate, in_frame, color, mapper, rotation, pixel_aspect) = |
| 5512 | match span.from.filter(|_| !layered_here) { |
| 5513 | Some((source, in_frame)) => { |
| 5514 | let entry = sources |
| 5515 | .get(source) |
| 5516 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; |
| 5517 | let (rate, color, _peak, rotation, pixel_aspect) = rates[source]; |
| 5518 | // A field-mode clip of an interlaced file counts fields, two a frame. |
| 5519 | let deint = span_deint(project, span.start, &entry.path); |
| 5520 | let rate = crate::deinterlace::counted_rate(deint, rate); |
| 5521 | let mapper = tone[source].as_ref(); |
| 5522 | // Nothing on the way from this span's decoder to the encoder |
| 5523 | // touches a sample: no tone map, no matrix remap, no grade -- |
| 5524 | // which is what lets the *decoded buffer itself* be encoded, |
| 5525 | // never read back and never written out again. The canvas is |
| 5526 | // the fourth thing that would touch it, and the decoder answers |
| 5527 | // that one: a picture of another size than this file's is one |
| 5528 | // the plugin hands back as pixels ([`HwSession::next_frame_dma`]). |
| 5529 | let untouched = mapper.is_none() |
| 5530 | && keyed_color.is_none() |
| 5531 | && burn.is_none() |
| 5532 | && remap_into(Some(color), false, out_color.matrix).is_none() |
| 5533 | && project |
| 5534 | .composite_color_at(span.start) |
| 5535 | .is_none_or(|params| params.is_identity()) |
| 5536 | && project |
| 5537 | .composite_transform_at(span.start) |
| 5538 | .is_none_or(|params| params.is_identity()) |
| 5539 | // A file whose display matrix asks for a turn is *not* |
| 5540 | // untouched, whatever else the timeline says: its pictures |
| 5541 | // have to be turned, which is a read-back no GPU buffer |
| 5542 | // survives. The sample aspect is the same refusal one |
| 5543 | // stage later: its pictures have to be stretched to the |
| 5544 | // square-pixel raster before an encoder sees them, which |
| 5545 | // is the same kind of touch. |
| 5546 | && rotation.is_none() |
| 5547 | && pixel_aspect.is_square() |
| 5548 | && dissolve.is_none() |
| 5549 | && !picture_faded_in(project, &span); |
| 5550 | let want = untouched.then(|| encoder.dma_want(meta)).flatten(); |
| 5551 | // Opened at the file's own frame, which is the only place the |
| 5552 | // file's numbering is used -- the span's are the timeline's. |
| 5553 | let flags = project.composite_visualizer_at(span.start); |
| 5554 | let pictures = if crate::is_audio(&entry.path) || flags & 1 != 0 { |
| 5555 | ClipDecoder::visualizer( |
| 5556 | &entry.path, |
| 5557 | entry.audio_stream, |
| 5558 | rate.source_at(in_frame), |
| 5559 | (meta.width, meta.height), |
| 5560 | meta.frame_rate, |
| 5561 | flags, |
| 5562 | project.composite_viz_paint_at(span.start), |
| 5563 | )? |
| 5564 | } else if span.reverse && !crate::is_image(&entry.path) { |
| 5565 | // Played backwards: from the file frame the span starts on, down |
| 5566 | // to the lowest it reads. The loop below counts the pictures it |
| 5567 | // takes off the decoder, which is how it reads a forward one. |
| 5568 | let lo = span.source_window().map_or(0, |(_, lo, _)| rate.source_at(lo)); |
| 5569 | ClipDecoder::reversed(&entry.path, rate.source_at(in_frame), lo, deint) |
| 5570 | } else { |
| 5571 | ClipDecoder::open_with(&entry.path, rate.source_at(in_frame), want, Some(&parked), ten_bit, deint)? |
| 5572 | }; |
| 5573 | ( |
| 5574 | Some(pictures), |
| 5575 | rate, |
| 5576 | in_frame, |
| 5577 | Some(color), |
| 5578 | mapper, |
| 5579 | rotation, |
| 5580 | pixel_aspect, |
| 5581 | ) |
| 5582 | } |
| 5583 | // A gap's black is 16/128/128, which is black in every matrix here |
| 5584 | // and on every curve: nothing to remap and nothing to tone-map, |
| 5585 | // which is what `None` says. A gap is no file either, so nothing |
| 5586 | // turns it. |
| 5587 | None => ( |
| 5588 | None, |
| 5589 | Rate::REAL_TIME, |
| 5590 | 0, |
| 5591 | None, |
| 5592 | None, |
| 5593 | Rotation::None, |
| 5594 | crate::demux::PixelAspect::SQUARE, |
| 5595 | ), |
| 5596 | }; |
| 5597 | // Mixed spaces on one timeline: a clip coded against another matrix than |
| 5598 | // the one this file declares is rewritten into it, *after* the grade -- |
| 5599 | // playback grades in the source's own space and converts for the screen |
| 5600 | // ([`crate::decode`]), so a grade applied to remapped samples is a |
| 5601 | // different picture than the one the canvas showed. Same-space clips -- |
| 5602 | // the whole of an ordinary project -- take `None` and not a byte is |
| 5603 | // touched. |
| 5604 | // |
| 5605 | // ...and what the samples mean when that remap sees them is not always |
| 5606 | // what the file said, which is [`remap_into`]'s whole question. |
| 5607 | let remap = remap_into(color, mapper.is_some(), out_color.matrix); |
| 5608 | // What this span is graded by -- the same answer playback's decoder |
| 5609 | // carries, so the export is the picture that was watched. `None` for a |
| 5610 | // gap and for an ungraded clip, and that is the path where not a byte |
| 5611 | // is touched. Scratch outside the frame loop: it is refilled per frame |
| 5612 | // and its allocation survives the whole span. |
| 5613 | // A layered span's clips carry their own grades and transforms, in the |
| 5614 | // [`LayerStack`] that composes them; the top clip's do not apply here. |
| 5615 | let grade = match layered_here { |
| 5616 | true => None, |
| 5617 | false => project.composite_color_at(span.start).copied(), |
| 5618 | }; |
| 5619 | let transform = match layered_here { |
| 5620 | true => TransformParams::default(), |
| 5621 | false => project |
| 5622 | .composite_transform_at(span.start) |
| 5623 | .copied() |
| 5624 | .unwrap_or_default(), |
| 5625 | }; |
| 5626 | // The composing stack for a layered span, open for the whole span. |
| 5627 | let mut layers = match layered_here { |
| 5628 | true => Some(LayerStack::open( |
| 5629 | project, |
| 5630 | meta, |
| 5631 | &stack_at(project, span.start), |
| 5632 | out_color.matrix, |
| 5633 | None, |
| 5634 | Some((&shared.cancel, &shared.measuring)), |
| 5635 | )?), |
| 5636 | false => None, |
| 5637 | }; |
| 5638 | // A 10-bit export composes a layered picture at 10 bits too ([`LayerStack::picture16`]). |
| 5639 | let layered_wide = ten_bit && layers.is_some(); |
| 5640 | let mut graded = (Vec::new(), Vec::new(), Vec::new()); |
| 5641 | let mut transformed = (Vec::new(), Vec::new(), Vec::new()); |
| 5642 | // The 10-bit scratch of A's placement, and the 10-bit copies of an 8-bit |
| 5643 | // picture (or of B's) that composes at 10 bits ([`widen_into`]). |
| 5644 | let mut scratch16 = Scratch16::default(); |
| 5645 | let mut widened_a: Planes16 = Planes16::default(); |
| 5646 | let mut widened_b: Planes16 = Planes16::default(); |
| 5647 | // A lone clip's effects stack on this path draws on copies of its placed |
| 5648 | // picture, at whichever depth it was placed ([`color_keyed_alone_at`]). |
| 5649 | let fx_clip = keyed_color.filter(|clip| crate::effects::active(&clip.effects)); |
| 5650 | let (mut fx8, mut fx16): (Planes, Planes16) = Default::default(); |
| 5651 | let mut fx_scratch8 = crate::effects::Scratch::<u8>::default(); |
| 5652 | let mut fx_scratch16 = crate::effects::Scratch::<u16>::default(); |
| 5653 | // ...and one more for the file's own display-matrix turn, which happens |
| 5654 | // before all of those (see [`place_picture`]): empty for every source |
| 5655 | // that states no turn. `stretched` is its twin for the pixel aspect, |
| 5656 | // which happens right after it. |
| 5657 | let mut rotated = (Vec::new(), Vec::new(), Vec::new()); |
| 5658 | let mut stretched = (Vec::new(), Vec::new(), Vec::new()); |
| 5659 | // ...and the canvas it is placed on, which is where a source of another |
| 5660 | // resolution becomes a picture at the project's. The same `Composer` |
| 5661 | // playback composes with, given the same policy, so an export is what |
| 5662 | // was watched down to the letterbox; a clip already the project's size |
| 5663 | // passes through it untouched. |
| 5664 | let mut canvas = Composer::new( |
| 5665 | meta.width, |
| 5666 | meta.height, |
| 5667 | project.composite_fit_at(span.start), |
| 5668 | ); |
| 5669 | // The 10-bit canvas: its own composer, because the 8-bit placement above |
| 5670 | // borrows `canvas` in the same frame. It places the same fit. |
| 5671 | let mut canvas16 = Composer::new( |
| 5672 | meta.width, |
| 5673 | meta.height, |
| 5674 | project.composite_fit_at(span.start), |
| 5675 | ); |
| 5676 | // Scratch for the 8-bit composition of a 10-bit picture ([`narrowed`]), |
| 5677 | // one for A's picture and one for B's. |
| 5678 | let mut narrow_a: [Vec<u8>; 3] = Default::default(); |
| 5679 | let mut narrow_b: [Vec<u8>; 3] = Default::default(); |
| 5680 | // B's own decoder, opened beside A's: the two streams come off their |
| 5681 | // files together for exactly the frames the tail below blends, and |
| 5682 | // nothing else in this span ever touches it. |
| 5683 | let mut b = dissolve |
| 5684 | .map( |
| 5685 | |(b_source, b_in_frame, window, b_start)| -> crate::Result<_> { |
| 5686 | let entry = sources.get(b_source).ok_or_else(|| { |
| 5687 | format!("clip names source {b_source} of {}", sources.len()) |
| 5688 | })?; |
| 5689 | let (b_rate, b_color, _peak, b_rotation, b_pixel_aspect) = rates[b_source]; |
| 5690 | // The blended tail of a dissolve takes one picture per timeline |
| 5691 | // frame, so it never counts fields: `Field` is its `Frame`. |
| 5692 | let b_deint = frame_counting(span_deint(project, b_start, &entry.path)); |
| 5693 | let b_rate = crate::deinterlace::counted_rate(b_deint, b_rate); |
| 5694 | let b_mapper = tone[b_source].as_ref(); |
| 5695 | let b_remap = remap_into(Some(b_color), b_mapper.is_some(), out_color.matrix); |
| 5696 | Ok(Dissolve { |
| 5697 | window, |
| 5698 | kind: crate::transitions::kind_at(project, span.start), |
| 5699 | tail_start: span.len - window, |
| 5700 | decoder: if crate::is_audio(&entry.path) |
| 5701 | || project.composite_visualizer_at(b_start) & 1 != 0 |
| 5702 | { |
| 5703 | ClipDecoder::visualizer( |
| 5704 | &entry.path, |
| 5705 | entry.audio_stream, |
| 5706 | b_rate.source_at(b_in_frame), |
| 5707 | (meta.width, meta.height), |
| 5708 | meta.frame_rate, |
| 5709 | project.composite_visualizer_at(b_start), |
| 5710 | project.composite_viz_paint_at(b_start), |
| 5711 | )? |
| 5712 | } else { |
| 5713 | ClipDecoder::open_with(&entry.path, b_rate.source_at(b_in_frame), None, Some(&parked), ten_bit, b_deint)? |
| 5714 | }, |
| 5715 | mapper: b_mapper, |
| 5716 | remap: b_remap, |
| 5717 | grade: project.composite_color_at(b_start).copied(), |
| 5718 | transform: project |
| 5719 | .composite_transform_at(b_start) |
| 5720 | .copied() |
| 5721 | .unwrap_or_default(), |
| 5722 | rotation: b_rotation, |
| 5723 | pixel_aspect: b_pixel_aspect, |
| 5724 | canvas: Composer::new( |
| 5725 | meta.width, |
| 5726 | meta.height, |
| 5727 | project.composite_fit_at(b_start), |
| 5728 | ), |
| 5729 | rotated: (Vec::new(), Vec::new(), Vec::new()), |
| 5730 | stretched: (Vec::new(), Vec::new(), Vec::new()), |
| 5731 | graded: (Vec::new(), Vec::new(), Vec::new()), |
| 5732 | transformed: (Vec::new(), Vec::new(), Vec::new()), |
| 5733 | scratch16: Scratch16::default(), |
| 5734 | }) |
| 5735 | }, |
| 5736 | ) |
| 5737 | .transpose()?; |
| 5738 | // Timeline frames, taken a *source* frame at a time: at a rate other |
| 5739 | // than real time the two are not the same count, and the span says which |
| 5740 | // source frame each timeline frame shows ([`Speed::source_at`]) -- the |
| 5741 | // very frame playback is holding there, because the two conversions are |
| 5742 | // one floor/ceil pair (`speed_maps_both_ways`). A speed-up decodes the |
| 5743 | // frames it skips and drops them, because the pictures after them |
| 5744 | // reference those; a slow-down encodes the picture it is holding again |
| 5745 | // rather than decoding it twice. At real time `repeats` is 1 and `want` |
| 5746 | // advances by one, which is the loop this always ran. |
| 5747 | let mut done_here = 0u32; |
| 5748 | // Source frames already taken out of this span's decoder. |
| 5749 | let mut taken = 0u32; |
| 5750 | // The whole of the mapping, in the order it composes: the speed says |
| 5751 | // which of the clip's (timeline-rate) frames a timeline frame shows, |
| 5752 | // and the rate says which frame of the *file* that is -- counted from |
| 5753 | // the one the decoder was opened at. At real time and at the timeline's |
| 5754 | // own rate this is `Speed::source_at` and nothing else, which is the |
| 5755 | // walk a single-rate project has always taken. |
| 5756 | let opened_at = rate.source_at(in_frame); |
| 5757 | let source_at = |
| 5758 | |offset: u32| rate.source_at(in_frame + span.source_offset(offset)) - opened_at; |
| 5759 | while done_here < span.len { |
| 5760 | cancelled(shared)?; |
| 5761 | // The sound's failure is the export's, and it is heard the moment |
| 5762 | // it happens rather than after the last frame: a mix this engine |
| 5763 | // cannot decode used to refuse in seconds, before any picture was |
| 5764 | // encoded, and an overlapped pass that reported only at the end |
| 5765 | // would spend the whole encode first. Also where its measured |
| 5766 | // codec reaches the line on screen. |
| 5767 | if audio_job.is_finished() { |
| 5768 | late = join_audio(audio_job.take().expect("just seen to be there"))?; |
| 5769 | sound = late.as_ref().map(|track| track.copied); |
| 5770 | opus = late |
| 5771 | .as_ref() |
| 5772 | .is_some_and(|track| track.opus_pre_skip.is_some()); |
| 5773 | publish_seats(shared, seat, project, settings, sound, opus, false); |
| 5774 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!( |
| 5775 | "export audio: done {:.1} s into the picture", |
| 5776 | picture_started.elapsed().as_secs_f64() |
| 5777 | ); } |
| 5778 | feed_late_audio(&mut muxer, &late, &mut audio_fed)?; |
| 5779 | } |
| 5780 | let want = source_at(done_here); |
| 5781 | // A colour-keyed clip on the 10-bit path: this picture's grade is the |
| 5782 | // keys' value at its first timeline frame (a slowed picture repeated |
| 5783 | // over several frames keeps it). |
| 5784 | let grade = match keyed_color { |
| 5785 | Some(clip) => Some(crate::project::clip_color_at( |
| 5786 | clip, |
| 5787 | grade.unwrap_or_default(), |
| 5788 | span.start + done_here, |
| 5789 | )), |
| 5790 | None => grade, |
| 5791 | }; |
| 5792 | // How many timeline frames from here show that same picture: one at |
| 5793 | // real time, more when the clip is slowed or its file is slower |
| 5794 | // than the timeline. Encoded again rather than decoded twice. |
| 5795 | // A layered span composes every timeline frame, so it never repeats one. |
| 5796 | // ...nor does a lone clip whose effects move from frame to frame (a |
| 5797 | // shake); a static stack is drawn once and its picture held like any other. |
| 5798 | let repeats = match layered_here || fx_clip.is_some_and(|c| crate::effects::animated(&c.effects)) { |
| 5799 | true => 1, |
| 5800 | false => (done_here..span.len) |
| 5801 | .take_while(|&offset| source_at(offset) == want) |
| 5802 | .count() as u32, |
| 5803 | }; |
| 5804 | // The composed picture of a layered span, owned for this frame. |
| 5805 | let mut composed: Option<Planes> = None; |
| 5806 | let mut composed16: Option<Planes16> = None; |
| 5807 | let picture = match (&mut layers, &mut pictures) { |
| 5808 | (Some(stack), _) if layered_wide => match stack.picture16(span.start + done_here)? { |
| 5809 | Some(planes) => { |
| 5810 | let planes = composed16.insert(planes); |
| 5811 | Some(Frame::Wide( |
| 5812 | &planes.0[..], |
| 5813 | &planes.1[..], |
| 5814 | &planes.2[..], |
| 5815 | meta.width, |
| 5816 | meta.height, |
| 5817 | )) |
| 5818 | } |
| 5819 | None => None, |
| 5820 | }, |
| 5821 | (Some(stack), _) => match stack.picture(span.start + done_here)? { |
| 5822 | Some(planes) => { |
| 5823 | let planes = composed.insert(planes); |
| 5824 | Some(Frame::Pixels( |
| 5825 | &planes.0[..], |
| 5826 | &planes.1[..], |
| 5827 | &planes.2[..], |
| 5828 | meta.width, |
| 5829 | meta.height, |
| 5830 | )) |
| 5831 | } |
| 5832 | None => None, |
| 5833 | }, |
| 5834 | (None, Some(pictures)) => { |
| 5835 | let mut ran_out = false; |
| 5836 | while taken < want && !ran_out { |
| 5837 | ran_out = pictures.next()?.is_none(); |
| 5838 | taken += 1; |
| 5839 | } |
| 5840 | match ran_out { |
| 5841 | true => None, |
| 5842 | false => { |
| 5843 | taken += 1; |
| 5844 | pictures.next()? |
| 5845 | } |
| 5846 | } |
| 5847 | } |
| 5848 | (None, None) => { |
| 5849 | let (y, u, v, width, height) = black.picture(); |
| 5850 | Some(Frame::Pixels(y, u, v, width, height)) |
| 5851 | } |
| 5852 | }; |
| 5853 | let Some(frame) = picture else { |
| 5854 | // The file ran out before its clip did: this span's tail never |
| 5855 | // gets a picture -- and *only* this span's tail, because the |
| 5856 | // span loop this break sits in carries on with the spans after |
| 5857 | // it and writes every picture they have. Counted, not |
| 5858 | // swallowed: the bar reaches its end whatever happens, so |
| 5859 | // without this a truncated file reads as a whole one. The same |
| 5860 | // sentence `planned_subtitles` gives cues that hang past the |
| 5861 | // last picture, said after the fact here because how many |
| 5862 | // pictures a *file* holds is only known by opening it. |
| 5863 | // |
| 5864 | // `span.len > done_here` holds by the loop's own condition, and |
| 5865 | // the sum over every break is exactly `total - done` at the end |
| 5866 | // of the walk: the spans are disjoint and cover the whole edit. |
| 5867 | skipped += span.len - done_here; |
| 5868 | break; // source ran out early; the clip list outlives the file |
| 5869 | }; |
| 5870 | // A picture still on the GPU has nothing waiting for it here: the |
| 5871 | // span was opened that way only where none of what follows would |
| 5872 | // have touched a sample of it, so it is placed by nobody and goes |
| 5873 | // into the encoder as the buffer the decoder wrote. |
| 5874 | // A 10-bit picture goes to the encoder whole only where nothing on the |
| 5875 | // way touches a sample: no layer, dissolve, tone map, remap, grade, |
| 5876 | // transform, turn, stretch, caption or fade. Anything else composes at |
| 5877 | // 8 bits as it always did, narrowed here. |
| 5878 | let untouched = ten_bit |
| 5879 | && !layered_here |
| 5880 | && b.is_none() |
| 5881 | && mapper.is_none() |
| 5882 | && remap.is_none() |
| 5883 | && grade.is_none() |
| 5884 | && transform == TransformParams::default() |
| 5885 | && matches!(rotation, Rotation::None) |
| 5886 | && pixel_aspect.is_square() |
| 5887 | && burn |
| 5888 | .as_ref() |
| 5889 | .is_none_or(|b| b.cues.is_empty() && b.titles.is_empty()) |
| 5890 | && (done_here..done_here + repeats) |
| 5891 | .all(|off| picture_fade_at(project, span.start + off).is_none()); |
| 5892 | // A 10-bit export composes at 10 bits wherever the picture is touched at |
| 5893 | // all. The exceptions stay at 8 bits: a tone map (HDR), a turn or a |
| 5894 | // stretch, and a layered picture (composed per clip). |
| 5895 | let wide16 = ten_bit |
| 5896 | && (layered_wide || !layered_here) |
| 5897 | && !untouched; |
| 5898 | let frame = match frame { |
| 5899 | Frame::Wide(_, _, _, width, height) |
| 5900 | if !wide16 && !(untouched && width == meta.width && height == meta.height) => |
| 5901 | { |
| 5902 | narrowed(frame, &mut narrow_a) |
| 5903 | } |
| 5904 | other => other, |
| 5905 | }; |
| 5906 | // The picture at 10 bits, composed: a 10-bit one as it is, an 8-bit one widened. |
| 5907 | let placed16 = match (wide16, &frame) { |
| 5908 | (true, Frame::Wide(y, u, v, width, height)) => Some(place_picture16( |
| 5909 | y, |
| 5910 | u, |
| 5911 | v, |
| 5912 | *width, |
| 5913 | *height, |
| 5914 | rotation, |
| 5915 | pixel_aspect, |
| 5916 | grade, |
| 5917 | transform, |
| 5918 | remap.filter(|_| !layered_here), |
| 5919 | mapper, |
| 5920 | &mut scratch16, |
| 5921 | &mut canvas16, |
| 5922 | )), |
| 5923 | (true, Frame::Pixels(y, u, v, width, height)) => { |
| 5924 | widen_into(y, &mut widened_a.0); |
| 5925 | widen_into(u, &mut widened_a.1); |
| 5926 | widen_into(v, &mut widened_a.2); |
| 5927 | Some(place_picture16( |
| 5928 | &widened_a.0[..], |
| 5929 | &widened_a.1[..], |
| 5930 | &widened_a.2[..], |
| 5931 | *width, |
| 5932 | *height, |
| 5933 | rotation, |
| 5934 | pixel_aspect, |
| 5935 | grade, |
| 5936 | transform, |
| 5937 | remap.filter(|_| !layered_here), |
| 5938 | mapper, |
| 5939 | &mut scratch16, |
| 5940 | &mut canvas16, |
| 5941 | )) |
| 5942 | } |
| 5943 | _ => None, |
| 5944 | }; |
| 5945 | let placed = match frame { |
| 5946 | Frame::Dma(_) => None, |
| 5947 | // Encoded whole below, at 10 bits. |
| 5948 | Frame::Wide(..) => None, |
| 5949 | // Composed at 10 bits above. |
| 5950 | Frame::Pixels(..) if wide16 => None, |
| 5951 | // A layered picture is composed already, per clip: nothing here |
| 5952 | // places it again. |
| 5953 | Frame::Pixels(y, u, v, width, height) if layered_here => { |
| 5954 | Some((y, u, v, width, height)) |
| 5955 | } |
| 5956 | Frame::Pixels(y, u, v, width, height) => Some(place_picture( |
| 5957 | y, |
| 5958 | u, |
| 5959 | v, |
| 5960 | width, |
| 5961 | height, |
| 5962 | rotation, |
| 5963 | pixel_aspect, |
| 5964 | grade, |
| 5965 | transform, |
| 5966 | remap, |
| 5967 | mapper, |
| 5968 | &mut rotated, |
| 5969 | &mut stretched, |
| 5970 | &mut graded, |
| 5971 | &mut transformed, |
| 5972 | &mut canvas, |
| 5973 | )), |
| 5974 | }; |
| 5975 | // A lone clip's effects, drawn on its placed picture and laid over black. |
| 5976 | let (placed16, placed) = match fx_clip { |
| 5977 | None => (placed16, placed), |
| 5978 | Some(clip) => { |
| 5979 | let secs = f64::from(span.start + done_here) / meta.frame_rate; |
| 5980 | let src = crate::project::key_sample_pos(clip, span.start + done_here); |
| 5981 | let placed16 = placed16.map(|(y, u, v, w, h)| { |
| 5982 | fx16 = (y.to_vec(), u.to_vec(), v.to_vec()); |
| 5983 | effected(&clip.effects, &mut fx16, w, h, secs, src, out_color.matrix, &mut fx_scratch16); |
| 5984 | (&fx16.0[..], &fx16.1[..], &fx16.2[..], w, h) |
| 5985 | }); |
| 5986 | let placed = placed.map(|(y, u, v, w, h)| { |
| 5987 | fx8 = (y.to_vec(), u.to_vec(), v.to_vec()); |
| 5988 | effected(&clip.effects, &mut fx8, w, h, secs, src, out_color.matrix, &mut fx_scratch8); |
| 5989 | (&fx8.0[..], &fx8.1[..], &fx8.2[..], w, h) |
| 5990 | }); |
| 5991 | (placed16, placed) |
| 5992 | } |
| 5993 | }; |
| 5994 | // Once per timeline frame this source frame covers: one at real time |
| 5995 | // and faster, more when the clip is slowed -- the picture is already |
| 5996 | // graded and placed, so a held frame costs an encode and no decode. |
| 5997 | for r in 0..repeats { |
| 5998 | // Inside the window every *output* frame gets its own B |
| 5999 | // picture -- decoded fresh here rather than once for the |
| 6000 | // whole held A frame -- which is what makes a slowed A's |
| 6001 | // tail still ramp one weight per frame shown rather than one |
| 6002 | // per source frame. |
| 6003 | let in_window = b.as_ref().is_some_and(|d| done_here + r >= d.tail_start); |
| 6004 | let coded = match (&mut b, in_window) { |
| 6005 | (Some(d), true) if placed16.is_some() => { |
| 6006 | let (ay, au, av, aw, ah) = placed16.expect("checked by the guard"); |
| 6007 | let t = dissolve_weight(done_here + r - d.tail_start, d.window); |
| 6008 | let blended: Option<Planes16> = match d.decoder.next()? { |
| 6009 | // B's file ran out inside the window: A's own picture carries the frame. |
| 6010 | None => None, |
| 6011 | Some(b) => { |
| 6012 | // B at 10 bits: a 10-bit picture as it is, an 8-bit one widened. |
| 6013 | let (by, bu, bv, bw, bh): (&[u16], &[u16], &[u16], u32, u32) = match b { |
| 6014 | Frame::Wide(y, u, v, w, h) => (y, u, v, w, h), |
| 6015 | Frame::Pixels(y, u, v, w, h) => { |
| 6016 | widen_into(y, &mut widened_b.0); |
| 6017 | widen_into(u, &mut widened_b.1); |
| 6018 | widen_into(v, &mut widened_b.2); |
| 6019 | (&widened_b.0[..], &widened_b.1[..], &widened_b.2[..], w, h) |
| 6020 | } |
| 6021 | Frame::Dma(_) => unreachable!("b's decoder is never a DMA buffer"), |
| 6022 | }; |
| 6023 | let (y, u, v, _, _) = place_picture16( |
| 6024 | by, |
| 6025 | bu, |
| 6026 | bv, |
| 6027 | bw, |
| 6028 | bh, |
| 6029 | d.rotation, |
| 6030 | d.pixel_aspect, |
| 6031 | d.grade, |
| 6032 | d.transform, |
| 6033 | d.remap, |
| 6034 | d.mapper, |
| 6035 | &mut d.scratch16, |
| 6036 | &mut d.canvas, |
| 6037 | ); |
| 6038 | Some(crate::transitions::blend_planes( |
| 6039 | d.kind, |
| 6040 | (ay, au, av), |
| 6041 | (y, u, v), |
| 6042 | t, |
| 6043 | aw as usize, |
| 6044 | ah as usize, |
| 6045 | )) |
| 6046 | } |
| 6047 | }; |
| 6048 | let frame_at = span.start + done_here + r; |
| 6049 | let (y, u, v) = match &blended { |
| 6050 | Some(p) => borrow_planes(p), |
| 6051 | None => (ay, au, av), |
| 6052 | }; |
| 6053 | let faded = picture_fade_at(project, frame_at).map(|k| fade_planes((y, u, v), k)); |
| 6054 | let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes); |
| 6055 | let painted = burned16(&mut burn, frame_at, aw, ah, (y, u, v)); |
| 6056 | let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes); |
| 6057 | encoder.encode_wide(y, u, v, aw, ah)? |
| 6058 | } |
| 6059 | (Some(d), true) => { |
| 6060 | let (ay, au, av, aw, ah) = |
| 6061 | placed.expect("a dissolving span always decodes to pixels"); |
| 6062 | match d.decoder.next()?.map(|f| narrowed(f, &mut narrow_b)) { |
| 6063 | // B's file ran out inside the window: A's own |
| 6064 | // picture carries the frame rather than the |
| 6065 | // export losing it. |
| 6066 | None => { |
| 6067 | let frame_at = span.start + done_here + r; |
| 6068 | let faded = picture_fade_at(project, frame_at) |
| 6069 | .map(|k| fade_planes((ay, au, av), k)); |
| 6070 | let (ay, au, av) = |
| 6071 | faded.as_ref().map_or((ay, au, av), borrow_planes); |
| 6072 | let painted = burned(&mut burn, frame_at, aw, ah, (ay, au, av)); |
| 6073 | let (ay, au, av) = painted.as_ref().map_or((ay, au, av), borrow_planes); |
| 6074 | encoder.encode(ay, au, av, aw, ah, settings.intra_only)? |
| 6075 | } |
| 6076 | Some(Frame::Dma(_) | Frame::Wide(..)) => { |
| 6077 | unreachable!("b's decoder was opened with no DMA want and is narrowed") |
| 6078 | } |
| 6079 | Some(Frame::Pixels(by, bu, bv, bw, bh)) => { |
| 6080 | let (by, bu, bv, _, _) = place_picture( |
| 6081 | by, |
| 6082 | bu, |
| 6083 | bv, |
| 6084 | bw, |
| 6085 | bh, |
| 6086 | d.rotation, |
| 6087 | d.pixel_aspect, |
| 6088 | d.grade, |
| 6089 | d.transform, |
| 6090 | d.remap, |
| 6091 | d.mapper, |
| 6092 | &mut d.rotated, |
| 6093 | &mut d.stretched, |
| 6094 | &mut d.graded, |
| 6095 | &mut d.transformed, |
| 6096 | &mut d.canvas, |
| 6097 | ); |
| 6098 | let idx_in_window = done_here + r - d.tail_start; |
| 6099 | let t = dissolve_weight(idx_in_window, d.window); |
| 6100 | let (y, u, v) = crate::transitions::blend_planes( |
| 6101 | d.kind, |
| 6102 | (ay, au, av), |
| 6103 | (by, bu, bv), |
| 6104 | t, |
| 6105 | aw as usize, |
| 6106 | ah as usize, |
| 6107 | ); |
| 6108 | let frame_at = span.start + done_here + r; |
| 6109 | let faded = picture_fade_at(project, frame_at) |
| 6110 | .map(|k| fade_planes((&y[..], &u[..], &v[..]), k)); |
| 6111 | let (y, u, v) = |
| 6112 | faded.as_ref().map_or((&y[..], &u[..], &v[..]), borrow_planes); |
| 6113 | let painted = |
| 6114 | burned(&mut burn, frame_at, aw, ah, (y, u, v)); |
| 6115 | let (y, u, v) = |
| 6116 | painted.as_ref().map_or((y, u, v), borrow_planes); |
| 6117 | encoder.encode(y, u, v, aw, ah, settings.intra_only)? |
| 6118 | } |
| 6119 | } |
| 6120 | } |
| 6121 | _ => match (&frame, placed16) { |
| 6122 | (_, Some((y, u, v, width, height))) => { |
| 6123 | let frame_at = span.start + done_here + r; |
| 6124 | // A layered picture's fades were applied per clip in its stack. |
| 6125 | let faded = picture_fade_at(project, frame_at) |
| 6126 | .filter(|_| !layered_here) |
| 6127 | .map(|k| fade_planes((y, u, v), k)); |
| 6128 | let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes); |
| 6129 | let painted = burned16(&mut burn, frame_at, width, height, (y, u, v)); |
| 6130 | let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes); |
| 6131 | encoder.encode_wide(y, u, v, width, height)? |
| 6132 | } |
| 6133 | (Frame::Dma(dma), None) => encoder.encode_dma(dma, settings.intra_only)?, |
| 6134 | (Frame::Wide(y, u, v, width, height), None) => { |
| 6135 | encoder.encode_wide(y, u, v, *width, *height)? |
| 6136 | } |
| 6137 | (Frame::Pixels(..), None) => { |
| 6138 | let (y, u, v, width, height) = |
| 6139 | placed.expect("a picture with pixels was placed"); |
| 6140 | let frame_at = span.start + done_here + r; |
| 6141 | // A layered picture's fades were applied per clip in |
| 6142 | // its stack; the top clip's does not fade the frame. |
| 6143 | let faded = picture_fade_at(project, frame_at) |
| 6144 | .filter(|_| !layered_here) |
| 6145 | .map(|k| fade_planes((y, u, v), k)); |
| 6146 | let (y, u, v) = faded.as_ref().map_or((y, u, v), borrow_planes); |
| 6147 | let painted = burned(&mut burn, frame_at, width, height, (y, u, v)); |
| 6148 | let (y, u, v) = painted.as_ref().map_or((y, u, v), borrow_planes); |
| 6149 | encoder.encode(y, u, v, width, height, settings.intra_only)? |
| 6150 | } |
| 6151 | }, |
| 6152 | }; |
| 6153 | if let Some((au, key)) = coded { |
| 6154 | write_video( |
| 6155 | &mut muxer, |
| 6156 | out, |
| 6157 | meta, |
| 6158 | settings, |
| 6159 | container_colour, |
| 6160 | source_language.as_deref(), |
| 6161 | audio_params.as_ref(), |
| 6162 | &mut packets, |
| 6163 | &mut subs, |
| 6164 | au, |
| 6165 | key, |
| 6166 | ten_bit, |
| 6167 | )?; |
| 6168 | // Retried here rather than only where the mix lands: the |
| 6169 | // very first coded picture is what creates `muxer`, and a |
| 6170 | // mix that lands before it (a short film, or a slow first |
| 6171 | // frame) has nothing to hand it to until now. |
| 6172 | feed_late_audio(&mut muxer, &late, &mut audio_fed)?; |
| 6173 | inject_export_test_panic(out); |
| 6174 | } |
| 6175 | done += 1; |
| 6176 | // Forwards only: an audio pass still running beside this one |
| 6177 | // publishes its own share of [`AUDIO_BAND`], and a bar that |
| 6178 | // went backwards every time it did would be worse than one |
| 6179 | // that stood still. |
| 6180 | shared |
| 6181 | .progress |
| 6182 | .fetch_max(picture_progress(done, total), Ordering::Relaxed); |
| 6183 | } |
| 6184 | done_here += repeats; |
| 6185 | } |
| 6186 | } |
| 6187 | // The whole walk is over, so what it could not write is known to the frame |
| 6188 | // and is published once. `fetch_max` and not `fetch_add`, because a |
| 6189 | // hardware seat that died has the *whole* walk run again from its first |
| 6190 | // frame ([`start`]): the same project and the same picture counts, so a |
| 6191 | // second run must not double a number that is already on the line. |
| 6192 | shared.truncated.fetch_max(skipped, Ordering::Relaxed); |
| 6193 | while let Some((au, key)) = encoder.drain()? { |
| 6194 | write_video( |
| 6195 | &mut muxer, |
| 6196 | out, |
| 6197 | meta, |
| 6198 | settings, |
| 6199 | container_colour, |
| 6200 | source_language.as_deref(), |
| 6201 | audio_params.as_ref(), |
| 6202 | &mut packets, |
| 6203 | &mut subs, |
| 6204 | au, |
| 6205 | key, |
| 6206 | ten_bit, |
| 6207 | )?; |
| 6208 | } |
| 6209 | // Progress reads 100% from here on, but nothing is published yet: draining, |
| 6210 | // the audio pass and `finish` are all still cancellable. |
| 6211 | cancelled(shared)?; |
| 6212 | |
| 6213 | let Some(muxer) = muxer else { |
| 6214 | return Err("export produced no coded pictures".into()); |
| 6215 | }; |
| 6216 | // The mp4's audio and subtitle tracks after its picture -- the Matroska one |
| 6217 | // interleaved its own as it went and left `packets` and `subs` empty behind |
| 6218 | // it. The text last, so its samples are written knowing how long the picture |
| 6219 | // turned out to be. |
| 6220 | let muxer = match muxer { |
| 6221 | Muxer::Mp4(mut mp4) => { |
| 6222 | // The sound, collected where this file first needs it: it has been |
| 6223 | // mixing and encoding under the whole picture, and an mp4 declares |
| 6224 | // its audio track here rather than at the open precisely so that |
| 6225 | // could happen ([`Mp4Muxer::add_audio_track`]). |
| 6226 | let track = match audio_job.take() { |
| 6227 | Some(job) => { |
| 6228 | let track = join_audio(job)?; |
| 6229 | // The picture finished first and this waited for the |
| 6230 | // sound: the pair of stage lines is what says which of the |
| 6231 | // two an export is really bounded by. |
| 6232 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!( |
| 6233 | "export audio: waited for after {:.1} s of picture", |
| 6234 | picture_started.elapsed().as_secs_f64() |
| 6235 | ); } |
| 6236 | // ...and the line on screen finished with it. The loop above |
| 6237 | // publishes the measured codec the moment the pass lands |
| 6238 | // under the picture, but a picture that outran the mix never |
| 6239 | // reaches that branch -- and "working out the sound…" would |
| 6240 | // then be the last thing the card ever said about a track it |
| 6241 | // had long since written. |
| 6242 | publish_seats( |
| 6243 | shared, |
| 6244 | seat, |
| 6245 | project, |
| 6246 | settings, |
| 6247 | track.as_ref().map(|track| track.copied), |
| 6248 | track |
| 6249 | .as_ref() |
| 6250 | .is_some_and(|track| track.opus_pre_skip.is_some()), |
| 6251 | false, |
| 6252 | ); |
| 6253 | track |
| 6254 | } |
| 6255 | // `late` was already handed to `mp4` inside the picture loop |
| 6256 | // ([`feed_late_audio`]) unless the mix never landed there, in |
| 6257 | // which case it is still `None` and there was nothing to feed. |
| 6258 | None if audio_fed => None, |
| 6259 | None => late, |
| 6260 | }; |
| 6261 | if let Some(track) = &track { |
| 6262 | mp4.add_audio_track(¶ms_of(track))?; |
| 6263 | } |
| 6264 | for packet in track.into_iter().flat_map(|track| track.packets) { |
| 6265 | mp4.write_audio_packet(&packet.bytes)?; |
| 6266 | } |
| 6267 | mp4.set_faststart(settings.faststart); |
| 6268 | mp4.set_chapters(&settings.chapters)?; |
| 6269 | mp4.write_subtitles(&subs)?; |
| 6270 | Muxer::Mp4(mp4) |
| 6271 | } |
| 6272 | Muxer::Mov(mut mov) => { |
| 6273 | // The sound, PCM at the asked width, laid to the picture's length. |
| 6274 | if let Some(job) = pcm_job.take() |
| 6275 | && let Some((mut samples, rate, channels)) = join_pcm(job)? |
| 6276 | { |
| 6277 | let want = (f64::from(done) / meta.frame_rate * f64::from(rate)).round() as usize |
| 6278 | * usize::from(channels.max(1)); |
| 6279 | samples.resize(want, 0); |
| 6280 | mov.write_sound(&samples, rate, channels, prores_audio_bits(settings))?; |
| 6281 | } |
| 6282 | Muxer::Mov(mov) |
| 6283 | } |
| 6284 | muxer => muxer, |
| 6285 | }; |
| 6286 | cancelled(shared)?; |
| 6287 | muxer.finish()?; |
| 6288 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); |
| 6289 | Ok(()) |
| 6290 | } |
| 6291 | |
| 6292 | /// The cues a burn of track `pick` draws, on this timeline's clock: what the |
| 6293 | /// screen shows. Once a track is placed on a subtitle lane, its placements are |
| 6294 | /// the answer -- a cut sentence is gone, a trimmed or moved one sits where it |
| 6295 | /// was put, and a hidden lane draws nothing -- with each cue's words read from |
| 6296 | /// its palette track, so a retyped cue burns retyped. A track no lane places is |
| 6297 | /// drawn as the export writes it whole ([`timeline_cues`]), whatever else is |
| 6298 | /// placed, so a burn and a soft track of the same pick never disagree. |
| 6299 | /// |
| 6300 | /// `Err` for a pick that is not a track of the project. |
| 6301 | pub fn burn_cues(project: &Project, pick: usize, fps: f64) -> crate::Result<Vec<Cue>> { |
| 6302 | Ok(burn_cues_indexed(project, pick, fps)?.into_iter().map(|(_, cue)| cue).collect()) |
| 6303 | } |
| 6304 | |
| 6305 | fn burn_cues_indexed(project: &Project, pick: usize, fps: f64) -> crate::Result<Vec<(usize, Cue)>> { |
| 6306 | let track = project |
| 6307 | .subtitles() |
| 6308 | .get(pick) |
| 6309 | .ok_or_else(|| format!("burn_subtitles: no subtitle track {pick} in this project"))?; |
| 6310 | if !placed_tracks(project).contains(&pick) { |
| 6311 | return Ok(timeline_cues_indexed(project, track, fps)); |
| 6312 | } |
| 6313 | let mut cues: Vec<(usize, Cue)> = project |
| 6314 | .subtitle_lanes() |
| 6315 | .into_iter() |
| 6316 | .flat_map(|lane| project.sub_lane_cue_spans(lane, fps)) |
| 6317 | .filter(|s| s.track == pick) |
| 6318 | .filter_map(|s| { |
| 6319 | let c = track.cues.get(s.cue)?; |
| 6320 | Some((s.cue, Cue { |
| 6321 | start_us: s.start_us, |
| 6322 | end_us: s.end_us, |
| 6323 | text: c.text.clone(), |
| 6324 | image: c.image.clone(), |
| 6325 | words: crate::subtitle::map_words(&c.words, s.window, (s.start_us, s.end_us)), |
| 6326 | karaoke: crate::subtitle::map_karaoke(&c.karaoke, s.window, (s.start_us, s.end_us)), |
| 6327 | })) |
| 6328 | }) |
| 6329 | .collect(); |
| 6330 | cues.sort_by_key(|(_, c)| c.start_us); |
| 6331 | Ok(cues) |
| 6332 | } |
| 6333 | |
| 6334 | /// The index of the cue on screen at timeline frame `frame`, if one is: a cue |
| 6335 | /// is shown from the instant of its start up to, not including, its end, read |
| 6336 | /// off the frame's own start time the way [`timeline_cues`] times the frames. |
| 6337 | /// Cues with no text (a picture track's, or a blank line) show nothing. |
| 6338 | pub fn cue_on_screen(cues: &[Cue], frame: u32, fps: f64) -> Option<usize> { |
| 6339 | let t = (f64::from(frame) / fps * 1e6).round() as i64; |
| 6340 | cues.iter().position(|c| { |
| 6341 | c.image.is_none() && c.start_us <= t && t < c.end_us && !c.text.trim().is_empty() |
| 6342 | }) |
| 6343 | } |
| 6344 | |
| 6345 | /// The indices of every cue on screen at timeline frame `frame`, in the order |
| 6346 | /// `cues` lists them (start order from [`burn_cues`]). The same test as |
| 6347 | /// [`cue_on_screen`], for a burn that draws all the cues up at once. |
| 6348 | pub fn cues_on_screen(cues: &[Cue], frame: u32, fps: f64) -> Vec<usize> { |
| 6349 | let t = (f64::from(frame) / fps * 1e6).round() as i64; |
| 6350 | cues.iter() |
| 6351 | .enumerate() |
| 6352 | .filter(|(_, c)| { |
| 6353 | c.image.is_none() && c.start_us <= t && t < c.end_us && !c.text.trim().is_empty() |
| 6354 | }) |
| 6355 | .map(|(i, _)| i) |
| 6356 | .collect() |
| 6357 | } |
| 6358 | |
| 6359 | /// Three planes of one picture, owned: what a burned-in frame is encoded from. |
| 6360 | type Planes<T = u8> = (Vec<T>, Vec<T>, Vec<T>); |
| 6361 | |
| 6362 | /// A picture at 10 bits a sample ([`Enc::encode_wide`]). |
| 6363 | type Planes16 = Planes<u16>; |
| 6364 | |
| 6365 | fn borrow_planes<T>(p: &Planes<T>) -> (&[T], &[T], &[T]) { |
| 6366 | (&p.0, &p.1, &p.2) |
| 6367 | } |
| 6368 | |
| 6369 | /// What one export draws into its pictures: the titles, then the captions |
| 6370 | /// ([`ExportSettings::burn_subtitles`]). The overlay of the cue last drawn is |
| 6371 | /// kept, so a caption on screen for a second is laid out once rather than once |
| 6372 | /// a frame, and each title's overlay is kept the same way. |
| 6373 | struct Burn { |
| 6374 | cues: Vec<Cue>, |
| 6375 | style: TextStyle, |
| 6376 | fps: f64, |
| 6377 | full_range: bool, |
| 6378 | /// The cues drawn last, by index, with the size, the animation state |
| 6379 | /// ([`crate::captionanim::blocks_key`]) and the stacked overlay. |
| 6380 | last: Option<(Vec<usize>, u32, u32, u64, Overlay)>, |
| 6381 | titles: Vec<Title>, |
| 6382 | /// One per title, the overlay it was last drawn as, with what made it ([`TitleKey`]). |
| 6383 | title_last: Vec<Option<(TitleKey, Overlay)>>, |
| 6384 | native: Option<Native>, |
| 6385 | } |
| 6386 | |
| 6387 | struct Native { |
| 6388 | captions: crate::assrender::Captions, |
| 6389 | sources: Vec<usize>, |
| 6390 | } |
| 6391 | |
| 6392 | fn native_script(project: &Project, pick: usize, style: &TextStyle) -> Option<crate::assrender::Captions> { |
| 6393 | if !style.native { |
| 6394 | return None; |
| 6395 | } |
| 6396 | let track = project.subtitles().get(pick)?; |
| 6397 | if track.track.is_some() { |
| 6398 | return None; |
| 6399 | } |
| 6400 | crate::assrender::Captions::from_file(&track.path) |
| 6401 | } |
| 6402 | |
| 6403 | fn native_shown(cues: &[Cue], sources: &[usize], on: &[usize]) -> Vec<crate::assrender::Shown> { |
| 6404 | on.iter() |
| 6405 | .map(|&i| crate::assrender::Shown { |
| 6406 | event: sources[i], |
| 6407 | start_us: cues[i].start_us, |
| 6408 | end_us: cues[i].end_us, |
| 6409 | }) |
| 6410 | .collect() |
| 6411 | } |
| 6412 | |
| 6413 | /// What a title's overlay is made from: a frame's size, how much of its text shows and its |
| 6414 | /// motion. A title that does not move keeps the same key, so it is laid out once. |
| 6415 | #[derive(Clone, Debug, PartialEq)] |
| 6416 | struct TitleKey { |
| 6417 | width: u32, |
| 6418 | height: u32, |
| 6419 | size: u32, |
| 6420 | dx: i32, |
| 6421 | dy: i32, |
| 6422 | /// The letters drawn, or `None` for all of them. |
| 6423 | shown: Option<usize>, |
| 6424 | } |
| 6425 | |
| 6426 | /// What a title draws at one frame, as a key: its size, where it is moved and how much of its |
| 6427 | /// text shows, for a `width` x `height` picture. Preview and export both draw a title from this |
| 6428 | /// same motion ([`Title::motion_at`]), so the animation reads the same in both. |
| 6429 | fn title_key(title: &Title, motion: &Motion, width: u32, height: u32) -> TitleKey { |
| 6430 | let size = ((title.style.size as f32 * motion.scale).round() as u32) |
| 6431 | .clamp(crate::text::SIZE_RANGE.0, crate::text::SIZE_RANGE.1); |
| 6432 | TitleKey { |
| 6433 | width, |
| 6434 | height, |
| 6435 | size, |
| 6436 | dx: (motion.dx * width as f32).round() as i32, |
| 6437 | dy: (motion.dy * height as f32).round() as i32, |
| 6438 | shown: motion.revealed(&title.text).map(|s| s.ink), |
| 6439 | } |
| 6440 | } |
| 6441 | |
| 6442 | /// The overlay a title's key stands for: the whole text laid out in the key's size and moved, |
| 6443 | /// with the letters past its reveal left out of the drawing but not out of the layout. |
| 6444 | fn title_overlay(title: &Title, key: &TitleKey) -> Overlay { |
| 6445 | let style = TextStyle { size: key.size, ..title.style.clone() }; |
| 6446 | let lines: Vec<String> = title.text.split('\n').map(str::to_string).collect(); |
| 6447 | let mut ov = match key.shown { |
| 6448 | None => overlay(&style, key.width, key.height, &lines), |
| 6449 | Some(ink) => crate::text::overlay_revealed(&style, key.width, key.height, &lines, ink), |
| 6450 | }; |
| 6451 | if (key.dx, key.dy) != (0, 0) { |
| 6452 | ov = ov.moved(key.dx, key.dy); |
| 6453 | } |
| 6454 | ov |
| 6455 | } |
| 6456 | |
| 6457 | impl Burn { |
| 6458 | /// What the settings and the timeline ask drawn in, or `None` for a picture |
| 6459 | /// left alone. A pick that is not a track of the project is named, not ignored. |
| 6460 | fn new( |
| 6461 | project: &Project, |
| 6462 | settings: &ExportSettings, |
| 6463 | fps: f64, |
| 6464 | full_range: bool, |
| 6465 | ) -> crate::Result<Option<Self>> { |
| 6466 | let titles = project.titles().to_vec(); |
| 6467 | let (cues, style, native) = match &settings.burn_subtitles { |
| 6468 | Some((pick, style)) => { |
| 6469 | let (sources, cues): (Vec<usize>, Vec<Cue>) = burn_cues_indexed(project, *pick, fps)?.into_iter().unzip(); |
| 6470 | let native = native_script(project, *pick, style).map(|captions| Native { captions, sources }); |
| 6471 | (cues, style.clamped(), native) |
| 6472 | } |
| 6473 | None => (Vec::new(), TextStyle::default(), None), |
| 6474 | }; |
| 6475 | if cues.is_empty() && titles.is_empty() && settings.burn_subtitles.is_none() { |
| 6476 | return Ok(None); |
| 6477 | } |
| 6478 | Ok(Some(Self { |
| 6479 | cues, |
| 6480 | style, |
| 6481 | fps, |
| 6482 | full_range, |
| 6483 | last: None, |
| 6484 | title_last: vec![None; titles.len()], |
| 6485 | titles, |
| 6486 | native, |
| 6487 | })) |
| 6488 | } |
| 6489 | |
| 6490 | /// The picture at timeline frame `frame` with the titles on screen and the |
| 6491 | /// caption drawn in, or `None` where nothing is on screen and the planes go |
| 6492 | /// on untouched. |
| 6493 | fn paint( |
| 6494 | &mut self, |
| 6495 | frame: u32, |
| 6496 | width: u32, |
| 6497 | height: u32, |
| 6498 | planes: (&[u8], &[u8], &[u8]), |
| 6499 | ) -> Option<Planes> { |
| 6500 | let mut out: Option<Planes> = None; |
| 6501 | for (i, t) in self.titles.iter().enumerate() { |
| 6502 | let Some(motion) = t.motion_at(frame) else { |
| 6503 | continue; |
| 6504 | }; |
| 6505 | let alpha = motion.alpha; |
| 6506 | if alpha == 0 { |
| 6507 | continue; |
| 6508 | } |
| 6509 | let key = title_key(t, &motion, width, height); |
| 6510 | if !matches!(&self.title_last[i], Some((k, _)) if *k == key) { |
| 6511 | let ov = title_overlay(t, &key); |
| 6512 | self.title_last[i] = Some((key, ov)); |
| 6513 | } |
| 6514 | let Some((_, ov)) = &self.title_last[i] else { |
| 6515 | continue; |
| 6516 | }; |
| 6517 | let mut planes = out |
| 6518 | .take() |
| 6519 | .unwrap_or_else(|| (planes.0.to_vec(), planes.1.to_vec(), planes.2.to_vec())); |
| 6520 | if alpha == 255 { |
| 6521 | ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range); |
| 6522 | } else { |
| 6523 | ov.faded(alpha).blend_i420( |
| 6524 | &mut planes.0, |
| 6525 | &mut planes.1, |
| 6526 | &mut planes.2, |
| 6527 | self.full_range, |
| 6528 | ); |
| 6529 | } |
| 6530 | out = Some(planes); |
| 6531 | } |
| 6532 | let on = cues_on_screen(&self.cues, frame, self.fps); |
| 6533 | if let Some(native) = self.native.as_mut() { |
| 6534 | if !on.is_empty() { |
| 6535 | let shown = native_shown(&self.cues, &native.sources, &on); |
| 6536 | let t_us = (f64::from(frame) / self.fps * 1e6).round() as i64; |
| 6537 | let mut planes = out |
| 6538 | .take() |
| 6539 | .unwrap_or_else(|| (planes.0.to_vec(), planes.1.to_vec(), planes.2.to_vec())); |
| 6540 | native.captions.draw_i420( |
| 6541 | (&mut planes.0, &mut planes.1, &mut planes.2), |
| 6542 | (width, height), |
| 6543 | self.full_range, |
| 6544 | &shown, |
| 6545 | t_us, |
| 6546 | ); |
| 6547 | out = Some(planes); |
| 6548 | } |
| 6549 | return out; |
| 6550 | } |
| 6551 | if !on.is_empty() { |
| 6552 | // A static style is keyed by the cues alone, so a cache hit builds nothing. |
| 6553 | // A karaoke cue moves with the clock whatever the style, so it is planned too. |
| 6554 | let lit = on.iter().any(|&i| self.cues[i].real_karaoke().is_some()); |
| 6555 | let planned = (!self.style.caption.is_plain() || lit) |
| 6556 | .then(|| crate::captionanim::plan(&self.style, &self.cues, &on, frame, self.fps)); |
| 6557 | let key = planned.as_deref().map_or(0, crate::captionanim::blocks_key); |
| 6558 | let hit = matches!(&self.last, Some((i, w, h, k, _)) |
| 6559 | if i == &on && (*w, *h) == (width, height) && *k == key); |
| 6560 | if !hit { |
| 6561 | let blocks = planned.unwrap_or_else(|| { |
| 6562 | crate::captionanim::plan(&self.style, &self.cues, &on, frame, self.fps) |
| 6563 | }); |
| 6564 | let ov = overlay_blocks(&self.style, width, height, &blocks); |
| 6565 | self.last = Some((on, width, height, key, ov)); |
| 6566 | } |
| 6567 | if let Some((_, _, _, _, ov)) = self.last.as_ref() { |
| 6568 | let mut planes = out |
| 6569 | .take() |
| 6570 | .unwrap_or_else(|| (planes.0.to_vec(), planes.1.to_vec(), planes.2.to_vec())); |
| 6571 | ov.blend_i420(&mut planes.0, &mut planes.1, &mut planes.2, self.full_range); |
| 6572 | out = Some(planes); |
| 6573 | } |
| 6574 | } |
| 6575 | out |
| 6576 | } |
| 6577 | } |
| 6578 | |
| 6579 | /// [`Burn::paint`] through an optional burn: the picture as it is when there is |
| 6580 | /// no burn, and as it is with the caption drawn in when there is one. |
| 6581 | fn burned( |
| 6582 | burn: &mut Option<Burn>, |
| 6583 | frame: u32, |
| 6584 | width: u32, |
| 6585 | height: u32, |
| 6586 | planes: (&[u8], &[u8], &[u8]), |
| 6587 | ) -> Option<Planes> { |
| 6588 | burn.as_mut()?.paint(frame, width, height, planes) |
| 6589 | } |
| 6590 | |
| 6591 | /// A lone clip's effects stack drawn on its placed `w` x `h` picture in place, and |
| 6592 | /// the result laid over black where the stack keys, masks or blends it -- what the |
| 6593 | /// layered path draws for the same clip with nothing beneath ([`LayerStack::picture`]). |
| 6594 | #[allow(clippy::too_many_arguments)] |
| 6595 | fn effected<T: Sample>( |
| 6596 | effects: &[crate::effects::Effect], |
| 6597 | planes: &mut Planes<T>, |
| 6598 | w: u32, |
| 6599 | h: u32, |
| 6600 | secs: f64, |
| 6601 | src: f64, |
| 6602 | matrix: Matrix, |
| 6603 | scratch: &mut crate::effects::Scratch<T>, |
| 6604 | ) { |
| 6605 | let (w, h) = (w as usize, h as usize); |
| 6606 | let out = crate::effects::apply(effects, (&mut planes.0, &mut planes.1, &mut planes.2), w, h, secs, src, matrix, scratch); |
| 6607 | crate::effects::over_black((&mut planes.0, &mut planes.1, &mut planes.2), &out, matrix, w, h); |
| 6608 | } |
| 6609 | |
| 6610 | /// One 8-bit code at 10 bits, as the encoder upshifts it (`v << 2 | v >> 6`), so a |
| 6611 | /// widened black is the black of the 10-bit span. |
| 6612 | fn widen_code(v: u8) -> u16 { |
| 6613 | (u16::from(v) << 2) | (u16::from(v) >> 6) |
| 6614 | } |
| 6615 | |
| 6616 | /// [`widen_code`] over a plane, into `out`. |
| 6617 | fn widen_into(src: &[u8], out: &mut Vec<u16>) { |
| 6618 | out.clear(); |
| 6619 | out.extend(src.iter().map(|&v| widen_code(v))); |
| 6620 | } |
| 6621 | |
| 6622 | /// [`burned`] at 10 bits. A caption or a title is an 8-bit overlay, so the picture is |
| 6623 | /// narrowed for it; where the overlay changed a code, that code is written back |
| 6624 | /// widened, and every other code keeps its 10-bit value. |
| 6625 | fn burned16( |
| 6626 | burn: &mut Option<Burn>, |
| 6627 | frame: u32, |
| 6628 | width: u32, |
| 6629 | height: u32, |
| 6630 | planes: (&[u16], &[u16], &[u16]), |
| 6631 | ) -> Option<Planes16> { |
| 6632 | let burn = burn.as_mut()?; |
| 6633 | let narrow = |s: &[u16]| -> Vec<u8> { s.iter().map(|&c| (c >> 2) as u8).collect() }; |
| 6634 | let (ny, nu, nv) = (narrow(planes.0), narrow(planes.1), narrow(planes.2)); |
| 6635 | let painted = burn.paint(frame, width, height, (&ny[..], &nu[..], &nv[..]))?; |
| 6636 | let merge = |orig: &[u16], before: &[u8], after: &[u8]| -> Vec<u16> { |
| 6637 | orig.iter() |
| 6638 | .zip(before.iter().zip(after)) |
| 6639 | .map(|(&o, (&b, &a))| if a == b { o } else { widen_code(a) }) |
| 6640 | .collect() |
| 6641 | }; |
| 6642 | Some(( |
| 6643 | merge(planes.0, &ny, &painted.0[..]), |
| 6644 | merge(planes.1, &nu, &painted.1[..]), |
| 6645 | merge(planes.2, &nv, &painted.2[..]), |
| 6646 | )) |
| 6647 | } |
| 6648 | |
| 6649 | /// The 10-bit placement's scratch: the turn, the pixel-aspect stretch, the grade and the |
| 6650 | /// transform each want a buffer the planes come back borrowed from. |
| 6651 | #[derive(Default)] |
| 6652 | struct Scratch16 { |
| 6653 | turned: Planes16, |
| 6654 | stretched: Planes16, |
| 6655 | graded: Planes16, |
| 6656 | transformed: Planes16, |
| 6657 | } |
| 6658 | |
| 6659 | /// [`place_picture`] at 10 bits: the pixel aspect, the display turn, the tone map, the grade, |
| 6660 | /// the matrix and range remap and the transform, all on 10-bit samples, in the 8-bit order. |
| 6661 | #[expect(clippy::too_many_arguments, reason = "one span's whole 10-bit picture path")] |
| 6662 | fn place_picture16<'a>( |
| 6663 | y: &'a [u16], |
| 6664 | u: &'a [u16], |
| 6665 | v: &'a [u16], |
| 6666 | width: u32, |
| 6667 | height: u32, |
| 6668 | rotation: Rotation, |
| 6669 | pixel_aspect: crate::demux::PixelAspect, |
| 6670 | grade: Option<crate::color::ColorParams>, |
| 6671 | transform: TransformParams, |
| 6672 | remap: Option<Remap>, |
| 6673 | mapper: Option<&ToneMapper>, |
| 6674 | scratch: &'a mut Scratch16, |
| 6675 | canvas: &'a mut Composer, |
| 6676 | ) -> (&'a [u16], &'a [u16], &'a [u16], u32, u32) { |
| 6677 | let Scratch16 { turned, stretched, graded, transformed } = scratch; |
| 6678 | let (y, u, v, width, height) = if pixel_aspect.is_square() { |
| 6679 | (y, u, v, width, height) |
| 6680 | } else { |
| 6681 | let display_width = pixel_aspect.width_factor(width); |
| 6682 | let (dcw, dch) = (display_width.div_ceil(2) as usize, height.div_ceil(2) as usize); |
| 6683 | stretched.0.resize(display_width as usize * height as usize, 0); |
| 6684 | stretched.1.resize(dcw * dch, 0); |
| 6685 | stretched.2.resize(dcw * dch, 0); |
| 6686 | crate::scale::scale_i420( |
| 6687 | y, |
| 6688 | u, |
| 6689 | v, |
| 6690 | width as usize, |
| 6691 | height as usize, |
| 6692 | &mut stretched.0, |
| 6693 | &mut stretched.1, |
| 6694 | &mut stretched.2, |
| 6695 | display_width as usize, |
| 6696 | height as usize, |
| 6697 | ); |
| 6698 | (&stretched.0[..], &stretched.1[..], &stretched.2[..], display_width, height) |
| 6699 | }; |
| 6700 | let (y, u, v, width, height) = match rotation.is_none() { |
| 6701 | true => (y, u, v, width, height), |
| 6702 | false => { |
| 6703 | let (w, h) = crate::scale::rotate_i420_90s_into(y, u, v, width, height, rotation.steps(), turned); |
| 6704 | (&turned.0[..], &turned.1[..], &turned.2[..], w, h) |
| 6705 | } |
| 6706 | }; |
| 6707 | let params = grade.filter(|p| !p.is_identity()); |
| 6708 | let (y, u, v) = match (params, remap, mapper) { |
| 6709 | (None, None, None) => (y, u, v), |
| 6710 | (params, remap, mapper) => { |
| 6711 | let (gy, gu, gv) = graded; |
| 6712 | gy.clear(); |
| 6713 | gy.extend_from_slice(y); |
| 6714 | gu.clear(); |
| 6715 | gu.extend_from_slice(u); |
| 6716 | gv.clear(); |
| 6717 | gv.extend_from_slice(v); |
| 6718 | if let Some(mapper) = mapper { |
| 6719 | mapper.map16(gy, gu, gv, width as usize, height as usize); |
| 6720 | } |
| 6721 | if let Some(params) = params { |
| 6722 | crate::color::apply_yuv_wide(¶ms, gy, gu, gv, width as usize, remap.is_some_and(|r| r.limit)); |
| 6723 | } |
| 6724 | if let Some(remap) = remap { |
| 6725 | if remap.limit { |
| 6726 | crate::colorspace::limit_range::<u16>(gy, gu, gv); |
| 6727 | } |
| 6728 | crate::colorspace::remap::<u16>(remap.from, remap.to, gy, gu, gv, width as usize); |
| 6729 | } |
| 6730 | (&gy[..], &gu[..], &gv[..]) |
| 6731 | } |
| 6732 | }; |
| 6733 | if transform.is_identity() { |
| 6734 | canvas.place_wide(y, u, v, width, height) |
| 6735 | } else { |
| 6736 | let (py, pu, pv, w, h) = canvas.place_transformed_wide(y, u, v, width, height, &transform); |
| 6737 | *transformed = (py, pu, pv); |
| 6738 | (&transformed.0[..], &transformed.1[..], &transformed.2[..], w, h) |
| 6739 | } |
| 6740 | } |
| 6741 | |
| 6742 | /// One decoded picture turned, graded, tone-mapped, remapped and placed on the |
| 6743 | /// canvas -- everything between a source's own samples and the ones an encoder |
| 6744 | /// is fed, which is exactly the work a zero-copy span has none of. |
| 6745 | /// |
| 6746 | /// `rotation` first, before the grade: it is the file's own display matrix, the |
| 6747 | /// turn a player would make before showing the picture at all, and everything |
| 6748 | /// after this -- the grade, the letterbox, the encoder -- is about the picture |
| 6749 | /// as it is *meant* to be seen. `turned`, `graded` and `canvas` are the span's |
| 6750 | /// scratch: the planes come back borrowed from one of them, or from the picture |
| 6751 | /// itself where not a byte was touched. |
| 6752 | #[expect(clippy::too_many_arguments, reason = "one span's whole picture path")] |
| 6753 | fn place_picture<'a>( |
| 6754 | y: &'a [u8], |
| 6755 | u: &'a [u8], |
| 6756 | v: &'a [u8], |
| 6757 | width: u32, |
| 6758 | height: u32, |
| 6759 | rotation: Rotation, |
| 6760 | pixel_aspect: crate::demux::PixelAspect, |
| 6761 | grade: Option<crate::color::ColorParams>, |
| 6762 | transform: TransformParams, |
| 6763 | remap: Option<Remap>, |
| 6764 | mapper: Option<&ToneMapper>, |
| 6765 | turned: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 6766 | stretched: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 6767 | graded: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 6768 | transformed: &'a mut (Vec<u8>, Vec<u8>, Vec<u8>), |
| 6769 | canvas: &'a mut Composer, |
| 6770 | ) -> (&'a [u8], &'a [u8], &'a [u8], u32, u32) { |
| 6771 | // The pixel aspect, applied exactly once -- the same single conversion to |
| 6772 | // the square-pixel raster the decode funnel makes, in the same order |
| 6773 | // (stretch the coded width, *then* turn, [`crate::decode::Render::frame`]'s |
| 6774 | // comment carries the 1440x1440 failure the other order produces). A |
| 6775 | // square-pixel file -- every file whose samples are one to one -- borrows |
| 6776 | // the planes through. |
| 6777 | let (y, u, v, width, height) = if pixel_aspect.is_square() { |
| 6778 | (y, u, v, width, height) |
| 6779 | } else { |
| 6780 | let display_width = pixel_aspect.width_factor(width); |
| 6781 | let (dcw, dch) = ( |
| 6782 | display_width.div_ceil(2) as usize, |
| 6783 | height.div_ceil(2) as usize, |
| 6784 | ); |
| 6785 | stretched |
| 6786 | .0 |
| 6787 | .resize(display_width as usize * height as usize, 0); |
| 6788 | stretched.1.resize(dcw * dch, 0); |
| 6789 | stretched.2.resize(dcw * dch, 0); |
| 6790 | crate::scale::scale_i420( |
| 6791 | y, |
| 6792 | u, |
| 6793 | v, |
| 6794 | width as usize, |
| 6795 | height as usize, |
| 6796 | &mut stretched.0, |
| 6797 | &mut stretched.1, |
| 6798 | &mut stretched.2, |
| 6799 | display_width as usize, |
| 6800 | height as usize, |
| 6801 | ); |
| 6802 | ( |
| 6803 | &stretched.0[..], |
| 6804 | &stretched.1[..], |
| 6805 | &stretched.2[..], |
| 6806 | display_width, |
| 6807 | height, |
| 6808 | ) |
| 6809 | }; |
| 6810 | // The file's own turn, taken exactly as playback's decode funnel takes it |
| 6811 | // ([`crate::decode`]): a phone's portrait video is landscape in the file, |
| 6812 | // and the encoder must be fed what the preview showed. A file that states |
| 6813 | // no turn skips this entirely -- the planes go on borrowed. |
| 6814 | let (y, u, v, width, height) = match rotation.is_none() { |
| 6815 | true => (y, u, v, width, height), |
| 6816 | false => { |
| 6817 | let (w, h) = crate::scale::rotate_i420_90s_into( |
| 6818 | y, |
| 6819 | u, |
| 6820 | v, |
| 6821 | width, |
| 6822 | height, |
| 6823 | rotation.steps(), |
| 6824 | turned, |
| 6825 | ); |
| 6826 | (&turned.0[..], &turned.1[..], &turned.2[..], w, h) |
| 6827 | } |
| 6828 | }; |
| 6829 | // The planes are borrowed from the decoder (and `Black::picture` hands the |
| 6830 | // same slice as both u and v), so a grade cannot be applied in place: it |
| 6831 | // goes onto a copy, which the encoder then reads instead. |
| 6832 | let params = grade.filter(|p| !p.is_identity()); |
| 6833 | let (y, u, v) = match (params, remap, mapper) { |
| 6834 | (None, None, None) => (y, u, v), |
| 6835 | (params, remap, mapper) => { |
| 6836 | let (gy, gu, gv) = graded; |
| 6837 | gy.clear(); |
| 6838 | gy.extend_from_slice(y); |
| 6839 | gu.clear(); |
| 6840 | gu.extend_from_slice(u); |
| 6841 | gv.clear(); |
| 6842 | gv.extend_from_slice(v); |
| 6843 | // Tone-map first, so the grade is applied to the SDR picture the |
| 6844 | // canvas showed and not to HDR codes; then remap the graded result. |
| 6845 | // The order playback renders in, and the only order in which |
| 6846 | // preview and export agree. |
| 6847 | if let Some(mapper) = mapper { |
| 6848 | mapper.map(gy, gu, gv, width as usize, height as usize); |
| 6849 | } |
| 6850 | if let Some(params) = params { |
| 6851 | crate::color::apply_yuv(¶ms, gy, gu, gv, width as usize, remap.is_some_and(|r| r.limit)); |
| 6852 | } |
| 6853 | if let Some(remap) = remap { |
| 6854 | // Range before matrix: the matrix arithmetic is written for limited |
| 6855 | // codes, so a full-range picture is brought into that span first. |
| 6856 | if remap.limit { |
| 6857 | crate::colorspace::limit_range(gy, gu, gv); |
| 6858 | } |
| 6859 | crate::colorspace::remap(remap.from, remap.to, gy, gu, gv, width as usize); |
| 6860 | } |
| 6861 | (&gy[..], &gu[..], &gv[..]) |
| 6862 | } |
| 6863 | }; |
| 6864 | // Grade first, place second: the grade is the clip's own pixels and the |
| 6865 | // bars around them are not the clip (see `scale::Composer`). |
| 6866 | if transform.is_identity() { |
| 6867 | canvas.place(y, u, v, width, height) |
| 6868 | } else { |
| 6869 | let (py, pu, pv, w, h) = canvas.place_transformed(y, u, v, width, height, &transform); |
| 6870 | *transformed = (py, pu, pv); |
| 6871 | ( |
| 6872 | &transformed.0[..], |
| 6873 | &transformed.1[..], |
| 6874 | &transformed.2[..], |
| 6875 | w, |
| 6876 | h, |
| 6877 | ) |
| 6878 | } |
| 6879 | } |
| 6880 | |
| 6881 | /// How a span's samples are rewritten on the way into a file whose own matrix is |
| 6882 | /// `to` and whose range is limited ([`ColorDescription::output`]): the matrix they |
| 6883 | /// are coded against, and whether they span the full byte and so need scaling |
| 6884 | /// into the limited span first ([`crate::colorspace::limit_range`]). |
| 6885 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 6886 | struct Remap { |
| 6887 | from: Matrix, |
| 6888 | to: Matrix, |
| 6889 | limit: bool, |
| 6890 | } |
| 6891 | |
| 6892 | /// What [`place_picture`] rewrites a span's samples by -- `None` when they are |
| 6893 | /// already coded against the output's matrix and span its range, and for a gap, |
| 6894 | /// whose 16/128/128 black is black in every matrix here. |
| 6895 | /// |
| 6896 | /// `toned` says the tone map ran on this span: it hands back BT.709 SDR whatever |
| 6897 | /// the source was coded as, so an HDR clip is never *also* given the matrix |
| 6898 | /// treatment its BT.2020 tag would ask for -- one conversion or the other, never |
| 6899 | /// both on one frame -- while a tone-mapped clip on a canvas below 720 lines |
| 6900 | /// still takes its 709 -> 601 step. It is also limited range already, so only an |
| 6901 | /// untouched full-range source is scaled here. |
| 6902 | fn remap_into(color: Option<ColorDescription>, toned: bool, out: Matrix) -> Option<Remap> { |
| 6903 | let from = match toned { |
| 6904 | true => Matrix::Bt709, |
| 6905 | false => color?.matrix, |
| 6906 | }; |
| 6907 | let limit = !toned && color?.full_range; |
| 6908 | (from != out || limit).then_some(Remap { |
| 6909 | from, |
| 6910 | to: out, |
| 6911 | limit, |
| 6912 | }) |
| 6913 | } |
| 6914 | |
| 6915 | /// The picture at timeline `frame`, composed the way [`run`] composes it: the |
| 6916 | /// same span and source frame, placed by [`place_picture`] (turn, pixel aspect, |
| 6917 | /// grade, transform, tone map, fit), dissolved into its successor over the |
| 6918 | /// tail window, and written as the BGRA picture the encoder would have been |
| 6919 | /// given. A gap is black. Visualizer and still clips take the same decoders |
| 6920 | /// export does. |
| 6921 | /// |
| 6922 | /// The output is the project's resolution scaled to fit a `width` x `height` |
| 6923 | /// box at the project's aspect (so a 16:9 project asked for 640x480 comes back |
| 6924 | /// 640x360). Each call opens its own decoder for the one source frame it needs, |
| 6925 | /// so it costs a decoder start; it is for the frame an agent asks for, not a |
| 6926 | /// sequence. |
| 6927 | pub fn compose_at( |
| 6928 | project: &Project, |
| 6929 | meta: &VideoMeta, |
| 6930 | frame: u32, |
| 6931 | width: u32, |
| 6932 | height: u32, |
| 6933 | ) -> crate::Result<crate::decode::Frame> { |
| 6934 | compose_at_with(project, meta, frame, width, height, None) |
| 6935 | } |
| 6936 | |
| 6937 | /// [`compose_at`] with every clip's grade taken off (its colour, its keys and |
| 6938 | /// its LUT): the picture as shot, which is the preview's "before" side and the |
| 6939 | /// frame Auto reads. A copy of the timeline is graded-off, so `project` is left |
| 6940 | /// as it is; nothing here is exported. Sequences a compound clip plays keep |
| 6941 | /// their own grades. |
| 6942 | pub fn compose_ungraded_at(project: &Project, meta: &VideoMeta, frame: u32, width: u32, height: u32) -> crate::Result<crate::decode::Frame> { |
| 6943 | let mut plain = project.clone(); |
| 6944 | for lane in plain.lanes() { |
| 6945 | for idx in 0..plain.lane(lane).len() { |
| 6946 | if !plain.color_keys_of(lane, idx).is_empty() { |
| 6947 | plain.set_color_keys(lane, idx, Vec::new()); |
| 6948 | } |
| 6949 | plain.set_color(lane, idx, None); |
| 6950 | } |
| 6951 | } |
| 6952 | compose_at(&plain, meta, frame, width, height) |
| 6953 | } |
| 6954 | |
| 6955 | /// [`compose_at`] with captions drawn in: `burn` is the subtitle track's index |
| 6956 | /// in [`Project::subtitles`] and the style, as [`ExportSettings::burn_subtitles`] |
| 6957 | /// takes them, and the cue on screen at `frame` is drawn over the output at its |
| 6958 | /// own size. `None` is exactly [`compose_at`]. |
| 6959 | pub fn compose_at_with( |
| 6960 | project: &Project, |
| 6961 | meta: &VideoMeta, |
| 6962 | frame: u32, |
| 6963 | width: u32, |
| 6964 | height: u32, |
| 6965 | burn: Option<(usize, TextStyle)>, |
| 6966 | ) -> crate::Result<crate::decode::Frame> { |
| 6967 | let end = project.media_frames(); |
| 6968 | if frame >= end { |
| 6969 | return Err(format!("frame {frame} is past the end of the timeline ({end} frames)").into()); |
| 6970 | } |
| 6971 | if width == 0 || height == 0 { |
| 6972 | return Err("compose_at: the output size must be non-zero".into()); |
| 6973 | } |
| 6974 | let out = ColorDescription::output_sized(meta.width, meta.height); |
| 6975 | let span = export_spans(project, None) |
| 6976 | .into_iter() |
| 6977 | .find(|s| s.start <= frame && frame - s.start < s.len); |
| 6978 | let layered = layered_at(project, frame); |
| 6979 | let (y, u, v) = match span { |
| 6980 | // Two or more clips cover the frame: each is decoded at this frame and |
| 6981 | // composed bottom to top, exactly as the export composes it. |
| 6982 | _ if layered => { |
| 6983 | let stack = stack_at(project, frame); |
| 6984 | let mut layers = LayerStack::open(project, meta, &stack, out.matrix, None, None)?; |
| 6985 | layers |
| 6986 | .picture(frame)? |
| 6987 | .ok_or_else(|| -> crate::Error { |
| 6988 | format!("compose_at: a clip ends before frame {frame}").into() |
| 6989 | })? |
| 6990 | } |
| 6991 | Some(s) if s.from.is_some() => { |
| 6992 | let (source, in_frame) = s.from.expect("checked above"); |
| 6993 | let offset = frame - s.start; |
| 6994 | let mut a = placed_info(project, meta, source)?; |
| 6995 | let deint = span_deint(project, s.start, &a.path); |
| 6996 | a.rate = crate::deinterlace::counted_rate(deint, a.rate); |
| 6997 | let source_frame = a.rate.source_at(s.source_at(in_frame, offset)); |
| 6998 | let (ay, au, av) = picture_at(project, meta, &a, source_frame, s.start, out.matrix, deint)?; |
| 6999 | match dissolve_window(project, &s) { |
| 7000 | Some((b_source, b_in, window, b_start)) |
| 7001 | if offset >= s.len.saturating_sub(window) => |
| 7002 | { |
| 7003 | let k = offset - (s.len - window); |
| 7004 | let mut b = placed_info(project, meta, b_source)?; |
| 7005 | let b_deint = frame_counting(span_deint(project, b_start, &b.path)); |
| 7006 | b.rate = crate::deinterlace::counted_rate(b_deint, b.rate); |
| 7007 | let b_frame = b.rate.source_at(b_in) + k; |
| 7008 | let (by, bu, bv) = picture_at(project, meta, &b, b_frame, b_start, out.matrix, b_deint)?; |
| 7009 | crate::transitions::blend_planes( |
| 7010 | crate::transitions::kind_at(project, s.start), |
| 7011 | (&ay, &au, &av), |
| 7012 | (&by, &bu, &bv), |
| 7013 | dissolve_weight(k, window), |
| 7014 | meta.width as usize, |
| 7015 | meta.height as usize, |
| 7016 | ) |
| 7017 | } |
| 7018 | _ => (ay, au, av), |
| 7019 | } |
| 7020 | } |
| 7021 | _ => { |
| 7022 | let (w, h) = (meta.width as usize, meta.height as usize); |
| 7023 | ( |
| 7024 | vec![16; w * h], |
| 7025 | vec![128; w.div_ceil(2) * h.div_ceil(2)], |
| 7026 | vec![128; w.div_ceil(2) * h.div_ceil(2)], |
| 7027 | ) |
| 7028 | } |
| 7029 | }; |
| 7030 | // A layered picture's fades were applied per clip inside its stack. |
| 7031 | let (y, u, v) = match picture_fade_at(project, frame).filter(|_| !layered) { |
| 7032 | Some(k) => fade_planes((&y, &u, &v), k), |
| 7033 | None => (y, u, v), |
| 7034 | }; |
| 7035 | let bgra = |
| 7036 | crate::convert::i420_to_bgra(&out, &y, &u, &v, meta.width as usize, meta.height as usize); |
| 7037 | let (tw, th) = fit_box(meta.width, meta.height, width, height); |
| 7038 | let mut bgra = if (tw, th) == (meta.width, meta.height) { |
| 7039 | bgra |
| 7040 | } else { |
| 7041 | resize_bgra(&bgra, meta.width, meta.height, tw, th) |
| 7042 | }; |
| 7043 | // The titles, then the caption, drawn at the size the caller gets, so their |
| 7044 | // size reads the same whatever the output box was asked for. |
| 7045 | for title in project.titles() { |
| 7046 | let Some(motion) = title.motion_at(frame) else { |
| 7047 | continue; |
| 7048 | }; |
| 7049 | let alpha = motion.alpha; |
| 7050 | if alpha == 0 { |
| 7051 | continue; |
| 7052 | } |
| 7053 | let ov = title_overlay(title, &title_key(title, &motion, tw, th)); |
| 7054 | if alpha == 255 { |
| 7055 | ov.blend_bgra(&mut bgra); |
| 7056 | } else { |
| 7057 | ov.faded(alpha).blend_bgra(&mut bgra); |
| 7058 | } |
| 7059 | } |
| 7060 | if let Some((pick, style)) = burn { |
| 7061 | let (sources, cues): (Vec<usize>, Vec<Cue>) = burn_cues_indexed(project, pick, meta.frame_rate)?.into_iter().unzip(); |
| 7062 | let on = cues_on_screen(&cues, frame, meta.frame_rate); |
| 7063 | match native_script(project, pick, &style).map(|c| c.for_video_height(meta.height)) { |
| 7064 | Some(mut captions) => { |
| 7065 | let shown = native_shown(&cues, &sources, &on); |
| 7066 | let t_us = (f64::from(frame) / meta.frame_rate * 1e6).round() as i64; |
| 7067 | captions.draw_bgra(&mut bgra, (tw, th), &shown, t_us); |
| 7068 | } |
| 7069 | None if !on.is_empty() => { |
| 7070 | let style = style.clamped(); |
| 7071 | let blocks = crate::captionanim::plan(&style, &cues, &on, frame, meta.frame_rate); |
| 7072 | overlay_blocks(&style, tw, th, &blocks).blend_bgra(&mut bgra); |
| 7073 | } |
| 7074 | None => {} |
| 7075 | } |
| 7076 | } |
| 7077 | Ok(crate::decode::Frame { |
| 7078 | index: frame, |
| 7079 | width: tw, |
| 7080 | height: th, |
| 7081 | bgra, |
| 7082 | }) |
| 7083 | } |
| 7084 | |
| 7085 | /// A source as [`run`] reads it for placement: its path and audio stream, its |
| 7086 | /// rate against the timeline, its colour, the tone map its curve asks for, and |
| 7087 | /// its display-matrix turn and pixel aspect. |
| 7088 | struct Placed { |
| 7089 | path: PathBuf, |
| 7090 | stream: usize, |
| 7091 | rate: Rate, |
| 7092 | color: ColorDescription, |
| 7093 | mapper: Option<ToneMapper>, |
| 7094 | rotation: Rotation, |
| 7095 | pixel_aspect: crate::demux::PixelAspect, |
| 7096 | } |
| 7097 | |
| 7098 | /// The deinterlace setting of the clip the composite shows at `frame`, as it |
| 7099 | /// applies to `path` (`Frame` for anything but interlaced H.264). |
| 7100 | fn span_deint(project: &Project, frame: u32, path: &Path) -> Deinterlace { |
| 7101 | let mode = project |
| 7102 | .composite_clip_at(frame) |
| 7103 | .map_or(Deinterlace::Frame, |(lane, idx)| project.deinterlace_of(lane, idx)); |
| 7104 | crate::deinterlace::effective(mode, path) |
| 7105 | } |
| 7106 | |
| 7107 | /// `Field` counts two pictures a frame, which a picture-per-timeline-frame reader |
| 7108 | /// cannot follow: it takes `Frame` (the same first field at the file's own rate). |
| 7109 | fn frame_counting(mode: Deinterlace) -> Deinterlace { |
| 7110 | if mode == Deinterlace::Field { Deinterlace::Frame } else { mode } |
| 7111 | } |
| 7112 | |
| 7113 | fn placed_info(project: &Project, meta: &VideoMeta, source: usize) -> crate::Result<Placed> { |
| 7114 | let sources = project.sources(); |
| 7115 | let entry = sources |
| 7116 | .get(source) |
| 7117 | .ok_or_else(|| format!("clip names source {source} of {}", sources.len()))?; |
| 7118 | let (rate, color, peak, rotation, pixel_aspect) = source_rate(&entry.path, meta.frame_rate); |
| 7119 | let mapper = match color.transfer { |
| 7120 | Transfer::Sdr => None, |
| 7121 | Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, project.tone(), peak)), |
| 7122 | Transfer::Hlg => Some(ToneMapper::new( |
| 7123 | tonemap::Transfer::Hlg, |
| 7124 | project.tone(), |
| 7125 | peak, |
| 7126 | )), |
| 7127 | }; |
| 7128 | Ok(Placed { |
| 7129 | path: entry.path.clone(), |
| 7130 | stream: entry.audio_stream, |
| 7131 | rate, |
| 7132 | color, |
| 7133 | mapper, |
| 7134 | rotation, |
| 7135 | pixel_aspect, |
| 7136 | }) |
| 7137 | } |
| 7138 | |
| 7139 | /// One source picture at `source_frame`, placed as [`run`] places it, as owned |
| 7140 | /// planes at the project's size. `key` is the timeline frame whose grade, |
| 7141 | /// transform, fit and visualizer state apply. |
| 7142 | fn picture_at( |
| 7143 | project: &Project, |
| 7144 | meta: &VideoMeta, |
| 7145 | info: &Placed, |
| 7146 | source_frame: u32, |
| 7147 | key: u32, |
| 7148 | out: Matrix, |
| 7149 | deint: Deinterlace, |
| 7150 | ) -> crate::Result<(Vec<u8>, Vec<u8>, Vec<u8>)> { |
| 7151 | let flags = project.composite_visualizer_at(key); |
| 7152 | let mut decoder = if crate::is_audio(&info.path) || flags & 1 != 0 { |
| 7153 | ClipDecoder::visualizer( |
| 7154 | &info.path, |
| 7155 | info.stream, |
| 7156 | source_frame, |
| 7157 | (meta.width, meta.height), |
| 7158 | meta.frame_rate, |
| 7159 | flags, |
| 7160 | project.composite_viz_paint_at(key), |
| 7161 | )? |
| 7162 | } else { |
| 7163 | ClipDecoder::open_with(&info.path, source_frame, None, None, false, deint)? |
| 7164 | }; |
| 7165 | let Some(picture) = decoder.next()? else { |
| 7166 | return Err(format!("{} ends before frame {source_frame}", info.path.display()).into()); |
| 7167 | }; |
| 7168 | let Frame::Pixels(y, u, v, width, height) = picture else { |
| 7169 | return Err("a single-frame decode produced no pixels".into()); |
| 7170 | }; |
| 7171 | let remap = remap_into(Some(info.color), info.mapper.is_some(), out); |
| 7172 | let grade = project.composite_color_at(key).copied(); |
| 7173 | let transform = project |
| 7174 | .composite_transform_at(key) |
| 7175 | .copied() |
| 7176 | .unwrap_or_default(); |
| 7177 | let mut canvas = Composer::new(meta.width, meta.height, project.composite_fit_at(key)); |
| 7178 | let (mut rotated, mut stretched, mut graded, mut transformed) = Default::default(); |
| 7179 | let (py, pu, pv, _, _) = place_picture( |
| 7180 | y, |
| 7181 | u, |
| 7182 | v, |
| 7183 | width, |
| 7184 | height, |
| 7185 | info.rotation, |
| 7186 | info.pixel_aspect, |
| 7187 | grade, |
| 7188 | transform, |
| 7189 | remap, |
| 7190 | info.mapper.as_ref(), |
| 7191 | &mut rotated, |
| 7192 | &mut stretched, |
| 7193 | &mut graded, |
| 7194 | &mut transformed, |
| 7195 | &mut canvas, |
| 7196 | ); |
| 7197 | Ok((py.to_vec(), pu.to_vec(), pv.to_vec())) |
| 7198 | } |
| 7199 | |
| 7200 | /// The largest size with the project's `w:h` aspect that fits in `bw` x `bh`. |
| 7201 | fn fit_box(w: u32, h: u32, bw: u32, bh: u32) -> (u32, u32) { |
| 7202 | let (w, h, bw, bh) = (w as u64, h as u64, bw as u64, bh as u64); |
| 7203 | let th = (bw * h / w).max(1); |
| 7204 | if th <= bh { |
| 7205 | (bw as u32, th as u32) |
| 7206 | } else { |
| 7207 | let tw = (bh * w / h).max(1); |
| 7208 | (tw as u32, bh as u32) |
| 7209 | } |
| 7210 | } |
| 7211 | |
| 7212 | /// Box-filter resize of a tightly packed BGRA picture. Each destination pixel |
| 7213 | /// averages the source pixels it covers, so an upscale is nearest-neighbour |
| 7214 | /// and a downscale is an area average; no float, so it is byte-stable. |
| 7215 | fn resize_bgra(src: &[u8], sw: u32, sh: u32, dw: u32, dh: u32) -> Vec<u8> { |
| 7216 | fn cover(i: usize, src: usize, dst: usize) -> (usize, usize) { |
| 7217 | let a = i * src / dst; |
| 7218 | let b = ((i + 1) * src / dst).max(a + 1).min(src); |
| 7219 | (a, b) |
| 7220 | } |
| 7221 | let (sw, sh, dw, dh) = (sw as usize, sh as usize, dw as usize, dh as usize); |
| 7222 | let mut out = vec![0u8; dw * dh * 4]; |
| 7223 | for dy in 0..dh { |
| 7224 | let (y0, y1) = cover(dy, sh, dh); |
| 7225 | for dx in 0..dw { |
| 7226 | let (x0, x1) = cover(dx, sw, dw); |
| 7227 | let mut acc = [0u32; 4]; |
| 7228 | for y in y0..y1 { |
| 7229 | for x in x0..x1 { |
| 7230 | let p = (y * sw + x) * 4; |
| 7231 | for (c, a) in acc.iter_mut().enumerate() { |
| 7232 | *a += src[p + c] as u32; |
| 7233 | } |
| 7234 | } |
| 7235 | } |
| 7236 | let n = ((y1 - y0) * (x1 - x0)) as u32; |
| 7237 | let q = (dy * dw + dx) * 4; |
| 7238 | for (c, a) in acc.iter().enumerate() { |
| 7239 | out[q + c] = ((a + n / 2) / n) as u8; |
| 7240 | } |
| 7241 | } |
| 7242 | } |
| 7243 | out |
| 7244 | } |
| 7245 | |
| 7246 | /// What rate `path` was shot at against a timeline at `timeline_fps` |
| 7247 | /// ([`Rate`]). [`Rate::REAL_TIME`] for the files that have no rate of their own |
| 7248 | /// -- a still, a song -- and for one that will not open here: the decoder is |
| 7249 | /// opened a few lines later and fails the export by name, which is a better |
| 7250 | /// error than this one could raise. |
| 7251 | fn source_rate( |
| 7252 | path: &Path, |
| 7253 | timeline_fps: f64, |
| 7254 | ) -> ( |
| 7255 | Rate, |
| 7256 | ColorDescription, |
| 7257 | Option<f32>, |
| 7258 | Rotation, |
| 7259 | crate::demux::PixelAspect, |
| 7260 | ) { |
| 7261 | if crate::is_image(path) || crate::is_audio(path) { |
| 7262 | // A still is BT.601 by construction whatever it was authored as: |
| 7263 | // `decode::rgb_to_i420` is the one matrix that turns its pixels into |
| 7264 | // planes. A song has no picture and the answer is never read. Neither |
| 7265 | // has a display matrix to be turned by, nor an aspect to be widened |
| 7266 | // by: both are authored square. A still's *EXIF* turn is not in this |
| 7267 | // arm either, and for a better reason -- `decode::Still::open` already |
| 7268 | // made it before the planes were written, so `place_picture` is handed |
| 7269 | // the picture the preview showed and must not be told to turn it again. |
| 7270 | return ( |
| 7271 | Rate::REAL_TIME, |
| 7272 | ColorDescription::default(), |
| 7273 | None, |
| 7274 | Rotation::None, |
| 7275 | crate::demux::PixelAspect::SQUARE, |
| 7276 | ); |
| 7277 | } |
| 7278 | match Demuxer::open(path) { |
| 7279 | // ...and one whose rate cannot be named against the timeline's, which |
| 7280 | // `matches_timeline` refuses at import, so nothing on a timeline is on |
| 7281 | // this arm either. |
| 7282 | // |
| 7283 | // The declared peak comes off the same open the space does, which is |
| 7284 | // what keeps export on the number playback's decode funnel read: one |
| 7285 | // header parse, both answers. |
| 7286 | Ok((meta, demuxer)) => ( |
| 7287 | Rate::from_fps(meta.frame_rate, timeline_fps).unwrap_or(Rate::REAL_TIME), |
| 7288 | meta.color, |
| 7289 | demuxer.light().peak(), |
| 7290 | // The file's own turn, so the encoder is fed the picture the |
| 7291 | // preview shows: the same header read, one more answer. |
| 7292 | meta.rotation, |
| 7293 | // ...and its own sample aspect, for the same reason on the same |
| 7294 | // read: the encoder is fed the shape the preview showed. |
| 7295 | meta.pixel_aspect, |
| 7296 | ), |
| 7297 | // Unreadable here means unreadable below too, where the span dies with a |
| 7298 | // real message; the file's own space is the least of that. |
| 7299 | Err(_) => ( |
| 7300 | Rate::REAL_TIME, |
| 7301 | ColorDescription::default(), |
| 7302 | None, |
| 7303 | Rotation::None, |
| 7304 | crate::demux::PixelAspect::SQUARE, |
| 7305 | ), |
| 7306 | } |
| 7307 | } |
| 7308 | |
| 7309 | /// The audio lanes alone, summed, as a WAV or a FLAC. |
| 7310 | /// |
| 7311 | /// Nothing here re-derives the edit: the play lists are |
| 7312 | /// [`Project::audio_segments_from`] and they are handed to the very |
| 7313 | /// [`AudioSession::open_mixed_streams`] playback feeds from, so what is written |
| 7314 | /// is what was heard -- every lane, mixed the same way, gaps included, which |
| 7315 | /// arrive as real silence from that choke point rather than as a hole this would |
| 7316 | /// have to invent. |
| 7317 | /// |
| 7318 | /// The length is the *timeline's*: each segment resolves its window to whole |
| 7319 | /// samples on its own, so the sum can miss the timeline by a sample or two, and |
| 7320 | /// a source that runs out early would leave the file short. Both are settled by |
| 7321 | /// one `resize` at the end -- padding with silence, trimming what overshot -- |
| 7322 | /// so an exported file is exactly as long as what was edited. |
| 7323 | /// The timeline frames a picture export covers: its range, clipped to the media, or the whole media. |
| 7324 | fn picture_span(project: &Project, settings: &ExportSettings) -> (u32, u32) { |
| 7325 | let media = project.media_frames(); |
| 7326 | match settings.range { |
| 7327 | Some((from, to)) => { |
| 7328 | let from = from.min(media); |
| 7329 | (from, to.min(media).max(from)) |
| 7330 | } |
| 7331 | None => (0, media), |
| 7332 | } |
| 7333 | } |
| 7334 | |
| 7335 | /// The picture at timeline frame `frame` as a PNG file's bytes, at the project's own size. What |
| 7336 | /// the still formats write: [`compose_at_with`] draws it as the export would, titles and burnt |
| 7337 | /// captions included. |
| 7338 | fn still_png(project: &Project, meta: &VideoMeta, frame: u32, settings: &ExportSettings) -> crate::Result<Vec<u8>> { |
| 7339 | let picture = compose_at_with(project, meta, frame, meta.width, meta.height, settings.burn_subtitles.clone())?; |
| 7340 | crate::decode::to_png_bytes(&picture) |
| 7341 | } |
| 7342 | |
| 7343 | /// A numbered PNG run ([`Format::PngSequence`]) into the folder `out`, one file per frame, |
| 7344 | /// named after the folder: `name_00001.png`. A run that fails part way leaves no files behind. |
| 7345 | fn run_png_sequence( |
| 7346 | project: &Project, |
| 7347 | meta: &VideoMeta, |
| 7348 | out: &Path, |
| 7349 | shared: &Arc<Shared>, |
| 7350 | settings: &ExportSettings, |
| 7351 | ) -> crate::Result<()> { |
| 7352 | let (from, to) = picture_span(project, settings); |
| 7353 | let total = to - from; |
| 7354 | std::fs::create_dir_all(out)?; |
| 7355 | let name = out.file_name().and_then(|n| n.to_str()).unwrap_or("frame").to_string(); |
| 7356 | let mut written: Vec<PathBuf> = Vec::new(); |
| 7357 | let result = (|| -> crate::Result<()> { |
| 7358 | for k in 0..total { |
| 7359 | cancelled(shared)?; |
| 7360 | let path = out.join(format!("{name}_{:05}.png", k + 1)); |
| 7361 | std::fs::write(&path, still_png(project, meta, from + k, settings)?)?; |
| 7362 | written.push(path); |
| 7363 | shared.progress.fetch_max(picture_progress(k + 1, total), Ordering::Relaxed); |
| 7364 | } |
| 7365 | Ok(()) |
| 7366 | })(); |
| 7367 | if result.is_err() { |
| 7368 | for path in &written { |
| 7369 | let _ = std::fs::remove_file(path); |
| 7370 | } |
| 7371 | } |
| 7372 | result |
| 7373 | } |
| 7374 | |
| 7375 | /// The poster frame ([`Format::Still`]): the picture at the start of the range, written to `part` |
| 7376 | /// for the caller to publish. |
| 7377 | fn run_still(project: &Project, meta: &VideoMeta, part: &Path, settings: &ExportSettings) -> crate::Result<()> { |
| 7378 | let frame = settings.range.map_or(0, |(from, _)| from); |
| 7379 | std::fs::write(part, still_png(project, meta, frame, settings)?)?; |
| 7380 | Ok(()) |
| 7381 | } |
| 7382 | |
| 7383 | /// The animated GIF ([`Format::Gif`]): the range sampled at [`GifSettings::fps`], each picture |
| 7384 | /// composed at [`GifSettings::width`], handed to the GIF writer one frame at a time. |
| 7385 | fn run_gif( |
| 7386 | project: &Project, |
| 7387 | meta: &VideoMeta, |
| 7388 | part: &Path, |
| 7389 | shared: &Arc<Shared>, |
| 7390 | settings: &ExportSettings, |
| 7391 | ) -> crate::Result<()> { |
| 7392 | let gif = settings.gif; |
| 7393 | // The encoder holds every frame until `finish`, so a GIF is bounded in what it can hold. |
| 7394 | if gif.width == 0 || gif.width > GIF_MAX_WIDTH || gif.fps == 0 || gif.fps > 60 { |
| 7395 | return Err(format!("a GIF is 1 to {GIF_MAX_WIDTH} pixels wide and 1 to 60 frames a second").into()); |
| 7396 | } |
| 7397 | let (from, to) = picture_span(project, settings); |
| 7398 | if f64::from(to - from) / meta.frame_rate > GIF_MAX_SECS { |
| 7399 | return Err(format!("a GIF is at most {GIF_MAX_SECS} s long: export a shorter range").into()); |
| 7400 | } |
| 7401 | let (width, height) = fit_box(meta.width, meta.height, gif.width, GIF_MAX_WIDTH); |
| 7402 | let mut writer = GifWriter::open(width, height, gif.loop_forever)?; |
| 7403 | let fps = f64::from(gif.fps); |
| 7404 | let frames = ((f64::from(to - from) * fps) / meta.frame_rate).ceil() as u32; |
| 7405 | if frames == 0 { |
| 7406 | return Err("the range holds no frames".into()); |
| 7407 | } |
| 7408 | for i in 0..frames { |
| 7409 | cancelled(shared)?; |
| 7410 | // The timeline frame this GIF frame shows, and how long it holds: the hundredths of a |
| 7411 | // second between this frame's start and the next, so the rounding never drifts. |
| 7412 | let at = ((f64::from(i) * meta.frame_rate) / fps) as u32; |
| 7413 | let shown = from + at.min(to - from - 1); |
| 7414 | let next = (f64::from(i + 1) * 100.0 / fps).round() as u32; |
| 7415 | let delay = (next - (f64::from(i) * 100.0 / fps).round() as u32).max(1) as u16; |
| 7416 | let picture = compose_at_with(project, meta, shown, width, height, settings.burn_subtitles.clone())?; |
| 7417 | let rgba: Vec<u8> = picture |
| 7418 | .bgra |
| 7419 | .as_chunks::<4>() |
| 7420 | .0 |
| 7421 | .iter() |
| 7422 | .flat_map(|px| [px[2], px[1], px[0], 255]) |
| 7423 | .collect(); |
| 7424 | writer.push(&rgba, delay)?; |
| 7425 | shared.progress.fetch_max(picture_progress(i + 1, frames), Ordering::Relaxed); |
| 7426 | } |
| 7427 | std::fs::write(part, writer.finish()?)?; |
| 7428 | Ok(()) |
| 7429 | } |
| 7430 | |
| 7431 | /// The widest GIF, and the longest: the encoder keeps every frame until it is finished. |
| 7432 | const GIF_MAX_WIDTH: u32 = 720; |
| 7433 | const GIF_MAX_SECS: f64 = 30.0; |
| 7434 | |
| 7435 | /// The GIF writer, over `ec_image::gif_encode`: 256 colours with dithering (video gradients band |
| 7436 | /// badly without it), looping forever or playing once. |
| 7437 | struct GifWriter(ec_image::gif_encode::Encoder); |
| 7438 | |
| 7439 | impl GifWriter { |
| 7440 | fn open(width: u32, height: u32, loop_forever: bool) -> crate::Result<Self> { |
| 7441 | let opts = ec_image::gif_encode::GifOptions { |
| 7442 | loop_count: if loop_forever { Some(0) } else { None }, |
| 7443 | max_colors: 256, |
| 7444 | dither: true, |
| 7445 | }; |
| 7446 | let encoder = ec_image::gif_encode::Encoder::new(width as u16, height as u16, opts) |
| 7447 | .map_err(|e| format!("GIF: {e}"))?; |
| 7448 | Ok(Self(encoder)) |
| 7449 | } |
| 7450 | |
| 7451 | fn push(&mut self, rgba: &[u8], delay_cs: u16) -> crate::Result<()> { |
| 7452 | self.0.push_rgba8(rgba, delay_cs).map_err(|e| format!("GIF: {e}").into()) |
| 7453 | } |
| 7454 | |
| 7455 | fn finish(self) -> crate::Result<Vec<u8>> { |
| 7456 | self.0.finish().map_err(|e| format!("GIF: {e}").into()) |
| 7457 | } |
| 7458 | } |
| 7459 | |
| 7460 | fn run_audio( |
| 7461 | project: &Project, |
| 7462 | meta: &VideoMeta, |
| 7463 | out: &Path, |
| 7464 | shared: &Shared, |
| 7465 | settings: &ExportSettings, |
| 7466 | sample_rate: Option<u32>, |
| 7467 | ) -> crate::Result<()> { |
| 7468 | let format = settings.format; |
| 7469 | let (samples, audio) = mix_pcm(project, meta, shared, settings, sample_rate, 16)? |
| 7470 | .ok_or("this timeline has no audio to export")?; |
| 7471 | // Written in one go and still cancellable up to here, exactly as the mp4 |
| 7472 | // path is up to its `finish`: the `.part` is what either gets renamed or |
| 7473 | // deleted. |
| 7474 | cancelled(shared)?; |
| 7475 | match format { |
| 7476 | Format::Wav => write_wav(out, &samples, &audio)?, |
| 7477 | Format::Flac => write_flac(out, &samples, &audio)?, |
| 7478 | Format::Mp3 => write_mp3(out, &samples, &audio, audio_kbps_of(settings))?, |
| 7479 | Format::Ogg => write_ogg(out, &samples, &audio)?, |
| 7480 | Format::Opus => write_opus(out, &samples, &audio, project, settings, shared)?, |
| 7481 | _ => unreachable!("the picture formats are `run`"), |
| 7482 | } |
| 7483 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); |
| 7484 | Ok(()) |
| 7485 | } |
| 7486 | |
| 7487 | /// The sample width of a ProRes file's PCM sound: 24 unless |
| 7488 | /// [`ExportSettings::audio_bit_depth`] says 16. |
| 7489 | fn prores_audio_bits(settings: &ExportSettings) -> u8 { |
| 7490 | match settings.audio_bit_depth { |
| 7491 | Some(16) => 16, |
| 7492 | _ => 24, |
| 7493 | } |
| 7494 | } |
| 7495 | |
| 7496 | /// The ProRes file's sound pass: the mix as `bits`-wide samples, `(samples, rate, |
| 7497 | /// channels)`, or `None` for a timeline with no sound. Runs beside the picture. |
| 7498 | fn mix_pcm16( |
| 7499 | project: &Project, |
| 7500 | meta: &VideoMeta, |
| 7501 | shared: &Shared, |
| 7502 | settings: &ExportSettings, |
| 7503 | sample_rate: Option<u32>, |
| 7504 | bits: u8, |
| 7505 | ) -> crate::Result<Option<(Vec<i32>, u32, u16)>> { |
| 7506 | Ok(mix_pcm(project, meta, shared, settings, sample_rate, bits)? |
| 7507 | .map(|(samples, audio)| (samples, audio.sample_rate, audio.channels))) |
| 7508 | } |
| 7509 | |
| 7510 | /// A running ProRes sound pass, joined when dropped for the reason [`AudioPass`] is. |
| 7511 | struct PcmPass(Option<PcmJob>); |
| 7512 | |
| 7513 | /// The ProRes sound pass's thread: `(samples, rate, channels)` or `None` for no sound. |
| 7514 | type PcmJob = thread::JoinHandle<crate::Result<Option<(Vec<i32>, u32, u16)>>>; |
| 7515 | |
| 7516 | impl PcmPass { |
| 7517 | fn take(&mut self) -> Option<PcmJob> { |
| 7518 | self.0.take() |
| 7519 | } |
| 7520 | } |
| 7521 | |
| 7522 | impl Drop for PcmPass { |
| 7523 | fn drop(&mut self) { |
| 7524 | if let Some(job) = self.0.take() { |
| 7525 | let _ = job.join(); |
| 7526 | } |
| 7527 | } |
| 7528 | } |
| 7529 | |
| 7530 | fn join_pcm(job: PcmJob) -> crate::Result<Option<(Vec<i32>, u32, u16)>> { |
| 7531 | job.join() |
| 7532 | .map_err(|_| crate::Error::from("the sound pass stopped without a picture or a reason"))? |
| 7533 | } |
| 7534 | |
| 7535 | /// The audio lanes mixed to 16-bit samples (in an `i32`), the length of the |
| 7536 | /// range: [`run_audio`]'s body up to the write, so a WAV and a ProRes file's PCM |
| 7537 | /// track are the same mix. `None` where the timeline has no sound. |
| 7538 | fn mix_pcm( |
| 7539 | project: &Project, |
| 7540 | meta: &VideoMeta, |
| 7541 | shared: &Shared, |
| 7542 | settings: &ExportSettings, |
| 7543 | sample_rate: Option<u32>, |
| 7544 | bits: u8, |
| 7545 | ) -> crate::Result<Option<(Vec<i32>, AudioMeta)>> { |
| 7546 | let format = settings.format; |
| 7547 | // Full scale of the sample width asked for: 32767 or 8388607. The f32 mix is |
| 7548 | // scaled straight to it, so a 24-bit file is not a widened 16-bit one. |
| 7549 | let full = ((1i64 << (bits - 1)) - 1) as f32; |
| 7550 | let sources = project.audio_sources(); |
| 7551 | let range_start = settings.range.map_or(0, |(s, _)| s); |
| 7552 | let pre = warm_up(project, range_start, meta.frame_rate); |
| 7553 | let offset = range_start - pre; |
| 7554 | let segs = project.audio_segments_from(offset, meta.frame_rate); |
| 7555 | // The equalizers with them, so what is written is what is heard down to the |
| 7556 | // filter: the worker applies them per segment before the lanes are summed |
| 7557 | // ([`AudioSession::open_mixed_streams_eq`]), which is the same choke point |
| 7558 | // playback's feeder reads from -- there is no second place here that could |
| 7559 | // apply them differently. |
| 7560 | let eqs = project.audio_eqs_from(offset, meta.frame_rate); |
| 7561 | // ...and the rates with them, for exactly the same reason: a speeded clip is |
| 7562 | // resampled inside the worker playback feeds from, so a WAV of a timeline at |
| 7563 | // 2x is half as long and holds the samples that were heard -- not a |
| 7564 | // second pass here that could disagree with what the ear got. |
| 7565 | let speeds = project.audio_speeds_from(offset, meta.frame_rate); |
| 7566 | // ...and the fades with them, the same choke-point reason again: a clip's |
| 7567 | // envelope runs inside the worker playback feeds from too. |
| 7568 | let fades = project.audio_fades_from(offset, meta.frame_rate); |
| 7569 | // ...and the mix over both: each lane's volume into the sum, the master |
| 7570 | // limiter out of it. The same opener playback's feeder reads from, so a |
| 7571 | // file is written at the levels it was heard at -- there is no second |
| 7572 | // place here that could mix it differently. |
| 7573 | let Some((audio, chunks)) = AudioSession::open_mixed_streams_master_at_fade( |
| 7574 | &sources, |
| 7575 | &segs, |
| 7576 | &eqs, |
| 7577 | &speeds, |
| 7578 | &fades, |
| 7579 | meta.frame_rate, |
| 7580 | &project.audio_gains(), |
| 7581 | &project.audio_ducks(), |
| 7582 | &project.audio_voices(), |
| 7583 | project.limiter(), |
| 7584 | sample_rate, |
| 7585 | )? |
| 7586 | else { |
| 7587 | return Ok(None); |
| 7588 | }; |
| 7589 | // The picture path's line, for a file that is sound alone: there is sound |
| 7590 | // by the line above, so this names the encoder writing it. A picture file |
| 7591 | // publishes its own. |
| 7592 | if !format.has_video() { |
| 7593 | *shared.encoders.lock().unwrap() = |
| 7594 | Some(audio_label(project, format, true, None, settings.range.is_some(), settings.reencode_audio).to_string()); |
| 7595 | } |
| 7596 | let channels = usize::from(audio.channels); |
| 7597 | let out_frames = settings.range.map_or(project.media_frames(), |(s, e)| { |
| 7598 | e.min(project.media_frames()).saturating_sub(s) |
| 7599 | }); |
| 7600 | let frames = |
| 7601 | (f64::from(out_frames) / meta.frame_rate * f64::from(audio.sample_rate)).round() as u64; |
| 7602 | let total = frames as usize * channels; |
| 7603 | // corner-cut: the whole export sits in memory (4 bytes a sample, so ~23 MB |
| 7604 | // per minute of 48 kHz stereo). `ec-flac` takes it that way and |
| 7605 | // the mp4 path already collects its copied AAC track the same. Upgrade path |
| 7606 | // is ec-riff's incremental writer, fed one block at a time. |
| 7607 | let skip = warm_up_samples(range_start, pre, meta.frame_rate, audio.sample_rate, channels); |
| 7608 | let mut samples: Vec<i32> = Vec::with_capacity(total + skip); |
| 7609 | // Only for a loudness target: the mix at f32, measured and levelled once whole. |
| 7610 | let mut wide: Vec<f32> = Vec::new(); |
| 7611 | for chunk in chunks { |
| 7612 | cancelled(shared)?; |
| 7613 | if shared.loudness.is_some() { |
| 7614 | wide.extend_from_slice(&chunk.samples); |
| 7615 | // The same range-only progress as the plain path below. |
| 7616 | let done = wide.len().saturating_sub(skip).min(total) * PROGRESS_SCALE as usize / total.max(1); |
| 7617 | if !format.has_video() { shared.progress.store(done as u32, Ordering::Relaxed); } |
| 7618 | if wide.len() >= skip + total { |
| 7619 | break; |
| 7620 | } |
| 7621 | continue; |
| 7622 | } |
| 7623 | // Already equalized: the chunks come out of the per-lane workers, which |
| 7624 | // filter each segment before the mix (`open_mixed_streams_eq` above). |
| 7625 | samples.extend( |
| 7626 | chunk |
| 7627 | .samples |
| 7628 | .iter() |
| 7629 | .map(|s| (s.clamp(-1.0, 1.0) * full).round() as i32), |
| 7630 | ); |
| 7631 | // Only the range counts towards the bar: not the pre-roll, not the mix past the end. |
| 7632 | let done = samples.len().saturating_sub(skip).min(total) * PROGRESS_SCALE as usize / total.max(1); |
| 7633 | if !format.has_video() { shared.progress.store(done as u32, Ordering::Relaxed); } |
| 7634 | if samples.len() >= skip + total { |
| 7635 | break; |
| 7636 | } |
| 7637 | } |
| 7638 | if let Some(target) = shared.loudness { |
| 7639 | // The voice warm-up is dropped first, so the gain is measured over the range alone. |
| 7640 | wide.drain(..skip.min(wide.len())); |
| 7641 | wide.resize(total, 0.0); |
| 7642 | level_to_target(&mut wide, audio.sample_rate, audio.channels.max(1), target); |
| 7643 | samples.extend( |
| 7644 | wide.iter().map(|s| (s.clamp(-1.0, 1.0) * full).round() as i32), |
| 7645 | ); |
| 7646 | if !format.has_video() { shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); } |
| 7647 | } else { |
| 7648 | // The pre-roll is in the samples in 16-bit form too, so it goes before the length is set. |
| 7649 | samples.drain(..skip.min(samples.len())); |
| 7650 | } |
| 7651 | samples.resize(total, 0); |
| 7652 | Ok(Some((samples, audio))) |
| 7653 | } |
| 7654 | |
| 7655 | /// The sound alone as AAC in an mp4 box: the `.m4a` file, and the `.mp4` of a |
| 7656 | /// timeline with no picture. The track is the one a picture export carries -- |
| 7657 | /// copied packet for packet where a copy says what the timeline says |
| 7658 | /// ([`copy_audio`]), encoded where it cannot -- so the two files hold the same |
| 7659 | /// samples and differ in the brand alone ([`Mp4Muxer::create_audio_only`]). |
| 7660 | fn run_aac( |
| 7661 | project: &Project, |
| 7662 | meta: &VideoMeta, |
| 7663 | out: &Path, |
| 7664 | shared: &Shared, |
| 7665 | settings: &ExportSettings, |
| 7666 | sample_rate: Option<u32>, |
| 7667 | ) -> crate::Result<()> { |
| 7668 | let track = copy_audio( |
| 7669 | project, |
| 7670 | meta, |
| 7671 | audio_kbps_of(settings), |
| 7672 | false, |
| 7673 | false, |
| 7674 | settings.reencode_audio, |
| 7675 | shared, |
| 7676 | sample_rate, |
| 7677 | settings.range, |
| 7678 | )? |
| 7679 | .ok_or("this timeline has no audio to export")?; |
| 7680 | let track = ExportAudio { |
| 7681 | language: audio_language(project), |
| 7682 | ..track |
| 7683 | }; |
| 7684 | *shared.encoders.lock().unwrap() = Some( |
| 7685 | audio_label( |
| 7686 | project, |
| 7687 | settings.format, |
| 7688 | true, |
| 7689 | Some(track.copied), |
| 7690 | settings.range.is_some(), |
| 7691 | settings.reencode_audio, |
| 7692 | ) |
| 7693 | .to_string(), |
| 7694 | ); |
| 7695 | let mut mp4 = Mp4Muxer::create_audio_only( |
| 7696 | out, |
| 7697 | ¶ms_of(&track), |
| 7698 | settings.format == Format::M4a, |
| 7699 | )?; |
| 7700 | if let Some(frames) = track.pcm_frames { |
| 7701 | mp4.set_audio_frames(frames)?; |
| 7702 | } |
| 7703 | let count = track.packets.len().max(1); |
| 7704 | for (i, packet) in track.packets.iter().enumerate() { |
| 7705 | cancelled(shared)?; |
| 7706 | mp4.write_audio_packet(&packet.bytes)?; |
| 7707 | shared |
| 7708 | .progress |
| 7709 | .fetch_max((i * PROGRESS_SCALE as usize / count) as u32, Ordering::Relaxed); |
| 7710 | } |
| 7711 | cancelled(shared)?; |
| 7712 | mp4.set_faststart(settings.faststart); |
| 7713 | mp4.set_chapters(&settings.chapters)?; |
| 7714 | mp4.finish()?; |
| 7715 | shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); |
| 7716 | Ok(()) |
| 7717 | } |
| 7718 | |
| 7719 | /// 16-bit PCM at the timeline's own rate and layout: no resampling anywhere in |
| 7720 | /// this engine, so what the decoder handed over is what the header says. |
| 7721 | fn write_wav(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { |
| 7722 | // Every sample is in hand, so the frame count is known before the header |
| 7723 | // is written: a long enough export gets RF64 instead of a RIFF that would |
| 7724 | // overflow its 32-bit sizes. |
| 7725 | let channels = u64::from(audio.channels.max(1)); |
| 7726 | let options = ec_riff::WavOptions { |
| 7727 | expected_frames: samples.len() as u64 / channels, |
| 7728 | ..Default::default() |
| 7729 | }; |
| 7730 | let mut writer = ec_riff::WavWriter::create_with_options( |
| 7731 | out, |
| 7732 | ec_riff::WavSpec { |
| 7733 | channels: audio.channels, |
| 7734 | sample_rate: audio.sample_rate, |
| 7735 | bits_per_sample: 16, |
| 7736 | sample_format: ec_riff::SampleType::Int, |
| 7737 | }, |
| 7738 | options, |
| 7739 | )?; |
| 7740 | for &sample in samples { |
| 7741 | writer.write_sample(sample as i16)?; |
| 7742 | } |
| 7743 | // Not `drop`: this is what rewrites the RIFF sizes in the header, and its |
| 7744 | // failure is the difference between a finished file and a truncated one. |
| 7745 | writer.finalize()?; |
| 7746 | Ok(()) |
| 7747 | } |
| 7748 | |
| 7749 | /// The same samples as MPEG-1 Layer III, `ec-mp3` doing the encoding -- the |
| 7750 | /// family's own, taking the seat at the same contract (CBR in, frames out, |
| 7751 | /// `Mp3EncoderConfig`'s fields are the old seat's names), so the swap cost the |
| 7752 | /// call sites nothing. |
| 7753 | /// |
| 7754 | /// CBR at the caller's rate, [`DEFAULT_AUDIO_KBPS`] where there was none. Every |
| 7755 | /// offered rate is already a legal Layer III value, so the encoder's snap is a |
| 7756 | /// backstop and not a silent substitution; a sample rate MPEG has no frame for |
| 7757 | /// (anything but the nine MPEG rates 8-48 kHz) is refused there by name rather |
| 7758 | /// than written as something else. |
| 7759 | /// |
| 7760 | /// corner-cut: CBR only -- the card offers rates and not a quality index. Upgrade |
| 7761 | /// path is `Mp3EncoderConfig::vbr_quality` behind a setting of its own. |
| 7762 | fn write_mp3(out: &Path, samples: &[i32], audio: &AudioMeta, kbps: u32) -> crate::Result<()> { |
| 7763 | let mut encoder = ec_mp3::encode::Mp3Encoder::new(ec_mp3::encode::Mp3EncoderConfig { |
| 7764 | bitrate_kbps: kbps, |
| 7765 | vbr_quality: None, |
| 7766 | }); |
| 7767 | // The samples are the 16-bit ones a WAV of this timeline holds, so the two |
| 7768 | // files are one mix -- and `push_pcm_s16` divides by 32768 exactly as this |
| 7769 | // engine's own decoders do. |
| 7770 | let pcm: Vec<i16> = samples.iter().map(|&s| s as i16).collect(); |
| 7771 | encoder |
| 7772 | .push_pcm_s16(&pcm, audio.channels, audio.sample_rate) |
| 7773 | .map_err(|e| format!("mp3 encode: {e}"))?; |
| 7774 | encoder.finish(); |
| 7775 | let mut file = BufWriter::new(File::create(out)?); |
| 7776 | // `next_packet` after `finish` yields frames until `Eof`, the Xing/Info |
| 7777 | // header first: the loop ends on the only error it can see. |
| 7778 | while let Ok(frame) = encoder.next_packet() { |
| 7779 | file.write_all(&frame)?; |
| 7780 | } |
| 7781 | file.flush()?; |
| 7782 | Ok(()) |
| 7783 | } |
| 7784 | |
| 7785 | /// Where the Vorbis rate loop starts, on `ec-vorbis`'s normalised `[0, 1]` |
| 7786 | /// scale, beside [`VORBIS_TARGET_BPS`] -- the two numbers every `.ogg` this |
| 7787 | /// program writes is coded at. |
| 7788 | /// |
| 7789 | /// A measured operating point, not a taste (2026-09-13 bench, every output |
| 7790 | /// decoded back with **symphonia** -- an independent decoder, and the very one |
| 7791 | /// [`crate::audio`] reopens an export with). The incumbent seat's own 0.85 -- |
| 7792 | /// its top quality that still decoded every fixture to exactly its own length |
| 7793 | /// -- measured 124-176 kbps across this suite's fixtures with correlation |
| 7794 | /// 0.9947-0.9957 against the source. The quality knob alone on the new seat |
| 7795 | /// saturates well under that band (0.98 lands ~87 kbps on a 30-second music |
| 7796 | /// clip), so the seat is driven the way its own rate gates are measured: the |
| 7797 | /// loop starts at 0.85 and is held to a 128 kbps target, which landed |
| 7798 | /// 124-134 kbps actual on the same inputs and beat the incumbent at its own |
| 7799 | /// operating point on every one of them -- correlation 0.9968 against 0.9947 |
| 7800 | /// on the music clip, +3.1 dB PSNR -- at the same size of file. Against |
| 7801 | /// ffmpeg's own libvorbis at `-q 5` (125.8 kbps actual on the same clip) it |
| 7802 | /// reads 0.9968 against 0.9973: par at the same rate. |
| 7803 | const VORBIS_QUALITY: f32 = 0.85; |
| 7804 | |
| 7805 | /// The rate [`VORBIS_QUALITY`]'s loop is held to, in bits per second. Measured |
| 7806 | /// landing within +1..+5% of target across the bench's inputs; the Sound row |
| 7807 | /// stays refused for this format because this target is the encoder's measured |
| 7808 | /// operating point, not a number a card may offer. |
| 7809 | const VORBIS_TARGET_BPS: i32 = 128_000; |
| 7810 | |
| 7811 | /// The same samples as Vorbis I in an Ogg container: `ec-vorbis` encodes, |
| 7812 | /// `ec-ogg` pages. Pure Rust on both halves, like every other encoder here. |
| 7813 | /// |
| 7814 | /// The old seat's two corrections are gone with it, and the going is measured |
| 7815 | /// rather than assumed (2026-09-13, every output decoded back with symphonia). |
| 7816 | /// This encoder numbers its packets the spec's way -- the first audio packet |
| 7817 | /// at granule 0, every packet after at the absolute sample position its block |
| 7818 | /// ends on -- and clamps its final granule to the sample count it was fed, so |
| 7819 | /// a decoder trims the block grid's tail on its own. Written straight through, |
| 7820 | /// every file decodes to exactly the timeline's frame count with the |
| 7821 | /// correlation peak at lag zero, which is what the one-hop pre-roll and the |
| 7822 | /// two granule corrections this function used to carry around the old encoder |
| 7823 | /// were for. |
| 7824 | /// |
| 7825 | /// **Stereo, always.** The format row promises stereo, so a mono mix is |
| 7826 | /// written as dual mono, both channels bit-identical (measured: `max|L-R|` is |
| 7827 | /// exactly 0; the encoder's own channel coupling codes the empty side channel |
| 7828 | /// for almost nothing). The encoder would serve a mono stream, but the row |
| 7829 | /// says stereo and folding the file back down must give exactly what was |
| 7830 | /// mixed. Wider than stereo cannot reach here -- [`crate::audio`] folds 5.1 |
| 7831 | /// to stereo when the source is opened -- but it is refused by name rather |
| 7832 | /// than left to the library's own message. |
| 7833 | /// |
| 7834 | /// corner-cut: one operating point, [`VORBIS_QUALITY`] + |
| 7835 | /// [`VORBIS_TARGET_BPS`], with no user control -- the Sound row is refused for |
| 7836 | /// this format. Upgrade path is a quality picker of its own, worth building |
| 7837 | /// the day the card has a control that speaks in quality rather than kbps. |
| 7838 | fn write_ogg(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { |
| 7839 | if audio.channels > 2 { |
| 7840 | return Err(format!( |
| 7841 | "Ogg Vorbis is written in stereo here and this mix has {} channels", |
| 7842 | audio.channels |
| 7843 | ) |
| 7844 | .into()); |
| 7845 | } |
| 7846 | // The mp3 path's conversion, so the two files are one mix -- the same |
| 7847 | // /32768 scaling this engine's own decoders do -- plus (for a mono mix) |
| 7848 | // the dual-mono widening: the same sample in both channels is the same |
| 7849 | // signal, not a widening of it, so what a player folds back down is what |
| 7850 | // was mixed. |
| 7851 | let pcm: Vec<f32> = match audio.channels < 2 { |
| 7852 | true => samples |
| 7853 | .iter() |
| 7854 | .flat_map(|&s| [f32::from(s as i16) / 32768.0; 2]) |
| 7855 | .collect(), |
| 7856 | false => samples |
| 7857 | .iter() |
| 7858 | .map(|&s| f32::from(s as i16) / 32768.0) |
| 7859 | .collect(), |
| 7860 | }; |
| 7861 | let frames = samples.len() / usize::from(audio.channels).max(1); |
| 7862 | |
| 7863 | let mut encoder = ec_vorbis::VorbisEncoder::new(ec_vorbis::EncoderConfig { |
| 7864 | sample_rate: audio.sample_rate, |
| 7865 | channels: 2, |
| 7866 | bitrate_bps: VORBIS_TARGET_BPS, |
| 7867 | quality: VORBIS_QUALITY, |
| 7868 | }) |
| 7869 | .map_err(|e| format!("vorbis encode: {e}"))?; |
| 7870 | encoder |
| 7871 | .push_interleaved(&pcm) |
| 7872 | .map_err(|e| format!("vorbis encode: {e}"))?; |
| 7873 | encoder.finish(); |
| 7874 | let mut packets = Vec::new(); |
| 7875 | loop { |
| 7876 | match encoder.next_packet() { |
| 7877 | Ok(packet) => packets.push(packet), |
| 7878 | Err(ec_core::Error::Eof) => break, |
| 7879 | Err(ec_core::Error::NeedMore) => continue, |
| 7880 | Err(e) => return Err(format!("vorbis encode: {e}").into()), |
| 7881 | } |
| 7882 | } |
| 7883 | // The three setup headers travel with the encoder, not in the packet |
| 7884 | // stream; with no audio packets there is no stream to page. |
| 7885 | if packets.is_empty() { |
| 7886 | return Err("vorbis encode: no audio packets is not a stream".into()); |
| 7887 | } |
| 7888 | let headers = encoder.headers(); |
| 7889 | let extradata = |
| 7890 | ec_ogg::xiph_lace(&headers).ok_or("vorbis encode: the three headers would not lace")?; |
| 7891 | |
| 7892 | let time_base = |
| 7893 | TimeBase::try_new(1, i64::from(audio.sample_rate)).map_err(|e| format!("ogg mux: {e}"))?; |
| 7894 | let mut params = CodecParameters::new(CodecId::Vorbis); |
| 7895 | params.extradata = Some(Buf::from(extradata)); |
| 7896 | params.media = MediaParameters::Audio(AudioParameters { |
| 7897 | sample_rate: audio.sample_rate, |
| 7898 | layout: ChannelLayout::Stereo, |
| 7899 | ..AudioParameters::default() |
| 7900 | }); |
| 7901 | let mut stream = StreamInfo::new(0, time_base, params); |
| 7902 | stream.duration = Some(frames as i64); |
| 7903 | stream.start_time = Some(0); |
| 7904 | let mut muxer = ec_ogg::OggMuxer::new(File::create(out)?); |
| 7905 | // Without this every audio packet of a short export lands on one page, and |
| 7906 | // the muxer's own note records what that costs: a first-audio-page-is-also- |
| 7907 | // EOS stream decodes short by half a small block in a reference decoder. |
| 7908 | muxer.set_page_target_bytes(Some(OGG_PAGE_BYTES)); |
| 7909 | muxer |
| 7910 | .add_stream(stream) |
| 7911 | .map_err(|e| format!("ogg mux: {e}"))?; |
| 7912 | for packet in &packets { |
| 7913 | // The granule is the encoder's own: the absolute sample position this |
| 7914 | // packet ends at, clamped to the mix's length on the last one. It goes |
| 7915 | // in as side data, which is where `ec-ogg` reads it, because a packet's |
| 7916 | // `pts + duration` would state the position one block late. |
| 7917 | let mut out_packet = |
| 7918 | Packet::new(0, time_base, packet.data.clone()).with_duration(packet.samples); |
| 7919 | out_packet |
| 7920 | .side_data |
| 7921 | .push(ec_ogg::granule_side_data(packet.granule)); |
| 7922 | muxer |
| 7923 | .write_packet(&out_packet) |
| 7924 | .map_err(|e| format!("ogg mux: {e}"))?; |
| 7925 | } |
| 7926 | muxer.finish().map_err(|e| format!("ogg mux: {e}"))?; |
| 7927 | Ok(()) |
| 7928 | } |
| 7929 | |
| 7930 | /// The same samples as Opus in Ogg ([`crate::opus_write`]), at the Sound row's |
| 7931 | /// rate clamped into Opus's own range (6-510 kbps, [`crate::opus_write::DEFAULT_KBPS`] |
| 7932 | /// where none was asked for), with the language and chapters in `OpusTags`. |
| 7933 | /// Cancellable per packet, like the mix before it. |
| 7934 | fn write_opus( |
| 7935 | out: &Path, |
| 7936 | samples: &[i32], |
| 7937 | audio: &AudioMeta, |
| 7938 | project: &Project, |
| 7939 | settings: &ExportSettings, |
| 7940 | shared: &Shared, |
| 7941 | ) -> crate::Result<()> { |
| 7942 | if audio.sample_rate != OPUS_RATE { |
| 7943 | return Err(format!("Opus is coded at 48 kHz and this mix came out at {} Hz", audio.sample_rate).into()); |
| 7944 | } |
| 7945 | let pcm: Vec<f32> = samples.iter().map(|&s| f32::from(s as i16) / 32768.0).collect(); |
| 7946 | let language = audio_language(project); |
| 7947 | let tags = crate::opus_write::Tags { language: language.as_deref(), chapters: &settings.chapters }; |
| 7948 | crate::opus_write::write( |
| 7949 | out, |
| 7950 | &pcm, |
| 7951 | usize::from(audio.channels.max(1)), |
| 7952 | audio.sample_rate, |
| 7953 | settings.audio_kbps.unwrap_or(crate::opus_write::DEFAULT_KBPS), |
| 7954 | &tags, |
| 7955 | &mut |_| cancelled(shared), |
| 7956 | ) |
| 7957 | } |
| 7958 | |
| 7959 | /// The page size [`write_ogg`] asks the Ogg muxer to aim at, in bytes. RFC 3533 |
| 7960 | /// describes pages as "usually 4-8 kB", which is also the muxer's own suggested |
| 7961 | /// general-purpose value. |
| 7962 | const OGG_PAGE_BYTES: usize = 4096; |
| 7963 | |
| 7964 | /// The same samples, losslessly compressed, through [`crate::flac_write`]. The |
| 7965 | /// export is always 16-bit: the samples were scaled to `i16` above. |
| 7966 | fn write_flac(out: &Path, samples: &[i32], audio: &AudioMeta) -> crate::Result<()> { |
| 7967 | crate::flac_write::write(out, samples, usize::from(audio.channels), 16, audio.sample_rate) |
| 7968 | } |
| 7969 | |
| 7970 | /// The I420 planes of one black picture, allocated once for a whole export: a |
| 7971 | /// gap in the video lane is encoded, not skipped, or every frame after it would |
| 7972 | /// arrive early. Limited-range black is `Y=16, U=V=128`, the same convention |
| 7973 | /// [`crate::convert`] decodes with. |
| 7974 | struct Black { |
| 7975 | y: Vec<u8>, |
| 7976 | uv: Vec<u8>, |
| 7977 | width: u32, |
| 7978 | height: u32, |
| 7979 | } |
| 7980 | |
| 7981 | impl Black { |
| 7982 | fn new(meta: &VideoMeta) -> Self { |
| 7983 | let (w, h) = (meta.width as usize, meta.height as usize); |
| 7984 | Self { |
| 7985 | y: vec![16; w * h], |
| 7986 | uv: vec![128; w.div_ceil(2) * h.div_ceil(2)], |
| 7987 | width: meta.width, |
| 7988 | height: meta.height, |
| 7989 | } |
| 7990 | } |
| 7991 | |
| 7992 | fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) { |
| 7993 | (&self.y, &self.uv, &self.uv, self.width, self.height) |
| 7994 | } |
| 7995 | } |
| 7996 | |
| 7997 | /// `Err` once a cancel has been asked for. Called at every point where the work |
| 7998 | /// left is more than an instant, so an `esc` at 99.9% still stops the export |
| 7999 | /// instead of quietly completing it. |
| 8000 | fn cancelled(shared: &Shared) -> crate::Result<()> { |
| 8001 | if shared.cancel.load(Ordering::Relaxed) { |
| 8002 | return Err("export cancelled".into()); |
| 8003 | } |
| 8004 | Ok(()) |
| 8005 | } |
| 8006 | |
| 8007 | /// The two containers an export writes, so the picture loop above is one loop: |
| 8008 | /// H.264 goes into mp4, AV1 into Matroska, and nothing else is offered. |
| 8009 | enum Muxer { |
| 8010 | Mp4(Mp4Muxer), |
| 8011 | Mkv(MkvMuxer), |
| 8012 | /// ProRes in QuickTime ([`crate::prores_out::MovWriter`]). |
| 8013 | Mov(crate::prores_out::MovWriter), |
| 8014 | } |
| 8015 | |
| 8016 | impl Muxer { |
| 8017 | fn finish(self) -> crate::Result<()> { |
| 8018 | match self { |
| 8019 | Self::Mp4(mp4) => mp4.finish(), |
| 8020 | Self::Mkv(mkv) => mkv.finish(), |
| 8021 | Self::Mov(mov) => mov.finish(), |
| 8022 | } |
| 8023 | } |
| 8024 | } |
| 8025 | |
| 8026 | /// Test-only panic point, so the worker's own `catch_unwind` branch in |
| 8027 | /// [`start`] is reachable without a codec parser that actually panics: the |
| 8028 | /// variable names the one `.part` whose export dies, and no export but that |
| 8029 | /// one ever matches it, so a concurrent export in the same process is safe. |
| 8030 | fn inject_export_test_panic(out: &Path) { |
| 8031 | if crate::envcfg::var_os("VE_EXPORT_TEST_PANIC").is_some_and(|target| target == out.as_os_str()) { |
| 8032 | panic!("export test panic: the .part is on disk"); |
| 8033 | } |
| 8034 | } |
| 8035 | |
| 8036 | /// Writes one access unit, creating the file on the first one -- the parameter |
| 8037 | /// sets for `avcC` (and the sequence header for `CodecPrivate`) only exist once |
| 8038 | /// the encoder has coded something. Units with no coded slice are skipped: a |
| 8039 | /// software encoder may hand back an empty buffer while it buffers, and the |
| 8040 | /// muxer rejects a sample that would carry no picture. |
| 8041 | #[allow( |
| 8042 | clippy::too_many_arguments, |
| 8043 | 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" |
| 8044 | )] |
| 8045 | fn write_video( |
| 8046 | muxer: &mut Option<Muxer>, |
| 8047 | out: &Path, |
| 8048 | meta: &VideoMeta, |
| 8049 | settings: &ExportSettings, |
| 8050 | source_colour: Tags, |
| 8051 | source_language: Option<&str>, |
| 8052 | audio: Option<&AudioParams>, |
| 8053 | packets: &mut Option<Vec<crate::AacPacket>>, |
| 8054 | subs: &mut Vec<SubParams>, |
| 8055 | au: &[u8], |
| 8056 | key: bool, |
| 8057 | ten_bit: bool, |
| 8058 | ) -> crate::Result<()> { |
| 8059 | if settings.format.is_prores() { |
| 8060 | // The encoder's own frame, one sample per picture; the track is declared |
| 8061 | // by the first one, the sound is written after the last. |
| 8062 | let Some(Muxer::Mov(mov)) = muxer else { |
| 8063 | unreachable!("the ProRes seat opens its own muxer") |
| 8064 | }; |
| 8065 | return mov.write_frame(au); |
| 8066 | } |
| 8067 | if settings.format.is_hevc() { |
| 8068 | // The parameter sets are in the access unit -- every intra AU carries |
| 8069 | // VPS, SPS and PPS -- and the record built from them is what *both* |
| 8070 | // containers declare the track with: an mp4's `hvcC` box and a |
| 8071 | // Matroska `CodecPrivate` are the same bytes, so the two files are one |
| 8072 | // stream written twice rather than two. |
| 8073 | let sample = |
| 8074 | crate::mux::annex_b_to_hvcc(au).ok_or("a coded HEVC unit with no slice in it")?; |
| 8075 | if settings.format == Format::Hevc { |
| 8076 | let muxer = match muxer { |
| 8077 | Some(Muxer::Mkv(mkv)) => mkv, |
| 8078 | Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), |
| 8079 | none => { |
| 8080 | let hvcc = hevc_params(au, ten_bit)?; |
| 8081 | let sound = audio.zip(packets.take()); |
| 8082 | let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create_hevc( |
| 8083 | out, |
| 8084 | &HevcParams { |
| 8085 | width: meta.width, |
| 8086 | height: meta.height, |
| 8087 | frame_rate: meta.frame_rate, |
| 8088 | hvcc: &hvcc, |
| 8089 | language: source_language.map(str::to_owned), |
| 8090 | colour: (settings.hdr.transfer != HdrTransfer::Sdr).then_some(source_colour), |
| 8091 | light: (settings.hdr.transfer != HdrTransfer::Sdr) |
| 8092 | .then(|| crate::mux::hdr_light(&settings.hdr)), |
| 8093 | }, |
| 8094 | sound, |
| 8095 | std::mem::take(subs), |
| 8096 | )?)) else { |
| 8097 | unreachable!("just inserted a Matroska muxer") |
| 8098 | }; |
| 8099 | mkv.set_chapters(&settings.chapters)?; |
| 8100 | mkv |
| 8101 | } |
| 8102 | }; |
| 8103 | return muxer.write_frame(&sample, key); |
| 8104 | } |
| 8105 | let muxer = match muxer { |
| 8106 | Some(Muxer::Mp4(mp4)) => mp4, |
| 8107 | Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), |
| 8108 | none => { |
| 8109 | let hvcc = hevc_params(au, ten_bit)?; |
| 8110 | let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_hevc( |
| 8111 | out, |
| 8112 | &HevcParams { |
| 8113 | width: meta.width, |
| 8114 | height: meta.height, |
| 8115 | frame_rate: meta.frame_rate, |
| 8116 | hvcc: &hvcc, |
| 8117 | // mp4 does not state a picture's language yet. |
| 8118 | language: None, |
| 8119 | colour: None, |
| 8120 | light: None, |
| 8121 | }, |
| 8122 | audio, |
| 8123 | )?)) else { |
| 8124 | unreachable!("just inserted an mp4 muxer") |
| 8125 | }; |
| 8126 | // The same `colr` rule as AV1's: the colour a 10-bit SDR export |
| 8127 | // declares, which the bitstream's VUI states as well. |
| 8128 | if source_colour != Tags::default() { |
| 8129 | mp4.set_colour(source_colour); |
| 8130 | } |
| 8131 | if settings.hdr.transfer != HdrTransfer::Sdr { |
| 8132 | mp4.set_hdr(&settings.hdr); |
| 8133 | } |
| 8134 | mp4 |
| 8135 | } |
| 8136 | }; |
| 8137 | return muxer.write_coded_sample(&sample, key); |
| 8138 | } |
| 8139 | if settings.format.is_av1() { |
| 8140 | // Every AV1 stream opens on a keyframe, and a keyframe carries the |
| 8141 | // sequence header the track has to declare: an encoder that handed back |
| 8142 | // neither has produced nothing a decoder can start. The same header goes |
| 8143 | // into a `CodecPrivate` and into an `av1C` -- one record, two containers. |
| 8144 | fn params<'a>( |
| 8145 | meta: &VideoMeta, |
| 8146 | au: &'a [u8], |
| 8147 | language: Option<&str>, |
| 8148 | ten_bit: bool, |
| 8149 | colour: Tags, |
| 8150 | ) -> crate::Result<Av1Params<'a>> { |
| 8151 | Ok(Av1Params { |
| 8152 | width: meta.width, |
| 8153 | height: meta.height, |
| 8154 | frame_rate: meta.frame_rate, |
| 8155 | config: crate::mux::av1_sequence_header(au) |
| 8156 | .ok_or("the first coded picture carries no AV1 sequence header")?, |
| 8157 | language: language.map(str::to_owned), |
| 8158 | ten_bit, |
| 8159 | colour: (colour != Tags::default()).then_some(colour), |
| 8160 | }) |
| 8161 | } |
| 8162 | if matches!(settings.format, Format::Av1 | Format::Webm) { |
| 8163 | let muxer = match muxer { |
| 8164 | Some(Muxer::Mkv(mkv)) => mkv, |
| 8165 | Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), |
| 8166 | none => { |
| 8167 | // The sound with it, all of it: the Matroska muxer writes the |
| 8168 | // packets into the clusters of the pictures they play under. |
| 8169 | let sound = audio.zip(packets.take()); |
| 8170 | let created = match settings.format { |
| 8171 | // WebM has no subtitle track to take ([`export_subtitles`]). |
| 8172 | Format::Webm => MkvMuxer::create_webm(out, ¶ms(meta, au, source_language, ten_bit, source_colour)?, sound)?, |
| 8173 | _ => { |
| 8174 | MkvMuxer::create( |
| 8175 | out, |
| 8176 | ¶ms(meta, au, source_language, ten_bit, source_colour)?, |
| 8177 | sound, |
| 8178 | std::mem::take(subs), |
| 8179 | )? |
| 8180 | } |
| 8181 | }; |
| 8182 | let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(created)) else { |
| 8183 | unreachable!("just inserted a Matroska muxer") |
| 8184 | }; |
| 8185 | mkv.set_chapters(&settings.chapters)?; |
| 8186 | mkv |
| 8187 | } |
| 8188 | }; |
| 8189 | return muxer.write_frame(au, key); |
| 8190 | } |
| 8191 | let muxer = match muxer { |
| 8192 | Some(Muxer::Mp4(mp4)) => mp4, |
| 8193 | Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), |
| 8194 | none => { |
| 8195 | let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_av1( |
| 8196 | out, |
| 8197 | ¶ms(meta, au, None, ten_bit, source_colour)?, |
| 8198 | audio, |
| 8199 | )?)) else { |
| 8200 | unreachable!("just inserted an mp4 muxer") |
| 8201 | }; |
| 8202 | // The `colr` box states the colour a 10-bit SDR export declares; an |
| 8203 | // export with no colour of its own keeps the output rule's box. |
| 8204 | if source_colour != Tags::default() { |
| 8205 | mp4.set_colour(source_colour); |
| 8206 | } |
| 8207 | mp4 |
| 8208 | } |
| 8209 | }; |
| 8210 | return muxer.write_coded_sample(au, key); |
| 8211 | } |
| 8212 | if !crate::mux::has_coded_slice(au) { |
| 8213 | return Ok(()); |
| 8214 | } |
| 8215 | let muxer = match muxer { |
| 8216 | Some(Muxer::Mp4(mp4)) => mp4, |
| 8217 | Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), |
| 8218 | none => { |
| 8219 | let (sps, pps) = crate::mux::parameter_sets(au) |
| 8220 | .ok_or("the first coded picture carries no SPS/PPS")?; |
| 8221 | let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create( |
| 8222 | out, |
| 8223 | &VideoParams { |
| 8224 | width: meta.width, |
| 8225 | height: meta.height, |
| 8226 | frame_rate: meta.frame_rate, |
| 8227 | sps, |
| 8228 | pps, |
| 8229 | }, |
| 8230 | audio, |
| 8231 | )?)) else { |
| 8232 | unreachable!("just inserted an mp4 muxer") |
| 8233 | }; |
| 8234 | // A file written in its source's own space says so, rather than |
| 8235 | // claiming the space its height would imply |
| 8236 | // ([`ExportSettings::keep_source_colour`]). |
| 8237 | if settings.keep_source_colour || source_colour != Tags::default() { |
| 8238 | mp4.set_colour(source_colour); |
| 8239 | } |
| 8240 | mp4 |
| 8241 | } |
| 8242 | }; |
| 8243 | muxer.write_video_au(au) |
| 8244 | } |
| 8245 | |
| 8246 | /// The `hvcC` record of the first coded unit, or the refusal by name. Split out |
| 8247 | /// because both HEVC containers ask it in the same words. |
| 8248 | fn hevc_params(au: &[u8], ten_bit: bool) -> crate::Result<Vec<u8>> { |
| 8249 | crate::mux::hvcc_record_at(au, ten_bit) |
| 8250 | .ok_or_else(|| crate::Error::from("the first coded picture carries no HEVC VPS/SPS/PPS")) |
| 8251 | } |
| 8252 | |
| 8253 | fn bitrate_for(meta: &VideoMeta) -> u64 { |
| 8254 | let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL; |
| 8255 | (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE) |
| 8256 | } |
| 8257 | |
| 8258 | fn forced(var: &str) -> bool { |
| 8259 | crate::envcfg::var_os(var).is_some_and(|v| v == "1") |
| 8260 | } |
| 8261 | |
| 8262 | /// Hardware where it is available, software everywhere else -- chosen once for |
| 8263 | /// the whole export, so the stream never changes encoder mid-file. Both codecs |
| 8264 | /// have both seats: an AV1 export runs on the plugin's VA-API encoder where the |
| 8265 | /// GPU has one and on `rav1e` where it has not, which is the same pair H.264 has |
| 8266 | /// had and the same silent fallback. |
| 8267 | enum Enc { |
| 8268 | Hw(HwEncoder), |
| 8269 | Sw { |
| 8270 | encoder: Encoder, |
| 8271 | /// The access unit currently lent out: the encoder hands back an owned |
| 8272 | /// `Vec` where the seat's contract lends a slice, so one lives here |
| 8273 | /// between the two. |
| 8274 | au: Vec<u8>, |
| 8275 | }, |
| 8276 | /// AV1 on the GPU, through the same plugin the H.264 seat uses. |
| 8277 | Av1Hw(HwEncoder), |
| 8278 | /// HEVC on the GPU, through that same plugin -- and intra-only there too, |
| 8279 | /// so this and [`Enc::Hevc`] write the same kind of file. |
| 8280 | HevcHw(HwEncoder, bool), |
| 8281 | /// AV1 software at 10 bits: `rav1e`'s 16-bit context. A picture that passes |
| 8282 | /// through the span untouched arrives as 16-bit planes off the 10-bit decode |
| 8283 | /// ([`Enc::encode_wide`]); an 8-bit picture (one composed on the way) is shifted |
| 8284 | /// up to the same scale in [`Enc::encode`]. |
| 8285 | Av1Sw16 { |
| 8286 | context: rav1e::Context<u16>, |
| 8287 | ready: std::collections::VecDeque<(Vec<u8>, bool)>, |
| 8288 | au: Vec<u8>, |
| 8289 | flushed: bool, |
| 8290 | scratch: [Vec<u16>; 3], |
| 8291 | }, |
| 8292 | Av1Sw { |
| 8293 | context: rav1e::Context<u8>, |
| 8294 | /// Temporal units the encoder has finished but the caller has not |
| 8295 | /// collected: `rav1e` reorders and may hand back several at once, while |
| 8296 | /// this interface is one picture in, one unit out (the plugin's own |
| 8297 | /// `ready` queue exists for the same reason). |
| 8298 | ready: std::collections::VecDeque<(Vec<u8>, bool)>, |
| 8299 | /// The unit currently lent out, for the same reason `Sw` owns one. |
| 8300 | au: Vec<u8>, |
| 8301 | flushed: bool, |
| 8302 | }, |
| 8303 | /// HEVC, intra-only and software: `ec-h265` codes every picture an IDR |
| 8304 | /// carrying its own VPS/SPS/PPS. A batch of frames codes on as many lane |
| 8305 | /// encoders as there are pictures, and each encoder's wavefront splits |
| 8306 | /// whatever cores the lanes leave over -- the same shape as the seat it |
| 8307 | /// replaced, the cores spent on frames and inside one picture at the same |
| 8308 | /// time. Asked for by [`ExportSettings::intra_only`]. |
| 8309 | Hevc(HevcEnc), |
| 8310 | /// HEVC, I+P GOPs, software: `ec-h265`'s sequence coder on a worker thread. |
| 8311 | /// The default HEVC seat ([`Enc::open_hevc_gop`]). |
| 8312 | HevcGop(HevcGop), |
| 8313 | /// ProRes, software: `ec-prores` codes one whole frame per call (its own |
| 8314 | /// worker threads inside), so one picture in is one sample out. The 4:2:0 |
| 8315 | /// pictures of the walk are widened to 10 bits and chroma-upsampled to the |
| 8316 | /// profile's layout ([`crate::prores_out`]). |
| 8317 | ProRes { |
| 8318 | encoder: ec_prores::ProResEncoder, |
| 8319 | /// The sample currently lent out. |
| 8320 | au: Vec<u8>, |
| 8321 | /// 4:4:4 profiles (4444, 4444 XQ) code full chroma. |
| 8322 | full_chroma: bool, |
| 8323 | }, |
| 8324 | } |
| 8325 | |
| 8326 | /// The intra HEVC seat. Frames arrive one at a time (the export walk is one |
| 8327 | /// picture per timeline frame) and are held until there is a lane for each, |
| 8328 | /// then coded in parallel and queued in **display order**. `ec-h265`'s |
| 8329 | /// wavefront spreads one picture across the workers it is given and the lanes |
| 8330 | /// spread the frames across the machine, so decode and render keep filling |
| 8331 | /// the next batch while this one codes -- a seat that coded one picture at a |
| 8332 | /// time would serialize the whole walk behind its encoder (measured: 7.4 fps |
| 8333 | /// against 11.8 at 1080p on the same box, which is the regression this |
| 8334 | /// batching exists to prevent). |
| 8335 | /// |
| 8336 | /// corner-cut: a batch of display-size planes sits in memory (~3 MB a frame |
| 8337 | /// at 1080p, so ~37 MB at 12 lanes) and the tail of a timeline is coded on |
| 8338 | /// fewer lanes than the middle. Upgrade path is a pipeline that keeps every |
| 8339 | /// lane fed from a decoder running ahead of the encoder rather than a batch |
| 8340 | /// barrier. |
| 8341 | struct HevcEnc { |
| 8342 | /// Display-size I420 pictures waiting for a lane, in display order. The |
| 8343 | /// encoder pads to its own coded grid, so nothing is pre-padded here. |
| 8344 | pending: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)>, |
| 8345 | /// Coded access units not yet collected, in the same order. |
| 8346 | ready: std::collections::VecDeque<Vec<u8>>, |
| 8347 | /// The unit currently lent out, for the reason `Sw` owns one: the encoder |
| 8348 | /// hands back an owned `Vec`, the seat's contract lends a slice. |
| 8349 | au: Vec<u8>, |
| 8350 | /// One encoder per lane. `ec-h265` is stateless from picture to picture |
| 8351 | /// (every picture is an IDR), so a lane coding frame *n* needs nothing |
| 8352 | /// the other lanes know. |
| 8353 | lanes: Vec<HevcEncoder>, |
| 8354 | /// The display width the planes arrive at; the height lives in each |
| 8355 | /// encoder's config, where the coded grid is derived from it. |
| 8356 | width: usize, |
| 8357 | /// Whether the lanes code at 10 bits: `pending` then holds little-endian |
| 8358 | /// 16-bit samples, which [`HevcEnc::code_batch`] reads back. |
| 8359 | ten_bit: bool, |
| 8360 | } |
| 8361 | |
| 8362 | impl Enc { |
| 8363 | /// Which seat this *is*, said the way [`video_label`] says it -- so the |
| 8364 | /// name a running export shows is the name the card showed, or the honest |
| 8365 | /// difference where the probe and the open disagreed. |
| 8366 | fn label(&self) -> &'static str { |
| 8367 | match self { |
| 8368 | Self::Hw(_) => video_label(Format::Mp4, true, false), |
| 8369 | Self::Sw { .. } => video_label(Format::Mp4, false, false), |
| 8370 | Self::Av1Hw(_) => video_label(Format::Av1, true, false), |
| 8371 | Self::Av1Sw { .. } | Self::Av1Sw16 { .. } => video_label(Format::Av1, false, false), |
| 8372 | Self::HevcHw(_, intra) => video_label(Format::Hevc, true, *intra), |
| 8373 | Self::Hevc(_) => video_label(Format::Hevc, false, true), |
| 8374 | Self::HevcGop(_) => video_label(Format::Hevc, false, false), |
| 8375 | Self::ProRes { .. } => video_label(Format::ProRes, false, true), |
| 8376 | } |
| 8377 | } |
| 8378 | |
| 8379 | /// The ProRes seat's codec parameters (the sample entry's fourcc rides in |
| 8380 | /// the extradata); `None` for every other seat. |
| 8381 | fn prores_params(&self) -> Option<&ec_core::registry::CodecParameters> { |
| 8382 | match self { |
| 8383 | Self::ProRes { encoder, .. } => Some(ec_core::registry::Encoder::codec_parameters(encoder)), |
| 8384 | _ => None, |
| 8385 | } |
| 8386 | } |
| 8387 | |
| 8388 | /// `ten_bit` is [`wide_ten_bit`]'s answer; it means something to AV1 and HEVC only. |
| 8389 | /// `colour` is what the file declares, in the bitstream as well as the container. |
| 8390 | fn open( |
| 8391 | meta: &VideoMeta, |
| 8392 | settings: &ExportSettings, |
| 8393 | ten_bit: bool, |
| 8394 | colour: ColorDescription, |
| 8395 | ) -> crate::Result<Self> { |
| 8396 | // Which *codec* the picture is, not which container it goes in: both AV1 |
| 8397 | // formats run the same encoder, and so do both HEVC ones. |
| 8398 | if settings.format.is_av1() { |
| 8399 | return Self::open_av1(meta, settings, ten_bit, colour); |
| 8400 | } |
| 8401 | if settings.format.is_hevc() { |
| 8402 | return Self::open_hevc(meta, settings, ten_bit, colour); |
| 8403 | } |
| 8404 | if settings.format.is_prores() { |
| 8405 | return Self::open_prores(meta, settings, colour); |
| 8406 | } |
| 8407 | // A caller's number goes through the same clamp as the computed one: a |
| 8408 | // zero bitrate switches the software encoder's lookahead on, which would |
| 8409 | // break the one-picture-per-call contract `encode` documents below. |
| 8410 | let bitrate = bitrate_of(meta, settings); |
| 8411 | // The plugin wants an exact rational, and the muxer already picks one |
| 8412 | // that is exact at every rate we can read -- `fps * 1000 / 1000` would |
| 8413 | // hand 24000/1001 over as a rounded 23.976, which is the same |
| 8414 | // truncation the container timing had. |
| 8415 | crate::mux::frame_timing(meta.frame_rate)?; |
| 8416 | if let Some(hw) = hw_seat(meta, settings)? { |
| 8417 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware (VA-API plugin)"); } |
| 8418 | return Ok(Self::Hw(hw)); |
| 8419 | } |
| 8420 | if settings.qp.is_some() { |
| 8421 | return Err(QP_SOFTWARE_REFUSAL.into()); |
| 8422 | } |
| 8423 | // H.264 codes 16x16 macroblocks, and ec-h264's floor is the |
| 8424 | // macroblock itself -- the old encoder took any positive even size. |
| 8425 | // Named here, where a card can show it, rather than let the encoder's |
| 8426 | // error surface from inside an export already under way. |
| 8427 | if meta.width < 16 || meta.height < 16 { |
| 8428 | return Err(format!( |
| 8429 | "{}x{} cannot be written as H.264: the picture is smaller \ |
| 8430 | than one 16x16 macroblock", |
| 8431 | meta.width, meta.height |
| 8432 | ) |
| 8433 | .into()); |
| 8434 | } |
| 8435 | // 4:2:0 addresses its conformance window in *chroma* samples, so an odd |
| 8436 | // picture cannot be cropped back to itself -- and an odd dimension has |
| 8437 | // no chroma plane of its own to begin with. Named rather than padded to |
| 8438 | // something a decoder would then show a column of: the same refusal the |
| 8439 | // HEVC seat makes, and x264's and ffmpeg's own for 4:2:0 H.264. |
| 8440 | if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) { |
| 8441 | return Err(format!( |
| 8442 | "{}x{} cannot be written as H.264: 4:2:0 needs even dimensions", |
| 8443 | meta.width, meta.height |
| 8444 | ) |
| 8445 | .into()); |
| 8446 | } |
| 8447 | let mut cfg = EncoderConfig::new(meta.width, meta.height); |
| 8448 | cfg.framerate = meta.frame_rate as f32; |
| 8449 | cfg.bitrate = bitrate.min(u32::MAX as u64) as u32; |
| 8450 | // Two seconds between key frames, and no B-frames on either path: the |
| 8451 | // muxer times everything by duration alone, which reordering would |
| 8452 | // break. A proxy asks for one frame a GOP, which is every frame its own |
| 8453 | // starting point ([`ExportSettings::intra_only`]). |
| 8454 | cfg.gop_size = match settings.intra_only { |
| 8455 | true => 1, |
| 8456 | false => gop_frames(meta, settings).unwrap_or((meta.frame_rate * 2.0).round().max(1.0) as u32), |
| 8457 | }; |
| 8458 | // Fast, the rung a fallback is allowed to cost -- the cheaper arm of |
| 8459 | // the preset ladder, the one the old seat's own S1 also picked when its |
| 8460 | // Balanced rung halved the rate for the same bitrate. |
| 8461 | cfg.preset = Preset::Fast; |
| 8462 | // 8x8 transform off. At this rung it is half the pure-encode cost |
| 8463 | // (17.2 ms/frame against 35.1 at 720p across all cores, measured at |
| 8464 | // the swap) for at most 0.7 dB BD-PSNR -- against an old seat that ran |
| 8465 | // Constrained Baseline and never had the transform in the first |
| 8466 | // place. The export stays Main-profile CABAC, which is where the |
| 8467 | // quality over the old seat lives; a constant-QP mode would be the |
| 8468 | // place to revisit the rung whole. |
| 8469 | cfg.transform_8x8 = false; |
| 8470 | let encoder = Encoder::new(cfg).map_err(|e| format!("software encoder: {e}"))?; |
| 8471 | Ok(Self::Sw { |
| 8472 | encoder, |
| 8473 | au: Vec::new(), |
| 8474 | }) |
| 8475 | } |
| 8476 | |
| 8477 | /// The AV1 pair. The hardware seat is the plugin's, opened by a symbol of |
| 8478 | /// its own (`vh_enc_av1_open`) so a plugin built before AV1 encode existed |
| 8479 | /// simply has none and this falls through -- the same "no" a GPU without an |
| 8480 | /// AV1 encode entrypoint gives, and the same silent fallback either way. |
| 8481 | /// |
| 8482 | /// It is **asked for by name**, which is the one place this pair does not |
| 8483 | /// mirror the H.264 one: the vendored cros-codecs AV1 encoder hung the GPU |
| 8484 | /// on this project's own radeonsi box -- `engine_hw: operation failed`, |
| 8485 | /// then an amdgpu hard recovery and a lost context, measured 2026-08-10 |
| 8486 | /// exporting the 720p fixture. A software encoder that takes half a minute |
| 8487 | /// is a worse export than a hardware one; a driver reset is not an export |
| 8488 | /// at all. So [`EncoderSeat::Auto`] takes `rav1e` here and only |
| 8489 | /// [`EncoderSeat::Hardware`] -- a person picking the GPU for AV1 on the |
| 8490 | /// card, under a row that names the risk -- enters the plugin's seat. It |
| 8491 | /// was an env pin (`VE_HW_AV1=1`) until the card could ask, which is a |
| 8492 | /// switch nobody exporting a film would ever find. |
| 8493 | /// |
| 8494 | /// corner-cut: the upgrade path is a driver this was reproduced against (or a |
| 8495 | /// cros-codecs release that fixes it) plus a probe encode of one frame at |
| 8496 | /// open, after which `Auto` can prefer hardware the way H.264 does. |
| 8497 | fn open_av1( |
| 8498 | meta: &VideoMeta, |
| 8499 | settings: &ExportSettings, |
| 8500 | ten_bit: bool, |
| 8501 | colour: ColorDescription, |
| 8502 | ) -> crate::Result<Self> { |
| 8503 | let bitrate = bitrate_of(meta, settings); |
| 8504 | let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; |
| 8505 | // Two seconds between keyframes, as the H.264 seat does: a seek may only |
| 8506 | // land on one, and this is what a cluster of the Matroska file is. |
| 8507 | let gop = gop_frames(meta, settings).map_or_else(|| (meta.frame_rate * 2.0).round().max(1.0) as u64, u64::from); |
| 8508 | // The 10-bit seat is software: the GPU encode is 8-bit only. |
| 8509 | let hw = match ten_bit { |
| 8510 | true => None, |
| 8511 | false => hw_seat(meta, settings)?, |
| 8512 | }; |
| 8513 | if let Some(hw) = hw { |
| 8514 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware AV1 (VA-API plugin)"); } |
| 8515 | return Ok(Self::Av1Hw(hw)); |
| 8516 | } |
| 8517 | if settings.qp.is_some() { |
| 8518 | return Err(QP_SOFTWARE_REFUSAL.into()); |
| 8519 | } |
| 8520 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software AV1 (rav1e)"); } |
| 8521 | // Seconds per frame, which is what `frame_timing` already has as an |
| 8522 | // exact rational -- 1001/24000 rather than a rounded 23.976. |
| 8523 | let mut cfg = rav1e::EncoderConfig { |
| 8524 | width: meta.width as usize, |
| 8525 | height: meta.height as usize, |
| 8526 | bit_depth: if ten_bit { 10 } else { 8 }, |
| 8527 | chroma_sampling: rav1e::prelude::ChromaSampling::Cs420, |
| 8528 | time_base: rav1e::prelude::Rational::new(u64::from(fps_den), u64::from(fps_num)), |
| 8529 | ..Default::default() |
| 8530 | }; |
| 8531 | cfg.min_key_frame_interval = gop; |
| 8532 | cfg.max_key_frame_interval = gop; |
| 8533 | cfg.bitrate = bitrate.min(i32::MAX as u64) as i32; |
| 8534 | // The fastest preset, with the settings that matter for speed at that |
| 8535 | // preset. Tiles spread one frame over the cores (one tile ran on a single |
| 8536 | // core); low latency drops the lookahead; CDEF and loop restoration are |
| 8537 | // off for speed (a 10 s 1080p export measured the same PSNR against the |
| 8538 | // source either way). Measured: 170 s before, about 17 s after, on a box |
| 8539 | // with load ~15. The `asm` feature in Cargo.toml is the other half. |
| 8540 | cfg.speed_settings = rav1e::prelude::SpeedSettings::from_preset(AV1_SPEED); |
| 8541 | cfg.tiles = AV1_TILES; |
| 8542 | cfg.low_latency = true; |
| 8543 | cfg.speed_settings.cdef = false; |
| 8544 | cfg.speed_settings.lrf = false; |
| 8545 | cfg.speed_settings.multiref = false; |
| 8546 | // What the sequence header says the samples mean, for the reason |
| 8547 | // [`video_signal_type`] gives: a container tag is the second answer a |
| 8548 | // decoder looks at, not the first. Written as rav1e's own enums rather |
| 8549 | // than the H.273 numbers -- the crate has no `from` for the code points, |
| 8550 | // and the output rule only ever picks one of these two spaces. |
| 8551 | let out = colour; |
| 8552 | cfg.pixel_range = rav1e::prelude::PixelRange::Limited; |
| 8553 | cfg.color_description = Some(match out.matrix { |
| 8554 | Matrix::Bt709 => rav1e::prelude::ColorDescription { |
| 8555 | color_primaries: rav1e::prelude::ColorPrimaries::BT709, |
| 8556 | transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT709, |
| 8557 | matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT709, |
| 8558 | }, |
| 8559 | // A 10-bit SDR export of a BT.2020 source: the source's own space. |
| 8560 | Matrix::Bt2020Ncl => rav1e::prelude::ColorDescription { |
| 8561 | color_primaries: rav1e::prelude::ColorPrimaries::BT2020, |
| 8562 | transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT2020_10Bit, |
| 8563 | matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT2020NCL, |
| 8564 | }, |
| 8565 | _ => rav1e::prelude::ColorDescription { |
| 8566 | color_primaries: rav1e::prelude::ColorPrimaries::BT601, |
| 8567 | transfer_characteristics: rav1e::prelude::TransferCharacteristics::BT601, |
| 8568 | matrix_coefficients: rav1e::prelude::MatrixCoefficients::BT601, |
| 8569 | }, |
| 8570 | }); |
| 8571 | let config = rav1e::Config::new() |
| 8572 | .with_encoder_config(cfg) |
| 8573 | .with_threads(std::thread::available_parallelism().map_or(1, |n| n.get())); |
| 8574 | if ten_bit { |
| 8575 | let context = config |
| 8576 | .new_context::<u16>() |
| 8577 | .map_err(|e| format!("software AV1 encoder: {e}"))?; |
| 8578 | return Ok(Self::Av1Sw16 { |
| 8579 | context, |
| 8580 | ready: std::collections::VecDeque::new(), |
| 8581 | au: Vec::new(), |
| 8582 | flushed: false, |
| 8583 | scratch: Default::default(), |
| 8584 | }); |
| 8585 | } |
| 8586 | let context = config |
| 8587 | .new_context::<u8>() |
| 8588 | .map_err(|e| format!("software AV1 encoder: {e}"))?; |
| 8589 | Ok(Self::Av1Sw { |
| 8590 | context, |
| 8591 | ready: std::collections::VecDeque::new(), |
| 8592 | au: Vec::new(), |
| 8593 | flushed: false, |
| 8594 | }) |
| 8595 | } |
| 8596 | |
| 8597 | /// The HEVC pair: the plugin's VA-API seat where the GPU has one, and the |
| 8598 | /// software intra encoder everywhere else -- below the driver's 384x384 |
| 8599 | /// floor, on a plugin too old to carry the symbol, on a GPU with no HEVC |
| 8600 | /// encode entrypoint. Silent either way, because both write the same kind |
| 8601 | /// of file. |
| 8602 | /// |
| 8603 | /// The default is I+P GOPs, on the hardware seat where there is one and on |
| 8604 | /// the software seat ([`Enc::open_hevc_gop`]) where there is not. With |
| 8605 | /// [`ExportSettings::intra_only`] it is intra: every picture an IDR, on the |
| 8606 | /// hardware seat where there is one and on the lanes below where there is |
| 8607 | /// not -- an intraframe master in the shape of ProRes or DNxHD, large |
| 8608 | /// files, every frame a cut point. |
| 8609 | /// |
| 8610 | /// The picture is coded at its own size and padded to whole minimum coding |
| 8611 | /// blocks *by the encoder*, which crops the padding back off with the SPS |
| 8612 | /// conformance window, so 1920x1080 is a legal export rather than a |
| 8613 | /// refusal. |
| 8614 | fn open_hevc( |
| 8615 | meta: &VideoMeta, |
| 8616 | settings: &ExportSettings, |
| 8617 | ten_bit: bool, |
| 8618 | colour: ColorDescription, |
| 8619 | ) -> crate::Result<Self> { |
| 8620 | // The muxers time by it and the mp4 one wants an exact rational: asked |
| 8621 | // here so an impossible rate fails before a frame is coded. The same |
| 8622 | // rational goes into the SPS's VUI, whose timing is also where the |
| 8623 | // encoder picks the level from. |
| 8624 | let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?; |
| 8625 | // 4:2:0 addresses its conformance window in *chroma* samples, so an odd |
| 8626 | // picture cannot be cropped back to itself -- and an odd dimension has |
| 8627 | // no chroma plane of its own to begin with. Named rather than padded to |
| 8628 | // something a decoder would then show a column of. |
| 8629 | if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) { |
| 8630 | return Err(format!( |
| 8631 | "{}x{} cannot be written as HEVC: 4:2:0 needs even dimensions", |
| 8632 | meta.width, meta.height |
| 8633 | ) |
| 8634 | .into()); |
| 8635 | } |
| 8636 | // The GPU seat is 8-bit only, so a 10-bit export is software. |
| 8637 | let hw = match ten_bit { |
| 8638 | true => None, |
| 8639 | false => hw_seat(meta, settings)?, |
| 8640 | }; |
| 8641 | if let Some(hw) = hw { |
| 8642 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: hardware HEVC (VA-API plugin)"); } |
| 8643 | return Ok(Self::HevcHw(hw, settings.intra_only)); |
| 8644 | } |
| 8645 | if !settings.intra_only { |
| 8646 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC I+P (ec-h265)"); } |
| 8647 | return Self::open_hevc_gop(meta, settings, (fps_num, fps_den), ten_bit, colour); |
| 8648 | } |
| 8649 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software HEVC intra (ec-h265)"); } |
| 8650 | // The cores are split between the lanes and the wavefront inside one: |
| 8651 | // twelve lanes of one worker each on this box's twelve threads, |
| 8652 | // fewer lanes on a smaller machine with a wider wavefront each. |
| 8653 | let cores = std::thread::available_parallelism().map_or(1, |n| n.get()); |
| 8654 | let lane_count = cores.clamp(1, HEVC_LANES); |
| 8655 | let per_lane = cores.div_ceil(lane_count); |
| 8656 | let mut lanes = Vec::with_capacity(lane_count); |
| 8657 | for _ in 0..lane_count { |
| 8658 | let mut cfg = HevcEncoderConfig::new(meta.width, meta.height); |
| 8659 | cfg.bit_depth = if ten_bit { 10 } else { 8 }; |
| 8660 | // The bitrate row a user picked, mapped through the same measured |
| 8661 | // anchor as before ([`hevc_qp`]) and held: a *quality* dial, not a |
| 8662 | // rate controller. The encoder's own per-picture target-bits mode |
| 8663 | // would chase the number with a correction pass -- named headroom, |
| 8664 | // not behaviour this seat takes silently. |
| 8665 | cfg.rate_control = RateControl::ConstantQp(settings.qp.map_or_else(|| hevc_qp(meta, settings), |qp| qp as i32)); |
| 8666 | cfg.timing = Some((fps_den, fps_num)); |
| 8667 | cfg.video_signal_type = Some(video_signal_type(colour)); |
| 8668 | apply_hdr(&mut cfg, settings); |
| 8669 | cfg.speed = settings.hevc_speed.unwrap_or_default().preset(); |
| 8670 | cfg.threads = per_lane; |
| 8671 | lanes.push(HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?); |
| 8672 | } |
| 8673 | Ok(Self::Hevc(HevcEnc { |
| 8674 | pending: Vec::new(), |
| 8675 | ready: std::collections::VecDeque::new(), |
| 8676 | au: Vec::new(), |
| 8677 | lanes, |
| 8678 | width: meta.width as usize, |
| 8679 | ten_bit, |
| 8680 | })) |
| 8681 | } |
| 8682 | |
| 8683 | /// The ProRes seat: the profile's encoder at the picture's size, tagged with |
| 8684 | /// the colour the file declares. Progressive, no alpha. |
| 8685 | fn open_prores(meta: &VideoMeta, settings: &ExportSettings, colour: ColorDescription) -> crate::Result<Self> { |
| 8686 | if !meta.width.is_multiple_of(2) || !meta.height.is_multiple_of(2) { |
| 8687 | return Err(format!( |
| 8688 | "{}x{} cannot be written as ProRes from a 4:2:0 picture: it needs even dimensions", |
| 8689 | meta.width, meta.height |
| 8690 | ) |
| 8691 | .into()); |
| 8692 | } |
| 8693 | let profile = settings.prores_profile; |
| 8694 | let mut cfg = ec_prores::EncoderConfig::new(profile.codec(), meta.width, meta.height); |
| 8695 | let (primaries, transfer, matrix) = colour.codes(); |
| 8696 | cfg.color = ec_core::frame::ColorInfo { |
| 8697 | primaries: primaries as u8, |
| 8698 | transfer: transfer as u8, |
| 8699 | matrix: matrix as u8, |
| 8700 | full_range: false, |
| 8701 | }; |
| 8702 | if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("export encoder: software ProRes (ec-prores)"); } |
| 8703 | let encoder = ec_prores::ProResEncoder::new(cfg).map_err(|e| format!("ProRes encoder: {e}"))?; |
| 8704 | Ok(Self::ProRes { encoder, au: Vec::new(), full_chroma: profile.is_444() }) |
| 8705 | } |
| 8706 | |
| 8707 | /// One 10-bit picture of 16-bit planes, at 10-bit scale, in and at most one |
| 8708 | /// access unit out. Asked only of the 10-bit seat, which [`wide_ten_bit`] opens |
| 8709 | /// with the same answer the export loop checks. |
| 8710 | fn encode_wide( |
| 8711 | &mut self, |
| 8712 | y: &[u16], |
| 8713 | u: &[u16], |
| 8714 | v: &[u16], |
| 8715 | width: u32, |
| 8716 | height: u32, |
| 8717 | ) -> crate::Result<Option<(&[u8], bool)>> { |
| 8718 | match self { |
| 8719 | Self::Av1Sw16 { context, ready, au, .. } => { |
| 8720 | submit_av1_16(context, ready, au, [y, u, v], width, height) |
| 8721 | } |
| 8722 | Self::HevcGop(gop) if gop.ten_bit => { |
| 8723 | gop.push_wide(y, u, v, width, height)?; |
| 8724 | Ok(pop_gop(gop)) |
| 8725 | } |
| 8726 | Self::ProRes { encoder, au, full_chroma } => { |
| 8727 | let frame = |
| 8728 | crate::prores_out::upsampled_frame(y, u, v, width as usize, height as usize, *full_chroma)?; |
| 8729 | *au = encoder.encode(&frame).map_err(|e| format!("ProRes encode: {e}"))?; |
| 8730 | Ok(Some((&au[..], true))) |
| 8731 | } |
| 8732 | Self::Hevc(hevc) if hevc.ten_bit => { |
| 8733 | hevc.pending.push((le_bytes(y), le_bytes(u), le_bytes(v))); |
| 8734 | if hevc.pending.len() >= hevc.lanes.len() { |
| 8735 | hevc.code_batch()?; |
| 8736 | } |
| 8737 | Ok(pop_hevc(hevc)) |
| 8738 | } |
| 8739 | _ => Err("a 10-bit picture needs a 10-bit seat".into()), |
| 8740 | } |
| 8741 | } |
| 8742 | |
| 8743 | /// Whether this is a software HEVC seat coding at 10 bits. |
| 8744 | fn hevc_ten_bit(&self) -> bool { |
| 8745 | match self { |
| 8746 | Self::HevcGop(gop) => gop.ten_bit, |
| 8747 | Self::Hevc(hevc) => hevc.ten_bit, |
| 8748 | _ => false, |
| 8749 | } |
| 8750 | } |
| 8751 | |
| 8752 | /// One picture in, at most one access unit out, and whether that unit is one |
| 8753 | /// a decoder may be started from -- which only the Matroska muxer asks, the |
| 8754 | /// mp4 one reading its own sync flag off the IDR slice. |
| 8755 | /// |
| 8756 | /// The H.264 seat keeps the contract structurally: `ec-h264` buffers |
| 8757 | /// nothing -- no lookahead, and B pictures coded as none -- so one call is |
| 8758 | /// one access unit by construction. The HEVC seat's lanes hold a small |
| 8759 | /// batch of pictures until there is a lane for each, so it says "at most |
| 8760 | /// one" and means it; the old H.264 seat only kept the contract because |
| 8761 | /// its GOP-buffering lookahead needed a zero bitrate and this path was |
| 8762 | /// always CBR. |
| 8763 | fn encode( |
| 8764 | &mut self, |
| 8765 | y: &[u8], |
| 8766 | u: &[u8], |
| 8767 | v: &[u8], |
| 8768 | width: u32, |
| 8769 | height: u32, |
| 8770 | intra: bool, |
| 8771 | ) -> crate::Result<Option<(&[u8], bool)>> { |
| 8772 | // A composed 8-bit picture on the 10-bit HEVC seat: shifted up to the |
| 8773 | // seat's scale, the same shift the AV1 10-bit seat makes. |
| 8774 | if self.hevc_ten_bit() { |
| 8775 | let up = |p: &[u8]| p.iter().map(|&v| u16::from(v) << 2 | u16::from(v) >> 6).collect::<Vec<u16>>(); |
| 8776 | let (y, u, v) = (up(y), up(u), up(v)); |
| 8777 | return self.encode_wide(&y, &u, &v, width, height); |
| 8778 | } |
| 8779 | if let Self::ProRes { encoder, au, full_chroma } = self { |
| 8780 | // A composed 8-bit picture: widened to 10 bits and upsampled in one pass. |
| 8781 | let frame = |
| 8782 | crate::prores_out::upsampled_frame_8(y, u, v, width as usize, height as usize, *full_chroma)?; |
| 8783 | *au = encoder.encode(&frame).map_err(|e| format!("ProRes encode: {e}"))?; |
| 8784 | return Ok(Some((&au[..], true))); |
| 8785 | } |
| 8786 | match self { |
| 8787 | Self::Av1Hw(hw) => { |
| 8788 | let au = hw.encode(y, u, v, width, height, false)?; |
| 8789 | // What the *bitstream* says, not what was asked for: an AV1 |
| 8790 | // keyframe carries the sequence header, which is the same mark |
| 8791 | // `demux` reads a sync point off. A driver that emitted one |
| 8792 | // unasked is then still a seek target, and one that skipped a |
| 8793 | // requested keyframe cannot be mistaken for a decoder's start. |
| 8794 | Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some()))) |
| 8795 | } |
| 8796 | Self::Av1Sw16 { |
| 8797 | context, |
| 8798 | ready, |
| 8799 | au, |
| 8800 | scratch, |
| 8801 | .. |
| 8802 | } => { |
| 8803 | // An 8-bit picture on the 10-bit seat: each sample scaled up to |
| 8804 | // the same range (255 maps to 1023, not 1020). |
| 8805 | let (w, h) = (width as usize, height as usize); |
| 8806 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 8807 | for (dst, (src, n)) in scratch.iter_mut().zip([(y, w * h), (u, cw * ch), (v, cw * ch)]) { |
| 8808 | dst.clear(); |
| 8809 | dst.extend(src[..n].iter().map(|&s| { |
| 8810 | let s = u16::from(s); |
| 8811 | (s << 2) | (s >> 6) |
| 8812 | })); |
| 8813 | } |
| 8814 | let [sy, su, sv] = &*scratch; |
| 8815 | submit_av1_16(context, ready, au, [&sy[..], &su[..], &sv[..]], width, height) |
| 8816 | } |
| 8817 | Self::Av1Sw { |
| 8818 | context, ready, au, .. |
| 8819 | } => { |
| 8820 | let mut frame = context.new_frame(); |
| 8821 | let (w, h) = (width as usize, height as usize); |
| 8822 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 8823 | frame.planes[0].copy_from_raw_u8(&y[..w * h], w, 1); |
| 8824 | frame.planes[1].copy_from_raw_u8(&u[..cw * ch], cw, 1); |
| 8825 | frame.planes[2].copy_from_raw_u8(&v[..cw * ch], cw, 1); |
| 8826 | if let Err(e) = context.send_frame(frame) { |
| 8827 | return Err(format!("software AV1 encode: {e}").into()); |
| 8828 | } |
| 8829 | collect_av1(context, ready)?; |
| 8830 | Ok(pop_av1(ready, au)) |
| 8831 | } |
| 8832 | Self::HevcHw(hw, intra) => Ok(hw |
| 8833 | .encode(y, u, v, width, height, *intra)? |
| 8834 | .map(|au| (au, hevc_irap(au)))), |
| 8835 | Self::Hevc(hevc) => { |
| 8836 | // The display-size planes are kept as they came: `ec-h265` |
| 8837 | // pads to its own coded grid and crops back through the SPS |
| 8838 | // conformance window. |
| 8839 | hevc.pending.push((y.to_vec(), u.to_vec(), v.to_vec())); |
| 8840 | if hevc.pending.len() >= hevc.lanes.len() { |
| 8841 | hevc.code_batch()?; |
| 8842 | } |
| 8843 | // Every intra AU is an IDR, so every one of them is a key |
| 8844 | // frame -- which is what an intraframe master means. |
| 8845 | Ok(pop_hevc(hevc)) |
| 8846 | } |
| 8847 | Self::HevcGop(gop) => { |
| 8848 | gop.push(y, u, v, width, height)?; |
| 8849 | Ok(pop_gop(gop)) |
| 8850 | } |
| 8851 | // A key frame is asked for on every picture where the file is an |
| 8852 | // intraframe one, and the flag says what was asked: the mp4 muxer |
| 8853 | // reads its own sync marks off the IDR slices either way, so this |
| 8854 | // is what a Matroska one would be told. |
| 8855 | Self::Hw(hw) => Ok(hw |
| 8856 | .encode(y, u, v, width, height, intra)? |
| 8857 | .map(|au| (au, intra))), |
| 8858 | Self::ProRes { .. } => unreachable!("the ProRes seat is handled before this match"), |
| 8859 | Self::Sw { encoder, au } => { |
| 8860 | // The key flag is what the bitstream says -- an IDR where the |
| 8861 | // GOP asked for one, every picture on an intraframe export -- |
| 8862 | // which is what the hardware seat's `intra` carries too. The |
| 8863 | // planes go in as borrows; the old seat was handed a copy. |
| 8864 | let view = PictureView::i420(width, height, y, u, v); |
| 8865 | let coded = encoder |
| 8866 | .encode(&view) |
| 8867 | .map_err(|e| format!("software encode: {e}"))?; |
| 8868 | *au = coded.au; |
| 8869 | Ok(Some((&au[..], coded.key_frame)).filter(|(au, _)| !au.is_empty())) |
| 8870 | } |
| 8871 | } |
| 8872 | } |
| 8873 | |
| 8874 | /// What a decoded buffer must look like to reach this seat without ever |
| 8875 | /// being read back -- `None` for every seat that reads bytes, which is both |
| 8876 | /// software encoders and the intra HEVC one. |
| 8877 | /// |
| 8878 | /// The AV1 hardware seat is left out on purpose: it is entered only when a |
| 8879 | /// person picks it by name because the vendored encoder reset this project's GPU |
| 8880 | /// ([`Enc::open_av1`]), and a path that cannot be measured is not one to |
| 8881 | /// widen. |
| 8882 | /// `&mut` because an isolated seat has to *ask* the process it lives in |
| 8883 | /// ([`crate::hwproc`]), which is a round trip on its socket. |
| 8884 | fn dma_want(&mut self, meta: &VideoMeta) -> Option<crate::hw::DmaWant> { |
| 8885 | match self { |
| 8886 | Self::Hw(hw) | Self::HevcHw(hw, _) => hw.dma_want(meta.width, meta.height), |
| 8887 | _ => None, |
| 8888 | } |
| 8889 | } |
| 8890 | |
| 8891 | /// One picture the decoder left on the GPU in, at most one access unit out. |
| 8892 | /// Same answer as [`Enc::encode`], including which units a decoder may be |
| 8893 | /// started from, because it is the same encoder -- only the picture took |
| 8894 | /// another way in. |
| 8895 | /// |
| 8896 | /// `intra` therefore carries here too, and not for symmetry's sake: a proxy |
| 8897 | /// of a file already small enough is coded at that file's own size |
| 8898 | /// ([`crate::proxy::size_for`]), which is the one case where an intraframe |
| 8899 | /// export's decoder and encoder agree on a surface and the buffer goes |
| 8900 | /// straight across. An access unit marked as no sync point there would give |
| 8901 | /// a stand-in whose whole reason to exist is that every frame is one. |
| 8902 | fn encode_dma(&mut self, dma: &DmaFrame, intra: bool) -> crate::Result<Option<(&[u8], bool)>> { |
| 8903 | match self { |
| 8904 | Self::Hw(hw) => Ok(hw.encode_dma(dma, intra)?.map(|au| (au, intra))), |
| 8905 | Self::HevcHw(hw, intra) => Ok(hw.encode_dma(dma, *intra)?.map(|au| (au, hevc_irap(au)))), |
| 8906 | // Unreachable through [`Enc::dma_want`], which is the only thing |
| 8907 | // that puts a span's decoder on this path. |
| 8908 | _ => Err("this encoder takes pictures as bytes, not as buffers".into()), |
| 8909 | } |
| 8910 | } |
| 8911 | |
| 8912 | /// End of stream; call until it returns `None`. |
| 8913 | fn drain(&mut self) -> crate::Result<Option<(&[u8], bool)>> { |
| 8914 | match self { |
| 8915 | Self::Av1Hw(hw) => { |
| 8916 | let au = hw.drain()?; |
| 8917 | Ok(au.map(|au| (au, crate::mux::av1_sequence_header(au).is_some()))) |
| 8918 | } |
| 8919 | Self::Av1Sw16 { |
| 8920 | context, |
| 8921 | ready, |
| 8922 | au, |
| 8923 | flushed, |
| 8924 | .. |
| 8925 | } => { |
| 8926 | if !*flushed { |
| 8927 | *flushed = true; |
| 8928 | context.flush(); |
| 8929 | collect_av1(context, ready)?; |
| 8930 | } |
| 8931 | Ok(pop_av1(ready, au)) |
| 8932 | } |
| 8933 | Self::Av1Sw { |
| 8934 | context, |
| 8935 | ready, |
| 8936 | au, |
| 8937 | flushed, |
| 8938 | } => { |
| 8939 | if !*flushed { |
| 8940 | *flushed = true; |
| 8941 | context.flush(); |
| 8942 | collect_av1(context, ready)?; |
| 8943 | } |
| 8944 | Ok(pop_av1(ready, au)) |
| 8945 | } |
| 8946 | Self::HevcHw(hw, _) => Ok(hw.drain()?.map(|au| (au, hevc_irap(au)))), |
| 8947 | // The tail batch: fewer frames than lanes, coded on as many |
| 8948 | // encoders as there are frames left. |
| 8949 | Self::Hevc(hevc) => { |
| 8950 | if !hevc.pending.is_empty() { |
| 8951 | hevc.code_batch()?; |
| 8952 | } |
| 8953 | Ok(pop_hevc(hevc)) |
| 8954 | } |
| 8955 | Self::HevcGop(gop) => { |
| 8956 | gop.finish()?; |
| 8957 | Ok(pop_gop(gop)) |
| 8958 | } |
| 8959 | Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))), |
| 8960 | // Nothing is held back: every picture `encode` took already came |
| 8961 | // back with its access unit, so end of stream is the empty answer. |
| 8962 | Self::Sw { .. } | Self::ProRes { .. } => Ok(None), |
| 8963 | } |
| 8964 | } |
| 8965 | } |
| 8966 | |
| 8967 | impl HevcEnc { |
| 8968 | /// The whole pending batch, one frame per lane, collected back in the |
| 8969 | /// order it went out -- `std::thread::scope`, because the encode borrows |
| 8970 | /// the planes and the lanes rather than copying them again. A panic inside |
| 8971 | /// a lane comes back as an error rather than unwinding the export thread. |
| 8972 | fn code_batch(&mut self) -> crate::Result<()> { |
| 8973 | let width = self.width; |
| 8974 | let chroma = width / 2; |
| 8975 | let pending = std::mem::take(&mut self.pending); |
| 8976 | let ten_bit = self.ten_bit; |
| 8977 | let coded: Vec<crate::Result<Vec<u8>>> = std::thread::scope(|scope| { |
| 8978 | let lanes: Vec<_> = self |
| 8979 | .lanes |
| 8980 | .iter() |
| 8981 | .zip(pending.iter()) |
| 8982 | .map(|(encoder, (y, cb, cr))| { |
| 8983 | scope.spawn(move || { |
| 8984 | let coded = if ten_bit { |
| 8985 | let samples = |p: &[u8]| -> Vec<u16> { |
| 8986 | p.as_chunks::<2>().0.iter().map(|c| u16::from_le_bytes(*c)).collect() |
| 8987 | }; |
| 8988 | let (y, cb, cr) = (samples(y), samples(cb), samples(cr)); |
| 8989 | encoder.encode_idr_samples(&y, width, &cb, chroma, &cr, chroma) |
| 8990 | } else { |
| 8991 | encoder.encode_idr_planes(y, width, cb, chroma, cr, chroma) |
| 8992 | }; |
| 8993 | coded |
| 8994 | .map(|coded| coded.au) |
| 8995 | .map_err(|e| crate::Error::from(format!("software HEVC encode: {e}"))) |
| 8996 | }) |
| 8997 | }) |
| 8998 | .collect(); |
| 8999 | lanes |
| 9000 | .into_iter() |
| 9001 | .map(|lane| { |
| 9002 | lane.join() |
| 9003 | .unwrap_or_else(|_| Err("an HEVC encode lane panicked".into())) |
| 9004 | }) |
| 9005 | .collect() |
| 9006 | }); |
| 9007 | for au in coded { |
| 9008 | self.ready.push_back(au?); |
| 9009 | } |
| 9010 | Ok(()) |
| 9011 | } |
| 9012 | } |
| 9013 | |
| 9014 | /// The oldest coded intra AU, lent out under the same "valid until the next |
| 9015 | /// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key |
| 9016 | /// flag is not a guess. |
| 9017 | fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> { |
| 9018 | hevc.au = hevc.ready.pop_front()?; |
| 9019 | Some((&hevc.au[..], true)) |
| 9020 | } |
| 9021 | |
| 9022 | /// The longest GOP the HEVC seat asks for, in pictures. `ec-h265` codes GOPs |
| 9023 | /// concurrently only up to this length, and the sequence coder's own limit is |
| 9024 | /// 256; a 60 fps export is 60 pictures and a faster one takes the serial path. |
| 9025 | const HEVC_GOP_MAX_KEYINT: usize = 64; |
| 9026 | |
| 9027 | /// The longest key interval `ec-h265` codes, in pictures; a `keyframe_s` past it is capped here. |
| 9028 | const HEVC_KEYINT_MAX: usize = 256; |
| 9029 | |
| 9030 | impl Enc { |
| 9031 | /// The HEVC I+P seat: `ec-h265`'s sequence coder, an IDR once a second at |
| 9032 | /// the picture's own rate with P pictures between, on a worker thread. |
| 9033 | /// |
| 9034 | /// The export walk pushes one picture at a time and the encoder pulls its |
| 9035 | /// frames from an iterator, so the two meet on a bounded channel: the walk |
| 9036 | /// is never more than one GOP ahead of the worker. The encoder codes whole |
| 9037 | /// GOPs concurrently on [`default_threads`](ec_h265::encoder::default_threads) |
| 9038 | /// workers, which is at most six, and hands the pictures back in order. |
| 9039 | /// |
| 9040 | /// Rate: an explicit bitrate row goes to bitrate control at that rate, the |
| 9041 | /// same number the H.264 seat codes at. No bitrate is the automatic quality |
| 9042 | /// row, constant QP at [`HEVC_GOP_QP`]: a quality default of its own, not |
| 9043 | /// the intra seat's [`hevc_qp`], whose anchor is measured on intra pictures. |
| 9044 | fn open_hevc_gop( |
| 9045 | meta: &VideoMeta, |
| 9046 | settings: &ExportSettings, |
| 9047 | (fps_num, fps_den): (u32, u32), |
| 9048 | ten_bit: bool, |
| 9049 | colour: ColorDescription, |
| 9050 | ) -> crate::Result<Self> { |
| 9051 | let keyint = gop_frames(meta, settings).map_or_else(|| hevc_gop_keyint(meta.frame_rate), |g| (g as usize).clamp(2, HEVC_KEYINT_MAX)); |
| 9052 | let mut cfg = HevcEncoderConfig::new(meta.width, meta.height); |
| 9053 | cfg.bit_depth = if ten_bit { 10 } else { 8 }; |
| 9054 | cfg.rate_control = match (settings.qp, settings.bitrate) { |
| 9055 | (Some(qp), _) => RateControl::ConstantQp(qp as i32), |
| 9056 | (None, Some(_)) => RateControl::Bitrate { |
| 9057 | kbps: (bitrate_of(meta, settings) / 1000).max(1) as u32, |
| 9058 | fps: meta.frame_rate, |
| 9059 | }, |
| 9060 | (None, None) => RateControl::ConstantQp(HEVC_GOP_QP), |
| 9061 | }; |
| 9062 | cfg.keyint = keyint; |
| 9063 | cfg.threads = ec_h265::encoder::default_threads(); |
| 9064 | cfg.timing = Some((fps_den, fps_num)); |
| 9065 | cfg.video_signal_type = Some(video_signal_type(colour)); |
| 9066 | apply_hdr(&mut cfg, settings); |
| 9067 | cfg.speed = settings.hevc_speed.unwrap_or_default().preset(); |
| 9068 | let encoder = HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?; |
| 9069 | let (frames_tx, frames_rx) = sync_channel::<VideoFrame>(keyint); |
| 9070 | let (au_tx, coded) = std::sync::mpsc::channel::<(Vec<u8>, bool)>(); |
| 9071 | // The P pictures refer to a second picture parameter set, which the |
| 9072 | // samples do not keep: the first unit carries it, so the record the |
| 9073 | // container builds from that unit holds it. |
| 9074 | let p_pps = encoder.p_picture_parameter_set(); |
| 9075 | let worker = thread::Builder::new() |
| 9076 | .name("ec-h265-gop".into()) |
| 9077 | .spawn(move || { |
| 9078 | let mut picture = 0usize; |
| 9079 | encoder |
| 9080 | .encode_sequence_with(frames_rx, |pic| { |
| 9081 | // Every GOP opens on an IDR, so a picture's key flag is |
| 9082 | // its place in the sequence. |
| 9083 | let key = picture.is_multiple_of(keyint); |
| 9084 | let au = if picture == 0 { |
| 9085 | with_parameter_set(pic.au, &p_pps) |
| 9086 | } else { |
| 9087 | pic.au |
| 9088 | }; |
| 9089 | picture += 1; |
| 9090 | // A closed receiver is an export dropped part way: the |
| 9091 | // rest is unwanted, and draining it is not an error. |
| 9092 | let _ = au_tx.send((au, key)); |
| 9093 | Ok(()) |
| 9094 | }) |
| 9095 | .map_err(|e| e.to_string()) |
| 9096 | }) |
| 9097 | .map_err(|e| format!("HEVC software encoder: {e}"))?; |
| 9098 | Ok(Self::HevcGop(HevcGop { |
| 9099 | frames: Some(frames_tx), |
| 9100 | worker: Some(worker), |
| 9101 | coded, |
| 9102 | ready: std::collections::VecDeque::new(), |
| 9103 | au: Vec::new(), |
| 9104 | ten_bit, |
| 9105 | })) |
| 9106 | } |
| 9107 | } |
| 9108 | |
| 9109 | /// The GOP the I+P seat codes at this frame rate: an IDR about a second apart. |
| 9110 | fn hevc_gop_keyint(frame_rate: f64) -> usize { |
| 9111 | (frame_rate.round() as usize).clamp(2, HEVC_GOP_MAX_KEYINT) |
| 9112 | } |
| 9113 | |
| 9114 | /// What an HEVC export codes as, in the words an export start names: the I+P |
| 9115 | /// GOP and its key interval and rate, or `intra-only`. `None` for any other |
| 9116 | /// format. The rate is the bitrate the file aims at, or, with no bitrate given, |
| 9117 | /// the quality mode the automatic row codes at: constant QP ([`HEVC_GOP_QP`]), named |
| 9118 | /// with its number and with how to ask for a fixed rate instead. |
| 9119 | pub fn hevc_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<String> { |
| 9120 | if !settings.format.is_hevc() { |
| 9121 | return None; |
| 9122 | } |
| 9123 | if settings.intra_only { |
| 9124 | return Some(match (settings.qp, settings.bitrate) { |
| 9125 | (Some(qp), _) => format!("intra-only, constant QP {qp}"), |
| 9126 | (None, Some(_)) => "intra-only".to_string(), |
| 9127 | (None, None) => format!( |
| 9128 | "intra-only, constant quality QP {} on the software seat (the GPU seat codes at the automatic rate); pass bitrate_kbps for a fixed rate", |
| 9129 | hevc_qp(meta, settings) |
| 9130 | ), |
| 9131 | }); |
| 9132 | } |
| 9133 | let seconds = gop_frames(meta, settings).map_or_else(|| hevc_gop_keyint(meta.frame_rate), |g| g as usize) as f64 / meta.frame_rate; |
| 9134 | let every = if (seconds - seconds.round()).abs() < 1e-6 { |
| 9135 | format!("{} s", seconds.round() as u64) |
| 9136 | } else { |
| 9137 | format!("{seconds:.2} s") |
| 9138 | }; |
| 9139 | let rate = match (settings.qp, settings.bitrate) { |
| 9140 | (Some(qp), _) => format!("constant QP {qp}"), |
| 9141 | (None, Some(_)) => rate_words(bitrate_of(meta, settings) / 1000), |
| 9142 | (None, None) => format!("constant quality QP {HEVC_GOP_QP}; pass bitrate_kbps for a fixed rate"), |
| 9143 | }; |
| 9144 | Some(format!("I+P GOP ({every} keyframes), {rate}")) |
| 9145 | } |
| 9146 | |
| 9147 | /// What an AV1 export codes as, in the words an export start names. AV1 is always |
| 9148 | /// coded at a bitrate, so with none given the automatic target is named as one |
| 9149 | /// (chosen from the picture size and frame rate). `None` for any other format. |
| 9150 | pub fn av1_mode_words(meta: &VideoMeta, settings: &ExportSettings) -> Option<String> { |
| 9151 | if !settings.format.is_av1() { |
| 9152 | return None; |
| 9153 | } |
| 9154 | if let Some(qp) = settings.qp { |
| 9155 | return Some(format!("constant QP {qp}")); |
| 9156 | } |
| 9157 | let rate = rate_words(bitrate_of(meta, settings) / 1000); |
| 9158 | Some(match settings.bitrate { |
| 9159 | Some(_) => format!("average bitrate {rate}"), |
| 9160 | None => format!("average bitrate {rate} chosen from the picture size and frame rate; pass bitrate_kbps for a fixed rate"), |
| 9161 | }) |
| 9162 | } |
| 9163 | |
| 9164 | /// A rate in kilobits a second, in the words a reply uses: `4 Mb/s` on a whole megabit, `6.2 Mb/s` |
| 9165 | /// above one, else `850 kb/s`. |
| 9166 | fn rate_words(kbps: u64) -> String { |
| 9167 | if kbps.is_multiple_of(1000) { |
| 9168 | format!("{} Mb/s", kbps / 1000) |
| 9169 | } else if kbps >= 1000 { |
| 9170 | format!("{:.1} Mb/s", kbps as f64 / 1000.0) |
| 9171 | } else { |
| 9172 | format!("{kbps} kb/s") |
| 9173 | } |
| 9174 | } |
| 9175 | |
| 9176 | /// The words an export start names when the source's chroma is reduced to 4:2:0 on |
| 9177 | /// the way out, e.g. `VP9 4:4:4 source: chroma reduced to 4:2:0 for export`. `codec` |
| 9178 | /// and `chroma` are the source's; the chroma is read off the stream |
| 9179 | /// ([`Demuxer::chroma`]). `None` where nothing is reduced: a 4:2:0 or grey source, |
| 9180 | /// or a sound-only format, which has no picture to reduce. |
| 9181 | pub fn chroma_reduction_words(codec: Codec, chroma: Chroma, settings: &ExportSettings) -> Option<String> { |
| 9182 | let format = match chroma { |
| 9183 | Chroma::C422 => "4:2:2", |
| 9184 | Chroma::C444 => "4:4:4", |
| 9185 | _ => return None, |
| 9186 | }; |
| 9187 | if !settings.format.has_video() { |
| 9188 | return None; |
| 9189 | } |
| 9190 | Some(format!("{} {format} source: chroma reduced to 4:2:0 for export", codec.name())) |
| 9191 | } |
| 9192 | |
| 9193 | /// The I+P seat's state: the worker running the sequence coder, the channel |
| 9194 | /// the frames go to it on, and the access units it has handed back. |
| 9195 | struct HevcGop { |
| 9196 | /// The frames for the worker, in display order. `None` once the sequence |
| 9197 | /// has ended, which is what lets the worker finish its last GOP. |
| 9198 | frames: Option<SyncSender<VideoFrame>>, |
| 9199 | worker: Option<thread::JoinHandle<Result<(), String>>>, |
| 9200 | /// Access units and their key flags, in coding order, which is display order. |
| 9201 | coded: Receiver<(Vec<u8>, bool)>, |
| 9202 | /// Units collected from `coded` and not yet handed to the caller. |
| 9203 | ready: std::collections::VecDeque<(Vec<u8>, bool)>, |
| 9204 | /// The unit currently lent out, for the reason `Sw` owns one. |
| 9205 | au: Vec<u8>, |
| 9206 | /// Whether the sequence codes at 10 bits: its frames are I010 then. |
| 9207 | ten_bit: bool, |
| 9208 | } |
| 9209 | |
| 9210 | impl HevcGop { |
| 9211 | fn push(&mut self, y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> crate::Result<()> { |
| 9212 | let frame = i420_frame(y, u, v, width, height)?; |
| 9213 | self.send(frame) |
| 9214 | } |
| 9215 | |
| 9216 | /// One 10-bit picture of 16-bit samples, as the I010 frame the 10-bit sequence takes. |
| 9217 | fn push_wide(&mut self, y: &[u16], u: &[u16], v: &[u16], width: u32, height: u32) -> crate::Result<()> { |
| 9218 | let frame = i010_frame(y, u, v, width, height)?; |
| 9219 | self.send(frame) |
| 9220 | } |
| 9221 | |
| 9222 | fn send(&mut self, frame: VideoFrame) -> crate::Result<()> { |
| 9223 | if self |
| 9224 | .frames |
| 9225 | .as_ref() |
| 9226 | .is_some_and(|tx| tx.send(frame).is_ok()) |
| 9227 | { |
| 9228 | self.collect(); |
| 9229 | return Ok(()); |
| 9230 | } |
| 9231 | // The worker has stopped on its own: its error is the answer. |
| 9232 | self.finish()?; |
| 9233 | Err("the HEVC encoder stopped before the export ended".into()) |
| 9234 | } |
| 9235 | |
| 9236 | /// Ends the sequence and waits for the worker's last GOP. |
| 9237 | fn finish(&mut self) -> crate::Result<()> { |
| 9238 | self.frames = None; |
| 9239 | if let Some(worker) = self.worker.take() { |
| 9240 | match worker.join() { |
| 9241 | Ok(Ok(())) => {} |
| 9242 | Ok(Err(e)) => return Err(format!("software HEVC encode: {e}").into()), |
| 9243 | Err(_) => return Err("the HEVC encoder thread panicked".into()), |
| 9244 | } |
| 9245 | } |
| 9246 | self.collect(); |
| 9247 | Ok(()) |
| 9248 | } |
| 9249 | |
| 9250 | fn collect(&mut self) { |
| 9251 | while let Ok(unit) = self.coded.try_recv() { |
| 9252 | self.ready.push_back(unit); |
| 9253 | } |
| 9254 | } |
| 9255 | } |
| 9256 | |
| 9257 | /// One I420 picture at the display size, as the sequence coder takes it. |
| 9258 | fn i420_frame(y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> crate::Result<VideoFrame> { |
| 9259 | let (w, h) = (width as usize, height as usize); |
| 9260 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 9261 | let planes = vec![ |
| 9262 | ec_core::frame::Plane::new(y[..w * h].to_vec(), w), |
| 9263 | ec_core::frame::Plane::new(u[..cw * ch].to_vec(), cw), |
| 9264 | ec_core::frame::Plane::new(v[..cw * ch].to_vec(), cw), |
| 9265 | ]; |
| 9266 | VideoFrame::try_new(ec_core::frame::PixelFormat::I420, width, height, planes) |
| 9267 | .map_err(|e| format!("HEVC frame: {e}").into()) |
| 9268 | } |
| 9269 | |
| 9270 | /// One 10-bit I010 picture at the display size: 16-bit little-endian samples, the |
| 9271 | /// stride in bytes, as the sequence coder takes it. |
| 9272 | fn i010_frame(y: &[u16], u: &[u16], v: &[u16], width: u32, height: u32) -> crate::Result<VideoFrame> { |
| 9273 | let (w, h) = (width as usize, height as usize); |
| 9274 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 9275 | let planes = vec![ |
| 9276 | ec_core::frame::Plane::new(le_bytes(&y[..w * h]), w * 2), |
| 9277 | ec_core::frame::Plane::new(le_bytes(&u[..cw * ch]), cw * 2), |
| 9278 | ec_core::frame::Plane::new(le_bytes(&v[..cw * ch]), cw * 2), |
| 9279 | ]; |
| 9280 | VideoFrame::try_new(ec_core::frame::PixelFormat::I010, width, height, planes) |
| 9281 | .map_err(|e| format!("HEVC frame: {e}").into()) |
| 9282 | } |
| 9283 | |
| 9284 | /// Little-endian bytes of 16-bit samples. |
| 9285 | fn le_bytes(samples: &[u16]) -> Vec<u8> { |
| 9286 | samples.iter().flat_map(|s| s.to_le_bytes()).collect() |
| 9287 | } |
| 9288 | |
| 9289 | /// `au` with `nal` (one Annex-B unit) placed before its first coded slice, so |
| 9290 | /// after the parameter sets that open the unit. `au` comes back as it went in |
| 9291 | /// where it has no slice. |
| 9292 | fn with_parameter_set(au: Vec<u8>, nal: &[u8]) -> Vec<u8> { |
| 9293 | let starts = (0..au.len().saturating_sub(3)).filter(|&i| au[i..i + 3] == [0, 0, 1]); |
| 9294 | for start in starts { |
| 9295 | // The NAL unit type is the six bits after the forbidden bit. |
| 9296 | if (au[start + 3] >> 1) & 0x3F < 32 { |
| 9297 | // A four-byte start code keeps its leading zero in front of the new unit. |
| 9298 | let at = if start > 0 && au[start - 1] == 0 { |
| 9299 | start - 1 |
| 9300 | } else { |
| 9301 | start |
| 9302 | }; |
| 9303 | let mut out = Vec::with_capacity(au.len() + nal.len()); |
| 9304 | out.extend_from_slice(&au[..at]); |
| 9305 | out.extend_from_slice(nal); |
| 9306 | out.extend_from_slice(&au[at..]); |
| 9307 | return out; |
| 9308 | } |
| 9309 | } |
| 9310 | au |
| 9311 | } |
| 9312 | |
| 9313 | fn pop_gop(gop: &mut HevcGop) -> Option<(&[u8], bool)> { |
| 9314 | let (au, key) = gop.ready.pop_front()?; |
| 9315 | gop.au = au; |
| 9316 | Some((&gop.au[..], key)) |
| 9317 | } |
| 9318 | /// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a |
| 9319 | /// user picked -- the card has no QP control and this codec has no rate control, |
| 9320 | /// so the two are joined by measurement rather than promised to each other. |
| 9321 | /// |
| 9322 | /// The encoder codes ~0.6 bits per pixel at QP 27 ([`HEVC_BPP_AT_27`], measured |
| 9323 | /// on the 720p and 1080p benches to within 4% of each other), and a step of 6 QP |
| 9324 | /// is a factor of two in rate, which is the classic HEVC relation. So the QP |
| 9325 | /// that would land on a target is `27 + 6 * log2(0.6 / target)` -- and it is |
| 9326 | /// clamped, because this is a *quality* dial and not a rate controller: below QP |
| 9327 | /// 22 the file grows without a picture to show for it, and past QP 40 an |
| 9328 | /// intra-only frame goes blocky in a way no bitrate row asked for. A 1080p30 |
| 9329 | /// timeline at the automatic 6.2 Mbps therefore codes at QP 40 and comes out |
| 9330 | /// bigger than that, which is what "intra-only, large files" on the format row |
| 9331 | /// means: the row buys quality, not a size. |
| 9332 | fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 { |
| 9333 | let pixels = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate; |
| 9334 | let target = bitrate_of(meta, settings) as f64 / pixels.max(1.0); |
| 9335 | let qp = 27.0 + 6.0 * (HEVC_BPP_AT_27 / target.max(f64::MIN_POSITIVE)).log2(); |
| 9336 | (qp.round() as i32).clamp(HEVC_QP_MIN, HEVC_QP_MAX) |
| 9337 | } |
| 9338 | |
| 9339 | /// What the *bitstream* says the samples mean, in the words a sequence header |
| 9340 | /// spells them -- the same H.273 code points [`crate::mux`] writes into the |
| 9341 | /// container, from the same colour the export declares there ([`source_sdr_colour`] or the |
| 9342 | /// [`ColorDescription::output`] rule), so the two halves of a file cannot drift apart. |
| 9343 | /// |
| 9344 | /// This exists because a container tag is not enough: libavcodec takes the |
| 9345 | /// bitstream's answer first, and a stream that says nothing is "unspecified", |
| 9346 | /// which renders BT.601 -- a visible shift on a 709 export that a player reads |
| 9347 | /// from the wrong matrix. Every export is limited range, which is what |
| 9348 | /// `video_full_range_flag = false` says here. |
| 9349 | fn video_signal_type(colour: ColorDescription) -> HevcVideoSignalType { |
| 9350 | let (primaries, transfer, matrix) = colour.codes(); |
| 9351 | HevcVideoSignalType { |
| 9352 | // "Unspecified", which is what every encoder here writes: the field is |
| 9353 | // the analogue system a picture came off, and none of these did. |
| 9354 | video_format: 5, |
| 9355 | video_full_range_flag: false, |
| 9356 | colour_description: Some(HevcColourDescription { |
| 9357 | colour_primaries: primaries as u8, |
| 9358 | transfer_characteristics: transfer as u8, |
| 9359 | matrix_coeffs: matrix as u8, |
| 9360 | }), |
| 9361 | } |
| 9362 | } |
| 9363 | |
| 9364 | /// The HDR extras of an HEVC export, in the bitstream: BT.2020's chroma sample |
| 9365 | /// location (type 2, top-left) in the VUI, and the mastering display and content |
| 9366 | /// light SEIs where [`ExportSettings::hdr`] gives them. Nothing for an SDR export, |
| 9367 | /// whose stream stays byte-identical to what it was. |
| 9368 | fn apply_hdr(cfg: &mut HevcEncoderConfig, settings: &ExportSettings) { |
| 9369 | let hdr = &settings.hdr; |
| 9370 | if hdr.transfer == HdrTransfer::Sdr { |
| 9371 | return; |
| 9372 | } |
| 9373 | cfg.chroma_sample_loc = Some((2, 2)); |
| 9374 | cfg.mastering_display = hdr.mastering_display.map(|m| ec_h265_syntax::sei::MasteringDisplay { |
| 9375 | display_primaries: m.primaries, |
| 9376 | white_point: m.white_point, |
| 9377 | max_luminance: m.max_luminance, |
| 9378 | min_luminance: m.min_luminance, |
| 9379 | }); |
| 9380 | cfg.content_light.max_cll = hdr.max_cll.map(f32::from); |
| 9381 | cfg.content_light.max_fall = hdr.max_fall.map(f32::from); |
| 9382 | } |
| 9383 | |
| 9384 | /// The colour a 10-bit export declares when every clip is SDR in one matrix: that |
| 9385 | /// matrix, limited range, the source's own rather than the output rule's. `None` |
| 9386 | /// for a mixed timeline, an HDR one or an empty one, which keep the rule. |
| 9387 | fn source_sdr_colour(colours: &[ColorDescription]) -> Option<ColorDescription> { |
| 9388 | let first = *colours.first()?; |
| 9389 | let same = colours |
| 9390 | .iter() |
| 9391 | .all(|c| c.transfer == Transfer::Sdr && c.matrix == first.matrix); |
| 9392 | (same && first.transfer == Transfer::Sdr).then_some(ColorDescription { |
| 9393 | matrix: first.matrix, |
| 9394 | transfer: Transfer::Sdr, |
| 9395 | full_range: false, |
| 9396 | }) |
| 9397 | } |
| 9398 | |
| 9399 | /// Whether a software export is written at 10 bits: the setting where it names a |
| 9400 | /// depth, the source's own where it does not. AV1 and HEVC have the choice -- |
| 9401 | /// H.264 is 8-bit here -- and a depth the file cannot be is refused. The HEVC |
| 9402 | /// hardware seat is 8-bit, so a 10-bit HEVC export falls back to software |
| 9403 | /// ([`open_hevc`]). |
| 9404 | fn wide_ten_bit( |
| 9405 | settings: &ExportSettings, |
| 9406 | source_ten_bit: impl FnOnce() -> bool, |
| 9407 | ) -> crate::Result<bool> { |
| 9408 | // ProRes is coded at 10 bits whatever the setting says (it has no 8-bit |
| 9409 | // sample), so the walk keeps 10-bit sources at 10 bits. |
| 9410 | if settings.format.is_prores() { |
| 9411 | return Ok(true); |
| 9412 | } |
| 9413 | if !settings.format.is_av1() && !settings.format.is_hevc() { |
| 9414 | return Ok(false); |
| 9415 | } |
| 9416 | // An HDR transfer is a 10-bit claim: 8 bits of PQ bands visibly. |
| 9417 | if settings.hdr.transfer != HdrTransfer::Sdr { |
| 9418 | return match settings.video_bit_depth { |
| 9419 | Some(8) => Err("an HDR export is 10-bit: PQ and HLG are not carried in 8 bits".into()), |
| 9420 | Some(10) | None => Ok(true), |
| 9421 | Some(bits) => Err(format!("an AV1 or HEVC export is 8 or 10 bits, not {bits}").into()), |
| 9422 | }; |
| 9423 | } |
| 9424 | match settings.video_bit_depth { |
| 9425 | None => Ok(source_ten_bit()), |
| 9426 | Some(8) => Ok(false), |
| 9427 | Some(10) => Ok(true), |
| 9428 | Some(bits) => Err(format!("an AV1 or HEVC export is 8 or 10 bits, not {bits}").into()), |
| 9429 | } |
| 9430 | } |
| 9431 | |
| 9432 | /// The colour an HDR HEVC export declares, or `None` for an SDR export; `Err` |
| 9433 | /// where the settings ask for HDR of something that cannot carry it. |
| 9434 | fn hdr_colour_of(settings: &ExportSettings) -> crate::Result<Option<ColorDescription>> { |
| 9435 | let hdr = &settings.hdr; |
| 9436 | let Some(colour) = hdr.transfer.colour() else { |
| 9437 | if hdr.mastering_display.is_some() || hdr.max_cll.is_some() || hdr.max_fall.is_some() { |
| 9438 | return Err("mastering display and MaxCLL/MaxFALL need an HDR transfer (PQ or HLG)".into()); |
| 9439 | } |
| 9440 | return Ok(None); |
| 9441 | }; |
| 9442 | if !settings.format.is_hevc() { |
| 9443 | return Err(format!("{} cannot be written as HDR: only HEVC is", settings.format.name()).into()); |
| 9444 | } |
| 9445 | if settings.keep_source_colour { |
| 9446 | return Err("an HDR export cannot also keep its source's colour".into()); |
| 9447 | } |
| 9448 | Ok(Some(colour)) |
| 9449 | } |
| 9450 | |
| 9451 | fn transfer_name(t: Transfer) -> &'static str { |
| 9452 | match t { |
| 9453 | Transfer::Sdr => "SDR", |
| 9454 | Transfer::Pq => "PQ", |
| 9455 | Transfer::Hlg => "HLG", |
| 9456 | } |
| 9457 | } |
| 9458 | |
| 9459 | /// Every temporal unit `rav1e` has finished, moved into the queue in display |
| 9460 | /// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is |
| 9461 | /// through) are the two ways it says there is nothing more; `Encoded` means a |
| 9462 | /// picture was coded but not yet packetised, which is a *keep asking* -- taking |
| 9463 | /// it for an end leaves the tail of the export inside the encoder. |
| 9464 | fn collect_av1<T: rav1e::prelude::Pixel>( |
| 9465 | context: &mut rav1e::Context<T>, |
| 9466 | ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>, |
| 9467 | ) -> crate::Result<()> { |
| 9468 | use rav1e::prelude::{EncoderStatus, FrameType}; |
| 9469 | loop { |
| 9470 | match context.receive_packet() { |
| 9471 | Ok(packet) => ready.push_back((packet.data, packet.frame_type == FrameType::KEY)), |
| 9472 | Err(EncoderStatus::Encoded) => {} |
| 9473 | Err(EncoderStatus::NeedMoreData | EncoderStatus::LimitReached) => return Ok(()), |
| 9474 | Err(e) => return Err(format!("software AV1 encode: {e}").into()), |
| 9475 | } |
| 9476 | } |
| 9477 | } |
| 9478 | |
| 9479 | /// The oldest finished unit, moved into the buffer that is lent out -- the same |
| 9480 | /// "valid until the next call" contract the plugin's slice has. |
| 9481 | fn pop_av1<'a>( |
| 9482 | ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>, |
| 9483 | au: &'a mut Vec<u8>, |
| 9484 | ) -> Option<(&'a [u8], bool)> { |
| 9485 | let (unit, key) = ready.pop_front()?; |
| 9486 | *au = unit; |
| 9487 | Some((&au[..], key)) |
| 9488 | } |
| 9489 | |
| 9490 | /// One picture of 16-bit planes into the 10-bit `rav1e` context, and whatever |
| 9491 | /// unit it finished. The planes are the picture's own size, 4:2:0. |
| 9492 | fn submit_av1_16<'a>( |
| 9493 | context: &mut rav1e::Context<u16>, |
| 9494 | ready: &mut std::collections::VecDeque<(Vec<u8>, bool)>, |
| 9495 | au: &'a mut Vec<u8>, |
| 9496 | planes: [&[u16]; 3], |
| 9497 | width: u32, |
| 9498 | height: u32, |
| 9499 | ) -> crate::Result<Option<(&'a [u8], bool)>> { |
| 9500 | let (w, h) = (width as usize, height as usize); |
| 9501 | let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); |
| 9502 | let mut frame = context.new_frame(); |
| 9503 | // A plane's rows sit `stride` apart from its origin, past any padding. |
| 9504 | let fill = |plane: &mut rav1e::prelude::Plane<u16>, src: &[u16], w: usize, h: usize| { |
| 9505 | let stride = plane.cfg.stride; |
| 9506 | let dst = plane.data_origin_mut(); |
| 9507 | for (row, line) in src.chunks_exact(w).take(h).enumerate() { |
| 9508 | dst[row * stride..row * stride + w].copy_from_slice(line); |
| 9509 | } |
| 9510 | }; |
| 9511 | fill(&mut frame.planes[0], &planes[0][..w * h], w, h); |
| 9512 | fill(&mut frame.planes[1], &planes[1][..cw * ch], cw, ch); |
| 9513 | fill(&mut frame.planes[2], &planes[2][..cw * ch], cw, ch); |
| 9514 | if let Err(e) = context.send_frame(frame) { |
| 9515 | return Err(format!("software AV1 encode: {e}").into()); |
| 9516 | } |
| 9517 | collect_av1(context, ready)?; |
| 9518 | Ok(pop_av1(ready, au)) |
| 9519 | } |
| 9520 | |
| 9521 | /// A 10-bit plane narrowed to 8 bits for the composition that runs at 8 bits: the |
| 9522 | /// same truncation [`crate::decode::narrow_av1`] makes on playback. |
| 9523 | fn narrow_10(src: &[u16], dst: &mut Vec<u8>) { |
| 9524 | dst.clear(); |
| 9525 | dst.extend(src.iter().map(|&s| (s >> 2) as u8)); |
| 9526 | } |
| 9527 | |
| 9528 | /// The frame as an 8-bit composition takes it: a 10-bit picture narrowed into |
| 9529 | /// `scratch`, anything else as it came. |
| 9530 | fn narrowed<'a>(frame: Frame<'a>, scratch: &'a mut [Vec<u8>; 3]) -> Frame<'a> { |
| 9531 | match frame { |
| 9532 | Frame::Wide(y, u, v, width, height) => { |
| 9533 | let [sy, su, sv] = scratch; |
| 9534 | narrow_10(y, sy); |
| 9535 | narrow_10(u, su); |
| 9536 | narrow_10(v, sv); |
| 9537 | Frame::Pixels(&sy[..], &su[..], &sv[..], width, height) |
| 9538 | } |
| 9539 | other => other, |
| 9540 | } |
| 9541 | } |
| 9542 | |
| 9543 | /// I420 straight out of the decoder: the export never converts to BGRA and back, |
| 9544 | /// which would cost two conversions and a generation of colour precision. |
| 9545 | /// |
| 9546 | /// This mirrors `decode`'s two worker loops rather than reusing `DecodeSession`, |
| 9547 | /// which only speaks BGRA. A hardware decode that fails *before* the first |
| 9548 | /// picture falls back to software, exactly as playback's does -- nothing has |
| 9549 | /// been encoded yet, so the span can be taken over cleanly. One that fails |
| 9550 | /// after the first picture fails the export, which then deletes the |
| 9551 | /// half-written file: a restart there would re-encode what the muxer holds. |
| 9552 | enum ClipDecoder { |
| 9553 | /// A stream, decoded on a thread of its own: the encode of picture *n* and |
| 9554 | /// the decode of picture *n + 1* are the two halves an export used to do in |
| 9555 | /// turns, each idle while the other worked. The channel is two pictures |
| 9556 | /// deep, so the decoder runs no further ahead than that (a 1080p I420 |
| 9557 | /// picture is 3.1 MB) and a slow encoder still stops it. |
| 9558 | /// |
| 9559 | /// The thread is also where the plugin is *opened*: a VA-API session is not |
| 9560 | /// ours to hand between threads ([`crate::decode::open_worker_deferred`] |
| 9561 | /// keeps the same rule), which is why the open's error comes back down the |
| 9562 | /// channel rather than out of [`ClipDecoder::open`]. |
| 9563 | Streamed(Streamed), |
| 9564 | /// A still image: one picture, handed out for as long as the span runs. |
| 9565 | /// It is decoded here rather than in `run`'s loop for the same reason the |
| 9566 | /// other two are opened there -- the span's pictures come from one place, |
| 9567 | /// and no thread can make one picture arrive sooner. |
| 9568 | Still(crate::decode::Still), |
| 9569 | /// A clip played backwards ([`Reversed`]): its pictures, last to first. |
| 9570 | Reversed(Box<Reversed>), |
| 9571 | /// An audio file playing as a picture: each `next` paints one visualizer |
| 9572 | /// frame from peaks already decoded ([`crate::decode::visualizer_i420`]). |
| 9573 | Visualizer { |
| 9574 | peaks: Vec<(f32, f32)>, |
| 9575 | width: u32, |
| 9576 | height: u32, |
| 9577 | fps: f64, |
| 9578 | next: u32, |
| 9579 | flags: u8, |
| 9580 | paint: u64, |
| 9581 | /// This seat's own painting scratch, kept for the whole export: the |
| 9582 | /// same reuse the playback worker's thread does. |
| 9583 | scratch: crate::decode::VizScratch, |
| 9584 | y: Vec<u8>, |
| 9585 | u: Vec<u8>, |
| 9586 | v: Vec<u8>, |
| 9587 | }, |
| 9588 | } |
| 9589 | |
| 9590 | /// One 8-bit picture owned: its three planes and the size. |
| 9591 | type Owned = (Vec<u8>, Vec<u8>, Vec<u8>, u32, u32); |
| 9592 | |
| 9593 | /// A clip's pictures in reverse ([`ClipDecoder::reversed`]). |
| 9594 | struct Reversed { |
| 9595 | path: PathBuf, |
| 9596 | walk: crate::reverse::Walk, |
| 9597 | /// The block being served, oldest first: the next picture is the last one. |
| 9598 | block: Vec<Owned>, |
| 9599 | /// The picture last handed out, which `next` lends. |
| 9600 | current: Option<Owned>, |
| 9601 | /// The clip's deinterlace setting; `Field` makes the numbers above fields. |
| 9602 | deint: Deinterlace, |
| 9603 | } |
| 9604 | |
| 9605 | impl Reversed { |
| 9606 | fn next(&mut self) -> crate::Result<Option<Frame<'_>>> { |
| 9607 | if self.block.is_empty() && !self.fill()? { |
| 9608 | return Ok(None); |
| 9609 | } |
| 9610 | self.current = self.block.pop(); |
| 9611 | Ok(self |
| 9612 | .current |
| 9613 | .as_ref() |
| 9614 | .map(|(y, u, v, w, h)| Frame::Pixels(y, u, v, *w, *h))) |
| 9615 | } |
| 9616 | |
| 9617 | /// Decodes the next block down, forwards, into `block`. `false` when the window |
| 9618 | /// has no frames left, or the file gave none. |
| 9619 | fn fill(&mut self) -> crate::Result<bool> { |
| 9620 | let Some((start, end)) = self.walk.next() else { |
| 9621 | return Ok(false); |
| 9622 | }; |
| 9623 | let mut decoder = ClipDecoder::open_with(&self.path, start, None, None, false, self.deint)?; |
| 9624 | for _ in start..end { |
| 9625 | match decoder.next()? { |
| 9626 | Some(Frame::Pixels(y, u, v, w, h)) => { |
| 9627 | if self.block.is_empty() { |
| 9628 | // The pictures' real size is known now: hold as many as the |
| 9629 | // budget allows from the next block on. |
| 9630 | let bytes = y.len() + u.len() + v.len(); |
| 9631 | self.walk.set_cap(crate::reverse::block_cap(bytes)); |
| 9632 | } |
| 9633 | self.block.push((y.to_vec(), u.to_vec(), v.to_vec(), w, h)); |
| 9634 | } |
| 9635 | Some(_) => return Err("a reversed clip's decoder produced no pixels".into()), |
| 9636 | None => break, |
| 9637 | } |
| 9638 | } |
| 9639 | Ok(!self.block.is_empty()) |
| 9640 | } |
| 9641 | } |
| 9642 | |
| 9643 | /// The planes of one 10-bit picture, borrowed from its seat: luma, the two |
| 9644 | /// chroma planes, and the size. |
| 9645 | type Wide16View<'a> = (&'a [u16], &'a [u16], &'a [u16], u32, u32); |
| 9646 | |
| 9647 | /// The receiving half of a decode thread, plus the picture it last handed out |
| 9648 | /// -- which is what lets `next` keep lending planes rather than moving them. |
| 9649 | /// |
| 9650 | /// The first two fields are in this order on purpose, and it is the order |
| 9651 | /// [`crate::decode::FrameStream`] states for the same pair: Rust drops fields as |
| 9652 | /// they are declared, so the receiver disconnects *first* -- the only thing that |
| 9653 | /// wakes a decoder parked in a full `send` -- and the join inside |
| 9654 | /// [`DecodeThread::drop`] runs second. The other way round is a hang and not a |
| 9655 | /// slow path. |
| 9656 | struct Streamed { |
| 9657 | frames: Receiver<crate::Result<Option<Yuv>>>, |
| 9658 | /// Held only to be dropped: joining is all it does, and it must happen |
| 9659 | /// after the receiver above (`_lib` in `crate::hw` is kept the same way). |
| 9660 | /// Its result is the software decoder a stopped span leaves behind, if any. |
| 9661 | _thread: DecodeThread<Option<Kept>>, |
| 9662 | current: Option<Yuv>, |
| 9663 | /// Whether the thread has said "no more pictures" in as many words. What |
| 9664 | /// separates a stream that ended from a thread that vanished: after this, |
| 9665 | /// the channel is disconnected because the decoder is *done*, and a further |
| 9666 | /// ask is end of stream rather than a failure. |
| 9667 | ended: bool, |
| 9668 | /// Where the decoder goes when this span is done with it, if it may be kept. |
| 9669 | park: Option<Park>, |
| 9670 | } |
| 9671 | |
| 9672 | /// What a software decode thread leaves behind when it is stopped: the |
| 9673 | /// decoder, and the pictures it had decoded past the last one its span took, |
| 9674 | /// in order -- the ones the channel still held, then the ones it had not sent. |
| 9675 | type Kept = (Box<SwDecoder>, VecDeque<Yuv>); |
| 9676 | |
| 9677 | /// The way back from a span's [`Streamed`] to the [`Parked`] lot: the lot, the |
| 9678 | /// file, and the flag that asks the decode thread to stop at its next picture. |
| 9679 | struct Park { |
| 9680 | lot: Arc<Parked>, |
| 9681 | path: PathBuf, |
| 9682 | stop: Arc<AtomicBool>, |
| 9683 | } |
| 9684 | |
| 9685 | /// Software H.264 decoders from spans that have ended, kept so that the next |
| 9686 | /// span of the same file can carry on from where they stopped instead of |
| 9687 | /// seeking back to a sync sample and decoding the whole GOP in front of its in |
| 9688 | /// point again (a long-GOP source pays up to a GOP per clip that way). |
| 9689 | /// |
| 9690 | /// Only a decoder that is *resumable* is ever taken: see [`resumable`]. Hardware |
| 9691 | /// sessions are never kept, since whether a span gets one is the hardware's |
| 9692 | /// answer and not this lot's. |
| 9693 | #[derive(Default)] |
| 9694 | struct Parked(Mutex<VecDeque<ParkedDecoder>>); |
| 9695 | |
| 9696 | /// Most decoders kept at once. Each holds a demuxer and its reference pictures, |
| 9697 | /// so the lot stays small: a dissolve needs two, and a multi-source edit a few. |
| 9698 | const PARKED_MAX: usize = 4; |
| 9699 | |
| 9700 | /// One decoder in the lot: the file it reads, the decoder itself, and the |
| 9701 | /// pictures it decoded that no span took (see [`Kept`]). |
| 9702 | struct ParkedDecoder { |
| 9703 | path: PathBuf, |
| 9704 | decoder: Box<SwDecoder>, |
| 9705 | backlog: VecDeque<Yuv>, |
| 9706 | } |
| 9707 | |
| 9708 | impl Parked { |
| 9709 | fn keep(&self, entry: ParkedDecoder) { |
| 9710 | let Ok(mut lot) = self.0.lock() else { return }; |
| 9711 | lot.push_back(entry); |
| 9712 | while lot.len() > PARKED_MAX { |
| 9713 | lot.pop_front(); |
| 9714 | } |
| 9715 | } |
| 9716 | |
| 9717 | /// The decoder that can serve a span of `path` starting at `start`, taken |
| 9718 | /// out of the lot and wound forward to that picture: whatever it holds |
| 9719 | /// before `start` is dropped, and the rest is what the span decodes from. |
| 9720 | fn take(&self, path: &Path, start: u32) -> Option<ParkedDecoder> { |
| 9721 | let mut lot = self.0.lock().ok()?; |
| 9722 | let at = lot |
| 9723 | .iter() |
| 9724 | .position(|entry| entry.path == path && entry.serves(start))?; |
| 9725 | let mut entry = lot.remove(at)?; |
| 9726 | let start = i64::from(start); |
| 9727 | while entry.backlog.front().is_some() |
| 9728 | && entry.decoder.index() - (entry.backlog.len() as i64) < start |
| 9729 | { |
| 9730 | entry.backlog.pop_front(); |
| 9731 | } |
| 9732 | entry.decoder.start = start as u32; |
| 9733 | Some(entry) |
| 9734 | } |
| 9735 | } |
| 9736 | |
| 9737 | impl ParkedDecoder { |
| 9738 | /// Whether this decoder can serve a span starting at `start`: asked of the |
| 9739 | /// file itself, where a fresh decoder would seek to. |
| 9740 | fn serves(&self, start: u32) -> bool { |
| 9741 | let Ok((_, mut demuxer)) = Demuxer::open(&self.path) else { |
| 9742 | return false; |
| 9743 | }; |
| 9744 | let restart = demuxer.seek_to_sync_at_or_before(start); |
| 9745 | resumable( |
| 9746 | self.decoder.index(), |
| 9747 | self.backlog.len(), |
| 9748 | self.decoder.origin(), |
| 9749 | restart, |
| 9750 | i64::from(start), |
| 9751 | ) |
| 9752 | } |
| 9753 | } |
| 9754 | |
| 9755 | /// Whether a decoder can carry on for a span starting at display frame `start` |
| 9756 | /// instead of a fresh one opened there. `next` is the display index of the |
| 9757 | /// picture it produces next, `backlog` how many decoded pictures sit before |
| 9758 | /// that, unclaimed; `origin` is the sync sample it was started at, and |
| 9759 | /// `restart` the sync sample a fresh decoder for `start` would start at. |
| 9760 | /// |
| 9761 | /// Two things must hold. The span's first picture must still be held or not |
| 9762 | /// yet decoded, since a decoder cannot go back. And the decoder must have been |
| 9763 | /// started at the sample a fresh one would start at, so that it has read the |
| 9764 | /// same access units from the same point and produces the same pictures -- a |
| 9765 | /// later sync sample is a restart the decoder did not make, and one that is not |
| 9766 | /// an IDR would be decoded from references the fresh one does not have. |
| 9767 | fn resumable(next: i64, backlog: usize, origin: i64, restart: i64, start: i64) -> bool { |
| 9768 | next - (backlog as i64) <= start && restart == origin |
| 9769 | } |
| 9770 | |
| 9771 | /// A decode thread, joined when its span's decoder is dropped -- the rule |
| 9772 | /// [`crate::decode::Worker`] is written for: a thread abandoned mid |
| 9773 | /// `vaInitialize` outlives the process, and Mesa's `atexit` handlers then free |
| 9774 | /// the state it is still reading, which is a SIGSEGV at exit long after the |
| 9775 | /// export succeeded. |
| 9776 | struct DecodeThread<T = ()>(Option<thread::JoinHandle<T>>); |
| 9777 | |
| 9778 | impl<T> DecodeThread<T> { |
| 9779 | /// The thread's result, once it has finished. Joins it if it has not. |
| 9780 | fn finish(&mut self) -> Option<T> { |
| 9781 | self.0.take().and_then(|handle| handle.join().ok()) |
| 9782 | } |
| 9783 | } |
| 9784 | |
| 9785 | impl<T> Drop for DecodeThread<T> { |
| 9786 | fn drop(&mut self) { |
| 9787 | if let Some(handle) = self.0.take() { |
| 9788 | // The receiver is already gone (see `Streamed`'s field order), so a |
| 9789 | // decoder blocked on `send` has been woken and this waits only for |
| 9790 | // the thread to unwind its VA-API session. |
| 9791 | let _ = handle.join(); |
| 9792 | } |
| 9793 | } |
| 9794 | } |
| 9795 | |
| 9796 | impl Drop for Streamed { |
| 9797 | fn drop(&mut self) { |
| 9798 | let Some(park) = self.park.take() else { |
| 9799 | return; |
| 9800 | }; |
| 9801 | // Ask the decoder to stop, then take what it sends until it does: its |
| 9802 | // next send is answered by this drain and its next look at the flag |
| 9803 | // ends it, dropping the sender, which is what the drain waits for. |
| 9804 | park.stop.store(true, Ordering::Relaxed); |
| 9805 | let mut backlog = VecDeque::new(); |
| 9806 | // A GPU buffer is not kept: a hardware decoder is waiting on the |
| 9807 | // surfaces it has lent, and nothing here would hand them back. |
| 9808 | while let Ok(item) = self.frames.recv() { |
| 9809 | if let Ok(Some(frame @ (Yuv::Pixels { .. } | Yuv::Wide { .. }))) = item { |
| 9810 | backlog.push_back(frame); |
| 9811 | } |
| 9812 | } |
| 9813 | if let Some((decoder, rest)) = self._thread.finish().flatten() { |
| 9814 | backlog.extend(rest); |
| 9815 | park.lot.keep(ParkedDecoder { |
| 9816 | path: park.path, |
| 9817 | decoder, |
| 9818 | backlog, |
| 9819 | }); |
| 9820 | } |
| 9821 | } |
| 9822 | } |
| 9823 | |
| 9824 | /// One picture on its way from a decode thread to the encoder: its bytes, or |
| 9825 | /// the GPU buffer they are still in. |
| 9826 | enum Yuv { |
| 9827 | Pixels { |
| 9828 | y: Vec<u8>, |
| 9829 | u: Vec<u8>, |
| 9830 | v: Vec<u8>, |
| 9831 | width: u32, |
| 9832 | height: u32, |
| 9833 | }, |
| 9834 | /// The same picture at 16 bits a sample, at 10-bit scale: what a 10-bit export |
| 9835 | /// encodes whole ([`Enc::encode_wide`]). |
| 9836 | Wide { |
| 9837 | y: Vec<u16>, |
| 9838 | u: Vec<u16>, |
| 9839 | v: Vec<u16>, |
| 9840 | width: u32, |
| 9841 | height: u32, |
| 9842 | }, |
| 9843 | /// Never read back and never copied: a DRM-PRIME handle the encoder imports |
| 9844 | /// on the other side of the channel. Sending it is sending an integer, and |
| 9845 | /// what keeps the buffer from being decoded over is the channel's own depth |
| 9846 | /// (see [`crate::hw::HwSession::next_frame_dma`]). |
| 9847 | Dma(DmaFrame), |
| 9848 | } |
| 9849 | |
| 9850 | impl Yuv { |
| 9851 | /// The decoder's own buffer copied out, which is what it costs to hand a |
| 9852 | /// picture to another thread when the pixels have to travel. |
| 9853 | fn pixels(y: &[u8], u: &[u8], v: &[u8], width: u32, height: u32) -> Self { |
| 9854 | Self::Pixels { |
| 9855 | y: y.to_vec(), |
| 9856 | u: u.to_vec(), |
| 9857 | v: v.to_vec(), |
| 9858 | width, |
| 9859 | height, |
| 9860 | } |
| 9861 | } |
| 9862 | } |
| 9863 | |
| 9864 | /// What [`ExportHandle::stage`] calls a stabilised clip's shake being measured. |
| 9865 | pub const MEASURING_SHAKE: &str = "Measuring shake"; |
| 9866 | |
| 9867 | /// How a layer opened for an export measures a stabilised clip with no finished |
| 9868 | /// analysis ([`LayerFeed::open`]): under this cancel flag, reporting to this |
| 9869 | /// stage ([`Shared::measuring`]). |
| 9870 | type Measure<'a> = (&'a AtomicBool, &'a AtomicU32); |
| 9871 | |
| 9872 | /// The luma of file frames `lo..hi` of `path` as a layer's decoder hands them to |
| 9873 | /// [`LayerFeed::advance`] -- before the file's display turn and pixel stretch -- |
| 9874 | /// for the stabilise analysis, whose maps move those same planes. `each` takes |
| 9875 | /// the frame number, the luma plane and its size, and stops the walk with `false`. |
| 9876 | pub(crate) fn each_layer_luma( |
| 9877 | path: &Path, |
| 9878 | lo: u32, |
| 9879 | hi: u32, |
| 9880 | mut each: impl FnMut(u32, &[u8], u32, u32) -> bool, |
| 9881 | ) -> crate::Result<()> { |
| 9882 | let mut decoder = ClipDecoder::open(path, lo, None, None, false)?; |
| 9883 | for index in lo..hi { |
| 9884 | match decoder.next()? { |
| 9885 | Some(Frame::Pixels(y, _, _, w, h)) => { |
| 9886 | if !each(index, y, w, h) { |
| 9887 | break; |
| 9888 | } |
| 9889 | } |
| 9890 | Some(_) => return Err("stabilise: the decoder gave no 8-bit pixels".into()), |
| 9891 | None => break, |
| 9892 | } |
| 9893 | } |
| 9894 | Ok(()) |
| 9895 | } |
| 9896 | |
| 9897 | /// One picture as the export loop sees it: planes to grade and place, or a |
| 9898 | /// buffer that goes straight into the encoder. |
| 9899 | enum Frame<'a> { |
| 9900 | Pixels(&'a [u8], &'a [u8], &'a [u8], u32, u32), |
| 9901 | /// A 10-bit picture at 10-bit scale, which only a 10-bit export asks for. |
| 9902 | Wide(&'a [u16], &'a [u16], &'a [u16], u32, u32), |
| 9903 | Dma(&'a DmaFrame), |
| 9904 | } |
| 9905 | |
| 9906 | impl ClipDecoder { |
| 9907 | /// A decoder for `path` from `start_frame`. `parked` is the lot a span's |
| 9908 | /// software decoder may be taken from and returned to; `None` never keeps one. |
| 9909 | fn open( |
| 9910 | path: &Path, |
| 9911 | start_frame: u32, |
| 9912 | want: Option<DmaWant>, |
| 9913 | parked: Option<&Arc<Parked>>, |
| 9914 | wide: bool, |
| 9915 | ) -> crate::Result<Self> { |
| 9916 | Self::open_with(path, start_frame, want, parked, wide, Deinterlace::Frame) |
| 9917 | } |
| 9918 | |
| 9919 | /// [`open`](Self::open) for a clip with a deinterlace setting. `Field` over an |
| 9920 | /// interlaced file makes `start_frame` a field number and every picture a field. |
| 9921 | fn open_with( |
| 9922 | path: &Path, |
| 9923 | start_frame: u32, |
| 9924 | want: Option<DmaWant>, |
| 9925 | parked: Option<&Arc<Parked>>, |
| 9926 | wide: bool, |
| 9927 | deint: Deinterlace, |
| 9928 | ) -> crate::Result<Self> { |
| 9929 | // Before either decoder: an image is not a stream, so `start_frame` |
| 9930 | // means nothing to it -- every frame of a still span is the same |
| 9931 | // picture, which is what playback shows for it too. |
| 9932 | if crate::is_image(path) { |
| 9933 | return Ok(Self::Still(crate::decode::Still::open_at(path, start_frame)?)); |
| 9934 | } |
| 9935 | let path = path.to_path_buf(); |
| 9936 | let (tx, frames) = sync_channel(2); |
| 9937 | let stop = Arc::new(AtomicBool::new(false)); |
| 9938 | let park = parked.map(|lot| Park { |
| 9939 | lot: Arc::clone(lot), |
| 9940 | path: path.clone(), |
| 9941 | stop: Arc::clone(&stop), |
| 9942 | }); |
| 9943 | let thread_park = parked.map(|lot| (Arc::clone(lot), Arc::clone(&stop))); |
| 9944 | let handle = thread::Builder::new() |
| 9945 | .name("export-decode".into()) |
| 9946 | .spawn(move || decode_stream(&path, start_frame, want, &tx, thread_park, wide, deint))?; |
| 9947 | Ok(Self::Streamed(Streamed { |
| 9948 | frames, |
| 9949 | _thread: DecodeThread(Some(handle)), |
| 9950 | current: None, |
| 9951 | ended: false, |
| 9952 | park, |
| 9953 | })) |
| 9954 | } |
| 9955 | |
| 9956 | fn visualizer( |
| 9957 | path: &Path, |
| 9958 | stream: usize, |
| 9959 | start_frame: u32, |
| 9960 | (width, height): (u32, u32), |
| 9961 | fps: f64, |
| 9962 | flags: u8, |
| 9963 | paint: u64, |
| 9964 | ) -> crate::Result<Self> { |
| 9965 | let peaks = crate::waveform::peaks(path, stream, crate::decode::VIZ_BUCKETS_PER_SEC) |
| 9966 | .ok() |
| 9967 | .flatten() |
| 9968 | .unwrap_or_default(); |
| 9969 | let fps = if fps.is_finite() && fps > 0.0 { |
| 9970 | fps |
| 9971 | } else { |
| 9972 | 30.0 |
| 9973 | }; |
| 9974 | Ok(Self::Visualizer { |
| 9975 | peaks, |
| 9976 | width, |
| 9977 | height, |
| 9978 | fps, |
| 9979 | next: start_frame, |
| 9980 | flags, |
| 9981 | paint, |
| 9982 | scratch: crate::decode::VizScratch::default(), |
| 9983 | y: Vec::new(), |
| 9984 | u: Vec::new(), |
| 9985 | v: Vec::new(), |
| 9986 | }) |
| 9987 | } |
| 9988 | |
| 9989 | /// The pictures of `path` from file frame `top` down to `lo`, last to first: |
| 9990 | /// a clip played backwards. Decoded forwards a block at a time and served from |
| 9991 | /// the back, so the memory held is one block ([`crate::reverse`]), and always |
| 9992 | /// 8-bit software pictures -- the block is copied out of the decoder, which a GPU |
| 9993 | /// buffer or a 10-bit plane does not allow. |
| 9994 | fn reversed(path: &Path, top: u32, lo: u32, deint: Deinterlace) -> Self { |
| 9995 | let mut sync = crate::reverse::sync_frames(path); |
| 9996 | if deint == Deinterlace::Field { |
| 9997 | sync.iter_mut().for_each(|f| *f *= 2); |
| 9998 | } |
| 9999 | Self::Reversed(Box::new(Reversed { |
| 10000 | deint, |
| 10001 | path: path.to_path_buf(), |
| 10002 | walk: crate::reverse::Walk::new( |
| 10003 | sync, |
| 10004 | lo, |
| 10005 | top + 1, |
| 10006 | // Until a picture says how big they are: the biggest the engine takes. |
| 10007 | crate::reverse::block_cap(3840 * 2160 * 3 / 2), |
| 10008 | ), |
| 10009 | block: Vec::new(), |
| 10010 | current: None, |
| 10011 | })) |
| 10012 | } |
| 10013 | |
| 10014 | /// The next picture, borrowed until the call after -- as tightly packed |
| 10015 | /// I420, or as the GPU buffer the decoder wrote it into. |
| 10016 | fn next(&mut self) -> crate::Result<Option<Frame<'_>>> { |
| 10017 | match self { |
| 10018 | Self::Still(still) => { |
| 10019 | let (y, u, v, width, height) = still.picture(); |
| 10020 | Ok(Some(Frame::Pixels(y, u, v, width, height))) |
| 10021 | } |
| 10022 | Self::Reversed(reversed) => reversed.next(), |
| 10023 | Self::Visualizer { |
| 10024 | peaks, |
| 10025 | width, |
| 10026 | height, |
| 10027 | fps, |
| 10028 | next, |
| 10029 | flags, |
| 10030 | paint, |
| 10031 | scratch, |
| 10032 | y, |
| 10033 | u, |
| 10034 | v, |
| 10035 | } => { |
| 10036 | let (yy, uu, vv) = crate::decode::visualizer_i420( |
| 10037 | scratch, |
| 10038 | peaks, |
| 10039 | f64::from(*next) / *fps, |
| 10040 | *width, |
| 10041 | *height, |
| 10042 | *flags, |
| 10043 | *paint, |
| 10044 | ); |
| 10045 | *y = yy; |
| 10046 | *u = uu; |
| 10047 | *v = vv; |
| 10048 | *next += 1; |
| 10049 | Ok(Some(Frame::Pixels(y, u, v, *width & !1, *height & !1))) |
| 10050 | } |
| 10051 | Self::Streamed(stream) if stream.ended => Ok(None), |
| 10052 | Self::Streamed(stream) => match stream.frames.recv() { |
| 10053 | Ok(Ok(Some(frame))) => Ok(Some(match stream.current.insert(frame) { |
| 10054 | Yuv::Pixels { |
| 10055 | y, |
| 10056 | u, |
| 10057 | v, |
| 10058 | width, |
| 10059 | height, |
| 10060 | } => Frame::Pixels(y, u, v, *width, *height), |
| 10061 | Yuv::Wide { |
| 10062 | y, |
| 10063 | u, |
| 10064 | v, |
| 10065 | width, |
| 10066 | height, |
| 10067 | } => Frame::Wide(y, u, v, *width, *height), |
| 10068 | Yuv::Dma(dma) => Frame::Dma(dma), |
| 10069 | })), |
| 10070 | Ok(Ok(None)) => { |
| 10071 | stream.ended = true; |
| 10072 | Ok(None) |
| 10073 | } |
| 10074 | Ok(Err(e)) => Err(e), |
| 10075 | Err(_) => Err("the decoder stopped without a picture or a reason".into()), |
| 10076 | }, |
| 10077 | } |
| 10078 | } |
| 10079 | } |
| 10080 | |
| 10081 | /// One span's decode, on its own thread: open the file (hardware if the plugin |
| 10082 | /// will have it, software otherwise) and send every picture until the encoder |
| 10083 | /// stops taking them. |
| 10084 | /// |
| 10085 | /// Hardware that fails, before the first picture or after some, hands the rest |
| 10086 | /// of the span to the software seat at the first picture not yet sent. |
| 10087 | /// |
| 10088 | /// Every way this returns says which way it was, down the channel: a picture, an |
| 10089 | /// error, or the `Ok(None)` that *is* end of stream. Closing the channel is not |
| 10090 | /// one of them -- a silent close is a panicked thread, and the receiver treats |
| 10091 | /// it as the failure it is rather than as a source that ran out. |
| 10092 | /// |
| 10093 | /// With `parked`, a software decode takes a parked decoder for this file when |
| 10094 | /// one can serve `start_frame`, and a decoder that is asked to stop (its span |
| 10095 | /// was dropped) is handed back: see [`Streamed`]'s drop. |
| 10096 | fn decode_stream( |
| 10097 | path: &Path, |
| 10098 | start_frame: u32, |
| 10099 | want: Option<DmaWant>, |
| 10100 | tx: &SyncSender<crate::Result<Option<Yuv>>>, |
| 10101 | parked: Option<(Arc<Parked>, Arc<AtomicBool>)>, |
| 10102 | wide: bool, |
| 10103 | deint: Deinterlace, |
| 10104 | ) -> Option<Kept> { |
| 10105 | // A 10-bit export decodes in software: the hardware seat hands 8-bit planes. |
| 10106 | let opened = match forced("VE_SW") || wide { |
| 10107 | // The decode door's own gate ([`crate::decode::open_hw`]): a VP9 4:2:2 or 4:4:4 |
| 10108 | // stream is never offered to the GPU, which would refuse it on stderr. |
| 10109 | false => crate::decode::open_hw(path, start_frame).map(|hw| Pictures::Hw(Box::new(hw))), |
| 10110 | true => None, |
| 10111 | }; |
| 10112 | // Pictures decoded ahead of the span that a parked decoder still holds. |
| 10113 | let (mut decoder, mut backlog) = match opened { |
| 10114 | Some(hw) => (hw, VecDeque::new()), |
| 10115 | None => match parked |
| 10116 | .as_ref() |
| 10117 | .and_then(|(lot, _)| lot.take(path, start_frame)) |
| 10118 | { |
| 10119 | Some(kept) => (Pictures::Sw(kept.decoder), kept.backlog), |
| 10120 | None => match Pictures::software(path, start_frame, wide, deint) { |
| 10121 | Ok(sw) => (sw, VecDeque::new()), |
| 10122 | Err(e) => { |
| 10123 | let _ = tx.send(Err(e)); |
| 10124 | return None; |
| 10125 | } |
| 10126 | }, |
| 10127 | }, |
| 10128 | }; |
| 10129 | // Pictures handed down the channel. Hardware that dies hands the rest of the |
| 10130 | // span to the software seat at `start_frame + decoded`: the first picture |
| 10131 | // not yet sent, so nothing already encoded is repeated. |
| 10132 | let mut decoded = 0u32; |
| 10133 | loop { |
| 10134 | // Asked to stop: the span is over, and a software decoder that has not |
| 10135 | // reached its end is what the next span may take up. |
| 10136 | if parked |
| 10137 | .as_ref() |
| 10138 | .is_some_and(|(_, stop)| stop.load(Ordering::Relaxed)) |
| 10139 | { |
| 10140 | return match decoder { |
| 10141 | Pictures::Sw(sw) if sw.parkable() && !sw.flushed() => Some((sw, backlog)), |
| 10142 | _ => None, |
| 10143 | }; |
| 10144 | } |
| 10145 | // Hardware that ends before its first picture has failed the same way |
| 10146 | // one that errors there has: the mid-GOP AV1 seek ends the stream with |
| 10147 | // nothing (see `decode::run_hw`), and it falls back here too. |
| 10148 | let next = match backlog.pop_front() { |
| 10149 | Some(frame) => Ok(Some(frame)), |
| 10150 | None => decoder.next(want), |
| 10151 | }; |
| 10152 | let next = match next { |
| 10153 | Ok(None) if decoded == 0 && matches!(decoder, Pictures::Hw(_)) => { |
| 10154 | Err("hardware gave no picture from the start frame".into()) |
| 10155 | } |
| 10156 | other => other, |
| 10157 | }; |
| 10158 | let frame = match next { |
| 10159 | Ok(Some(frame)) => frame, |
| 10160 | Ok(None) => { |
| 10161 | let _ = tx.send(Ok(None)); |
| 10162 | return None; |
| 10163 | } |
| 10164 | Err(e) => { |
| 10165 | if matches!(decoder, Pictures::Hw(_)) { |
| 10166 | // Before the first picture, or after some: either way the |
| 10167 | // software seat takes the span from the first picture not yet |
| 10168 | // sent (`decoded` is 0 in the first case), so nothing is |
| 10169 | // encoded twice and nothing is skipped. |
| 10170 | if std::env::var_os("EDITH_DEBUG").is_some() || decoded > 0 { eprintln!( |
| 10171 | "export decode: hardware failed at frame {} ({e}); falling back to software", |
| 10172 | start_frame + decoded |
| 10173 | ); } |
| 10174 | match Pictures::software(path, start_frame + decoded, wide, deint) { |
| 10175 | Ok(sw) => { |
| 10176 | decoder = sw; |
| 10177 | continue; |
| 10178 | } |
| 10179 | Err(sw_refusal) => { |
| 10180 | let _ = tx.send(Err(sw_refusal)); |
| 10181 | return None; |
| 10182 | } |
| 10183 | } |
| 10184 | } |
| 10185 | let _ = tx.send(Err(e)); |
| 10186 | return None; |
| 10187 | } |
| 10188 | }; |
| 10189 | // The consumer went away: the span ended early, or the export was |
| 10190 | // cancelled. Either way there is nothing left to decode for. A parked |
| 10191 | // span drains the channel before it drops it, so this is not reached. |
| 10192 | if tx.send(Ok(Some(frame))).is_err() { |
| 10193 | return None; |
| 10194 | } |
| 10195 | decoded += 1; |
| 10196 | } |
| 10197 | } |
| 10198 | |
| 10199 | /// The stream decoders, on the thread that opened them. |
| 10200 | enum Pictures { |
| 10201 | Hw(Box<HwSession>), |
| 10202 | /// `ec-h264`, on this thread. |
| 10203 | Sw(Box<SwDecoder>), |
| 10204 | /// `ec-av1`, on a thread of its own -- see [`Av1Stream`]. |
| 10205 | Av1(Box<Av1Stream>), |
| 10206 | } |
| 10207 | |
| 10208 | impl Pictures { |
| 10209 | /// The software seat for `path`: `ec-h264` for H.264, `ec-av1` on its own |
| 10210 | /// thread for AV1, and the pulled seats (`ec-h265`, `ec-vp9`, `ec-vp8`) for the |
| 10211 | /// rest. The codec is read once here, so it decides which seat takes the file. |
| 10212 | fn software(path: &Path, start_frame: u32, wide: bool, deint: Deinterlace) -> crate::Result<Self> { |
| 10213 | let (meta, demuxer) = Demuxer::open(path)?; |
| 10214 | match meta.codec { |
| 10215 | Codec::H264 => Ok(Self::Sw(Box::new(SwDecoder::new(demuxer, start_frame, wide, deint)))), |
| 10216 | Codec::Av1 => Ok(Self::Av1(Box::new(Av1Stream::spawn(demuxer, start_frame, wide)?))), |
| 10217 | _ => Ok(Self::Sw(Box::new(SwDecoder::open(path, start_frame, wide, deint)?))), |
| 10218 | } |
| 10219 | } |
| 10220 | |
| 10221 | /// The next picture, owned, ready to cross the channel. `want` is what the |
| 10222 | /// export's encoder can read straight off the GPU: where the hardware |
| 10223 | /// decoder can hand such a buffer over there is no copy here at all, and |
| 10224 | /// everything else is the 3 MB memcpy out of the decoder's own buffer that |
| 10225 | /// buys the decode and the encode their overlap. |
| 10226 | fn next(&mut self, want: Option<DmaWant>) -> crate::Result<Option<Yuv>> { |
| 10227 | match (self, want) { |
| 10228 | (Self::Hw(hw), Some(want)) => Ok(match hw.next_frame_dma(want)? { |
| 10229 | Some(HwPicture::Dma(dma)) => Some(Yuv::Dma(dma)), |
| 10230 | Some(HwPicture::Pixels(y, u, v, width, height)) => { |
| 10231 | Some(Yuv::pixels(y, u, v, width, height)) |
| 10232 | } |
| 10233 | None => None, |
| 10234 | }), |
| 10235 | (Self::Hw(hw), None) => Ok(hw |
| 10236 | .next_frame()? |
| 10237 | .map(|(y, u, v, width, height)| Yuv::pixels(y, u, v, width, height))), |
| 10238 | (Self::Av1(av1), _) => av1.next(), |
| 10239 | (Self::Sw(sw), _) => { |
| 10240 | if !sw.advance()? { |
| 10241 | return Ok(None); |
| 10242 | } |
| 10243 | if let Some((y, u, v, width, height)) = sw.picture16() { |
| 10244 | return Ok(Some(Yuv::Wide { |
| 10245 | y: y.to_vec(), |
| 10246 | u: u.to_vec(), |
| 10247 | v: v.to_vec(), |
| 10248 | width, |
| 10249 | height, |
| 10250 | })); |
| 10251 | } |
| 10252 | let (y, u, v, width, height) = sw.picture(); |
| 10253 | Ok(Some(Yuv::pixels(y, u, v, width, height))) |
| 10254 | } |
| 10255 | } |
| 10256 | } |
| 10257 | } |
| 10258 | |
| 10259 | /// The software decoder one export span reads from: H.264 with its own reorder |
| 10260 | /// and flush, or one of the pulled seats playback's spans read too. |
| 10261 | struct SwDecoder { |
| 10262 | demuxer: Demuxer, |
| 10263 | /// The first display index the export takes. Pictures before it are decoded |
| 10264 | /// (the target references them) and then dropped. |
| 10265 | start: u32, |
| 10266 | seat: SwSeat, |
| 10267 | } |
| 10268 | |
| 10269 | enum SwSeat { |
| 10270 | H264(Box<H264Seat>), |
| 10271 | /// `wide` is the 10-bit plane buffer when this seat decodes at 10 bits. |
| 10272 | Pulled { |
| 10273 | stream: Box<Pulled>, |
| 10274 | out: I420, |
| 10275 | wide: Option<Wide>, |
| 10276 | }, |
| 10277 | } |
| 10278 | |
| 10279 | struct H264Seat { |
| 10280 | decoder: H264Decoder, |
| 10281 | /// Display index of the next picture the decoder will produce. Signed: a |
| 10282 | /// sync sample inside what the edit list trims is before frame 0. |
| 10283 | index: i64, |
| 10284 | /// The display index the decoder started at (its sync sample), what |
| 10285 | /// [`resumable`] compares a later span's restart against. |
| 10286 | origin: i64, |
| 10287 | /// Set once the demuxer runs dry: `flush` has then released what the |
| 10288 | /// decoder's reorder still held, and only those pictures are left. |
| 10289 | flushed: bool, |
| 10290 | frame: Option<VideoFrame>, |
| 10291 | /// Whether the export is 10-bit, and the High 10 picture taken for it. |
| 10292 | wide: bool, |
| 10293 | deep: crate::decode::Deep, |
| 10294 | /// Deinterlaces an interlaced stream (a pass-through for every other). |
| 10295 | deint: crate::deinterlace::Deinterlacer, |
| 10296 | /// Pictures the deinterlacer released that `advance` has not handed over yet: |
| 10297 | /// the second field of a frame in field mode. |
| 10298 | pending: VecDeque<(i64, VideoFrame)>, |
| 10299 | } |
| 10300 | |
| 10301 | impl SwDecoder { |
| 10302 | fn open(path: &Path, start_frame: u32, wide: bool, deint: Deinterlace) -> crate::Result<Self> { |
| 10303 | let (meta, mut demuxer) = Demuxer::open(path)?; |
| 10304 | // Decoding restarts at a sync sample, so pictures between it and the in |
| 10305 | // point are decoded (the target references them) and then dropped. |
| 10306 | let seat = match Pulled::open(meta.codec, &mut demuxer, start_frame, deint) { |
| 10307 | Some(stream) => SwSeat::Pulled { |
| 10308 | stream: Box::new(stream), |
| 10309 | out: I420::default(), |
| 10310 | // Only HEVC and the intra-only professional codecs have a 10-bit seat; the others narrow as they always did. |
| 10311 | wide: (wide && (matches!(meta.codec, Codec::Hevc | Codec::ProRes | Codec::Dnxhd) || (meta.codec == Codec::Raw && demuxer.bit_depth() >= 10))).then(Wide::default), |
| 10312 | }, |
| 10313 | None if meta.codec == Codec::H264 => { |
| 10314 | SwSeat::H264(H264Seat::open(&mut demuxer, start_frame, wide, deint)) |
| 10315 | } |
| 10316 | // AV1 never gets here: `Pictures::software` gives it `Av1Stream`. |
| 10317 | None => return Err(format!("{} has no export seat", meta.codec.name()).into()), |
| 10318 | }; |
| 10319 | Ok(Self { |
| 10320 | demuxer, |
| 10321 | start: start_frame, |
| 10322 | seat, |
| 10323 | }) |
| 10324 | } |
| 10325 | |
| 10326 | /// Decodes up to and including the next picture at or after the in point. |
| 10327 | /// `false` at end of stream. |
| 10328 | fn advance(&mut self) -> crate::Result<bool> { |
| 10329 | match &mut self.seat { |
| 10330 | SwSeat::H264(seat) => seat.advance(&mut self.demuxer, self.start), |
| 10331 | SwSeat::Pulled { stream, out, wide } => loop { |
| 10332 | let next = match wide { |
| 10333 | Some(wide) => stream.next_wide(&mut self.demuxer, wide)?, |
| 10334 | None => stream.next(&mut self.demuxer, out)?, |
| 10335 | }; |
| 10336 | let Some(due) = next else { |
| 10337 | return Ok(false); |
| 10338 | }; |
| 10339 | if due >= i64::from(self.start) { |
| 10340 | return Ok(true); |
| 10341 | } |
| 10342 | }, |
| 10343 | } |
| 10344 | } |
| 10345 | |
| 10346 | /// The 10-bit planes of the picture `advance` stopped on, when this seat |
| 10347 | /// decodes at 10 bits; `None` otherwise. |
| 10348 | fn picture16(&self) -> Option<Wide16View<'_>> { |
| 10349 | match &self.seat { |
| 10350 | SwSeat::Pulled { wide: Some(w), .. } => Some((&w.y, &w.u, &w.v, w.width, w.height)), |
| 10351 | SwSeat::H264(s) if s.deep.in_wide => { |
| 10352 | let w = &s.deep.wide; |
| 10353 | Some((&w.y, &w.u, &w.v, w.width, w.height)) |
| 10354 | } |
| 10355 | _ => None, |
| 10356 | } |
| 10357 | } |
| 10358 | |
| 10359 | /// The picture `advance` stopped on, as planes and size. |
| 10360 | fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) { |
| 10361 | match &self.seat { |
| 10362 | SwSeat::H264(seat) if seat.deep.on => { |
| 10363 | let n = &seat.deep.narrow; |
| 10364 | (&n.y, &n.u, &n.v, n.width, n.height) |
| 10365 | } |
| 10366 | SwSeat::H264(seat) => { |
| 10367 | let frame = seat.frame.as_ref().expect("advance stored a picture"); |
| 10368 | let [y, u, v] = [&frame.planes[0], &frame.planes[1], &frame.planes[2]]; |
| 10369 | debug_assert_eq!(y.stride, frame.width as usize, "padded luma plane"); |
| 10370 | (&y.data, &u.data, &v.data, frame.width, frame.height) |
| 10371 | } |
| 10372 | SwSeat::Pulled { out, .. } => (&out.y, &out.u, &out.v, out.width, out.height), |
| 10373 | } |
| 10374 | } |
| 10375 | } |
| 10376 | |
| 10377 | /// An AV1 software span: [`decode_av1`] runs on a thread of its own and sends |
| 10378 | /// every picture down a channel two deep, the same shape [`Streamed`] gives a |
| 10379 | /// stream decoded elsewhere. The thread is needed because `ec-av1` pushes its |
| 10380 | /// pictures through a callback rather than handing them out one at a time. |
| 10381 | struct Av1Stream { |
| 10382 | frames: Receiver<crate::Result<Option<Yuv>>>, |
| 10383 | /// Held only to be joined: field order matters, as it does for |
| 10384 | /// [`Streamed`] -- `frames` drops first and wakes a decoder parked in a |
| 10385 | /// full `send`, and the join runs after. |
| 10386 | _thread: DecodeThread, |
| 10387 | /// Whether the thread has said "no more pictures" in as many words. |
| 10388 | ended: bool, |
| 10389 | } |
| 10390 | |
| 10391 | impl Av1Stream { |
| 10392 | fn spawn(demuxer: Demuxer, start_frame: u32, wide: bool) -> crate::Result<Self> { |
| 10393 | let (tx, frames) = sync_channel(2); |
| 10394 | let handle = thread::Builder::new() |
| 10395 | .name("export-decode-av1".into()) |
| 10396 | .spawn(move || decode_av1(demuxer, start_frame, wide, &tx))?; |
| 10397 | Ok(Self { |
| 10398 | frames, |
| 10399 | _thread: DecodeThread(Some(handle)), |
| 10400 | ended: false, |
| 10401 | }) |
| 10402 | } |
| 10403 | |
| 10404 | fn next(&mut self) -> crate::Result<Option<Yuv>> { |
| 10405 | if self.ended { |
| 10406 | return Ok(None); |
| 10407 | } |
| 10408 | match self.frames.recv() { |
| 10409 | Ok(Ok(Some(frame))) => Ok(Some(frame)), |
| 10410 | Ok(Ok(None)) => { |
| 10411 | self.ended = true; |
| 10412 | Ok(None) |
| 10413 | } |
| 10414 | Ok(Err(e)) => Err(e), |
| 10415 | Err(_) => Err("the decoder stopped without a picture or a reason".into()), |
| 10416 | } |
| 10417 | } |
| 10418 | } |
| 10419 | |
| 10420 | /// The chroma plane size `len` samples can be, for a `width` x `height` luma |
| 10421 | /// picture: full (4:4:4), half the width (4:2:2) or a quarter (4:2:0, odd sizes |
| 10422 | /// rounding up). `None` for any other count, which no decoder here produces. |
| 10423 | pub(crate) fn chroma_shape(len: usize, width: usize, height: usize) -> Option<(usize, usize)> { |
| 10424 | let (half_w, half_h) = (width.div_ceil(2), height.div_ceil(2)); |
| 10425 | [(width, height), (half_w, height), (half_w, half_h)] |
| 10426 | .into_iter() |
| 10427 | .find(|&(cw, ch)| cw * ch == len) |
| 10428 | } |
| 10429 | |
| 10430 | /// A chroma plane of `cw` x `ch` samples averaged down to `ow` x `oh`, the |
| 10431 | /// 4:2:0 size of the luma. A dimension that already matches is kept one sample |
| 10432 | /// to one; one that is larger takes the mean of the (at most two) source |
| 10433 | /// samples under each output sample, rounded to nearest. Samples keep the |
| 10434 | /// depth they came in at, so a 10-bit picture averages in 10 bits and |
| 10435 | /// [`crate::decode::narrow_av1`] shifts it as it would any other. |
| 10436 | pub(crate) fn chroma_420<T: Copy + Into<u32>>(src: &[T], cw: usize, ch: usize, ow: usize, oh: usize) -> Vec<u32> { |
| 10437 | // The source run under output index `i` along one axis. |
| 10438 | let run = |src_len: usize, out_len: usize, i: usize| match src_len == out_len { |
| 10439 | true => (i, i + 1), |
| 10440 | false => (2 * i, (2 * i + 2).min(src_len)), |
| 10441 | }; |
| 10442 | let mut out = Vec::with_capacity(ow * oh); |
| 10443 | for oy in 0..oh { |
| 10444 | let (y0, y1) = run(ch, oh, oy); |
| 10445 | for ox in 0..ow { |
| 10446 | let (x0, x1) = run(cw, ow, ox); |
| 10447 | let (mut sum, mut n) = (0u32, 0u32); |
| 10448 | for sy in y0..y1 { |
| 10449 | for sx in x0..x1 { |
| 10450 | sum += src[sy * cw + sx].into(); |
| 10451 | n += 1; |
| 10452 | } |
| 10453 | } |
| 10454 | out.push((sum + n / 2) / n); |
| 10455 | } |
| 10456 | } |
| 10457 | out |
| 10458 | } |
| 10459 | |
| 10460 | /// The AV1 software seat for the export: the same walk `decode::run_av1` makes |
| 10461 | /// for playback, one chunk at a time. `ec-av1` takes a whole OBU stream, so the |
| 10462 | /// demuxer's access units are gathered from one sync sample (a sequence header |
| 10463 | /// leads it) up to the next, and each chunk decodes to its end -- its hidden |
| 10464 | /// frames are references, and the frames they hold back in output order are |
| 10465 | /// the tail. Shown pictures before `start_frame` are decoded and dropped. |
| 10466 | /// |
| 10467 | /// Pictures are narrowed to 8-bit I420 by the same [`narrow_av1`] playback |
| 10468 | /// uses, so an export and a playback of one file hand the encoder the same |
| 10469 | /// planes. A 4:2:2 or 4:4:4 picture has its chroma averaged down to 4:2:0 first |
| 10470 | /// ([`chroma_420`]), since the composer and every software encoder take I420 and |
| 10471 | /// nothing else. A decode refusal ends the span with the error, after the |
| 10472 | /// pictures already sent. |
| 10473 | fn decode_av1( |
| 10474 | mut demuxer: Demuxer, |
| 10475 | start_frame: u32, |
| 10476 | wide: bool, |
| 10477 | tx: &SyncSender<crate::Result<Option<Yuv>>>, |
| 10478 | ) { |
| 10479 | let depth = demuxer.bit_depth(); |
| 10480 | // A monochrome stream states it in its sequence header; see the chroma below. |
| 10481 | let gray = demuxer.chroma() == Some(Chroma::Gray); |
| 10482 | // Decoding restarts at a sync sample; see [`SwDecoder::new`]. |
| 10483 | let mut index = demuxer.seek_to_sync_at_or_before(start_frame); |
| 10484 | let mut pending: Option<Vec<u8>> = None; |
| 10485 | let mut demux_dry = false; |
| 10486 | loop { |
| 10487 | // One chunk: the access units from a sync sample up to the next one. |
| 10488 | let mut stream = pending.take().unwrap_or_default(); |
| 10489 | while !demux_dry && pending.is_none() { |
| 10490 | match demuxer.next_access_unit() { |
| 10491 | Ok(Some(au)) => { |
| 10492 | if !stream.is_empty() && crate::decode::leads_with_sequence_header(&au) { |
| 10493 | pending = Some(au); |
| 10494 | } else { |
| 10495 | stream.extend_from_slice(&au); |
| 10496 | } |
| 10497 | } |
| 10498 | Ok(None) => demux_dry = true, |
| 10499 | Err(e) => { |
| 10500 | let _ = tx.send(Err(e)); |
| 10501 | return; |
| 10502 | } |
| 10503 | } |
| 10504 | } |
| 10505 | if stream.is_empty() { |
| 10506 | let _ = tx.send(Ok(None)); |
| 10507 | return; |
| 10508 | } |
| 10509 | // Set by the sink when the consumer is gone, or when a picture is |
| 10510 | // refused; `Eof` is the sentinel that stops the chunk's decode there. |
| 10511 | let mut gone = false; |
| 10512 | let mut refused = None; |
| 10513 | let decode = decode_stream_with(&stream, |picture, _, shown| { |
| 10514 | if !shown { |
| 10515 | return Ok(()); |
| 10516 | } |
| 10517 | let due = index; |
| 10518 | index += 1; |
| 10519 | if due < i64::from(start_frame) { |
| 10520 | return Ok(()); |
| 10521 | } |
| 10522 | let (w, h) = (picture.width, picture.height); |
| 10523 | let (ow, oh) = (w.div_ceil(2), h.div_ceil(2)); |
| 10524 | // 4:2:2 and 4:4:4 pictures are averaged down to the 4:2:0 the |
| 10525 | // composer and every software encoder take ([`chroma_420`]). A |
| 10526 | // monochrome stream carries no chroma, and the decoder hands back |
| 10527 | // zeros in its place: the neutral grey is written instead, at the |
| 10528 | // depth the samples are held in (512 for 10-bit). |
| 10529 | let Some((cw, ch)) = chroma_shape(picture.u.len(), w, h) else { |
| 10530 | refused = Some(format!( |
| 10531 | "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", |
| 10532 | picture.u.len() |
| 10533 | )); |
| 10534 | return Err(Av1Error::Eof); |
| 10535 | }; |
| 10536 | let half = if gray { |
| 10537 | let mid = 1u16 << (depth - 1); |
| 10538 | Some(Av1Picture { |
| 10539 | width: w, |
| 10540 | height: h, |
| 10541 | y: picture.y.clone(), |
| 10542 | u: vec![mid; ow * oh], |
| 10543 | v: vec![mid; ow * oh], |
| 10544 | }) |
| 10545 | } else if (cw, ch) != (ow, oh) { |
| 10546 | let down = |plane: &[u16]| -> Vec<u16> { |
| 10547 | chroma_420(plane, cw, ch, ow, oh) |
| 10548 | .into_iter() |
| 10549 | .map(|s| s as u16) |
| 10550 | .collect() |
| 10551 | }; |
| 10552 | Some(Av1Picture { |
| 10553 | width: w, |
| 10554 | height: h, |
| 10555 | y: picture.y.clone(), |
| 10556 | u: down(&picture.u), |
| 10557 | v: down(&picture.v), |
| 10558 | }) |
| 10559 | } else { |
| 10560 | None |
| 10561 | }; |
| 10562 | let src = half.as_ref().unwrap_or(picture); |
| 10563 | let frame = if wide { |
| 10564 | // At 10-bit scale: a 10-bit stream's samples are there already, an |
| 10565 | // 8-bit one (in a 10-bit export) is shifted up by two. |
| 10566 | // A 12-bit one is rounded down by two. |
| 10567 | let plane = |s: &[u16]| -> Vec<u16> { |
| 10568 | s.iter() |
| 10569 | .map(|&x| match depth { |
| 10570 | ..=9 => x << (10 - depth), |
| 10571 | 10 => x, |
| 10572 | _ => ((x + (1 << (depth - 11))) >> (depth - 10)).min(1023), |
| 10573 | }) |
| 10574 | .collect() |
| 10575 | }; |
| 10576 | Yuv::Wide { |
| 10577 | y: plane(&src.y), |
| 10578 | u: plane(&src.u), |
| 10579 | v: plane(&src.v), |
| 10580 | width: w as u32, |
| 10581 | height: h as u32, |
| 10582 | } |
| 10583 | } else { |
| 10584 | let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new()); |
| 10585 | crate::decode::narrow_av1(src, depth, &mut y, &mut u, &mut v); |
| 10586 | Yuv::Pixels { |
| 10587 | y, |
| 10588 | u, |
| 10589 | v, |
| 10590 | width: w as u32, |
| 10591 | height: h as u32, |
| 10592 | } |
| 10593 | }; |
| 10594 | if tx.send(Ok(Some(frame))).is_err() { |
| 10595 | gone = true; |
| 10596 | return Err(Av1Error::Eof); |
| 10597 | } |
| 10598 | Ok(()) |
| 10599 | }); |
| 10600 | if gone { |
| 10601 | return; |
| 10602 | } |
| 10603 | if let Some(msg) = refused { |
| 10604 | let _ = tx.send(Err(msg.into())); |
| 10605 | return; |
| 10606 | } |
| 10607 | if let Err(e) = decode { |
| 10608 | let msg = format!("software AV1 decode failed at picture {index}: {e}"); |
| 10609 | let _ = tx.send(Err(msg.into())); |
| 10610 | return; |
| 10611 | } |
| 10612 | } |
| 10613 | } |
| 10614 | |
| 10615 | impl SwDecoder { |
| 10616 | /// The H.264 seat over an opened demuxer. Decoding restarts at a sync |
| 10617 | /// sample, so pictures between it and the in point are decoded (the target |
| 10618 | /// references them) and then dropped. |
| 10619 | fn new(mut demuxer: Demuxer, start_frame: u32, wide: bool, deint: Deinterlace) -> Self { |
| 10620 | let seat = SwSeat::H264(H264Seat::open(&mut demuxer, start_frame, wide, deint)); |
| 10621 | Self { |
| 10622 | demuxer, |
| 10623 | start: start_frame, |
| 10624 | seat, |
| 10625 | } |
| 10626 | } |
| 10627 | |
| 10628 | /// Whether this decoder can be parked for a later span: only the H.264 seat |
| 10629 | /// has a display index to resume from, so the pulled seats never are. |
| 10630 | fn parkable(&self) -> bool { |
| 10631 | // An interlaced seat holds a picture back for its successor, so it has |
| 10632 | // no display index a later span could resume from. |
| 10633 | matches!(&self.seat, SwSeat::H264(s) if !s.deint.is_interlaced()) |
| 10634 | } |
| 10635 | |
| 10636 | /// The display index the seat's next picture will carry; `0` off the H.264 seat. |
| 10637 | fn index(&self) -> i64 { |
| 10638 | match &self.seat { |
| 10639 | SwSeat::H264(seat) => seat.index, |
| 10640 | SwSeat::Pulled { .. } => 0, |
| 10641 | } |
| 10642 | } |
| 10643 | |
| 10644 | /// The display index the seat started at; `0` off the H.264 seat. |
| 10645 | fn origin(&self) -> i64 { |
| 10646 | match &self.seat { |
| 10647 | SwSeat::H264(seat) => seat.origin, |
| 10648 | SwSeat::Pulled { .. } => 0, |
| 10649 | } |
| 10650 | } |
| 10651 | |
| 10652 | /// Set once the demuxer ran dry. Always `true` off the H.264 seat, which is |
| 10653 | /// what keeps a pulled decoder from being parked (see [`SwDecoder::parkable`]). |
| 10654 | fn flushed(&self) -> bool { |
| 10655 | match &self.seat { |
| 10656 | SwSeat::H264(seat) => seat.flushed || seat.deint.is_interlaced(), |
| 10657 | SwSeat::Pulled { .. } => true, |
| 10658 | } |
| 10659 | } |
| 10660 | } |
| 10661 | |
| 10662 | impl H264Seat { |
| 10663 | /// A fresh `ec-h264` seat whose first picture is display index `index`. |
| 10664 | /// |
| 10665 | /// An interlaced stream lands one picture earlier than the in point, so the |
| 10666 | /// deinterlacer has the picture before it, as a sequential decode does. |
| 10667 | fn open(demuxer: &mut Demuxer, start: u32, wide: bool, mode: Deinterlace) -> Box<Self> { |
| 10668 | let deint = crate::deinterlace::Deinterlacer::with_mode( |
| 10669 | mode, |
| 10670 | demuxer.h264_interlaced(), |
| 10671 | i64::from(start), |
| 10672 | ec_core::frame::Interlace::Progressive, |
| 10673 | ) |
| 10674 | .cadenced(mode, demuxer); |
| 10675 | let index = demuxer.seek_to_sync_at_or_before(deint.landing(start)); |
| 10676 | Box::new(Self { |
| 10677 | deint, |
| 10678 | ..*Self::at(index, wide) |
| 10679 | }) |
| 10680 | } |
| 10681 | |
| 10682 | fn at(index: i64, wide: bool) -> Box<Self> { |
| 10683 | Box::new(Self { |
| 10684 | decoder: H264Decoder::new(CodecParameters::new(CodecId::H264)) |
| 10685 | .expect("ec-h264 takes its own codec id"), |
| 10686 | index, |
| 10687 | origin: index, |
| 10688 | flushed: false, |
| 10689 | frame: None, |
| 10690 | wide, |
| 10691 | deep: Default::default(), |
| 10692 | deint: crate::deinterlace::Deinterlacer::new(false, 0, ec_core::frame::Interlace::Progressive), |
| 10693 | pending: VecDeque::new(), |
| 10694 | }) |
| 10695 | } |
| 10696 | |
| 10697 | /// Decodes up to and including the next picture at or after the in point, |
| 10698 | /// leaving it in `frame`. `false` at end of stream. Pictures leave the |
| 10699 | /// decoder in display order -- clause C.4.5.3, the same contract the |
| 10700 | /// playback seat keeps -- so the landing index, itself a display index by |
| 10701 | /// the demuxer's contract, counts one to one with them. |
| 10702 | fn advance(&mut self, demuxer: &mut Demuxer, start: u32) -> crate::Result<bool> { |
| 10703 | loop { |
| 10704 | // The second field of the frame the last call took the first of. |
| 10705 | if let Some((due, pic)) = self.pending.pop_front() { |
| 10706 | if due < i64::from(start) { |
| 10707 | continue; |
| 10708 | } |
| 10709 | self.deep.load(&pic, self.wide); |
| 10710 | self.frame = Some(pic); |
| 10711 | return Ok(true); |
| 10712 | } |
| 10713 | if !self.flushed { |
| 10714 | match demuxer.next_access_unit()? { |
| 10715 | Some(au) => self |
| 10716 | .decoder |
| 10717 | .send_packet(&Packet::new(0, TimeBase::new(1, 1), au)) |
| 10718 | .map_err(|e| format!("decode at picture {}: {e}", self.index))?, |
| 10719 | None => { |
| 10720 | self.flushed = true; |
| 10721 | self.decoder |
| 10722 | .flush() |
| 10723 | .map_err(|e| format!("decode at end of stream: {e}"))?; |
| 10724 | } |
| 10725 | } |
| 10726 | } |
| 10727 | match self.decoder.receive_frame() { |
| 10728 | Ok(frame) => { |
| 10729 | let ec_core::frame::Frame::Video(pic) = frame else { |
| 10730 | continue; |
| 10731 | }; |
| 10732 | let tag = self.index; |
| 10733 | self.index += 1; |
| 10734 | // Held one picture back while the deinterlacer waits for |
| 10735 | // the successor; below the in point it only primes. In |
| 10736 | // field mode it releases two, queued for the loop's top. |
| 10737 | self.pending.extend(self.deint.push_all(tag, pic)); |
| 10738 | } |
| 10739 | // End of stream counts once the flush has happened; before it, |
| 10740 | // either answer means go back for the next access unit. The |
| 10741 | // last picture an interlaced stream held leaves first. |
| 10742 | Err(e) if e.is_eof() && self.flushed => { |
| 10743 | self.pending.extend(self.deint.finish_all()); |
| 10744 | if self.pending.is_empty() { |
| 10745 | return Ok(false); |
| 10746 | } |
| 10747 | } |
| 10748 | Err(e) if e.is_need_more() || e.is_eof() => {} |
| 10749 | Err(e) => return Err(format!("decode at picture {}: {e}", self.index).into()), |
| 10750 | } |
| 10751 | } |
| 10752 | } |
| 10753 | } |
| 10754 | |
| 10755 | #[cfg(test)] |
| 10756 | mod tests { |
| 10757 | /// A standalone file's soft track is titled with its language's name, or left |
| 10758 | /// untitled, and never with its file name; an embedded track keeps the title |
| 10759 | /// its container gave it. |
| 10760 | #[test] |
| 10761 | fn a_soft_track_is_titled_by_its_language_never_its_file_name() { |
| 10762 | let file = |language: &str| SubtitleTrack { |
| 10763 | path: "/media/talk.fr.srt".into(), |
| 10764 | track: None, |
| 10765 | language: language.into(), |
| 10766 | name: String::new(), |
| 10767 | label: "talk.fr.srt".into(), |
| 10768 | cues: Vec::new(), |
| 10769 | bitmap: false, |
| 10770 | refused: None, |
| 10771 | }; |
| 10772 | assert_eq!(subtitle_title(&file("fra")), "French"); |
| 10773 | assert_eq!(subtitle_title(&file("")), "", "unset: no title, and never the file name"); |
| 10774 | let embedded = SubtitleTrack { |
| 10775 | track: Some(3), |
| 10776 | name: "Signs".into(), |
| 10777 | ..file("fra") |
| 10778 | }; |
| 10779 | assert_eq!(subtitle_title(&embedded), "Signs"); |
| 10780 | } |
| 10781 | |
| 10782 | /// Two caption lanes, one per palette track: a pick list names the lanes it |
| 10783 | /// keeps, and an empty one keeps them all -- in the plan and in the file. |
| 10784 | #[test] |
| 10785 | fn a_pick_list_keeps_only_the_lanes_it_names() { |
| 10786 | use crate::project::{LaneKind, SubClip}; |
| 10787 | let track = |label: &str, text: &str| SubtitleTrack { |
| 10788 | path: "/nonexistent/film.mkv".into(), |
| 10789 | track: Some(1), |
| 10790 | language: "eng".into(), |
| 10791 | name: label.into(), |
| 10792 | label: label.into(), |
| 10793 | bitmap: false, |
| 10794 | cues: vec![Cue { |
| 10795 | start_us: 0, |
| 10796 | end_us: 1_000_000, |
| 10797 | text: text.into(), |
| 10798 | image: None, |
| 10799 | words: Vec::new(), |
| 10800 | karaoke: Vec::new(), |
| 10801 | }], |
| 10802 | refused: None, |
| 10803 | }; |
| 10804 | let mut project = Project::single("/nonexistent/a.mp4", 150) |
| 10805 | .with_subtitles(vec![track("one", "first words"), track("two", "second words")]); |
| 10806 | for track in 0..2 { |
| 10807 | let lane = project.add_lane(LaneKind::Subtitle); |
| 10808 | project |
| 10809 | .place_sub( |
| 10810 | lane, |
| 10811 | 0, |
| 10812 | SubClip { |
| 10813 | start: 0, |
| 10814 | frames: 150, |
| 10815 | track, |
| 10816 | in_us: 0, |
| 10817 | out_us: 1_000_000, |
| 10818 | link: None, |
| 10819 | }, |
| 10820 | ) |
| 10821 | .expect("an empty lane takes the placement"); |
| 10822 | } |
| 10823 | let names = |subs: &[SubParams]| subs.iter().map(|s| s.name.clone()).collect::<Vec<_>>(); |
| 10824 | |
| 10825 | let only_zero = lane_subtitles(&project, 30.0, None, &[0]); |
| 10826 | assert_eq!(names(&only_zero), ["one"], "pick [0] keeps track 0's lane alone"); |
| 10827 | assert_eq!(only_zero[0].cues[0].text, "first words"); |
| 10828 | |
| 10829 | let all = lane_subtitles(&project, 30.0, None, &[]); |
| 10830 | assert_eq!(names(&all), ["one", "two"], "an empty pick list keeps every lane"); |
| 10831 | |
| 10832 | let plan = planned_subtitles(&project, Format::Mp4, [0]); |
| 10833 | assert!(plan.contains("S1 one") && !plan.contains("two"), "plan: {plan}"); |
| 10834 | let plan = planned_subtitles(&project, Format::Mp4, Vec::<usize>::new()); |
| 10835 | assert!(plan.contains("S1 one") && plan.contains("S2 two"), "plan: {plan}"); |
| 10836 | } |
| 10837 | |
| 10838 | /// Four palette tracks, lanes S1 and S2 holding tracks 0 and 2: the file writes the tracks in |
| 10839 | /// the order the caller gave them, placed or not, and the card names them in that order. |
| 10840 | #[test] |
| 10841 | fn soft_tracks_are_written_in_the_order_the_caller_gave() { |
| 10842 | use crate::project::{LaneKind, SubClip}; |
| 10843 | let track = |label: &str| SubtitleTrack { |
| 10844 | path: "/nonexistent/film.srt".into(), |
| 10845 | track: None, |
| 10846 | language: "eng".into(), |
| 10847 | name: label.into(), |
| 10848 | label: label.into(), |
| 10849 | bitmap: false, |
| 10850 | cues: vec![Cue { |
| 10851 | start_us: 0, |
| 10852 | end_us: 1_000_000, |
| 10853 | text: format!("{label} words"), |
| 10854 | image: None, |
| 10855 | words: Vec::new(), |
| 10856 | karaoke: Vec::new(), |
| 10857 | }], |
| 10858 | refused: None, |
| 10859 | }; |
| 10860 | let mut project = Project::single("/nonexistent/a.mp4", 150) |
| 10861 | .with_subtitles(vec![track("one"), track("two"), track("three"), track("four")]); |
| 10862 | for track in [0, 2] { |
| 10863 | let lane = project.add_lane(LaneKind::Subtitle); |
| 10864 | project |
| 10865 | .place_sub( |
| 10866 | lane, |
| 10867 | 0, |
| 10868 | SubClip { |
| 10869 | start: 0, |
| 10870 | frames: 150, |
| 10871 | track, |
| 10872 | in_us: 0, |
| 10873 | out_us: 1_000_000, |
| 10874 | link: None, |
| 10875 | }, |
| 10876 | ) |
| 10877 | .expect("an empty lane takes the placement"); |
| 10878 | } |
| 10879 | let lanes = project.subtitle_lanes(); |
| 10880 | let (s1, s2) = (lanes[0], lanes[1]); |
| 10881 | |
| 10882 | assert_eq!(soft_order(&project, &lanes, &[2, 0]), [SoftEntry::Lane(s2), SoftEntry::Lane(s1)]); |
| 10883 | assert_eq!(soft_order(&project, &lanes, &[0, 2]), [SoftEntry::Lane(s1), SoftEntry::Lane(s2)]); |
| 10884 | assert_eq!(soft_order(&project, &lanes, &[3, 1]), [SoftEntry::Track(3), SoftEntry::Track(1)]); |
| 10885 | assert_eq!(soft_order(&project, &lanes, &[]), [SoftEntry::Lane(s1), SoftEntry::Lane(s2)]); |
| 10886 | |
| 10887 | let plan = planned_subtitles(&project, Format::Mp4, [2, 0]); |
| 10888 | assert!(plan.contains("2 lanes → embedded (S2 three, S1 one)"), "plan: {plan}"); |
| 10889 | let plan = planned_subtitles(&project, Format::Mp4, [3, 1]); |
| 10890 | assert!(plan.contains("2 tracks → embedded (four, two)"), "plan: {plan}"); |
| 10891 | let plan = planned_subtitles(&project, Format::Mp4, [3, 2, 1, 0]); |
| 10892 | assert!(plan.contains("4 tracks → embedded (four, S2 three, two, S1 one)"), "plan: {plan}"); |
| 10893 | } |
| 10894 | |
| 10895 | /// A ranged file names a track with no cue inside the range as dropped, and carries the rest; |
| 10896 | /// a standalone ASS script with override blocks is named as styling the file drops. |
| 10897 | #[test] |
| 10898 | fn a_range_drops_tracks_with_no_cue_in_it_and_ass_styling_is_named() { |
| 10899 | use crate::project::{LaneKind, SubClip}; |
| 10900 | let track = |label: &str, path: &str| SubtitleTrack { |
| 10901 | path: path.into(), |
| 10902 | track: None, |
| 10903 | language: "eng".into(), |
| 10904 | name: label.into(), |
| 10905 | label: label.into(), |
| 10906 | bitmap: false, |
| 10907 | cues: vec![Cue { |
| 10908 | start_us: 0, |
| 10909 | end_us: 1_000_000, |
| 10910 | text: format!("{label} words"), |
| 10911 | image: None, |
| 10912 | words: Vec::new(), |
| 10913 | karaoke: Vec::new(), |
| 10914 | }], |
| 10915 | refused: None, |
| 10916 | }; |
| 10917 | let ass = std::env::temp_dir().join(format!("edith_export_styling_{}.ass", std::process::id())); |
| 10918 | std::fs::write( |
| 10919 | &ass, |
| 10920 | "[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", |
| 10921 | ) |
| 10922 | .expect("a scratch script"); |
| 10923 | let mut project = Project::single("/nonexistent/a.mp4", 150) |
| 10924 | .with_subtitles(vec![track("one", ass.to_str().unwrap()), track("two", "/nonexistent/film.srt")]); |
| 10925 | for t in 0..2 { |
| 10926 | let lane = project.add_lane(LaneKind::Subtitle); |
| 10927 | project |
| 10928 | .place_sub( |
| 10929 | lane, |
| 10930 | 0, |
| 10931 | SubClip { |
| 10932 | start: 0, |
| 10933 | frames: 30, |
| 10934 | track: t, |
| 10935 | in_us: 0, |
| 10936 | out_us: 1_000_000, |
| 10937 | link: None, |
| 10938 | }, |
| 10939 | ) |
| 10940 | .expect("an empty lane takes the placement"); |
| 10941 | } |
| 10942 | // Cues sit in the first second (frames 0 to 30 at 30 fps): a range after it has none. |
| 10943 | let late = planned_subtitles_in(&project, Format::Mp4, [0, 1], Some((60, 150)), 30.0); |
| 10944 | assert!(late.contains("S1 one — no cues in range") && late.contains("S2 two — no cues in range"), "plan: {late}"); |
| 10945 | assert!(!late.contains("→ embedded"), "plan: {late}"); |
| 10946 | let early = planned_subtitles_in(&project, Format::Mp4, [0, 1], Some((0, 30)), 30.0); |
| 10947 | assert!(early.contains("2 lanes → embedded (S1 one, S2 two)"), "plan: {early}"); |
| 10948 | |
| 10949 | assert_eq!(stripped_styling(&project, &[0, 1]), ["one"], "the ASS script's override tags"); |
| 10950 | assert!(stripped_styling(&project, &[1]).is_empty(), "a plain SRT has no styling to drop"); |
| 10951 | let _ = std::fs::remove_file(&ass); |
| 10952 | } |
| 10953 | |
| 10954 | #[test] |
| 10955 | fn fit_picture_clips_sets_every_picture_clip_on_the_copy() { |
| 10956 | let mut p = Project::single("/nonexistent/a.mp4", 90); |
| 10957 | let before = p.lane(Lane::V1)[0].fit; |
| 10958 | assert_eq!(before, FitPolicy::Fit, "a clip starts on its own default"); |
| 10959 | assert_eq!( |
| 10960 | fit_picture_clips(&mut p, FitPolicy::Fill), |
| 10961 | FitOutcome { lanes: vec![(Lane::V1, 1)], overlays: 0 }, |
| 10962 | "one picture clip" |
| 10963 | ); |
| 10964 | assert_eq!(p.lane(Lane::V1)[0].fit, FitPolicy::Fill); |
| 10965 | assert_eq!(p.fit_of(Lane::V1, 0), FitPolicy::Fill); |
| 10966 | } |
| 10967 | |
| 10968 | /// The I+P seat's automatic quality is its own default, not the intra |
| 10969 | /// seat's mapping: at 1080p30 the intra mapping clamps to QP 40 and the |
| 10970 | /// GOP seat must name QP 28 instead. |
| 10971 | #[test] |
| 10972 | fn the_gop_default_is_not_the_intra_seats_clamped_qp() { |
| 10973 | let m = meta(1920, 1080); |
| 10974 | let auto = ExportSettings { format: Format::HevcMp4, ..Default::default() }; |
| 10975 | assert_eq!(hevc_qp(&m, &auto), 40, "the intra mapping clamps at 1080p30"); |
| 10976 | assert_eq!( |
| 10977 | hevc_mode_words(&m, &auto), |
| 10978 | Some("I+P GOP (1 s keyframes), constant quality QP 28; pass bitrate_kbps for a fixed rate".to_string()) |
| 10979 | ); |
| 10980 | } |
| 10981 | |
| 10982 | #[test] |
| 10983 | fn hevc_and_av1_words_name_the_quality_or_the_rate() { |
| 10984 | let m = meta(1920, 1080); |
| 10985 | let auto = |format| ExportSettings { format, ..Default::default() }; |
| 10986 | let fixed = |format| ExportSettings { format, bitrate: Some(4_000_000), ..Default::default() }; |
| 10987 | // With no bitrate the HEVC row is constant QP: the number is the one the encoder is given. |
| 10988 | assert_eq!( |
| 10989 | hevc_mode_words(&m, &auto(Format::HevcMp4)), |
| 10990 | Some(format!("I+P GOP (1 s keyframes), constant quality QP {HEVC_GOP_QP}; pass bitrate_kbps for a fixed rate")) |
| 10991 | ); |
| 10992 | assert_eq!( |
| 10993 | hevc_mode_words(&m, &fixed(Format::HevcMp4)), |
| 10994 | Some("I+P GOP (1 s keyframes), 4 Mb/s".to_string()) |
| 10995 | ); |
| 10996 | assert_eq!(hevc_mode_words(&m, &auto(Format::Mp4)), None, "not an HEVC format"); |
| 10997 | // AV1 is coded at a bitrate: the automatic one is named as the target it is. |
| 10998 | let target = av1_mode_words(&m, &auto(Format::Av1)).expect("an AV1 format"); |
| 10999 | assert!(target.starts_with("average bitrate ") && target.contains("pass bitrate_kbps"), "{target}"); |
| 11000 | assert_eq!(av1_mode_words(&m, &fixed(Format::Av1Mp4)), Some("average bitrate 4 Mb/s".to_string())); |
| 11001 | assert_eq!(rate_words(6220), "6.2 Mb/s"); |
| 11002 | assert_eq!(rate_words(850), "850 kb/s"); |
| 11003 | assert_eq!(av1_mode_words(&m, &auto(Format::HevcMp4)), None, "not an AV1 format"); |
| 11004 | } |
| 11005 | |
| 11006 | #[test] |
| 11007 | fn fit_picture_clips_leaves_a_transformed_overlay_on_its_own_fit() { |
| 11008 | use crate::transform::TransformParams; |
| 11009 | let mut p = Project::single("/nonexistent/a.mp4", 90); |
| 11010 | let v2 = Lane::new(LaneKind::Video, 1); |
| 11011 | assert_eq!(p.add_lane(LaneKind::Video), v2); |
| 11012 | let logo = p.lane(Lane::V1)[0].clone(); |
| 11013 | assert!(p.place(v2, 0, logo), "a logo on V2"); |
| 11014 | // The logo as the project has it: 0.3 of the canvas width, 80% opaque, moved up and right. |
| 11015 | let placed = TransformParams { pos_x: 0.32, pos_y: -0.32, scale: 0.3, opacity: 0.8, ..Default::default() }; |
| 11016 | assert!(p.set_transform(v2, 0, Some(placed))); |
| 11017 | assert_eq!( |
| 11018 | fit_picture_clips(&mut p, FitPolicy::Fill), |
| 11019 | FitOutcome { lanes: vec![(Lane::V1, 1)], overlays: 1 }, |
| 11020 | "the base picture refits, the overlay does not" |
| 11021 | ); |
| 11022 | assert_eq!(p.fit_of(Lane::V1, 0), FitPolicy::Fill); |
| 11023 | assert_eq!(p.fit_of(v2, 0), FitPolicy::Fit, "the overlay keeps its own fit"); |
| 11024 | assert_eq!(p.transform_of(v2, 0), Some(&placed), "and its placement"); |
| 11025 | |
| 11026 | // An identity transform is not an overlay: it refits like any full-frame clip. |
| 11027 | assert!(p.set_transform(v2, 0, Some(TransformParams::default()))); |
| 11028 | assert_eq!(fit_picture_clips(&mut p, FitPolicy::Fill).overlays, 0); |
| 11029 | assert_eq!(p.fit_of(v2, 0), FitPolicy::Fill); |
| 11030 | } |
| 11031 | |
| 11032 | #[test] |
| 11033 | fn a_caption_and_a_title_clash_only_in_the_same_place_and_on_screen_together() { |
| 11034 | use crate::project::Title; |
| 11035 | use crate::text::TextStyle; |
| 11036 | let cue = |start_s: f64, end_s: f64, text: &str| Cue { |
| 11037 | start_us: (start_s * 1e6) as i64, |
| 11038 | end_us: (end_s * 1e6) as i64, |
| 11039 | text: text.into(), |
| 11040 | image: None, |
| 11041 | words: Vec::new(), |
| 11042 | karaoke: Vec::new(), |
| 11043 | }; |
| 11044 | let title = |start: u32, frames: u32, text: &str, place: Place| Title { |
| 11045 | start, |
| 11046 | frames, |
| 11047 | text: text.into(), |
| 11048 | style: TextStyle { place, ..TextStyle::default() }, |
| 11049 | fade_in: 0, |
| 11050 | fade_out: 0, |
| 11051 | in_anim: Default::default(), |
| 11052 | out_anim: Default::default(), |
| 11053 | anim_frames: 0, |
| 11054 | keys: Vec::new(), |
| 11055 | }; |
| 11056 | // Captions 86.0 to 88.0 s; a bottom title from frame 2163 (86.52 s at 25 fps) for 3 s. |
| 11057 | let cues = [cue(86.0, 88.0, "hello")]; |
| 11058 | let titles = [title(2163, 75, "EVENING, MIRADOURO", Place::Bottom)]; |
| 11059 | let clash = caption_title_clash(&cues, &titles, Place::Bottom, 25.0).expect("same place, on screen together"); |
| 11060 | assert!((clash.0 - 86.52).abs() < 0.01, "the clash starts where both are up: {clash:?}"); |
| 11061 | assert_eq!(clash.1, 0); |
| 11062 | assert_eq!(caption_title_clash(&cues, &titles, Place::Top, 25.0), None, "a top caption clears a bottom title"); |
| 11063 | // The title is up after the captions end: no clash. |
| 11064 | let late = [title(2300, 25, "LATE", Place::Bottom)]; |
| 11065 | assert_eq!(caption_title_clash(&cues, &late, Place::Bottom, 25.0), None, "not on screen together"); |
| 11066 | // A blank cue is no words on the picture. |
| 11067 | let blank = [cue(86.0, 88.0, " ")]; |
| 11068 | assert_eq!(caption_title_clash(&blank, &titles, Place::Bottom, 25.0), None); |
| 11069 | } |
| 11070 | |
| 11071 | #[test] |
| 11072 | fn h264_levels_follow_table_a1() { |
| 11073 | use super::h264_level_idc; |
| 11074 | assert_eq!(h264_level_idc(1280, 720, 30, 1), 31); |
| 11075 | assert_eq!(h264_level_idc(1920, 1080, 30, 1), 40); |
| 11076 | assert_eq!(h264_level_idc(1920, 1080, 60, 1), 42); |
| 11077 | assert_eq!(h264_level_idc(2560, 1440, 30, 1), 50); |
| 11078 | assert_eq!(h264_level_idc(3840, 1608, 24000, 1001), 51); |
| 11079 | assert_eq!(h264_level_idc(3840, 2160, 60, 1), 52); |
| 11080 | assert_eq!(h264_level_idc(640, 360, 30, 1), 30); |
| 11081 | } |
| 11082 | |
| 11083 | use super::*; |
| 11084 | |
| 11085 | /// The bar of a *feature film*: a picture count times a permille is a |
| 11086 | /// product that has to be computed in `u64`, or a timeline past ~4.5 M |
| 11087 | /// pictures (42 hours at 30 fps) overflowed the `u32` this used to be -- |
| 11088 | /// a panic in debug inside the export thread, and a bar that thrashed in |
| 11089 | /// release. Every value here is a fraction of the whole, so none of them |
| 11090 | /// may leave the scale, and the counts straddle the old overflow point. |
| 11091 | #[test] |
| 11092 | fn a_films_frame_count_does_not_overflow_the_bar() { |
| 11093 | // The straddle, in the very product the old shape computed: `boundary` |
| 11094 | // is the largest picture count whose `done * band` still fitted a |
| 11095 | // `u32`, and one more is where it began to wrap -- a panic in debug, |
| 11096 | // inside the export thread. |
| 11097 | let band = u64::from(PROGRESS_SCALE - AUDIO_BAND); |
| 11098 | let boundary = u64::from(u32::MAX) / band; |
| 11099 | assert!(boundary * band <= u64::from(u32::MAX)); |
| 11100 | assert!((boundary + 1) * band > u64::from(u32::MAX)); |
| 11101 | for total in [boundary as u32 + 1, 21_600_000, u32::MAX] { |
| 11102 | assert_eq!(picture_progress(total, total), PROGRESS_SCALE, "{total}"); |
| 11103 | assert_eq!(picture_progress(0, total), AUDIO_BAND, "{total}"); |
| 11104 | let half = picture_progress(total / 2, total); |
| 11105 | assert!( |
| 11106 | (AUDIO_BAND..PROGRESS_SCALE).contains(&half), |
| 11107 | "half of {total} is {half}" |
| 11108 | ); |
| 11109 | assert!( |
| 11110 | picture_progress(total - 1, total) <= PROGRESS_SCALE, |
| 11111 | "{total}" |
| 11112 | ); |
| 11113 | } |
| 11114 | } |
| 11115 | |
| 11116 | /// How a decode thread ended is never guessed from the channel being shut. |
| 11117 | /// A source that genuinely ran out says so, and the span ends on it; a |
| 11118 | /// thread that died without a word is a failure, because reading it as end |
| 11119 | /// of stream would truncate the picture and *report the export finished*. |
| 11120 | #[test] |
| 11121 | fn a_decoder_that_dies_without_a_word_is_not_end_of_stream() { |
| 11122 | let streamed = |handle, frames| { |
| 11123 | ClipDecoder::Streamed(Streamed { |
| 11124 | frames, |
| 11125 | _thread: DecodeThread(Some(handle)), |
| 11126 | current: None, |
| 11127 | ended: false, |
| 11128 | park: None, |
| 11129 | }) |
| 11130 | }; |
| 11131 | |
| 11132 | let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2); |
| 11133 | // Said its piece, then finished: the span walks on to its next clip. |
| 11134 | let handle = thread::spawn(move || { |
| 11135 | tx.send(Ok(None)).expect("the receiver is alive"); |
| 11136 | None |
| 11137 | }); |
| 11138 | let mut ended = streamed(handle, frames); |
| 11139 | assert!(ended.next().expect("a clean end is not an error").is_none()); |
| 11140 | // ...and asking again is the same answer and not a disconnect error. |
| 11141 | assert!(ended.next().expect("still not an error").is_none()); |
| 11142 | |
| 11143 | let (tx, frames) = sync_channel::<crate::Result<Option<Yuv>>>(2); |
| 11144 | // Died holding the sender: the channel shuts with nothing said. |
| 11145 | let handle = thread::spawn(move || { |
| 11146 | let _tx = tx; |
| 11147 | panic!("decoder died"); |
| 11148 | }); |
| 11149 | let mut died = streamed(handle, frames); |
| 11150 | let Err(e) = died.next() else { |
| 11151 | panic!("a silent death must fail the export, not end the clip") |
| 11152 | }; |
| 11153 | assert!( |
| 11154 | e.to_string().contains("without a picture or a reason"), |
| 11155 | "{e}" |
| 11156 | ); |
| 11157 | } |
| 11158 | |
| 11159 | /// When a parked decoder may carry on for a later span. A decoder cannot go |
| 11160 | /// back, so the span must start at or after the first picture it still |
| 11161 | /// holds; and it must have been started at the sync sample a fresh decoder |
| 11162 | /// would seek to, or the pictures after it would not be the fresh ones. |
| 11163 | #[test] |
| 11164 | fn a_parked_decoder_resumes_only_where_a_fresh_one_would_match() { |
| 11165 | // Stopped at display 330 with two decoded pictures unclaimed (328 and |
| 11166 | // 329), started at the sync sample 250. |
| 11167 | let stopped = |start| resumable(330, 2, 250, 250, start); |
| 11168 | assert!(stopped(328), "the first held picture is the span's first"); |
| 11169 | assert!(stopped(329), "the second held picture is the span's first"); |
| 11170 | assert!(stopped(330), "the span starts where the decoder stopped"); |
| 11171 | assert!(stopped(400), "a span further on decodes on to its picture"); |
| 11172 | assert!(!stopped(327), "a span before what is held needs a restart"); |
| 11173 | // Nothing unclaimed: the decoder's own position is the first picture. |
| 11174 | assert!(resumable(330, 0, 250, 250, 330)); |
| 11175 | assert!(!resumable(330, 0, 250, 250, 329)); |
| 11176 | // A fresh decoder for the span would seek to a later sync sample than |
| 11177 | // the one this decoder started at, so this one is not the same decode. |
| 11178 | assert!(!resumable(330, 2, 250, 300, 400)); |
| 11179 | // And one that started at a later sync sample than a fresh one would |
| 11180 | // is not the same decode either. |
| 11181 | assert!(!resumable(330, 2, 300, 250, 330)); |
| 11182 | } |
| 11183 | |
| 11184 | /// Three seconds of two tones, one per channel, interleaved: enough shape |
| 11185 | /// that a correlation says something and enough length that the encoder |
| 11186 | /// settles into a mode. |
| 11187 | fn two_tones(secs: usize) -> Vec<f32> { |
| 11188 | (0..OPUS_RATE as usize * secs) |
| 11189 | .flat_map(|i| { |
| 11190 | let t = i as f32 / OPUS_RATE as f32; |
| 11191 | let tau = std::f32::consts::TAU; |
| 11192 | [ |
| 11193 | 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin(), |
| 11194 | 0.25 * (tau * 880.0 * t).sin(), |
| 11195 | ] |
| 11196 | }) |
| 11197 | .collect() |
| 11198 | } |
| 11199 | |
| 11200 | /// Three seconds of the same two tones summed onto one channel: the mono |
| 11201 | /// mix `opus-rs 0.1.26` mis-encoded at every rate, which is why a mono |
| 11202 | /// export kept the AAC path until `ec-opus` took the seat. |
| 11203 | fn mono_tones(secs: usize) -> Vec<f32> { |
| 11204 | (0..OPUS_RATE as usize * secs) |
| 11205 | .map(|i| { |
| 11206 | let t = i as f32 / OPUS_RATE as f32; |
| 11207 | let tau = std::f32::consts::TAU; |
| 11208 | 0.3 * (tau * 440.0 * t).sin() + 0.2 * (tau * 1234.0 * t).sin() |
| 11209 | }) |
| 11210 | .collect() |
| 11211 | } |
| 11212 | |
| 11213 | /// The best correlation of one channel of `got` against `want`, and the |
| 11214 | /// offset it sat at. `stride` is the interleave width: 2 for the stereo |
| 11215 | /// fixtures, 1 for mono. |
| 11216 | fn align(want: &[f32], got: &[f32], stride: usize) -> (f64, usize) { |
| 11217 | let (mut best, mut at) = (-2.0, 0); |
| 11218 | let window = OPUS_RATE as usize; |
| 11219 | for lag in 0..1400 { |
| 11220 | let (mut num, mut da, mut db) = (0.0, 0.0, 0.0); |
| 11221 | for (x, y) in want[..window] |
| 11222 | .iter() |
| 11223 | .step_by(stride) |
| 11224 | .zip(got[lag * stride..].iter().step_by(stride)) |
| 11225 | { |
| 11226 | num += f64::from(*x) * f64::from(*y); |
| 11227 | da += f64::from(*x) * f64::from(*x); |
| 11228 | db += f64::from(*y) * f64::from(*y); |
| 11229 | } |
| 11230 | let c = num / (da.sqrt() * db.sqrt()).max(1e-12); |
| 11231 | if c > best { |
| 11232 | (best, at) = (c, lag); |
| 11233 | } |
| 11234 | } |
| 11235 | (best, at) |
| 11236 | } |
| 11237 | |
| 11238 | fn ec_decode(packets: &[crate::AacPacket]) -> Vec<f32> { |
| 11239 | let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 1, &[0, 1]); |
| 11240 | let mut pcm = Vec::new(); |
| 11241 | for packet in packets { |
| 11242 | pcm.extend( |
| 11243 | decoder |
| 11244 | .decode_packet(&packet.bytes) |
| 11245 | .expect("a valid packet"), |
| 11246 | ); |
| 11247 | } |
| 11248 | pcm |
| 11249 | } |
| 11250 | |
| 11251 | /// [`ec_decode`] for a mono packet stream: one stream, no coupling. |
| 11252 | fn ec_decode_mono(packets: &[crate::AacPacket]) -> Vec<f32> { |
| 11253 | let mut decoder = ec_opus::MultistreamDecoder::with_rate(OPUS_RATE, 1, 0, &[0]); |
| 11254 | let mut pcm = Vec::new(); |
| 11255 | for packet in packets { |
| 11256 | pcm.extend( |
| 11257 | decoder |
| 11258 | .decode_packet(&packet.bytes) |
| 11259 | .expect("a valid packet"), |
| 11260 | ); |
| 11261 | } |
| 11262 | pcm |
| 11263 | } |
| 11264 | |
| 11265 | /// Why [`OPUS_MAX_KBPS`] is a cap, why [`OPUS_PRE_SKIP`] is a constant and |
| 11266 | /// why [`opus_fidelity`] exists at all -- all three measured here through |
| 11267 | /// the same decoder door the product reads every Opus file back with, the |
| 11268 | /// decoder being the witness and the *encoder* the one under test. |
| 11269 | /// |
| 11270 | /// The second half pins the two failures the seat's move here fixed: under |
| 11271 | /// `opus-rs 0.1.26` the encoder wrote stereo packets that only its own |
| 11272 | /// decoder read back above roughly 165 kbps (fidelity 0.06 at 256), and it |
| 11273 | /// mis-encoded mono at every rate -- which is what the old 128 cap and the |
| 11274 | /// mono-mix-keeps-AAC rule stood on. Both asserts are survival now, and a |
| 11275 | /// regression fails here, loudly: that is the signal to lower |
| 11276 | /// [`OPUS_MAX_KBPS`] again, not a reason to widen it quietly. |
| 11277 | #[test] |
| 11278 | fn the_opus_encoder_is_pinned_to_the_band_it_was_measured_in() { |
| 11279 | let pcm = two_tones(3); |
| 11280 | for kbps in [96, OPUS_MAX_KBPS] { |
| 11281 | let (packets, pre_skip) = encode_opus(&pcm, kbps, 2) |
| 11282 | .expect("the encoder opens") |
| 11283 | .expect("and inside the band it passes its own round trip"); |
| 11284 | assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16); |
| 11285 | assert_eq!( |
| 11286 | packets.len(), |
| 11287 | pcm.len().div_ceil(OPUS_FRAME * 2) + 2, |
| 11288 | "one packet per 20 ms frame, plus the warm-up and the flush" |
| 11289 | ); |
| 11290 | let decoded = ec_decode(&packets); |
| 11291 | let (c, lag) = align(&pcm, &decoded, 2); |
| 11292 | // From the first audible sample, head included -- and the head is |
| 11293 | // why this is 0.98 and not the 0.999 below: the encoder's first |
| 11294 | // audible 20 ms comes out a few dB down (one frame of cold start; |
| 11295 | // a second warm-up frame changes the numbers in no decimal place), |
| 11296 | // so that ramp is stated rather than hidden behind a loose |
| 11297 | // threshold. |
| 11298 | assert!(c >= 0.98, "{kbps} kbps came back at correlation {c:.4}"); |
| 11299 | let (settled, _) = align(&pcm[OPUS_FRAME * 2..], &decoded[OPUS_FRAME * 2..], 2); |
| 11300 | assert!( |
| 11301 | settled >= 0.999, |
| 11302 | "{kbps} kbps past the first frame: correlation {settled:.4}" |
| 11303 | ); |
| 11304 | // The whole point of the number in the header: drop exactly that |
| 11305 | // many samples and the sound starts where the timeline says. A lag |
| 11306 | // that is not it is a file that plays late or eats its own head. |
| 11307 | assert_eq!( |
| 11308 | lag, |
| 11309 | usize::from(pre_skip), |
| 11310 | "{kbps} kbps: the declared pre-skip is not where the sound starts" |
| 11311 | ); |
| 11312 | // ...and the tail is all there: the flush frame pushed the last |
| 11313 | // samples out, so what is left after the pre-skip covers the input. |
| 11314 | assert!( |
| 11315 | decoded.len() - usize::from(pre_skip) * 2 >= pcm.len(), |
| 11316 | "{kbps} kbps: the track ends {} samples short of the timeline", |
| 11317 | (pcm.len() + usize::from(pre_skip) * 2 - decoded.len()) / 2 |
| 11318 | ); |
| 11319 | // The gate the export runs before it writes anything, on a track |
| 11320 | // that deserves to pass it. |
| 11321 | let fidelity = opus_fidelity(&packets, &pcm, usize::from(pre_skip), 2); |
| 11322 | assert!( |
| 11323 | fidelity >= OPUS_MIN_FIDELITY, |
| 11324 | "{kbps} kbps scored {fidelity:.4} on its own round trip" |
| 11325 | ); |
| 11326 | } |
| 11327 | |
| 11328 | // Mono, the shape `opus-rs 0.1.26` mis-encoded at every rate and the |
| 11329 | // reason a mono mix kept the AAC path: straight through the same seat, |
| 11330 | // including at the rate where the old encoder was already writing |
| 11331 | // stereo noise, let alone mono. |
| 11332 | let mono = mono_tones(3); |
| 11333 | for kbps in [96, 256] { |
| 11334 | let (packets, pre_skip) = encode_opus(&mono, kbps, 1) |
| 11335 | .expect("the encoder opens") |
| 11336 | .expect("and mono passes its own round trip"); |
| 11337 | assert_eq!(pre_skip, OPUS_PRE_SKIP + OPUS_FRAME as u16); |
| 11338 | let decoded = ec_decode_mono(&packets); |
| 11339 | let (c, lag) = align(&mono, &decoded, 1); |
| 11340 | assert!( |
| 11341 | c >= 0.98, |
| 11342 | "mono at {kbps} kbps came back at correlation {c:.4}" |
| 11343 | ); |
| 11344 | let (settled, _) = align(&mono[OPUS_FRAME..], &decoded[OPUS_FRAME..], 1); |
| 11345 | assert!( |
| 11346 | settled >= 0.999, |
| 11347 | "mono at {kbps} kbps past the first frame: correlation {settled:.4}" |
| 11348 | ); |
| 11349 | assert_eq!( |
| 11350 | lag, |
| 11351 | usize::from(pre_skip), |
| 11352 | "mono at {kbps} kbps: the declared pre-skip is not where the sound starts" |
| 11353 | ); |
| 11354 | assert!( |
| 11355 | decoded.len() - usize::from(pre_skip) >= mono.len(), |
| 11356 | "mono at {kbps} kbps: the track ends {} samples short of the timeline", |
| 11357 | mono.len() + usize::from(pre_skip) - decoded.len() |
| 11358 | ); |
| 11359 | let fidelity = opus_fidelity(&packets, &mono, usize::from(pre_skip), 1); |
| 11360 | assert!( |
| 11361 | fidelity >= OPUS_MIN_FIDELITY, |
| 11362 | "mono at {kbps} kbps scored {fidelity:.4} on its own round trip" |
| 11363 | ); |
| 11364 | } |
| 11365 | } |
| 11366 | |
| 11367 | /// The gate on a track too long to listen to whole: it samples, and the |
| 11368 | /// middle of what it hears is the answer. A track whose sound is *not* what |
| 11369 | /// was encoded fails it; one bad five-second window does not, which is |
| 11370 | /// deliberate and measured ([`opus_fidelity`] carries the distribution: |
| 11371 | /// five windows of a good film's mix score under 0.95, the lowest 0.803). |
| 11372 | /// A silent track is not a failure either, which is what it used to be |
| 11373 | /// scored as -- 0.0 against a denominator of nothing, and an all-quiet |
| 11374 | /// timeline fell back to AAC for it. |
| 11375 | /// |
| 11376 | /// 61 s of sound: one second past the minute the gate stops listening whole, |
| 11377 | /// which is what puts this on the sampled path at all. |
| 11378 | #[test] |
| 11379 | fn a_long_track_is_judged_by_the_middle_of_what_it_samples() { |
| 11380 | let pcm = two_tones(61); |
| 11381 | let (packets, pre_skip) = encode_opus(&pcm, 96, 2) |
| 11382 | .expect("the encoder opens") |
| 11383 | .expect("and passes its own round trip"); |
| 11384 | assert!( |
| 11385 | packets.len() > FIDELITY_WINDOW * FIDELITY_WINDOWS, |
| 11386 | "{} packets is not the sampled path", |
| 11387 | packets.len() |
| 11388 | ); |
| 11389 | let pre_skip = usize::from(pre_skip); |
| 11390 | let whole = opus_fidelity(&packets, &pcm, pre_skip, 2); |
| 11391 | assert!(whole >= OPUS_MIN_FIDELITY, "a good track scored {whole:.4}"); |
| 11392 | |
| 11393 | // One window's worth of the *mix* replaced by its own phase inverse: |
| 11394 | // the packets still decode, they are simply no longer this sound. Placed |
| 11395 | // on a window the gate samples -- window 6 of the twelve, by the same |
| 11396 | // arithmetic the gate spreads them with. The track still passes, and |
| 11397 | // that is the measured decision, not an oversight: this codec really |
| 11398 | // does score 0.80 on five seconds of film it otherwise handles at 0.998. |
| 11399 | let step = (packets.len() - FIDELITY_WINDOW) / (FIDELITY_WINDOWS - 1); |
| 11400 | let from = (6 * step * OPUS_FRAME).saturating_sub(pre_skip) * 2; |
| 11401 | let mut one_bad = pcm.clone(); |
| 11402 | for sample in &mut one_bad[from..(from + FIDELITY_WINDOW * OPUS_FRAME * 2).min(pcm.len())] { |
| 11403 | *sample = -*sample; |
| 11404 | } |
| 11405 | let dip = opus_fidelity(&packets, &one_bad, pre_skip, 2); |
| 11406 | assert!( |
| 11407 | dip >= OPUS_MIN_FIDELITY, |
| 11408 | "one ruined window sank the whole track ({dip:.4})" |
| 11409 | ); |
| 11410 | |
| 11411 | // ...and the shape the gate is actually for, which is what a rate the |
| 11412 | // encoder cannot hold does: the track is not the mix any more, not one |
| 11413 | // window of it. The middle of the list moves with it. |
| 11414 | let mut ruined = pcm.clone(); |
| 11415 | for sample in &mut ruined[pcm.len() / 4..] { |
| 11416 | *sample = -*sample; |
| 11417 | } |
| 11418 | let ruined = opus_fidelity(&packets, &ruined, pre_skip, 2); |
| 11419 | assert!( |
| 11420 | ruined < OPUS_MIN_FIDELITY, |
| 11421 | "a track that is no longer the mix scored {ruined:.4}" |
| 11422 | ); |
| 11423 | |
| 11424 | // ...and silence is silence: nothing to correlate is not a round trip |
| 11425 | // that failed. Short, because the floor is the same on either path. |
| 11426 | let quiet = vec![0f32; OPUS_RATE as usize * 2 * 2]; |
| 11427 | let (packets, pre_skip) = encode_opus(&quiet, 96, 2) |
| 11428 | .expect("the encoder opens") |
| 11429 | .expect("silence is written as Opus, not sent to AAC"); |
| 11430 | let fidelity = opus_fidelity(&packets, &quiet, usize::from(pre_skip), 2); |
| 11431 | assert!( |
| 11432 | fidelity >= OPUS_MIN_FIDELITY, |
| 11433 | "a silent track scored {fidelity:.4} and would fall back to AAC" |
| 11434 | ); |
| 11435 | } |
| 11436 | |
| 11437 | /// The one rule that keeps a picture from being converted twice: a frame the |
| 11438 | /// tone map has already brought to BT.709 is never handed the 2020 matrix as |
| 11439 | /// well, on either canvas -- and everything else about the remap is |
| 11440 | /// unchanged by the tone map existing. |
| 11441 | #[test] |
| 11442 | fn a_tone_mapped_span_is_never_matrix_remapped_too() { |
| 11443 | let hdr = ColorDescription { |
| 11444 | matrix: Matrix::Bt2020Ncl, |
| 11445 | transfer: Transfer::Pq, |
| 11446 | full_range: false, |
| 11447 | }; |
| 11448 | let sdr = ColorDescription::default(); // BT.601 |
| 11449 | // The (from, to) pair of a remap, which is all these cases are about. |
| 11450 | let pair = |remap: Option<Remap>| remap.map(|r| (r.from, r.to)); |
| 11451 | for out in [Matrix::Bt709, Matrix::Bt601] { |
| 11452 | let toned = pair(remap_into(Some(hdr), true, out)); |
| 11453 | assert!( |
| 11454 | toned.is_none_or(|(from, _)| from == Matrix::Bt709), |
| 11455 | "tone-mapped onto a {out:?} canvas asked for {toned:?}" |
| 11456 | ); |
| 11457 | // Untouched by any of this: the 2020 clip that was *not* tone-mapped |
| 11458 | // (an unreachable state today, and still the matrix answer), the |
| 11459 | // ordinary 601-on-709 reconcile, and a gap. |
| 11460 | assert_eq!( |
| 11461 | pair(remap_into(Some(hdr), false, out)), |
| 11462 | (out != Matrix::Bt2020Ncl).then_some((Matrix::Bt2020Ncl, out)) |
| 11463 | ); |
| 11464 | assert_eq!( |
| 11465 | pair(remap_into(Some(sdr), false, out)), |
| 11466 | (out != Matrix::Bt601).then_some((Matrix::Bt601, out)) |
| 11467 | ); |
| 11468 | assert_eq!(remap_into(None, false, out), None); |
| 11469 | } |
| 11470 | assert_eq!( |
| 11471 | pair(remap_into(Some(hdr), true, Matrix::Bt601)), |
| 11472 | Some((Matrix::Bt709, Matrix::Bt601)), |
| 11473 | "a tone-mapped clip below 720 lines still takes its 709 -> 601 step" |
| 11474 | ); |
| 11475 | } |
| 11476 | |
| 11477 | /// A full-range source is scaled into the limited span before it is matrix |
| 11478 | /// converted, and only an untouched one: a tone-mapped picture is already |
| 11479 | /// limited, and a limited source has nothing to scale. |
| 11480 | #[test] |
| 11481 | fn a_full_range_source_is_limited_before_it_is_remapped() { |
| 11482 | let full = ColorDescription { |
| 11483 | matrix: Matrix::Bt709, |
| 11484 | transfer: Transfer::Sdr, |
| 11485 | full_range: true, |
| 11486 | }; |
| 11487 | let limited = ColorDescription { |
| 11488 | full_range: false, |
| 11489 | ..full |
| 11490 | }; |
| 11491 | assert_eq!( |
| 11492 | remap_into(Some(full), false, Matrix::Bt709), |
| 11493 | Some(Remap { |
| 11494 | from: Matrix::Bt709, |
| 11495 | to: Matrix::Bt709, |
| 11496 | limit: true, |
| 11497 | }), |
| 11498 | "same matrix, but the range still has to come down" |
| 11499 | ); |
| 11500 | assert_eq!(remap_into(Some(limited), false, Matrix::Bt709), None); |
| 11501 | assert_eq!(remap_into(Some(full), true, Matrix::Bt709), None); |
| 11502 | } |
| 11503 | |
| 11504 | /// The picture as [`place_picture`] hands it to the encoder: a full-range |
| 11505 | /// source on a canvas of its own size, so the placement is the identity and |
| 11506 | /// what comes out is exactly the range change. |
| 11507 | #[test] |
| 11508 | fn a_full_range_picture_is_placed_as_limited_codes() { |
| 11509 | let (w, h) = (4u32, 2u32); |
| 11510 | let y = [0u8, 255, 130, 130, 0, 255, 130, 130]; |
| 11511 | let (u, v) = ([0u8, 255], [255u8, 0]); |
| 11512 | let mut canvas = Composer::new(w, h, crate::scale::FitPolicy::default()); |
| 11513 | let (mut turned, mut stretched, mut graded, mut transformed) = ( |
| 11514 | (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()), |
| 11515 | (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()), |
| 11516 | (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()), |
| 11517 | (Vec::<u8>::new(), Vec::<u8>::new(), Vec::<u8>::new()), |
| 11518 | ); |
| 11519 | let remap = Some(Remap { |
| 11520 | from: Matrix::Bt709, |
| 11521 | to: Matrix::Bt709, |
| 11522 | limit: true, |
| 11523 | }); |
| 11524 | let (py, pu, pv, _, _) = place_picture( |
| 11525 | &y, |
| 11526 | &u, |
| 11527 | &v, |
| 11528 | w, |
| 11529 | h, |
| 11530 | Rotation::default(), |
| 11531 | crate::demux::PixelAspect::SQUARE, |
| 11532 | None, |
| 11533 | TransformParams::default(), |
| 11534 | remap, |
| 11535 | None, |
| 11536 | &mut turned, |
| 11537 | &mut stretched, |
| 11538 | &mut graded, |
| 11539 | &mut transformed, |
| 11540 | &mut canvas, |
| 11541 | ); |
| 11542 | assert_eq!(py, [16, 235, 128, 128, 16, 235, 128, 128]); |
| 11543 | assert_eq!(pu, [16, 240]); |
| 11544 | assert_eq!(pv, [240, 16]); |
| 11545 | } |
| 11546 | |
| 11547 | /// A track of three cues, in whichever clock `track` says: `Some(n)` is a |
| 11548 | /// track of the media file, `None` a `.srt` beside it. |
| 11549 | fn subtitles(path: &str, track: Option<u64>) -> SubtitleTrack { |
| 11550 | SubtitleTrack { |
| 11551 | path: path.into(), |
| 11552 | track, |
| 11553 | language: "eng".into(), |
| 11554 | name: String::new(), |
| 11555 | label: "eng".into(), |
| 11556 | bitmap: false, |
| 11557 | cues: vec![ |
| 11558 | Cue { |
| 11559 | start_us: 500_000, |
| 11560 | end_us: 1_500_000, |
| 11561 | text: "first".into(), |
| 11562 | image: None, |
| 11563 | words: Vec::new(), |
| 11564 | karaoke: Vec::new(), |
| 11565 | }, |
| 11566 | Cue { |
| 11567 | start_us: 2_000_000, |
| 11568 | end_us: 3_250_000, |
| 11569 | text: "second".into(), |
| 11570 | image: None, |
| 11571 | words: Vec::new(), |
| 11572 | karaoke: Vec::new(), |
| 11573 | }, |
| 11574 | Cue { |
| 11575 | start_us: 4_000_000, |
| 11576 | end_us: 4_750_000, |
| 11577 | text: "third".into(), |
| 11578 | image: None, |
| 11579 | words: Vec::new(), |
| 11580 | karaoke: Vec::new(), |
| 11581 | }, |
| 11582 | ], |
| 11583 | refused: None, |
| 11584 | } |
| 11585 | } |
| 11586 | |
| 11587 | /// A standalone subtitle file is timed against the timeline itself -- there |
| 11588 | /// is no clip to hang it on -- so a cut moves the pictures and not it. What |
| 11589 | /// it does get is the exported length: a cue past the end of the file would |
| 11590 | /// otherwise be a block after the last picture. |
| 11591 | /// |
| 11592 | /// The pair of this, the embedded clock, is measured against a real exported |
| 11593 | /// file in `tests/export_subs.rs`; both live in one function and this is the |
| 11594 | /// half that needs no encoder. |
| 11595 | #[test] |
| 11596 | fn a_subtitle_file_beside_the_media_keeps_the_timelines_own_clock() { |
| 11597 | // 5 seconds at 30, with `[0.5s, 2.5s)` cut out of it: 3 seconds left. |
| 11598 | let mut project = Project::single("/nonexistent/film.mp4", 150); |
| 11599 | let track = subtitles("/nonexistent/film.srt", None); |
| 11600 | assert!(project.ripple_delete(15, 60)); |
| 11601 | assert_eq!(project.timeline_frames(), 90); |
| 11602 | let cues = timeline_cues(&project, &track, 30.0); |
| 11603 | assert_eq!( |
| 11604 | cues, |
| 11605 | vec![ |
| 11606 | Cue { |
| 11607 | start_us: 500_000, |
| 11608 | end_us: 1_500_000, |
| 11609 | text: "first".into(), |
| 11610 | image: None, |
| 11611 | words: Vec::new(), |
| 11612 | karaoke: Vec::new(), |
| 11613 | }, |
| 11614 | // Clipped to the three seconds the export writes... |
| 11615 | Cue { |
| 11616 | start_us: 2_000_000, |
| 11617 | end_us: 3_000_000, |
| 11618 | text: "second".into(), |
| 11619 | image: None, |
| 11620 | words: Vec::new(), |
| 11621 | karaoke: Vec::new(), |
| 11622 | }, |
| 11623 | // ...and the one wholly past the end is not written at all. |
| 11624 | ] |
| 11625 | ); |
| 11626 | // A track *of a file* the project no longer plays has no span to be |
| 11627 | // carried through either, so it falls back to the same clock rather |
| 11628 | // than exporting nothing. |
| 11629 | let orphan = subtitles("/nonexistent/other.mkv", Some(2)); |
| 11630 | assert_eq!(timeline_cues(&project, &orphan, 30.0).len(), 2); |
| 11631 | } |
| 11632 | |
| 11633 | /// The embedded clock, without an encoder in it: the cut moves the cues with |
| 11634 | /// the pictures, and a cue nothing clipped keeps its own microseconds. |
| 11635 | #[test] |
| 11636 | fn a_track_of_the_media_is_carried_through_the_cut() { |
| 11637 | let mut project = Project::single("/nonexistent/film.mkv", 150); |
| 11638 | let track = subtitles("/nonexistent/film.mkv", Some(2)); |
| 11639 | assert!(project.ripple_delete(15, 60), "cut 0.5s..2.5s out"); |
| 11640 | let cues = timeline_cues(&project, &track, 30.0); |
| 11641 | assert_eq!( |
| 11642 | cues, |
| 11643 | vec![ |
| 11644 | // The first cue was wholly inside the cut. The second straddled |
| 11645 | // its far edge and kept the 0.75s that is still there... |
| 11646 | Cue { |
| 11647 | start_us: 500_000, |
| 11648 | end_us: 1_250_000, |
| 11649 | text: "second".into(), |
| 11650 | image: None, |
| 11651 | words: Vec::new(), |
| 11652 | karaoke: Vec::new(), |
| 11653 | }, |
| 11654 | // ...and the third simply moves back the two seconds that went. |
| 11655 | Cue { |
| 11656 | start_us: 2_000_000, |
| 11657 | end_us: 2_750_000, |
| 11658 | text: "third".into(), |
| 11659 | image: None, |
| 11660 | words: Vec::new(), |
| 11661 | karaoke: Vec::new(), |
| 11662 | }, |
| 11663 | ] |
| 11664 | ); |
| 11665 | } |
| 11666 | |
| 11667 | #[test] |
| 11668 | fn export_spans_clips_to_the_marked_range_keeping_absolute_start() { |
| 11669 | let project = Project::single("/nonexistent/film.mkv", 150); |
| 11670 | // The whole timeline, unmarked: one span, the source's own length. |
| 11671 | let whole = export_spans(&project, None); |
| 11672 | assert_eq!(whole.len(), 1); |
| 11673 | assert_eq!((whole[0].start, whole[0].len), (0, 150)); |
| 11674 | // A range wholly inside the span: `start` stays the timeline's own |
| 11675 | // coordinate ([`composite_color_at`] needs that), and the length is |
| 11676 | // exactly what the mark asked for. |
| 11677 | let clipped = export_spans(&project, Some((30, 100))); |
| 11678 | assert_eq!(clipped.len(), 1); |
| 11679 | assert_eq!((clipped[0].start, clipped[0].len), (30, 70)); |
| 11680 | // A range past the end of the media clamps to it rather than reading |
| 11681 | // short on the wrong side. |
| 11682 | let past_end = export_spans(&project, Some((100, 500))); |
| 11683 | assert_eq!((past_end[0].start, past_end[0].len), (100, 50)); |
| 11684 | } |
| 11685 | |
| 11686 | #[test] |
| 11687 | fn bitrate_clamps_at_both_ends() { |
| 11688 | let meta = |width, height, frame_rate| VideoMeta { |
| 11689 | width, |
| 11690 | height, |
| 11691 | frame_rate, |
| 11692 | frame_count: 1, |
| 11693 | codec: crate::demux::Codec::H264, |
| 11694 | color: Default::default(), |
| 11695 | matrix_assumed: false, |
| 11696 | rotation: Rotation::None, |
| 11697 | // Square pixels, coded where they are declared: a meta no container |
| 11698 | // wrote, so nothing was read to disagree with it. |
| 11699 | coded_width: width, |
| 11700 | coded_height: height, |
| 11701 | pixel_aspect: crate::demux::PixelAspect::SQUARE, |
| 11702 | }; |
| 11703 | // 1280 * 720 * 30 * 0.1 |
| 11704 | assert_eq!(bitrate_for(&meta(1280, 720, 30.0)), 2_764_800); |
| 11705 | assert_eq!(bitrate_for(&meta(320, 240, 30.0)), 230_400, "tiny"); |
| 11706 | assert_eq!( |
| 11707 | bitrate_for(&meta(160, 120, 15.0)), |
| 11708 | MIN_BITRATE, |
| 11709 | "tinier floors" |
| 11710 | ); |
| 11711 | assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge"); |
| 11712 | // A rate somebody typed goes through untouched to its own ceiling, which |
| 11713 | // is above where the derived one stops: the card offers 50 Mbps, and a |
| 11714 | // second clamp here would write a file at a bitrate nobody picked. |
| 11715 | let asked = |bps| { |
| 11716 | bitrate_of( |
| 11717 | &meta(1920, 1080, 30.0), |
| 11718 | &ExportSettings { |
| 11719 | bitrate: Some(bps), |
| 11720 | ..Default::default() |
| 11721 | }, |
| 11722 | ) |
| 11723 | }; |
| 11724 | assert_eq!(asked(50_000_000), 50_000_000, "the card's ceiling travels"); |
| 11725 | assert_eq!(asked(21_000_000), 21_000_000, "past the derived range"); |
| 11726 | assert_eq!(asked(600_000), 600_000, "a sub-Mbps ask travels"); |
| 11727 | assert_eq!(asked(999_000_000), MAX_EXPLICIT_BITRATE, "still bounded"); |
| 11728 | assert_eq!(asked(1), MIN_BITRATE, "and floored"); |
| 11729 | } |
| 11730 | |
| 11731 | /// A clip's fade takes the copy path away, exactly as an equalizer does: |
| 11732 | /// a copied AAC packet cannot carry gain math nobody put in the file. The |
| 11733 | /// bug this guards is [`forces_encode`] gating on `equalized`/`mastered` |
| 11734 | /// but never checking a clip's own `fade_in`/`fade_out` at all -- the |
| 11735 | /// default Web MP4 export then labelled and took the "AAC copy" path for |
| 11736 | /// a project whose picture showed a fade, and the fade never reached the |
| 11737 | /// file. |
| 11738 | #[test] |
| 11739 | fn a_fade_forces_the_audio_to_be_re_encoded() { |
| 11740 | let mut project = Project::single("/nonexistent/film.mp4", 90); |
| 11741 | assert!(!forces_encode(&project, false), "flat, so a copy is fine"); |
| 11742 | assert!(project.set_fade_in( |
| 11743 | crate::project::Lane::new(crate::project::LaneKind::Audio, 0), |
| 11744 | 0, |
| 11745 | 15 |
| 11746 | )); |
| 11747 | assert!( |
| 11748 | forces_encode(&project, false), |
| 11749 | "a fade-in on the only clip must force a re-encode" |
| 11750 | ); |
| 11751 | } |
| 11752 | |
| 11753 | fn meta(width: u32, height: u32) -> VideoMeta { |
| 11754 | VideoMeta { |
| 11755 | width, |
| 11756 | height, |
| 11757 | frame_rate: 30.0, |
| 11758 | frame_count: 1, |
| 11759 | codec: crate::demux::Codec::H264, |
| 11760 | color: Default::default(), |
| 11761 | matrix_assumed: false, |
| 11762 | rotation: Rotation::None, |
| 11763 | // Square pixels, coded where they are declared: a meta no |
| 11764 | // container wrote, so nothing was read to disagree with it. |
| 11765 | coded_width: width, |
| 11766 | coded_height: height, |
| 11767 | pixel_aspect: crate::demux::PixelAspect::SQUARE, |
| 11768 | } |
| 11769 | } |
| 11770 | |
| 11771 | /// The bitrate row a user picked, read as the quality tier it is: a higher |
| 11772 | /// row is a lower QP, the band is honoured at both ends, and the same |
| 11773 | /// picture at the same rate gets the same number whatever its size (the |
| 11774 | /// mapping is bits per *pixel*, which is what makes 720p and 1080p one |
| 11775 | /// table). |
| 11776 | #[test] |
| 11777 | fn the_quality_rows_map_onto_quantisers_that_only_go_one_way() { |
| 11778 | let at = |width, height, mbps: Option<u64>| { |
| 11779 | hevc_qp( |
| 11780 | &meta(width, height), |
| 11781 | &ExportSettings { |
| 11782 | bitrate: mbps.map(|m| m * 1_000_000), |
| 11783 | ..Default::default() |
| 11784 | }, |
| 11785 | ) |
| 11786 | }; |
| 11787 | // 20 Mbps at 1080p30 is 0.32 bits a pixel against the 0.6 measured at |
| 11788 | // QP 27, which is just over half: five QP up, and QP is not an |
| 11789 | // arithmetic scale, so this is the number the formula gives. |
| 11790 | assert_eq!(at(1920, 1080, Some(20)), 32); |
| 11791 | // Every step down the card is a step up in QP, never sideways. |
| 11792 | let rows: Vec<i32> = [20, 12, 8, 4, 2, 1] |
| 11793 | .into_iter() |
| 11794 | .map(|mbps| at(1920, 1080, Some(mbps))) |
| 11795 | .collect(); |
| 11796 | assert!( |
| 11797 | rows.windows(2).all(|w| w[0] <= w[1]), |
| 11798 | "a lower bitrate row must never code at a lower QP: {rows:?}" |
| 11799 | ); |
| 11800 | assert_eq!(*rows.last().unwrap(), HEVC_QP_MAX, "the floor is clamped"); |
| 11801 | // ...and the top of the range is the clamp, not an unbounded number: 20 |
| 11802 | // Mbps at 320x240 is 8.7 bits a pixel, which no picture needs. |
| 11803 | assert_eq!(at(320, 240, Some(20)), HEVC_QP_MIN); |
| 11804 | // The same bits per pixel is the same quantiser at any size: 1080p at |
| 11805 | // 20 Mbps and 720p at 8.9 Mbps are one picture quality. |
| 11806 | assert_eq!(at(1920, 1080, Some(20)), at(1280, 720, Some(9))); |
| 11807 | // The automatic bitrate is 0.1 bpp at every size, so it is one QP |
| 11808 | // everywhere -- the honest end of "intra-only, large files": the file |
| 11809 | // will be bigger than the row says, and the row buys quality. |
| 11810 | assert_eq!(at(1920, 1080, None), at(1280, 720, None)); |
| 11811 | } |
| 11812 | |
| 11813 | /// An odd picture cannot be cropped back to itself in 4:2:0 -- the |
| 11814 | /// conformance window is stated in chroma samples -- so it is refused by |
| 11815 | /// name rather than written a column wider than the timeline. |
| 11816 | #[test] |
| 11817 | fn an_odd_picture_is_refused_an_hevc_export_by_name() { |
| 11818 | let settings = ExportSettings { |
| 11819 | format: Format::Hevc, |
| 11820 | ..Default::default() |
| 11821 | }; |
| 11822 | let refused = Enc::open(&meta(1919, 1080), &settings, false, ColorDescription::default()) |
| 11823 | .err() |
| 11824 | .expect("an odd width has no chroma plane") |
| 11825 | .to_string(); |
| 11826 | assert!(refused.contains("1919x1080"), "{refused}"); |
| 11827 | assert!(refused.contains("even"), "{refused}"); |
| 11828 | // ...and the even one it neighbours opens. |
| 11829 | assert!(Enc::open(&meta(1920, 1080), &settings, false, ColorDescription::default()).is_ok()); |
| 11830 | } |
| 11831 | |
| 11832 | /// H.264 codes 16x16 macroblocks and ec-h264's floor is the macroblock |
| 11833 | /// itself -- the old encoder took any positive even size -- so a |
| 11834 | /// sub-macroblock picture is refused by name, like every other seat |
| 11835 | /// refusal, rather than surfaced from inside a running export. |
| 11836 | #[test] |
| 11837 | fn a_sub_macroblock_picture_is_refused_an_h264_export_by_name() { |
| 11838 | let settings = ExportSettings { |
| 11839 | format: Format::Mp4, |
| 11840 | seat: EncoderSeat::Software, |
| 11841 | ..Default::default() |
| 11842 | }; |
| 11843 | let refused = Enc::open(&meta(8, 8), &settings, false, ColorDescription::default()) |
| 11844 | .err() |
| 11845 | .expect("8x8 is smaller than one macroblock") |
| 11846 | .to_string(); |
| 11847 | assert!(refused.contains("8x8"), "{refused}"); |
| 11848 | assert!(refused.contains("16x16"), "{refused}"); |
| 11849 | } |
| 11850 | |
| 11851 | /// Weights ramp from just above 0 to just below 1 and never touch either |
| 11852 | /// end -- the frame *after* the window is where a viewer would see plain |
| 11853 | /// B, and the window itself never quite repeats a hard cut's own instant. |
| 11854 | #[test] |
| 11855 | fn dissolve_weight_ramps_strictly_between_zero_and_one() { |
| 11856 | assert_eq!( |
| 11857 | dissolve_weight(0, 1), |
| 11858 | 0.5, |
| 11859 | "a one-frame window is the midpoint" |
| 11860 | ); |
| 11861 | assert_eq!(dissolve_weight(0, 4), 0.2); |
| 11862 | assert_eq!(dissolve_weight(1, 4), 0.4); |
| 11863 | assert_eq!(dissolve_weight(2, 4), 0.6); |
| 11864 | assert_eq!(dissolve_weight(3, 4), 0.8); |
| 11865 | } |
| 11866 | |
| 11867 | /// [`dissolve_window`] reads [`crate::project::Clip::transition_out`] back |
| 11868 | /// only once adjacency is re-checked at render time: two clips a split |
| 11869 | /// just made, still touching, still name B by its own source and its own |
| 11870 | /// timeline start. |
| 11871 | #[test] |
| 11872 | fn dissolve_window_names_bs_source_in_frame_window_and_start() { |
| 11873 | use crate::project::{Lane, Project}; |
| 11874 | let mut p = Project::single("/nonexistent/film.mkv", 20); |
| 11875 | assert!(p.split(15)); |
| 11876 | assert!(p.set_transition_out(Lane::V1, 0, 5)); |
| 11877 | let spans = export_spans(&p, None); |
| 11878 | let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span"); |
| 11879 | assert_eq!( |
| 11880 | dissolve_window(&p, a_span), |
| 11881 | Some((0, 15, 5, 15)), |
| 11882 | "b's source, b's in_frame, the window, b's timeline start" |
| 11883 | ); |
| 11884 | } |
| 11885 | |
| 11886 | /// A `transition_out` set while two clips touched, then made stale by a |
| 11887 | /// trim that opens a gap between them: the number is still in storage, |
| 11888 | /// [`dissolve_window`] reads `None` from it, and the span renders as the |
| 11889 | /// hard cut two clips that no longer touch actually are. |
| 11890 | #[test] |
| 11891 | fn a_stale_transition_out_after_a_trim_renders_as_a_hard_cut() { |
| 11892 | use crate::project::{Edge, Lane, Project}; |
| 11893 | let mut p = Project::single("/nonexistent/film.mkv", 20); |
| 11894 | assert!(p.split(15)); |
| 11895 | assert!(p.set_transition_out(Lane::V1, 0, 5)); |
| 11896 | assert!(p.trim(Lane::V1, 1, Edge::Start, 18, &[100]), "opens a gap"); |
| 11897 | let spans = export_spans(&p, None); |
| 11898 | let a_span = spans.iter().find(|s| s.start == 0).expect("clip A's span"); |
| 11899 | assert!( |
| 11900 | dissolve_window(&p, a_span).is_none(), |
| 11901 | "b no longer abuts a; hard cut" |
| 11902 | ); |
| 11903 | } |
| 11904 | } |
| 11905 | |
| 11906 | #[cfg(test)] |
| 11907 | mod audio_language_tests { |
| 11908 | use super::*; |
| 11909 | |
| 11910 | fn asset(name: &str) -> PathBuf { |
| 11911 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 11912 | } |
| 11913 | |
| 11914 | /// `test_multilang.mp4` has an `und` track 0 and a `fra` track 1. |
| 11915 | #[test] |
| 11916 | fn a_stream_states_its_language_or_none() { |
| 11917 | let path = asset("test_multilang.mp4"); |
| 11918 | assert_eq!(stream_language(&path, 0), None, "und is no language"); |
| 11919 | assert_eq!(stream_language(&path, 1).as_deref(), Some("fra")); |
| 11920 | assert_eq!(stream_language(&path, 9), None, "a track the file does not have"); |
| 11921 | } |
| 11922 | |
| 11923 | /// The tag is the one language every clip shares; any disagreement or any `und` leaves it out. |
| 11924 | #[test] |
| 11925 | fn the_mix_takes_a_language_only_when_every_clip_shares_it() { |
| 11926 | let s = |l: &str| Some(l.to_string()); |
| 11927 | assert_eq!(shared_language([s("fra"), s("fra")]), s("fra")); |
| 11928 | assert_eq!(shared_language([s("fra"), s("eng")]), None, "two languages"); |
| 11929 | assert_eq!(shared_language([s("fra"), None]), None, "one clip states none"); |
| 11930 | assert_eq!(shared_language(Vec::<Option<String>>::new()), None, "no sound at all"); |
| 11931 | } |
| 11932 | |
| 11933 | /// The clips on the audio lanes name the streams the sound comes from: a `und` clip beside |
| 11934 | /// a `fra` one leaves the tag out. |
| 11935 | #[test] |
| 11936 | fn a_mix_of_und_and_french_clips_has_no_tag() { |
| 11937 | let path = asset("test_multilang.mp4"); |
| 11938 | let mut p = Project::single(&path, 30); |
| 11939 | assert_eq!(audio_language(&p), None, "the first track is und"); |
| 11940 | let fra = p.import(&path, 1); |
| 11941 | assert!(p.append_clip(fra, 30)); |
| 11942 | assert_eq!(audio_language(&p), None, "the und clip is still on A1"); |
| 11943 | } |
| 11944 | } |
| 11945 | |
| 11946 | #[cfg(test)] |
| 11947 | mod burn_stack_tests { |
| 11948 | #[test] |
| 11949 | fn two_overlapping_cues_are_both_drawn_stacked() { |
| 11950 | use super::{Burn, Cue, cues_on_screen}; |
| 11951 | use crate::text::TextStyle; |
| 11952 | let cue = |text: &str| Cue { |
| 11953 | start_us: 0, |
| 11954 | end_us: 5_000_000, |
| 11955 | text: text.to_string(), |
| 11956 | image: None, |
| 11957 | words: Vec::new(), |
| 11958 | karaoke: Vec::new(), |
| 11959 | }; |
| 11960 | let (w, h) = (640u32, 360u32); |
| 11961 | let paint = |cues: Vec<Cue>| { |
| 11962 | let mut burn = Burn { |
| 11963 | cues, |
| 11964 | style: TextStyle { |
| 11965 | boxed: false, |
| 11966 | ..TextStyle::default() |
| 11967 | }, |
| 11968 | fps: 30.0, |
| 11969 | full_range: false, |
| 11970 | last: None, |
| 11971 | titles: Vec::new(), |
| 11972 | title_last: Vec::new(), |
| 11973 | native: None, |
| 11974 | }; |
| 11975 | let y = vec![40u8; (w * h) as usize]; |
| 11976 | let u = vec![128u8; (w / 2 * (h / 2)) as usize]; |
| 11977 | let v = u.clone(); |
| 11978 | burn.paint(30, w, h, (&y, &u, &v)) |
| 11979 | .expect("a caption is drawn") |
| 11980 | }; |
| 11981 | // The rows that carry a lit (white) pixel in the luma plane. |
| 11982 | let lit_rows = |planes: &(Vec<u8>, Vec<u8>, Vec<u8>)| -> Vec<u32> { |
| 11983 | (0..h) |
| 11984 | .filter(|&r| { |
| 11985 | let row = &planes.0[(r * w) as usize..((r + 1) * w) as usize]; |
| 11986 | row.iter().any(|&l| l > 40) |
| 11987 | }) |
| 11988 | .collect() |
| 11989 | }; |
| 11990 | let cues = vec![cue("First cue"), cue("Second cue")]; |
| 11991 | assert_eq!(cues_on_screen(&cues, 30, 30.0), vec![0, 1], "both are on screen"); |
| 11992 | let one = lit_rows(&paint(vec![cue("First cue")])); |
| 11993 | let both = lit_rows(&paint(cues)); |
| 11994 | assert!( |
| 11995 | both.len() >= 2 * one.len() - 1, |
| 11996 | "second cue not drawn: {} lit rows against {} for the first alone", |
| 11997 | both.len(), |
| 11998 | one.len() |
| 11999 | ); |
| 12000 | // The first cue keeps its place on the bottom edge; the second stacks above. |
| 12001 | assert_eq!(both.last(), one.last(), "the first cue moved"); |
| 12002 | } |
| 12003 | } |
| 12004 | |
| 12005 | #[cfg(test)] |
| 12006 | mod chroma_420_tests { |
| 12007 | use super::*; |
| 12008 | |
| 12009 | fn asset(name: &str) -> PathBuf { |
| 12010 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 12011 | } |
| 12012 | |
| 12013 | /// The layout a chroma plane's sample count names, for each subsampling. |
| 12014 | #[test] |
| 12015 | fn a_chroma_count_names_its_layout() { |
| 12016 | assert_eq!(chroma_shape(64 * 64, 64, 64), Some((64, 64)), "4:4:4"); |
| 12017 | assert_eq!(chroma_shape(32 * 64, 64, 64), Some((32, 64)), "4:2:2"); |
| 12018 | assert_eq!(chroma_shape(32 * 32, 64, 64), Some((32, 32)), "4:2:0"); |
| 12019 | assert_eq!(chroma_shape(3 * 3, 5, 3), Some((3, 3)), "odd 4:4:4 keeps its width"); |
| 12020 | assert_eq!(chroma_shape(3 * 2, 5, 3), Some((3, 2)), "odd 4:2:2"); |
| 12021 | assert_eq!(chroma_shape(7, 5, 3), None, "no layout has seven samples"); |
| 12022 | } |
| 12023 | |
| 12024 | /// A 2x2 block of 4:4:4 chroma becomes its rounded mean. |
| 12025 | #[test] |
| 12026 | fn a_444_block_averages_to_its_rounded_mean() { |
| 12027 | let src: Vec<u16> = vec![1, 2, 3, 4]; |
| 12028 | assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![3], "(10 + 2) / 4"); |
| 12029 | let src: Vec<u16> = vec![0, 0, 0, 1]; |
| 12030 | assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![0], "a quarter rounds down"); |
| 12031 | let src: Vec<u16> = vec![0, 0, 1, 1]; |
| 12032 | assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![1], "a half rounds up"); |
| 12033 | } |
| 12034 | |
| 12035 | /// 4:2:2 has full height, so only the rows pair up. |
| 12036 | #[test] |
| 12037 | fn a_422_plane_pairs_rows_only() { |
| 12038 | // Two columns, four rows: rows (0,1) and (2,3) average, columns stay apart. |
| 12039 | let src: Vec<u8> = vec![10, 100, 20, 200, 30, 0, 40, 0]; |
| 12040 | assert_eq!(chroma_420(&src, 2, 4, 2, 2), vec![15, 150, 35, 0]); |
| 12041 | } |
| 12042 | |
| 12043 | /// An odd edge averages the samples there are, and 10-bit samples stay in 10 bits. |
| 12044 | #[test] |
| 12045 | fn an_odd_edge_and_ten_bit_samples_are_handled() { |
| 12046 | // 3x3 chroma down to 2x2: the last column and row are a single sample each, |
| 12047 | // so the corner is the 8 alone and the edge pairs are (2, 5) and (6, 7). |
| 12048 | let src: Vec<u16> = (0..9).collect(); |
| 12049 | assert_eq!(chroma_420(&src, 3, 3, 2, 2), vec![2, 4, 7, 8]); |
| 12050 | // A 10-bit mean is still a 10-bit value, not a truncated 8-bit one. |
| 12051 | let src: Vec<u16> = vec![1023, 1023, 1022, 1023]; |
| 12052 | assert_eq!(chroma_420(&src, 2, 2, 1, 1), vec![1023]); |
| 12053 | } |
| 12054 | |
| 12055 | /// The AV1 seat hands the composer 4:2:0 planes for every layout edith decodes |
| 12056 | /// (4:2:0, 4:2:2, 4:4:4 and gray), at the size a 4:2:0 picture would have. |
| 12057 | #[test] |
| 12058 | fn every_av1_fixture_arrives_as_420() { |
| 12059 | for name in ["test_av1_444.mp4", "test_av1_422.mp4", "test_av1_12bit.mp4"] { |
| 12060 | let mut pictures = Pictures::software(&asset(name), 0, false, Deinterlace::Frame).expect(name); |
| 12061 | let Ok(Some(Yuv::Pixels { u, v, width, height, .. })) = pictures.next(None) else { |
| 12062 | panic!("{name}: no picture"); |
| 12063 | }; |
| 12064 | let (cw, ch) = (width.div_ceil(2) as usize, height.div_ceil(2) as usize); |
| 12065 | assert_eq!((u.len(), v.len()), (cw * ch, cw * ch), "{name}: chroma is 4:2:0"); |
| 12066 | } |
| 12067 | for name in ["test_av1_gray.mp4", "test_av1_420.mp4"] { |
| 12068 | let mut pictures = Pictures::software(&asset(name), 0, false, Deinterlace::Frame).expect(name); |
| 12069 | let Ok(Some(Yuv::Pixels { y, u, v, width, height })) = pictures.next(None) else { |
| 12070 | panic!("{name}: no picture"); |
| 12071 | }; |
| 12072 | let (cw, ch) = (width.div_ceil(2) as usize, height.div_ceil(2) as usize); |
| 12073 | assert_eq!(y.len(), (width * height) as usize, "{name}: luma"); |
| 12074 | assert_eq!((u.len(), v.len()), (cw * ch, cw * ch), "{name}: chroma is 4:2:0"); |
| 12075 | if name.contains("gray") { |
| 12076 | assert!(u.iter().chain(&v).all(|&s| s == 128), "{name}: grey chroma is 128"); |
| 12077 | } |
| 12078 | } |
| 12079 | } |
| 12080 | } |
| 12081 | |
| 12082 | #[cfg(test)] |
| 12083 | mod planned_sound_tests { |
| 12084 | use super::*; |
| 12085 | |
| 12086 | fn asset(name: &str) -> PathBuf { |
| 12087 | Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets").join(name) |
| 12088 | } |
| 12089 | |
| 12090 | /// The sound [`planned_seats`] predicts for `timeline` in an mp4, with the |
| 12091 | /// picture's meta taken from `picture`. |
| 12092 | fn predicted_sound(timeline: &str, picture: &str) -> &'static str { |
| 12093 | let project = Project::single(asset(timeline), 30); |
| 12094 | let (meta, _) = Demuxer::open(&asset(picture)).expect("the picture's file opens"); |
| 12095 | let settings = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 12096 | planned_seats(&project, &meta, &settings).1 |
| 12097 | } |
| 12098 | |
| 12099 | /// A DTS track is decoded by `ec-dts`, so the export predicts an encode of its |
| 12100 | /// sound (as it does for an mp3), not the "can't be decoded" card. |
| 12101 | #[test] |
| 12102 | fn a_dts_source_is_predicted_as_an_encode() { |
| 12103 | assert_eq!( |
| 12104 | predicted_sound("test_dts.mkv", "test_dts.mkv"), |
| 12105 | "AAC · SW encode (ec-aac)" |
| 12106 | ); |
| 12107 | } |
| 12108 | |
| 12109 | /// An mp3 on the timeline has no sample table to copy from: the sound is |
| 12110 | /// decoded and encoded as AAC, not copied. |
| 12111 | #[test] |
| 12112 | fn a_standalone_mp3_source_is_predicted_as_an_encode() { |
| 12113 | assert_eq!( |
| 12114 | predicted_sound("test_tone.mp3", "test_av.mp4"), |
| 12115 | "AAC · SW encode (ec-aac)" |
| 12116 | ); |
| 12117 | } |
| 12118 | |
| 12119 | /// The untouched AAC of an mp4 is still the copy it was. |
| 12120 | #[test] |
| 12121 | fn an_untouched_aac_mp4_is_still_predicted_as_a_copy() { |
| 12122 | assert_eq!(predicted_sound("test_av.mp4", "test_av.mp4"), "AAC copy"); |
| 12123 | } |
| 12124 | |
| 12125 | /// The HDR meta and picture size of a fixture, as the export reads them. |
| 12126 | fn meta_of(name: &str) -> VideoMeta { |
| 12127 | Demuxer::open(&asset(name)).expect("the fixture opens").0 |
| 12128 | } |
| 12129 | |
| 12130 | /// A PQ source is tone-mapped to SDR in every picture export, and the plan says so. |
| 12131 | #[test] |
| 12132 | fn a_pq_source_is_predicted_as_tone_mapped() { |
| 12133 | let project = Project::single(asset("test_pq.mp4"), 30); |
| 12134 | let meta = meta_of("test_pq.mp4"); |
| 12135 | let settings = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 12136 | let expected = match ColorDescription::output_sized(meta.width, meta.height).matrix { |
| 12137 | Matrix::Bt601 => "HDR (PQ) source tone-mapped to SDR BT.601", |
| 12138 | _ => "HDR (PQ) source tone-mapped to SDR BT.709", |
| 12139 | }; |
| 12140 | assert_eq!(planned_tone(&project, &meta, &settings).as_deref(), Some(expected)); |
| 12141 | } |
| 12142 | |
| 12143 | /// The matrix the words name is the one the file is tagged with: a standard-definition |
| 12144 | /// canvas is BT.601 and an HD one BT.709, whatever the source's own size, and a |
| 12145 | /// `size` setting moves the canvas the rule is applied to. |
| 12146 | #[test] |
| 12147 | fn the_tone_map_names_the_matrix_of_the_size_it_is_written_at() { |
| 12148 | let project = Project::single(asset("test_pq.mp4"), 30); |
| 12149 | let mut hd = meta_of("test_pq.mp4"); |
| 12150 | hd.width = 1920; |
| 12151 | hd.height = 1080; |
| 12152 | let mut sd = hd; |
| 12153 | sd.width = 720; |
| 12154 | sd.height = 576; |
| 12155 | let mp4 = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 12156 | assert_eq!( |
| 12157 | planned_tone(&project, &hd, &mp4).as_deref(), |
| 12158 | Some("HDR (PQ) source tone-mapped to SDR BT.709") |
| 12159 | ); |
| 12160 | assert_eq!( |
| 12161 | planned_tone(&project, &sd, &mp4).as_deref(), |
| 12162 | Some("HDR (PQ) source tone-mapped to SDR BT.601"), |
| 12163 | "720x576 is SD, and is tagged BT.601" |
| 12164 | ); |
| 12165 | let small = ExportSettings { size: Some((640, 360)), ..mp4.clone() }; |
| 12166 | assert_eq!( |
| 12167 | planned_tone(&project, &hd, &small).as_deref(), |
| 12168 | Some("HDR (PQ) source tone-mapped to SDR BT.601"), |
| 12169 | "a 640x360 export is SD though the project is HD" |
| 12170 | ); |
| 12171 | let hd_again = ExportSettings { size: Some((1280, 720)), ..mp4.clone() }; |
| 12172 | assert_eq!( |
| 12173 | planned_tone(&project, &sd, &hd_again).as_deref(), |
| 12174 | Some("HDR (PQ) source tone-mapped to SDR BT.709"), |
| 12175 | "a 1280x720 export of an SD canvas is HD" |
| 12176 | ); |
| 12177 | } |
| 12178 | |
| 12179 | /// A preview that keeps its source's curve is not tone-mapped, and an SDR timeline or a |
| 12180 | /// sound-only format has nothing to say. |
| 12181 | #[test] |
| 12182 | fn only_a_tone_mapped_picture_is_predicted_as_one() { |
| 12183 | let pq = Project::single(asset("test_hdr_sei.mkv"), 30); |
| 12184 | let meta = meta_of("test_hdr_sei.mkv"); |
| 12185 | let keep = ExportSettings { |
| 12186 | format: Format::Mp4, |
| 12187 | keep_source_colour: true, |
| 12188 | ..Default::default() |
| 12189 | }; |
| 12190 | assert_eq!(planned_tone(&pq, &meta, &keep), None, "a preview keeps the curve"); |
| 12191 | let mp4 = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 12192 | assert!(planned_tone(&pq, &meta, &mp4).is_some(), "the mkv's PQ too"); |
| 12193 | let sdr = Project::single(asset("test_av.mp4"), 30); |
| 12194 | assert_eq!(planned_tone(&sdr, &meta, &mp4), None, "an SDR timeline"); |
| 12195 | let wav = ExportSettings { format: Format::Wav, ..Default::default() }; |
| 12196 | assert_eq!(planned_tone(&pq, &meta, &wav), None, "no picture to tone-map"); |
| 12197 | } |
| 12198 | |
| 12199 | /// A size setting draws the export at that size, coded size included, and leaves every |
| 12200 | /// other fact of the project's canvas as it is; no size is the project's canvas. |
| 12201 | #[test] |
| 12202 | fn a_size_setting_moves_the_canvas_and_only_the_canvas() { |
| 12203 | let meta = meta_of("test_av.mp4"); |
| 12204 | let none = ExportSettings::default(); |
| 12205 | assert_eq!(output_meta(&meta, &none), meta); |
| 12206 | let small = ExportSettings { size: Some((640, 360)), ..Default::default() }; |
| 12207 | let out = output_meta(&meta, &small); |
| 12208 | assert_eq!((out.width, out.height), (640, 360)); |
| 12209 | assert_eq!((out.coded_width, out.coded_height), (640, 360)); |
| 12210 | assert_eq!(out.frame_rate, meta.frame_rate); |
| 12211 | assert_eq!(out.frame_count, meta.frame_count); |
| 12212 | assert_eq!(out.pixel_aspect, meta.pixel_aspect); |
| 12213 | } |
| 12214 | |
| 12215 | /// An mkv export that is encoded names the codec its mix will get: Opus when the sources |
| 12216 | /// put it at 48 kHz mono or stereo, AAC otherwise. `test_av1.mkv` is 44.1 kHz stereo AAC, |
| 12217 | /// so its export is AAC, as its done line says; `test_seek_chirp.mkv` is 48 kHz mono Opus. |
| 12218 | #[test] |
| 12219 | fn a_matroska_export_names_the_codec_its_mix_will_get() { |
| 12220 | let settings = ExportSettings { format: Format::Av1, ..Default::default() }; |
| 12221 | let aac = Project::single(asset("test_av1.mkv"), 30); |
| 12222 | let meta = meta_of("test_av1.mkv"); |
| 12223 | let (_, sound) = planned_seats(&aac, &meta, &settings); |
| 12224 | assert_eq!(sound, "AAC · SW encode (ec-aac)"); |
| 12225 | let opus = Project::single(asset("test_seek_chirp.mkv"), 30); |
| 12226 | let meta = meta_of("test_seek_chirp.mkv"); |
| 12227 | let (_, sound) = planned_seats(&opus, &meta, &settings); |
| 12228 | assert_eq!(sound, "Opus · SW encode (ec-opus)"); |
| 12229 | } |
| 12230 | } |
| 12231 | |
| 12232 | #[cfg(test)] |
| 12233 | mod vp9_444_tests { |
| 12234 | use super::*; |
| 12235 | |
| 12236 | #[test] |
| 12237 | fn a_422_or_444_source_names_its_reduction_on_a_video_export() { |
| 12238 | let mut settings = ExportSettings { format: Format::Mp4, ..Default::default() }; |
| 12239 | assert_eq!( |
| 12240 | chroma_reduction_words(Codec::Vp9, Chroma::C444, &settings).as_deref(), |
| 12241 | Some("VP9 4:4:4 source: chroma reduced to 4:2:0 for export"), |
| 12242 | ); |
| 12243 | assert_eq!( |
| 12244 | chroma_reduction_words(Codec::Vp9, Chroma::C422, &settings).as_deref(), |
| 12245 | Some("VP9 4:2:2 source: chroma reduced to 4:2:0 for export"), |
| 12246 | ); |
| 12247 | assert_eq!( |
| 12248 | chroma_reduction_words(Codec::H264, Chroma::C444, &settings).as_deref(), |
| 12249 | Some("H.264 4:4:4 source: chroma reduced to 4:2:0 for export"), |
| 12250 | ); |
| 12251 | assert!(chroma_reduction_words(Codec::Vp9, Chroma::C420, &settings).is_none()); |
| 12252 | assert!(chroma_reduction_words(Codec::Vp9, Chroma::Gray, &settings).is_none()); |
| 12253 | for format in [Format::Wav, Format::Flac, Format::Mp3, Format::Ogg, Format::M4a, Format::Opus] { |
| 12254 | settings.format = format; |
| 12255 | assert!( |
| 12256 | chroma_reduction_words(Codec::Vp9, Chroma::C444, &settings).is_none(), |
| 12257 | "{format:?} has no picture to reduce", |
| 12258 | ); |
| 12259 | } |
| 12260 | } |
| 12261 | |
| 12262 | /// A VP9 profile 1 4:4:4 file is never offered to the GPU on an export: the decode |
| 12263 | /// door's gate refuses it before the plugin is asked, so the plugin's refusal never |
| 12264 | /// reaches stderr. Stderr is not read in-process; the seam is the plugin's attempt count. |
| 12265 | #[test] |
| 12266 | fn a_vp9_444_export_never_offers_the_file_to_the_gpu() { |
| 12267 | let path = std::env::temp_dir().join(format!("edith-vp9-444-{}.webm", std::process::id())); |
| 12268 | let generated = std::process::Command::new("ffmpeg") |
| 12269 | .args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=64x64:rate=5:duration=1"]) |
| 12270 | .args(["-c:v", "libvpx-vp9", "-pix_fmt", "yuv444p", "-f", "webm"]) |
| 12271 | .arg(&path) |
| 12272 | .status() |
| 12273 | .map(|status| status.success() && path.exists()) |
| 12274 | .unwrap_or(false); |
| 12275 | if !generated { |
| 12276 | eprintln!("no ffmpeg with libvpx-vp9: the 4:4:4 fixture cannot be generated, skipping"); |
| 12277 | return; |
| 12278 | } |
| 12279 | let chroma = Demuxer::open(&path).ok().and_then(|(_, demuxer)| demuxer.chroma()); |
| 12280 | assert_eq!(chroma, Some(Chroma::C444), "the fixture is a 4:4:4 stream"); |
| 12281 | let (tx, rx) = sync_channel(64); |
| 12282 | let before = crate::hw::OPEN_ATTEMPTS.with(|n| n.get()); |
| 12283 | let _ = decode_stream(&path, 0, None, &tx, None, false, Deinterlace::Frame); |
| 12284 | let after = crate::hw::OPEN_ATTEMPTS.with(|n| n.get()); |
| 12285 | drop(rx); |
| 12286 | let _ = std::fs::remove_file(&path); |
| 12287 | assert_eq!(after, before, "the GPU was asked for a decoder for a 4:4:4 VP9 file"); |
| 12288 | } |
| 12289 | } |