forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

decode.rs5203 lines, 213.0 KiBHistoryRawDownload
1//! Background decode worker. Frames leave over a bounded channel so the caller's
2//! thread (the UI thread) never blocks on decode and memory stays capped.
3
4use std::path::{Path, PathBuf};
5use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
6use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};
7use std::sync::{Arc, Mutex};
8use std::thread;
9
10use ec_av1::encode::Picture as Av1Picture;
11use ec_av1::stream::decode_stream_with;
12use ec_core::frame::VideoFrame;
13use ec_core::registry::Decoder as _;
14use ec_core::registry::{CodecId, CodecParameters};
15use ec_core::{Error as Av1Error, Packet, TimeBase};
16use ec_h264::H264Decoder;
17
18use crate::color::ColorParams;
19use crate::colorspace::{Chroma, ColorDescription, Matrix, Transfer};
20use crate::convert::{i420_to_bgra, i420_to_bgra_with};
21use crate::demux::{Codec, Demuxer, PixelAspect, Rotation, VideoMeta};
22use crate::hw::HwSession;
23use crate::project::Speed;
24use crate::scale::Composer;
25use crate::tonemap::{self, ToneMapper};
26use crate::transform::TransformParams;
27
28mod dnxhd;
29mod dv;
30mod hevc;
31pub(crate) mod intra;
32mod mjpeg;
33mod raw;
34mod prores;
35use hevc::run_hevc;
36mod mpeg2;
37use mpeg2::run_mpeg2;
38mod mpeg4;
39use mpeg4::run_mpeg4;
40mod vp8;
41use vp8::run_vp8;
42mod vp9;
43use vp9::run_vp9;
44
45/// One software picture as the tightly packed 8-bit I420 every converter takes:
46/// the buffers a pulled decoder fills, reused for every picture of a stream.
47#[derive(Default)]
48pub(crate) struct I420 {
49 pub(crate) width: u32,
50 pub(crate) height: u32,
51 pub(crate) y: Vec<u8>,
52 pub(crate) u: Vec<u8>,
53 pub(crate) v: Vec<u8>,
54}
55
56/// The 10-bit planes of a picture an export's 10-bit seat encodes: the same
57/// shape as [`I420`], at 16 bits a sample and 10 bits of depth.
58#[derive(Default)]
59pub(crate) struct Wide {
60 pub(crate) width: u32,
61 pub(crate) height: u32,
62 pub(crate) y: Vec<u16>,
63 pub(crate) u: Vec<u16>,
64 pub(crate) v: Vec<u16>,
65}
66
67/// What `ec-h264` hands over for a High 10 stream (`I010`: 16-bit little-endian
68/// samples, 10 bits of depth, a 9-bit stream left-aligned), taken into the two
69/// shapes the engine reads: [`Wide`] for a 10-bit export, and the truncated
70/// 8-bit [`I420`] playback and an 8-bit export use (`>> 2`, the same
71/// truncation `ec-h265`'s narrowing and the P010 read-back make). Buffers are
72/// reused for every picture of a stream.
73#[derive(Default)]
74pub(crate) struct Deep {
75 pub(crate) wide: Wide,
76 pub(crate) narrow: I420,
77 /// Whether the last picture loaded was `I010`.
78 pub(crate) on: bool,
79 /// Whether it went into `wide` (else into `narrow`).
80 pub(crate) in_wide: bool,
81}
82
83impl Deep {
84 /// Takes `pic` when it is anything but plain 8-bit 4:2:0: `I010` (High 10),
85 /// the 4:2:2 shapes `I422` and `I210`, whose chroma is full height and is
86 /// averaged down a pair of rows to 4:2:0 as HEVC 4:2:2 is
87 /// (`(a + b + 1) >> 1`), and the 4:4:4 shapes `I444` and `I410`, averaged
88 /// down over 2x2 the same way. Into `wide` when `want_wide` and the picture is
89 /// above 8 bits, into `narrow` otherwise (`>> 2` for 10-bit); a plain
90 /// picture just clears [`Deep::on`].
91 pub(crate) fn load(&mut self, pic: &VideoFrame, want_wide: bool) {
92 use ec_core::frame::PixelFormat as F;
93 // (bytes per sample, chroma is full height, chroma is full width)
94 let (bytes, full_height, full_width) = match pic.format {
95 F::I010 => (2usize, false, false),
96 F::I210 => (2, true, false),
97 F::I422 => (1, true, false),
98 F::I410 => (2, true, true),
99 F::I444 => (1, true, true),
100 _ => {
101 self.on = false;
102 self.in_wide = false;
103 return;
104 }
105 };
106 self.on = true;
107 self.in_wide = want_wide && bytes == 2;
108 let (w, h) = (pic.width as usize, pic.height as usize);
109 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
110 let src_ch = if full_height { h } else { ch };
111 let src_cw = if full_width { w } else { cw };
112 let dims = [(w, h, h, w), (cw, ch, src_ch, src_cw), (cw, ch, src_ch, src_cw)];
113 let sample = |line: &[u8], x: usize| -> u32 {
114 if bytes == 2 { u32::from(u16::from_le_bytes([line[2 * x], line[2 * x + 1]])) } else { u32::from(line[x]) }
115 };
116 // One output sample (r, x): the sample itself, or the rounded average of
117 // the 2x1 / 1x2 / 2x2 source samples under it for chroma stored at full
118 // height and/or width (`(a + b + 1) >> 1`, applied per axis).
119 let row_value = |plane: &ec_core::Plane, r: usize, rows_in: usize, cols_in: usize, x: usize, avg_v: bool, avg_h: bool| -> u32 {
120 let line = |row: usize| &plane.data[row * plane.stride..row * plane.stride + cols_in * bytes];
121 let at = |row: usize| -> u32 {
122 if avg_h {
123 let (a, b) = (2 * x, (2 * x + 1).min(cols_in - 1));
124 (sample(line(row), a) + sample(line(row), b) + 1) >> 1
125 } else {
126 sample(line(row), x)
127 }
128 };
129 if avg_v {
130 let (a, b) = (2 * r, (2 * r + 1).min(rows_in - 1));
131 (at(a) + at(b) + 1) >> 1
132 } else {
133 at(r)
134 }
135 };
136 if self.in_wide {
137 self.wide.width = pic.width;
138 self.wide.height = pic.height;
139 let out = [&mut self.wide.y, &mut self.wide.u, &mut self.wide.v];
140 for (i, ((plane, (pw, ph, rows_in, cols_in)), out)) in pic.planes.iter().zip(dims).zip(out).enumerate() {
141 out.clear();
142 for r in 0..ph {
143 out.extend((0..pw).map(|x| row_value(plane, r, rows_in, cols_in, x, full_height && i > 0, full_width && i > 0) as u16));
144 }
145 }
146 } else {
147 self.narrow.width = pic.width;
148 self.narrow.height = pic.height;
149 let shift = if bytes == 2 { 2 } else { 0 };
150 let out = [&mut self.narrow.y, &mut self.narrow.u, &mut self.narrow.v];
151 for (i, ((plane, (pw, ph, rows_in, cols_in)), out)) in pic.planes.iter().zip(dims).zip(out).enumerate() {
152 out.clear();
153 for r in 0..ph {
154 out.extend((0..pw).map(|x| (row_value(plane, r, rows_in, cols_in, x, full_height && i > 0, full_width && i > 0) >> shift) as u8));
155 }
156 }
157 }
158 }
159}
160
161/// The software seats whose pictures come one at a time: `ec-h265`, `ec-vp9`,
162/// `ec-vp8`, `ec-mpeg2`, `ec-mpeg4` and the intra-only `ec-prores`, `ec-dnxhd`, `ec-mjpeg` and `ec-dv`. Export decodes its sources through here, and playback's span
163/// loops read the same streams, so each codec's decode is written once.
164pub(crate) enum Pulled {
165 Hevc(Box<hevc::Stream>),
166 Vp9(Box<vp9::Stream>),
167 Vp8(Box<vp8::Stream>),
168 Mpeg2(Box<mpeg2::Stream>),
169 ProRes(Box<prores::Stream>),
170 Dnxhd(Box<dnxhd::Stream>),
171 Mjpeg(Box<mjpeg::Stream>),
172 Dv(Box<dv::Stream>),
173 Mpeg4(Box<mpeg4::Stream>),
174 Raw(Box<raw::Stream>),
175}
176
177impl Pulled {
178 /// A stream positioned at the sync sample at or before `start_frame`. `None`
179 /// for a codec with no pulled seat: H.264 and AV1 keep their own loops.
180 pub(crate) fn open(
181 codec: Codec,
182 demuxer: &mut Demuxer,
183 start_frame: u32,
184 deint: crate::project::Deinterlace,
185 ) -> Option<Self> {
186 Some(match codec {
187 Codec::Hevc => Self::Hevc(Box::new(hevc::Stream::open(demuxer, start_frame))),
188 Codec::Vp9 => Self::Vp9(Box::new(vp9::Stream::open(demuxer, start_frame))),
189 Codec::Vp8 => Self::Vp8(Box::new(vp8::Stream::open(demuxer, start_frame))),
190 Codec::Mpeg2 => Self::Mpeg2(Box::new(mpeg2::Stream::open(demuxer, start_frame, deint))),
191 Codec::ProRes => Self::ProRes(Box::new(prores::Stream::open(demuxer, start_frame))),
192 Codec::Dnxhd => Self::Dnxhd(Box::new(dnxhd::Stream::open(demuxer, start_frame))),
193 Codec::Mjpeg => Self::Mjpeg(Box::new(mjpeg::Stream::open(demuxer, start_frame))),
194 Codec::Dv => Self::Dv(Box::new(dv::Stream::open(demuxer, start_frame))),
195 Codec::Mpeg4 | Codec::MsMpeg4 => Self::Mpeg4(Box::new(mpeg4::Stream::open(demuxer, start_frame))),
196 Codec::Raw => Self::Raw(Box::new(raw::Stream::open(demuxer, start_frame))),
197 Codec::H264 | Codec::Av1 => return None,
198 })
199 }
200
201 /// The next picture in display order at 10-bit scale, into `out`, with its
202 /// display index. HEVC and the intra-only seats (ProRes, DNxHD, MJPEG) have such
203 /// a seat; the others are an error here, and the export asks for it only of those.
204 pub(crate) fn next_wide(
205 &mut self,
206 demuxer: &mut Demuxer,
207 out: &mut Wide,
208 ) -> Result<Option<i64>, String> {
209 match self {
210 Self::Hevc(stream) => stream.next_wide(demuxer, out),
211 Self::ProRes(stream) => stream.next_wide(demuxer, out),
212 Self::Dnxhd(stream) => stream.next_wide(demuxer, out),
213 Self::Mjpeg(stream) => stream.next_wide(demuxer, out),
214 Self::Raw(stream) => stream.next_wide(demuxer, out),
215 Self::Vp9(_) | Self::Vp8(_) | Self::Mpeg2(_) | Self::Dv(_) | Self::Mpeg4(_) => Err("no 10-bit seat for this codec".into()),
216 }
217 }
218
219 /// The next picture in display order, narrowed into `out`, with its display
220 /// index. `None` at end of stream; `Err` names a refusal.
221 pub(crate) fn next(
222 &mut self,
223 demuxer: &mut Demuxer,
224 out: &mut I420,
225 ) -> Result<Option<i64>, String> {
226 match self {
227 Self::Hevc(stream) => stream.next(demuxer, out),
228 Self::Vp9(stream) => stream.next(demuxer, out),
229 Self::Vp8(stream) => stream.next(demuxer, out),
230 Self::Mpeg2(stream) => stream.next(demuxer, out),
231 Self::ProRes(stream) => stream.next(demuxer, out),
232 Self::Dnxhd(stream) => stream.next(demuxer, out),
233 Self::Mjpeg(stream) => stream.next(demuxer, out),
234 Self::Dv(stream) => stream.next(demuxer, out),
235 Self::Mpeg4(stream) => stream.next(demuxer, out),
236 Self::Raw(stream) => stream.next(demuxer, out),
237 }
238 }
239}
240
241/// One decoded picture, ready to hand to a renderer.
242pub struct Frame {
243 /// Position in display order, starting at 0.
244 pub index: u32,
245 pub width: u32,
246 pub height: u32,
247 /// BGRA8, straight alpha, tightly packed.
248 pub bgra: Vec<u8>,
249}
250
251/// `frame` as a PNG file at `path` (RGBA, colours swizzled from BGRA).
252pub fn to_png(frame: &Frame, path: &Path) -> crate::Result<()> {
253 std::fs::write(path, to_png_bytes(frame)?)?;
254 Ok(())
255}
256
257/// `frame` as PNG-encoded bytes (RGBA, colours swizzled from BGRA).
258pub fn to_png_bytes(frame: &Frame) -> crate::Result<Vec<u8>> {
259 let pixels = frame.width as usize * frame.height as usize;
260 if frame.bgra.len() != pixels * 4 {
261 return Err(format!(
262 "frame is {}x{} but carries {} bytes",
263 frame.width,
264 frame.height,
265 frame.bgra.len()
266 )
267 .into());
268 }
269 let mut rgba = Vec::with_capacity(pixels * 4);
270 for px in frame.bgra.as_chunks::<4>().0 {
271 rgba.extend_from_slice(&[px[2], px[1], px[0], px[3]]);
272 }
273 Ok(ec_image::png_encode::encode_rgba8(frame.width, frame.height, &rgba)?)
274}
275
276/// Which decoder a source is really running on. Read-only introspection: it
277/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose --
278/// a hardware session that opened and then failed before its first picture
279/// falls back to software and this says so, because it is written where the
280/// fallback happens rather than where it was hoped for.
281#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
282pub enum Backend {
283 /// The worker has not reached its decoder yet: the plugin's VA-API init is
284 /// ~90 ms, and this is what a caller reads in that window.
285 #[default]
286 Opening,
287 /// The VA-API plugin (`libengine_hw.so`).
288 Hardware,
289 /// This project's own software seat: `ec-h264`, `ec-h265`, `ec-av1`, `ec-vp9`
290 /// or `ec-vp8`, in this process.
291 Software,
292 /// A still image: one `image` decode, no stream and no decoder to pick.
293 Still,
294 /// A gap: black frames, nothing decoded at all.
295 Gap,
296 /// A waveform visualizer: the picture is painted from the audio's peaks
297 /// ([`visualizer_i420`]), no decoder seat and no stream of pictures at all.
298 Visualizer,
299}
300
301impl Backend {
302 /// Short enough for a library row and a transport line.
303 pub fn label(self) -> &'static str {
304 match self {
305 Self::Opening => "opening",
306 Self::Hardware => "HW",
307 Self::Software => "SW",
308 Self::Still => "still",
309 Self::Gap => "gap",
310 Self::Visualizer => "viz",
311 }
312 }
313
314 fn code(self) -> u8 {
315 match self {
316 Self::Opening => 0,
317 Self::Hardware => 1,
318 Self::Software => 2,
319 Self::Still => 3,
320 Self::Gap => 4,
321 Self::Visualizer => 5,
322 }
323 }
324
325 fn from_code(code: u8) -> Self {
326 match code {
327 1 => Self::Hardware,
328 2 => Self::Software,
329 3 => Self::Still,
330 4 => Self::Gap,
331 5 => Self::Visualizer,
332 _ => Self::Opening,
333 }
334 }
335}
336
337/// Where a worker publishes the decoder it opened, for whoever holds the other
338/// end of its channel. One atomic byte, written once at open (and once more if
339/// hardware hands the range back to software), read whenever a caller repaints
340/// -- never per frame on either side.
341#[derive(Clone, Default)]
342pub struct BackendCell(Arc<AtomicU8>);
343
344impl BackendCell {
345 pub(crate) fn new(backend: Backend) -> Self {
346 Self(Arc::new(AtomicU8::new(backend.code())))
347 }
348
349 fn set(&self, backend: Backend) {
350 self.0.store(backend.code(), Ordering::Relaxed);
351 }
352
353 pub fn get(&self) -> Backend {
354 Backend::from_code(self.0.load(Ordering::Relaxed))
355 }
356}
357
358/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`]
359/// decides it: the same `VE_SW` pin and the same plugin probe against this very
360/// file. What lets a front-end name the decoder *before* anything plays.
361///
362/// The codec is `None` for a still image and for a sound-only file, which have no
363/// coded stream (both answer [`Backend::Still`]). Every codec
364/// here has a software seat, so a plugin that will not take the file is not a
365/// refusal: the file plays in software, and the only `Err` is the container's.
366///
367/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per
368/// file, off a render thread, and keep the answer.
369pub fn probe(path: &Path) -> crate::Result<(Option<Codec>, Backend)> {
370 // A still, and a sound-only file ([`crate::is_audio`]): neither has a picture
371 // stream, so there is no coded stream to open and no container to read as a
372 // movie. Asking the mp4 reader of a wav would refuse it with the mp4 reader's
373 // words, which the media panel would show beside a file that plays.
374 if crate::is_image(path) || crate::is_audio(path) {
375 return Ok((None, Backend::Still));
376 }
377 let path = path.to_path_buf();
378 let (meta, _demuxer) = Demuxer::open(&path)?;
379 if hw_decodes(&path, 0, meta.codec).is_ok() {
380 return Ok((Some(meta.codec), Backend::Hardware));
381 }
382 Ok((Some(meta.codec), Backend::Software))
383}
384
385/// A running decode worker: the flag that stops it, and the handle to wait on.
386///
387/// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize`
388/// outlives the process otherwise, and Mesa's `atexit` handlers free the state
389/// it is still reading -- a SIGSEGV at exit, long after the last test passed.
390pub(crate) struct Worker {
391 cancel: Arc<AtomicBool>,
392 /// `None` once detached, and for a range with nothing to decode: either way
393 /// there is no thread left to wait for.
394 handle: Option<thread::JoinHandle<()>>,
395 /// How a *later* span reaches this same thread ([`Worker::reseek`]), for the
396 /// workers that decode a file: the still, the gap and a detached worker have
397 /// no such door and are the one-span threads they always were.
398 reuse: Option<Reuse>,
399}
400
401/// The door a persistent decode worker is steered through: the file it has open,
402/// the channel its next span arrives on, and the generation counter that tells
403/// the span it is decoding *now* that nobody is waiting for it any more.
404///
405/// The point of all three is that a seek onto the same file costs a demuxer
406/// seek and a decoder flush ([`crate::hw::HwSession::seek`]) rather than a
407/// thread, a container parse and a VA-API initialisation (98 ms measured).
408struct Reuse {
409 path: PathBuf,
410 spans: std::sync::mpsc::Sender<SpanCmd>,
411 /// Bumped by every reseek and by [`Worker::abandon`]; the decode loop stops
412 /// the moment it no longer matches the span it was handed.
413 generation: Arc<AtomicU64>,
414 /// The worker's decoder, published once and read across every span it
415 /// decodes -- so a reseek onto a file already open says "hardware" from the
416 /// first repaint instead of going back through `opening`.
417 backend: BackendCell,
418 /// Where the caller's playhead stands, in this file's own frames
419 /// ([`Worker::playhead`]): the worker converts and sends nothing behind it.
420 /// Rewritten to the target by every reseek, so it can never carry one span's
421 /// position into the next.
422 floor: Arc<AtomicU32>,
423}
424
425/// One span asked of a persistent worker: the range in the file's own frames,
426/// everything a picture is graded, placed and mapped by, and the channel the
427/// pictures go down. Carries its generation, so a command already superseded on
428/// its way through the queue is dropped rather than decoded.
429struct SpanCmd {
430 generation: u64,
431 start: u32,
432 end: u32,
433 color: ColorParams,
434 transform: TransformParams,
435 canvas: Composer,
436 tone: tonemap::Preset,
437 /// The clip's own playback speed ([`crate::project::Clip::speed`]), for
438 /// [`skip_for_speed`]: at faster than real time several source frames in a
439 /// row land on the same timeline frame, and only the last of a run is ever
440 /// shown. [`Speed::NORMAL`] for a file-level open ([`DecodeSession::open`]
441 /// and friends), which has no clip and skips nothing.
442 speed: Speed,
443 /// The clip's deinterlace setting ([`crate::project::Clip::deinterlace`]). With
444 /// `Field` on an interlaced source the file's frame numbers in `start`, `end`
445 /// and every [`Frame::index`] are **field** numbers, `2 * frame + 0 or 1`.
446 deint: crate::project::Deinterlace,
447 tx: SyncSender<Frame>,
448}
449
450/// What stops a decode loop: the worker's terminal flag (the thread itself is
451/// going away) and the generation of the span it was handed (only *this* span is
452/// going away). One check, so every loop treats them alike.
453///
454/// ...and where the playhead has reached ([`Abort::late`]), which is the same
455/// question one picture at a time: a frame due before it is a frame nobody can
456/// be shown any more.
457struct Abort<'a> {
458 cancel: &'a AtomicBool,
459 generation: &'a AtomicU64,
460 mine: u64,
461 floor: &'a AtomicU32,
462}
463
464impl Abort<'_> {
465 fn hit(&self) -> bool {
466 self.cancel.load(Ordering::Relaxed) || self.generation.load(Ordering::Acquire) != self.mine
467 }
468
469 /// Whether the picture at source frame `index` is already past due: the
470 /// caller's playhead has gone by it, so converting it (a full BGRA pass over
471 /// 8 MB at 1080p) and queueing it would only push a picture nobody sees in
472 /// front of the one they are waiting for.
473 ///
474 /// It is still *decoded* -- the pictures after it reference it -- and the
475 /// floor only ever moves with the playhead the session publishes, so a
476 /// paused session (and every seek, which republishes its own target) drops
477 /// nothing at all.
478 fn late(&self, index: u32) -> bool {
479 self.floor.load(Ordering::Relaxed) > index
480 }
481}
482
483/// Whether the picture at source frame `due` (of a span starting at `start` and
484/// ending at `end`) is redundant *by construction* at `speed`, and its convert
485/// and send can be skipped without ever waiting on the playhead
486/// ([`Abort::late`]): at faster than real time several source frames in a row
487/// map to the same timeline frame ([`Speed::timeline_at`]), and only the last
488/// of such a run is ever shown -- the newest one always lands after the others
489/// in `try_frame`'s stamp comparison. Unlike a late drop this needs no run
490/// limit: the gap between two kept frames is at most `speed` source frames, so
491/// the picture stream this leaves is never silent, only sparser.
492///
493/// The last frame of the whole span is never skipped by this: it is the
494/// picture [`crate::project::Span::source_len`] was built to land exactly on,
495/// and this is what proves that promise here instead of trusting it blind.
496///
497/// corner-cut: `due` and `start` are the file's own frame numbers, so this
498/// is only correct when the file plays at the timeline's own rate
499/// ([`crate::project::Rate::is_real_time`]) -- callers pass [`Speed::NORMAL`]
500/// (never skip) otherwise. Upgrade path is composing `Rate` into this the way
501/// [`crate::project::Span::timeline_at`] does.
502fn skip_for_speed(speed: Speed, start: u32, due: u32, end: u32) -> bool {
503 if speed.is_normal() || due + 1 >= end {
504 return false;
505 }
506 let rel = due - start;
507 speed.timeline_at(rel) == speed.timeline_at(rel + 1)
508}
509
510impl Worker {
511 /// Stops the worker *and its thread* at their next check, without waiting.
512 /// Callers that replace a worker should do this first and drop the receiver
513 /// second: a worker parked in `send` only wakes on the disconnect, so the
514 /// join below would otherwise wait for a consumer that is never coming.
515 ///
516 /// The command channel goes with it, which is what wakes a persistent worker
517 /// parked between spans -- without that it would sit in `recv` forever and a
518 /// retired worker would never be reaped (nor joined at exit in any bounded
519 /// time, which is the Mesa `atexit` hazard this whole type exists for).
520 pub(crate) fn cancel(&mut self) {
521 self.cancel.store(true, Ordering::Release);
522 self.reuse = None;
523 }
524
525 /// Stops the span the worker is decoding, keeping the *thread* -- and with
526 /// it the open file and the open decoder -- for the span that follows. What
527 /// a seek does, since the next thing it says is [`Worker::reseek`].
528 ///
529 /// Falls back to [`cancel`](Self::cancel) for a worker with nothing to
530 /// reuse (a still, a gap, a detached one), where the two mean the same
531 /// thing: this worker has no next span.
532 pub(crate) fn abandon(&mut self) {
533 match &self.reuse {
534 Some(reuse) => {
535 reuse.generation.fetch_add(1, Ordering::Release);
536 }
537 None => self.cancel(),
538 }
539 }
540
541 /// Tells the worker where the caller's playhead stands, in the file's own
542 /// frames: it converts and queues nothing behind that, because a picture
543 /// whose moment has passed cannot be shown and would only delay the one that
544 /// can (see [`Abort::late`]). A worker with no reuse door -- a still, a gap
545 /// -- has nothing to tell, and this costs it nothing to say.
546 pub(crate) fn playhead(&self, source_frame: u32) {
547 if let Some(reuse) = &self.reuse {
548 reuse.floor.store(source_frame, Ordering::Relaxed);
549 }
550 }
551
552 /// Points this worker at another range of the file it already has open,
553 /// handing back the channel the new span's pictures arrive on and the cell
554 /// that says what is decoding them. `None` when this worker cannot take the
555 /// job -- another file, no reuse door, or a thread that has already returned
556 /// -- and the caller then opens a worker of its own, exactly as it always
557 /// did.
558 ///
559 /// The pictures of the *old* span are left in their own channel, which the
560 /// caller drops: that disconnect is what wakes this worker if it is parked
561 /// in `send`, and only then does it reach the command below. So the order at
562 /// the call site is unchanged -- install the new receiver, and the old
563 /// worker finds out by losing its consumer.
564 #[allow(clippy::too_many_arguments, dead_code, reason = "the playback session calls reseek_with once the lane's playback.rs hunk is in")]
565 pub(crate) fn reseek(
566 &mut self,
567 path: &Path,
568 start: u32,
569 end: u32,
570 color: ColorParams,
571 transform: TransformParams,
572 canvas: Composer,
573 tone: tonemap::Preset,
574 speed: Speed,
575 ) -> Option<(Receiver<Frame>, BackendCell)> {
576 self.reseek_with(path, start, end, color, transform, canvas, tone, speed, Default::default())
577 }
578
579 /// [`reseek`](Self::reseek) for a clip with a deinterlace setting: `start` and
580 /// `end` are field numbers when `deint` is `Field` and the file is interlaced.
581 #[allow(clippy::too_many_arguments)]
582 pub(crate) fn reseek_with(
583 &mut self,
584 path: &Path,
585 start: u32,
586 end: u32,
587 color: ColorParams,
588 transform: TransformParams,
589 canvas: Composer,
590 tone: tonemap::Preset,
591 speed: Speed,
592 deint: crate::project::Deinterlace,
593 ) -> Option<(Receiver<Frame>, BackendCell)> {
594 let reuse = self.reuse.as_ref()?;
595 if reuse.path != path || self.is_finished() {
596 return None;
597 }
598 let (tx, rx) = sync_channel(canvas.queue_depth());
599 // The new span's own playhead, before its first picture is decoded: a
600 // floor left over from where the timeline *was* would drop every
601 // picture of a seek that went backwards.
602 reuse.floor.store(start, Ordering::Relaxed);
603 // Bumped before the command is queued, so the span running now stops at
604 // its next picture whatever order the two threads are scheduled in.
605 let generation = reuse.generation.fetch_add(1, Ordering::Release) + 1;
606 reuse
607 .spans
608 .send(SpanCmd {
609 generation,
610 start,
611 end,
612 color,
613 transform,
614 canvas,
615 tone,
616 speed,
617 deint,
618 tx,
619 })
620 .ok()?;
621 Some((rx, reuse.backend.clone()))
622 }
623
624 /// Whether the thread has already returned, i.e. dropping this would not
625 /// wait. `true` for a worker that never had a thread. What lets a caller
626 /// park cancelled workers and reap them without ever blocking.
627 pub(crate) fn is_finished(&self) -> bool {
628 self.handle
629 .as_ref()
630 .is_none_or(thread::JoinHandle::is_finished)
631 }
632
633 /// Lets the worker run on unwatched -- what the public API does, since it
634 /// hands out the flag alone.
635 ///
636 /// The reuse door goes with the handle: nothing can steer a worker nobody
637 /// holds, and dropping the command channel is what makes such a thread end
638 /// at its span rather than park waiting for a next one it can never be
639 /// given -- with a VA-API session open, into Mesa's `atexit`.
640 fn detach(mut self) -> Arc<AtomicBool> {
641 self.handle = None;
642 self.reuse = None;
643 Arc::clone(&self.cancel)
644 }
645}
646
647impl Drop for Worker {
648 fn drop(&mut self) {
649 if let Some(handle) = self.handle.take() {
650 // `cancel` drops the command channel too, so a worker parked between
651 // spans wakes on the disconnect and this join is bounded.
652 self.cancel();
653 let _ = handle.join();
654 }
655 }
656}
657
658/// A running worker and the frames it is sending, handed out as one value
659/// because they must be *dropped* as one, in this order: the receiver
660/// disconnects first, which is the only thing that wakes a worker parked in a
661/// full `send`, and the join inside [`Worker::drop`] runs second.
662///
663/// Rust drops fields in declaration order, so this struct *is* that rule, and
664/// it holds wherever the value goes: an early return out of a half-built
665/// session, an unwind, a caller not written yet. Two separate locals do not
666/// hold it -- they drop in reverse order of declaration, so the worker there
667/// joins a thread nobody will ever drain, which is a hang and not a slow path.
668pub(crate) struct FrameStream {
669 pub(crate) frames: Receiver<Frame>,
670 pub(crate) worker: Worker,
671 /// What this stream's pictures are being decoded by. Dropped last and read
672 /// by the caller, so it outlives nothing and blocks nothing.
673 pub(crate) backend: BackendCell,
674 /// Why this stream stopped early, if it did -- the answer a closed channel
675 /// cannot give. Cloned into the worker, so it outlives the span that set it.
676 pub(crate) failure: DecodeFailure,
677}
678
679/// Why a decode worker stopped **before** the end of its stream, if it did.
680///
681/// The reason channel the sound path already has ([`crate::playback::Audio`]'s
682/// `died` flag, read back as `audio_disabled_reason`), for the picture side. It
683/// exists because a closed channel is not an answer: a worker that ran to the end
684/// of the file and a worker that gave up on a corrupt packet both drop the
685/// sender, and to a caller reading [`std::sync::mpsc::Receiver::try_recv`]
686/// those are one event. The app read that as `Transport::Ended`, so a file with
687/// a broken middle froze on its last good picture and said nothing -- identical
688/// to the film finishing, with no notice and no banner.
689///
690/// The **first** reason wins: a span that fails and is then reseeked keeps the
691/// failure that stopped it until a span succeeds, which is what makes this a
692/// statement about the file rather than about the last attempt. A clean
693/// end-of-stream sets nothing at all -- silence is not a fault, and a notice
694/// that fires on every film would be a notice nobody reads.
695#[derive(Clone, Default)]
696pub struct DecodeFailure(Arc<Mutex<Option<String>>>);
697
698impl DecodeFailure {
699 /// The reason the last span failed, if one did.
700 pub fn reason(&self) -> Option<String> {
701 self.0.lock().ok().and_then(|reason| reason.clone())
702 }
703
704 /// Records a failure and says so on stderr, which is where these used to go
705 /// and where they still belong: the stderr line is for whoever is reading a
706 /// log, and this cell is for whoever is looking at a window.
707 pub(crate) fn set(&self, reason: String) {
708 eprintln!("{reason}");
709 let Ok(mut slot) = self.0.lock() else {
710 return; // poisoned by a panic elsewhere: the stderr line still stands
711 };
712 if slot.is_none() {
713 *slot = Some(reason);
714 }
715 }
716
717 /// Takes the reason back, for a caller that has read it: a fresh span that
718 /// gets all the way through its range has answered the question.
719 pub(crate) fn clear(&self) {
720 if let Ok(mut slot) = self.0.lock() {
721 slot.take();
722 }
723 }
724}
725
726pub struct DecodeSession;
727
728impl DecodeSession {
729 /// Opens `path`, returning stream metadata immediately and a receiver that
730 /// yields frames as the worker decodes them. The worker stops when the
731 /// receiver is dropped, at end of stream, or on the first decode error.
732 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
733 let (meta, rx, _cancel) = Self::open_at(path, 0)?;
734 Ok((meta, rx))
735 }
736
737 /// As [`DecodeSession::open`], but the first frame delivered is
738 /// `start_frame` (0-based display index; [`Frame::index`] stays absolute).
739 /// Setting the returned flag stops the worker at its next access unit,
740 /// which is how a caller abandons a session it no longer wants to drain.
741 pub fn open_at(
742 path: impl AsRef<Path>,
743 start_frame: u32,
744 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
745 // `u32::MAX` is clamped to the stream's frame count below, so this is
746 // "to the end of the file".
747 Self::open_range(path, start_frame, u32::MAX)
748 }
749
750 /// As [`DecodeSession::open_at`], but the worker also stops on its own
751 /// after sending `end_frame - 1`: the range is half-open `[start, end)` in
752 /// absolute source frames, which is what a clip of a longer file needs.
753 /// `end_frame` is capped at the stream's frame count, and an empty range
754 /// yields a receiver that is simply already disconnected.
755 pub fn open_range(
756 path: impl AsRef<Path>,
757 start_frame: u32,
758 end_frame: u32,
759 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
760 // Ungraded: the public API opens a *file*, and a colour grade belongs to
761 // a clip of a timeline. `PlaybackSession` is what has one to pass.
762 let (meta, stream) = Self::open_worker(
763 path,
764 start_frame,
765 end_frame,
766 ColorParams::default(),
767 // No clip, no transform either: the file-level API hands back the
768 // pictures the file holds, untouched.
769 TransformParams::default(),
770 // No project, no canvas: the file-level API hands back the
771 // pictures the file holds, at the size it holds them.
772 Composer::passthrough(),
773 // ...and no project means no picked rendition either: an HDR file
774 // opened through this door is mapped the published way.
775 tonemap::Preset::default(),
776 )?;
777 // The public API hands out the flag alone, so the worker is detached and
778 // the receiver goes to the caller: nothing here joins anything.
779 Ok((meta, stream.frames, stream.worker.detach()))
780 }
781
782 /// A worker that decodes nothing and emits `len` black frames, indexed from
783 /// zero -- what a *gap* in the video lane looks like. It goes down the same
784 /// channel as decoded frames, so a gap costs the caller no branch at all
785 /// beyond choosing this opener: same bounded channel, same backpressure,
786 /// same cancel, same retire path.
787 pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream {
788 let (tx, rx) = sync_channel(2);
789 let cancel = Arc::new(AtomicBool::new(false));
790 if len == 0 {
791 return FrameStream {
792 frames: rx,
793 worker: Worker {
794 cancel,
795 handle: None,
796 reuse: None,
797 },
798 backend: BackendCell::new(Backend::Gap),
799 failure: DecodeFailure::default(),
800 };
801 }
802 let worker_cancel = Arc::clone(&cancel);
803 // One buffer, cloned per frame: opaque black is a constant, and the
804 // clone is a memcpy against a decode this replaces entirely.
805 let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat();
806 let handle = thread::Builder::new()
807 .name("black".into())
808 .spawn(move || {
809 for index in 0..len {
810 if worker_cancel.load(Ordering::Relaxed) {
811 return;
812 }
813 let frame = Frame {
814 index,
815 width,
816 height,
817 bgra: black.clone(),
818 };
819 if tx.send(frame).is_err() {
820 return; // caller moved on
821 }
822 }
823 })
824 .ok();
825 FrameStream {
826 frames: rx,
827 worker: Worker {
828 cancel,
829 handle,
830 reuse: None,
831 },
832 backend: BackendCell::new(Backend::Gap),
833 failure: DecodeFailure::default(),
834 }
835 }
836
837 /// A stream whose frames `body` produces on a thread of its own, sent down
838 /// the same bounded channel, with the same cancel and the same retire path,
839 /// as a decoder's. What a layered picture's composed frames come down.
840 pub(crate) fn spawn_stream(
841 name: &'static str,
842 backend: Backend,
843 body: impl FnOnce(&std::sync::mpsc::SyncSender<Frame>, &AtomicBool) + Send + 'static,
844 ) -> FrameStream {
845 let (tx, rx) = sync_channel(2);
846 let cancel = Arc::new(AtomicBool::new(false));
847 let worker_cancel = Arc::clone(&cancel);
848 let handle = thread::Builder::new()
849 .name(name.into())
850 .spawn(move || body(&tx, &worker_cancel))
851 .ok();
852 FrameStream {
853 frames: rx,
854 worker: Worker {
855 cancel,
856 handle,
857 reuse: None,
858 },
859 backend: BackendCell::new(backend),
860 failure: DecodeFailure::default(),
861 }
862 }
863
864 /// A worker that plays `count` frames of `path` **backwards**, from file frame
865 /// `top` down: the picture of a reversed clip. Frame `d` of the stream is file
866 /// frame `top - d`, numbered `top + d` -- the clip's *own* frame numbers, counted
867 /// as if the file ran backwards from `top`, so everything downstream that stamps,
868 /// skips and drops by a frame's number (and every span mapping in
869 /// [`crate::project::Span`]) treats it as the forward stream it looks like.
870 ///
871 /// The frames are decoded by a forward worker a block at a time and served last
872 /// to first ([`crate::reverse`]), which is what bounds the memory: one block of
873 /// finished canvases, never the clip. The picture is graded and placed exactly as
874 /// a forward span's is -- the same inner worker does it -- so a reversed frame is
875 /// a forward frame, bit for bit, in another order. A block that ends early (a file
876 /// shorter than the window) ends the stream there.
877 #[allow(clippy::too_many_arguments)]
878 #[allow(dead_code, reason = "the playback session calls open_reversed_with once the lane's playback.rs hunk is in")]
879 pub(crate) fn open_reversed(
880 path: &Path,
881 top: u32,
882 count: u32,
883 color: ColorParams,
884 transform: TransformParams,
885 canvas: Composer,
886 tone: tonemap::Preset,
887 ) -> FrameStream {
888 Self::open_reversed_with(path, top, count, color, transform, canvas, tone, Default::default())
889 }
890
891 /// [`open_reversed`](Self::open_reversed) for a clip with a deinterlace
892 /// setting. In field mode `top` and `count` are field numbers: the fields of
893 /// an interlaced file play last to first, so each frame's second field comes
894 /// before its first.
895 #[allow(clippy::too_many_arguments)]
896 pub(crate) fn open_reversed_with(
897 path: &Path,
898 top: u32,
899 count: u32,
900 color: ColorParams,
901 transform: TransformParams,
902 canvas: Composer,
903 tone: tonemap::Preset,
904 deint: crate::project::Deinterlace,
905 ) -> FrameStream {
906 let path = path.to_path_buf();
907 let deint = crate::deinterlace::effective(deint, &path);
908 let (cw, ch) = canvas.dims();
909 // A pass-through canvas has no size of its own: plan for the biggest picture
910 // the engine decodes so that the block stays inside its budget whatever it is.
911 let (cw, ch) = if cw == 0 || ch == 0 { (3840, 2160) } else { (cw, ch) };
912 Self::spawn_stream("decode-reverse", Backend::Software, move |tx, cancel| {
913 let lo = (top + 1).saturating_sub(count);
914 let mut sync = crate::reverse::sync_frames(&path);
915 if deint == crate::project::Deinterlace::Field {
916 // Sync frames are frame numbers; a field-mode block starts at a
917 // frame's first field.
918 sync.iter_mut().for_each(|f| *f *= 2);
919 }
920 if deint == crate::project::Deinterlace::Ivtc {
921 // ...and a film-frame block at the first film frame that starts at or
922 // after the sync frame.
923 sync.iter_mut().for_each(|f| *f = crate::deinterlace::counted_frames(deint, &path, *f));
924 }
925 let cap = crate::reverse::block_cap(cw as usize * ch as usize * 4);
926 let mut walk = crate::reverse::Walk::new(sync, lo, top + 1, cap);
927 let mut inner: Option<FrameStream> = None;
928 let mut rx: Option<Receiver<Frame>> = None;
929 while let Some((start, end)) = walk.next() {
930 if cancel.load(Ordering::Relaxed) {
931 return;
932 }
933 match inner.as_mut() {
934 None => {
935 let stream = span_worker(
936 path.clone(),
937 None,
938 start,
939 end,
940 color,
941 transform,
942 canvas.fresh(),
943 tone,
944 Speed::NORMAL,
945 deint,
946 );
947 inner = Some(stream);
948 }
949 Some(stream) => {
950 match stream.worker.reseek_with(
951 &path,
952 start,
953 end,
954 color,
955 transform,
956 canvas.fresh(),
957 tone,
958 Speed::NORMAL,
959 deint,
960 ) {
961 Some((next, _)) => rx = Some(next),
962 // The worker is gone (the file would not open, or it died):
963 // nothing more to serve.
964 None => return,
965 }
966 }
967 }
968 let stream = inner.as_ref().expect("opened above");
969 let frames = rx.as_ref().unwrap_or(&stream.frames);
970 let mut block: Vec<Frame> = Vec::with_capacity((end - start) as usize);
971 loop {
972 match frames.recv_timeout(std::time::Duration::from_millis(50)) {
973 Ok(frame) => block.push(frame),
974 Err(RecvTimeoutError::Timeout) => {
975 if cancel.load(Ordering::Relaxed) {
976 return;
977 }
978 }
979 Err(RecvTimeoutError::Disconnected) => break,
980 }
981 }
982 if block.is_empty() {
983 return; // the inner worker found nothing: the file ended or failed
984 }
985 for mut frame in block.into_iter().rev() {
986 if cancel.load(Ordering::Relaxed) {
987 return;
988 }
989 frame.index = 2 * top - frame.index;
990 if tx.send(frame).is_err() {
991 return; // caller moved on
992 }
993 }
994 }
995 })
996 }
997
998 /// A worker for a still image ([`crate::is_image`]): the file is decoded
999 /// *once* and the same picture goes down the channel `len` times, indexed
1000 /// from `start_frame` exactly as a decoder's pictures are -- so a placed
1001 /// image is a clip like any other to everything downstream (`try_frame`
1002 /// rewrites those indices, `next_clip` walks off the end of the range).
1003 ///
1004 /// Graded and placed on the canvas once too, before the repeat: a still is
1005 /// the same pixels every frame, so the whole cost of one is one conversion
1006 /// plus a memcpy per frame -- what [`open_black`](Self::open_black) pays.
1007 pub(crate) fn open_still(
1008 path: &Path,
1009 start_frame: u32,
1010 len: u32,
1011 color: ColorParams,
1012 transform: TransformParams,
1013 canvas: Composer,
1014 ) -> crate::Result<FrameStream> {
1015 // A numbered run opens on the frame the stream starts at; a file opens as it always did.
1016 let still = match crate::sequence::Run::parse(path) {
1017 Some(_) => Still::open_at(path, start_frame)?,
1018 None => Still::open(path)?,
1019 };
1020 if still.seq.is_some() {
1021 return Self::open_run(still, start_frame, len, color, transform, canvas);
1022 }
1023 let (tx, rx) = sync_channel(2);
1024 let cancel = Arc::new(AtomicBool::new(false));
1025 if len == 0 {
1026 return Ok(FrameStream {
1027 frames: rx,
1028 worker: Worker {
1029 cancel,
1030 handle: None,
1031 reuse: None,
1032 },
1033 backend: BackendCell::new(Backend::Still),
1034 // A still has no stream to fail in: `Still::open` raised
1035 // anything that was wrong with the file at the door, before a
1036 // worker existed.
1037 failure: DecodeFailure::default(),
1038 });
1039 }
1040 // The one conversion, on this thread: it is a few milliseconds and the
1041 // error it could raise has already been raised by `Still::open`.
1042 // BT.601 limited, because that is what `rgb_to_i420` above wrote these
1043 // planes in: a still round-trips through the pair, not through the
1044 // colour of whatever file is on the timeline beside it.
1045 // No preset argument, and none wanted: a still is decoded into BT.601
1046 // SDR planes, so the tone map is not built at all whichever rendition
1047 // the project is watching.
1048 let first = Render::new(
1049 color,
1050 transform,
1051 // A still's own turn is already in these planes: `Still::open` made
1052 // it before the conversion above, exactly where the video door
1053 // makes a display matrix, so the render must not make it twice.
1054 Rotation::None,
1055 // ...and no sample aspect either: a still is authored square.
1056 PixelAspect::SQUARE,
1057 ColorDescription::default(),
1058 canvas,
1059 tonemap::Preset::default(),
1060 // ...and no declared peak either, for the same reason: there is no
1061 // tone map on this path to hand one to.
1062 None,
1063 )
1064 .frame(
1065 start_frame,
1066 &still.y,
1067 &still.u,
1068 &still.v,
1069 still.width,
1070 still.height,
1071 );
1072 let worker_cancel = Arc::clone(&cancel);
1073 let handle = thread::Builder::new()
1074 .name("still".into())
1075 .spawn(move || {
1076 let (width, height, bgra) = (first.width, first.height, first.bgra);
1077 for index in 0..len {
1078 if worker_cancel.load(Ordering::Relaxed) {
1079 return;
1080 }
1081 let frame = Frame {
1082 index: start_frame + index,
1083 width,
1084 height,
1085 bgra: bgra.clone(),
1086 };
1087 if tx.send(frame).is_err() {
1088 return; // caller moved on
1089 }
1090 }
1091 })
1092 .ok();
1093 Ok(FrameStream {
1094 frames: rx,
1095 worker: Worker {
1096 cancel,
1097 handle,
1098 reuse: None,
1099 },
1100 backend: BackendCell::new(Backend::Still),
1101 failure: DecodeFailure::default(),
1102 })
1103 }
1104
1105 /// A numbered run ([`crate::sequence`]) as a stream: one picture per frame of the clip, each
1106 /// frame of the run read on the worker when its turn comes, so a long run never sits decoded
1107 /// in memory. The same stream shape [`open_still`](Self::open_still) gives a single picture.
1108 fn open_run(
1109 mut still: Still,
1110 start_frame: u32,
1111 len: u32,
1112 color: ColorParams,
1113 transform: TransformParams,
1114 canvas: Composer,
1115 ) -> crate::Result<FrameStream> {
1116 let (tx, rx) = sync_channel(2);
1117 let cancel = Arc::new(AtomicBool::new(false));
1118 let mut render = Render::new(
1119 color,
1120 transform,
1121 // A frame's own turn is already in its planes, made by `Still::open_at`.
1122 Rotation::None,
1123 PixelAspect::SQUARE,
1124 ColorDescription::default(),
1125 canvas,
1126 tonemap::Preset::default(),
1127 None,
1128 );
1129 let worker_cancel = Arc::clone(&cancel);
1130 let handle = thread::Builder::new()
1131 .name("still-run".into())
1132 .spawn(move || {
1133 for index in 0..len {
1134 if worker_cancel.load(Ordering::Relaxed) {
1135 return;
1136 }
1137 // The first call hands out the frame the stream opened on; each later one reads the next.
1138 let (y, u, v, width, height) = still.picture();
1139 let frame = render.frame(start_frame + index, y, u, v, width, height);
1140 if tx.send(frame).is_err() {
1141 return; // caller moved on
1142 }
1143 }
1144 })
1145 .ok();
1146 Ok(FrameStream {
1147 frames: rx,
1148 worker: Worker {
1149 cancel,
1150 handle,
1151 reuse: None,
1152 },
1153 backend: BackendCell::new(Backend::Still),
1154 failure: DecodeFailure::default(),
1155 })
1156 }
1157
1158 /// A worker for an audio file played as a *picture* ([`crate::is_audio`]):
1159 /// the file's peaks are decoded **once** on the worker, and every picture
1160 /// after that is painted -- a sliding visualizer
1161 /// ([`visualizer_i420`]) at the canvas's own size, then graded, placed and
1162 /// converted exactly like a decoded picture, so a grade, a transform and a
1163 /// fit policy reach it the way they reach anything else on the timeline.
1164 ///
1165 /// `start_frame` and `len` are the file's own frames at `fps` -- which for
1166 /// an audio source are also the timeline's
1167 /// ([`crate::project::Rate::REAL_TIME`]) -- so `Frame::index` runs
1168 /// `start_frame ..` like a decoder's output and a speed reaches it through
1169 /// the same rewrite as any other clip.
1170 #[allow(
1171 clippy::too_many_arguments,
1172 reason = "playback.rs calls this seat positionally; bundling its arguments is a change to that caller too"
1173 )]
1174 pub(crate) fn open_visualizer(
1175 path: &Path,
1176 stream: usize,
1177 start_frame: u32,
1178 len: u32,
1179 fps: f64,
1180 color: ColorParams,
1181 transform: TransformParams,
1182 canvas: Composer,
1183 flags: u8,
1184 paint: u64,
1185 ) -> crate::Result<FrameStream> {
1186 let (tx, rx) = sync_channel(2);
1187 let cancel = Arc::new(AtomicBool::new(false));
1188 if len == 0 {
1189 return Ok(FrameStream {
1190 frames: rx,
1191 worker: Worker {
1192 cancel,
1193 handle: None,
1194 reuse: None,
1195 },
1196 backend: BackendCell::new(Backend::Visualizer),
1197 // A painted picture has no decoder to fail: an unreadable audio
1198 // file is `VizEnvelope::Silent`, which is what silence looks like.
1199 failure: DecodeFailure::default(),
1200 });
1201 }
1202 // Painted at the canvas's own size, so the composite places nothing:
1203 // the picture *is* the canvas, and whatever transform the clip
1204 // carries still reaches it through the render below.
1205 //
1206 // Masked to even dimensions first: that is what the painter does to the
1207 // planes it hands back, so a canvas it cannot divide evenly (an odd
1208 // `resolution 1921 1081` line, or a one-pixel-high one) used to be
1209 // *declared* at a size the picture never had -- and the conversion below
1210 // then indexes a chroma plane that is not there (`index out of bounds`
1211 // on a zero-length slice, in this worker, where no frame ever arrives
1212 // and nothing catches it). No floor under the mask: a canvas with no
1213 // size is asked for no picture, and the painter answers that with empty
1214 // planes ([`visualizer_window_i420`]), which the declared size now
1215 // matches.
1216 let (canvas_w, canvas_h) = canvas.dims();
1217 let (width, height) = (canvas_w & !1, canvas_h & !1);
1218 let worker_cancel = Arc::clone(&cancel);
1219 let path = path.to_path_buf();
1220 let handle = thread::Builder::new()
1221 .name("viz".into())
1222 .spawn(move || {
1223 // The envelope this span paints from, asked for once for the
1224 // whole span: the memo's own handle when it holds one, and
1225 // otherwise a *window* of the file's envelope per frame --
1226 // which is what makes a rebuild cheap for a source whose whole
1227 // envelope does not fit the memo at all ([`viz_envelope`]). A
1228 // file that will not open -- and one with no track at all --
1229 // paints the flat line, which is what its silence looks like
1230 // anyway: a visualizer frame always exists, and is never worth
1231 // failing a span over.
1232 let mut envelope =
1233 crate::waveform::viz_envelope(&path, stream, VIZ_BUCKETS_PER_SEC)
1234 .unwrap_or(crate::waveform::VizEnvelope::Silent);
1235 if worker_cancel.load(Ordering::Relaxed) {
1236 return;
1237 }
1238 let fps = if fps.is_finite() && fps > 0.0 {
1239 fps
1240 } else {
1241 30.0
1242 };
1243 // One frame's painting no longer allocates per strand per
1244 // frame: this thread lives for the span.
1245 let mut scratch = VizScratch::default();
1246 let mut render = Render::new(
1247 color,
1248 transform,
1249 // Painted here, at the canvas's own size: nothing turned it.
1250 Rotation::None,
1251 // ...and nothing drew it anamorphic: it is square by
1252 // construction.
1253 PixelAspect::SQUARE,
1254 ColorDescription::default(),
1255 canvas,
1256 tonemap::Preset::default(),
1257 None,
1258 );
1259 for index in 0..len {
1260 if worker_cancel.load(Ordering::Relaxed) {
1261 return;
1262 }
1263 let t = f64::from(start_frame + index) / fps;
1264 // One window of the envelope about this frame's own time:
1265 // the same window for every frame a sliding paint asks of
1266 // the same thirty seconds, and no decode at all for the
1267 // rebuilds of a look edit.
1268 let view = envelope.view_at(t);
1269 let (y, u, v) =
1270 visualizer_window_i420(&mut scratch, &view, t, width, height, flags, paint);
1271 let frame = render.frame(start_frame + index, &y, &u, &v, width, height);
1272 if tx.send(frame).is_err() {
1273 return; // caller moved on
1274 }
1275 }
1276 })
1277 .ok();
1278 Ok(FrameStream {
1279 frames: rx,
1280 worker: Worker {
1281 cancel,
1282 handle,
1283 reuse: None,
1284 },
1285 backend: BackendCell::new(Backend::Visualizer),
1286 // ...and nothing in the paint loop can fail either, for the same
1287 // reason.
1288 failure: DecodeFailure::default(),
1289 })
1290 }
1291
1292 /// As [`DecodeSession::open_range`], but the caller gets the whole
1293 /// [`Worker`] and can therefore *wait* for it, and the range is graded by
1294 /// `color` -- the clip's own setting, folded into the conversion the frames
1295 /// go through anyway (see [`i420_to_bgra_with`]). It is captured here rather
1296 /// than read per frame because a worker *is* one clip's range: a grade
1297 /// changed while this one runs reaches the picture when the session reseeks
1298 /// onto the new one, which every edit does.
1299 ///
1300 /// In-process only: a caller that outlives its workers has to be able to
1301 /// join them at exit.
1302 ///
1303 /// `canvas` is the project's own resolution and this clip's fit policy: the
1304 /// frames come out at *that* size, whatever the file's is. A
1305 /// [`Composer::passthrough`] (or one already the source's size) leaves every
1306 /// picture exactly as it was decoded.
1307 ///
1308 /// `tone` is the project's HDR rendition ([`tonemap::Preset`]), captured
1309 /// here for the reason the grade is: it is constant across one span, and a
1310 /// preset picked while this worker runs reaches the picture when the session
1311 /// reseeks onto the new one. An SDR source ignores it entirely.
1312 pub(crate) fn open_worker(
1313 path: impl AsRef<Path>,
1314 start_frame: u32,
1315 end_frame: u32,
1316 color: ColorParams,
1317 transform: TransformParams,
1318 canvas: Composer,
1319 tone: tonemap::Preset,
1320 ) -> crate::Result<(VideoMeta, FrameStream)> {
1321 Self::open_worker_with(path, start_frame, end_frame, color, transform, canvas, tone, Default::default())
1322 }
1323
1324 /// [`open_worker`](Self::open_worker) for a clip with a deinterlace setting:
1325 /// with `Field` over an interlaced file `start_frame` and `end_frame` are field
1326 /// numbers, and the range is capped at twice the file's frame count.
1327 #[allow(clippy::too_many_arguments)]
1328 pub(crate) fn open_worker_with(
1329 path: impl AsRef<Path>,
1330 start_frame: u32,
1331 end_frame: u32,
1332 color: ColorParams,
1333 transform: TransformParams,
1334 canvas: Composer,
1335 tone: tonemap::Preset,
1336 deint: crate::project::Deinterlace,
1337 ) -> crate::Result<(VideoMeta, FrameStream)> {
1338 let path = path.as_ref().to_path_buf();
1339 // A still is not a stream: handing one to the mp4 demuxer answers "a
1340 // box with a larger size than it", which is a true sentence about a
1341 // container and nothing a person can act on -- and it made this door,
1342 // the one a front-end opens a file through, refuse every picture
1343 // outright. The still door answers with a meta of its own, so a poster
1344 // thumbnail and a preview window get the same picture the timeline
1345 // does, at the same size. No `tone` argument is passed on and none is
1346 // wanted: a still is decoded into BT.601 SDR planes, so there is no
1347 // map to build whichever rendition the project is watching.
1348 if crate::is_image(&path) {
1349 let still = Still::open(&path)?;
1350 let meta = VideoMeta {
1351 width: still.width,
1352 height: still.height,
1353 frame_rate: 1.0,
1354 frame_count: 1,
1355 codec: Codec::H264,
1356 color: ColorDescription::default(),
1357 matrix_assumed: false,
1358 // A still's own turn was made in `Still::open`, before these
1359 // planes were written, so there is nothing left to state here.
1360 rotation: Rotation::None,
1361 coded_width: still.width,
1362 coded_height: still.height,
1363 pixel_aspect: PixelAspect::SQUARE,
1364 };
1365 return Self::open_still(&path, start_frame, 1, color, transform, canvas)
1366 .map(|stream| (meta, stream));
1367 }
1368 let (meta, mut demuxer) = Demuxer::open(&path)?;
1369 // Before any decoder is chosen: a stream whose parameter sets the parser
1370 // refuses is refused here, for hardware and software alike, because the
1371 // driver would otherwise open it and hand back no picture.
1372 if meta.codec == Codec::Hevc && !demuxer.hevc_parameter_sets_parse() {
1373 return Err(Codec::Hevc.undecodable().into());
1374 }
1375 let deint = effective_deint(deint, &meta, &demuxer);
1376 let end_frame = end_frame.min(crate::deinterlace::counted_frames(deint, &path, meta.frame_count));
1377 if end_frame <= start_frame {
1378 // Nothing to decode: a disconnected receiver and no thread at all,
1379 // so the caller sees an immediate end of stream rather than an error.
1380 let (_, rx) = sync_channel(1);
1381 return Ok((
1382 meta,
1383 FrameStream {
1384 frames: rx,
1385 worker: Worker {
1386 cancel: Arc::new(AtomicBool::new(false)),
1387 handle: None,
1388 reuse: None,
1389 },
1390 backend: BackendCell::default(),
1391 failure: DecodeFailure::default(),
1392 },
1393 ));
1394 }
1395 Ok((
1396 meta,
1397 span_worker(
1398 path,
1399 Some((demuxer, meta)),
1400 start_frame,
1401 end_frame,
1402 color,
1403 transform,
1404 canvas,
1405 tone,
1406 // A file-level open has no clip and no speed to skip frames
1407 // for: every picture in range is delivered, as it always was.
1408 Speed::NORMAL,
1409 deint,
1410 ),
1411 ))
1412 }
1413
1414 /// As [`open_worker`](Self::open_worker), but the *file* is opened on the
1415 /// worker too: nothing here touches the disk, so the caller pays a thread
1416 /// spawn and not a demux -- 550-750 ms warm on a 25 GB film, seconds cold,
1417 /// which is what a seek or a clip boundary used to cost the UI thread.
1418 ///
1419 /// The price is that there is no [`VideoMeta`] to return and no synchronous
1420 /// refusal either: a file that will not open, and a codec no decoder here
1421 /// takes (the plugin probe is skipped -- the worker's own refusal below
1422 /// covers it), simply drop the sender. The disconnected receiver is what
1423 /// carries a session on to the next span, which is exactly what a failed
1424 /// open did on this path before. Callers that must *tell* the user why --
1425 /// an import at the door -- keep the sync opener.
1426 #[allow(clippy::too_many_arguments)]
1427 #[allow(dead_code, reason = "the playback session calls open_worker_deferred_with once the lane's playback.rs hunk is in")]
1428 pub(crate) fn open_worker_deferred(
1429 path: impl AsRef<Path>,
1430 start_frame: u32,
1431 end_frame: u32,
1432 color: ColorParams,
1433 transform: TransformParams,
1434 canvas: Composer,
1435 tone: tonemap::Preset,
1436 speed: Speed,
1437 ) -> FrameStream {
1438 Self::open_worker_deferred_with(path, start_frame, end_frame, color, transform, canvas, tone, speed, Default::default())
1439 }
1440
1441 /// [`open_worker_deferred`](Self::open_worker_deferred) for a clip with a
1442 /// deinterlace setting (see [`open_worker_with`](Self::open_worker_with)).
1443 #[allow(clippy::too_many_arguments)]
1444 pub(crate) fn open_worker_deferred_with(
1445 path: impl AsRef<Path>,
1446 start_frame: u32,
1447 end_frame: u32,
1448 color: ColorParams,
1449 transform: TransformParams,
1450 canvas: Composer,
1451 tone: tonemap::Preset,
1452 speed: Speed,
1453 deint: crate::project::Deinterlace,
1454 ) -> FrameStream {
1455 span_worker(
1456 path.as_ref().to_path_buf(),
1457 None,
1458 start_frame,
1459 end_frame,
1460 color,
1461 transform,
1462 canvas,
1463 tone,
1464 speed,
1465 deint,
1466 )
1467 }
1468}
1469
1470/// Spawns a decode worker over `path` and gives it its first span. The thread
1471/// **outlives that span**: it parks on its command channel afterwards, so the
1472/// next seek onto the same file reaches it through [`Worker::reseek`] and costs
1473/// a demuxer seek and a decoder flush instead of a thread, a container parse and
1474/// a VA-API initialisation (98 ms measured worst case).
1475///
1476/// `opened` is the demuxer when the caller already read the file (the sync opener,
1477/// which demuxes on the caller's thread to have metadata to return); `None` is the
1478/// deferred one, where the worker opens it and nothing here touches the disk.
1479/// The [`Source`] itself is built on the worker, so the hardware session it may
1480/// hold never crosses a thread boundary.
1481#[allow(clippy::too_many_arguments)]
1482fn span_worker(
1483 path: PathBuf,
1484 opened: Option<(Demuxer, VideoMeta)>,
1485 start_frame: u32,
1486 end_frame: u32,
1487 color: ColorParams,
1488 transform: TransformParams,
1489 canvas: Composer,
1490 tone: tonemap::Preset,
1491 speed: Speed,
1492 deint: crate::project::Deinterlace,
1493) -> FrameStream {
1494 // The depth is the size of the pictures this worker will *emit*, which for a
1495 // pass-through canvas is the stream's own -- and the sync opener has already
1496 // read that on the caller's thread. Asking the canvas alone is how the file
1497 // door came up with 2: every session opens pass-through (a freshly opened
1498 // file *is* the project resolution), so a whole file would play at the
1499 // decode-ahead this engine had before there was one, until the first seek
1500 // built a real canvas.
1501 let depth = match (&opened, canvas.places_nothing()) {
1502 (Some((_, meta)), true) => crate::scale::queue_depth(meta.width, meta.height),
1503 _ => canvas.queue_depth(),
1504 };
1505 let (tx, rx) = sync_channel(depth);
1506 let cancel = Arc::new(AtomicBool::new(false));
1507 // Written by the worker the moment it knows, so a caller reading it sees
1508 // what opened rather than what was hoped for -- and kept across the spans
1509 // that follow, since they are decoded by that very decoder.
1510 let backend = BackendCell::default();
1511 // One cell for the whole worker, not one per span: the thread outlives its
1512 // spans (that is what a reseek costs nothing for), so the reason a span
1513 // failed has to outlive the span too, and be visible to whoever opened this
1514 // stream.
1515 let failure = DecodeFailure::default();
1516 let generation = Arc::new(AtomicU64::new(0));
1517 // The playhead starts where the span does: nothing is behind it yet.
1518 let floor = Arc::new(AtomicU32::new(start_frame));
1519 let (spans, commands) = std::sync::mpsc::channel();
1520 let first = SpanCmd {
1521 generation: 0,
1522 start: start_frame,
1523 end: end_frame,
1524 color,
1525 transform,
1526 canvas,
1527 tone,
1528 speed,
1529 deint,
1530 tx,
1531 };
1532 let worker_cancel = Arc::clone(&cancel);
1533 let worker_backend = backend.clone();
1534 let worker_failure = failure.clone();
1535 let worker_generation = Arc::clone(&generation);
1536 let worker_floor = Arc::clone(&floor);
1537 let worker_path = path.clone();
1538 let handle = thread::Builder::new()
1539 .name("decode".into())
1540 .spawn(move || {
1541 let mut source = opened.map(|(demuxer, meta)| Source::demuxed(demuxer, meta));
1542 let mut cmd = first;
1543 loop {
1544 let abort = Abort {
1545 cancel: &worker_cancel,
1546 generation: &worker_generation,
1547 mine: cmd.generation,
1548 floor: &worker_floor,
1549 };
1550 // Superseded (or cancelled) before this thread was even
1551 // scheduled: do not open the file, and do not enter VA-API
1552 // initialisation, which is the one stretch a cancel cannot
1553 // interrupt. A scrub abandons spans by the dozen and this is
1554 // where all but the last of them stop.
1555 if !abort.hit() {
1556 run_span(
1557 &worker_path,
1558 &mut source,
1559 cmd,
1560 &abort,
1561 &worker_backend,
1562 &worker_failure,
1563 );
1564 }
1565 // Parked between spans. A seek and a clip boundary arrive in
1566 // milliseconds and find the decoder still open, which is the
1567 // whole point of this thread -- but a session nobody comes back
1568 // to (the timeline played out, the window was left alone) must
1569 // not sit on the driver: it would hold a live libva thread into
1570 // whatever exit path the process takes, which is the SIGSEGV in
1571 // Mesa's `atexit` the retired pool exists to prevent, and
1572 // holding it *while idle* would widen that from "quit during a
1573 // decode" to "quit any time after opening a file".
1574 //
1575 // So the wait is in two halves: the fast one keeps everything,
1576 // and past [`IDLE`] the hardware session is closed. The demuxer
1577 // stays -- it is a file handle and an index, not driver state,
1578 // and rebuilding it is what costs seconds on a big Matroska --
1579 // so the reseek after a long pause pays one VA-API init and
1580 // nothing else.
1581 match commands.recv_timeout(IDLE) {
1582 Ok(next) => cmd = next,
1583 Err(RecvTimeoutError::Timeout) => {
1584 if let Some(source) = &mut source
1585 && source.hw.take().is_some()
1586 && std::env::var_os("EDITH_DEBUG").is_some()
1587 {
1588 eprintln!("decode worker idle: hardware session closed");
1589 }
1590 // The session dropped the command channel: this worker
1591 // is retired (or was detached), so the file goes now.
1592 match commands.recv() {
1593 Ok(next) => cmd = next,
1594 Err(_) => return,
1595 }
1596 }
1597 Err(RecvTimeoutError::Disconnected) => return,
1598 }
1599 }
1600 })
1601 .ok();
1602 FrameStream {
1603 frames: rx,
1604 worker: Worker {
1605 cancel,
1606 handle,
1607 reuse: Some(Reuse {
1608 path,
1609 spans,
1610 generation,
1611 backend: backend.clone(),
1612 floor,
1613 }),
1614 },
1615 backend,
1616 failure,
1617 }
1618}
1619
1620/// How long a parked worker keeps its hardware session before closing it. Long
1621/// enough that a seek, a scrub step and a clip boundary all find the decoder
1622/// where they left it -- and long enough for the think-time between two
1623/// samples of a live slider drag (a colour or transform card nudge), which
1624/// reseeks the very same worker and paid the *closed* half of this window
1625/// every time a person paused a beat to look before nudging again: a session
1626/// found the hardware gone and rebuilt it (measured seconds on a big file)
1627/// for what should have cost one `hw.seek`. Short enough that a session left
1628/// alone for real (the window switched away from, a scrub that stopped) is
1629/// not holding libva when the process exits.
1630const IDLE: std::time::Duration = std::time::Duration::from_secs(8);
1631
1632/// How many pictures in a row a worker may drop for being late before it hands
1633/// one over regardless. The policy needs a floor of its own: a machine that
1634/// cannot decode a file in real time is late on *every* picture, and dropping
1635/// every picture is a black screen rather than a stutter -- so the slowest seat
1636/// still gets one in nine, which is roughly what it could paint before (the
1637/// front-end restarted the decoder once every two seconds to the same effect,
1638/// and paid a VA-API init for each restart).
1639const LATE_RUN: u32 = 8;
1640
1641/// What a decode worker keeps **between** the spans it is asked for: the
1642/// container it read, what the stream says about itself, and the hardware
1643/// session -- the three things a seek used to throw away and buy again.
1644struct Source {
1645 meta: VideoMeta,
1646 /// What the film says its brightest picture is ([`Demuxer::light`]): the
1647 /// tone map's assumed peak on the reference rendition, so a 1759 cd/m^2
1648 /// grade is converted at 1759 rather than at the 1000 a file that declared
1649 /// nothing is assumed at. A property of the stream, read once with it.
1650 peak: Option<f32>,
1651 demuxer: Demuxer,
1652 /// The plugin's session, opened on this thread (its VA-API state is not
1653 /// `Send`-safe across a hand-off) and *kept*. `None` for software: forced by
1654 /// `VE_SW`, refused by the plugin, or handed back by a session that opened
1655 /// and then decoded nothing.
1656 hw: Option<HwSession>,
1657}
1658
1659impl Source {
1660 /// The file as the sync opener already read it.
1661 fn demuxed(demuxer: Demuxer, meta: VideoMeta) -> Self {
1662 Self {
1663 meta,
1664 peak: demuxer.light().peak(),
1665 demuxer,
1666 hw: None,
1667 }
1668 }
1669
1670 /// ...and as the deferred opener reads it, on the worker. `None` is a file
1671 /// that would not open: the caller drops the sender, and the disconnected
1672 /// receiver is the session's "walk on to the next span".
1673 fn open(path: &Path) -> Option<Self> {
1674 match Demuxer::open(path) {
1675 Ok((meta, demuxer)) => Some(Self::demuxed(demuxer, meta)),
1676 Err(e) => {
1677 eprintln!("video open failed: {e}");
1678 None
1679 }
1680 }
1681 }
1682
1683 /// Puts the hardware decoder at `start`, keeping the session open where the
1684 /// plugin can reposition it. `None` when there is no hardware here at all;
1685 /// otherwise whether the session was **reused** -- which is what lets the
1686 /// caller tell a driver that cannot decode this stream from one that merely
1687 /// did not follow a reseek.
1688 fn position_hw(&mut self, path: &Path, start: u32) -> Option<bool> {
1689 if let Some(hw) = &mut self.hw {
1690 if hw.seek(start) {
1691 if std::env::var_os("EDITH_DEBUG").is_some() {
1692 eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})");
1693 }
1694 return Some(true);
1695 }
1696 // A plugin too old to reposition, or a decoder that would not
1697 // flush: closed and opened again, which is what every seek did.
1698 self.hw = None;
1699 }
1700 self.hw = open_hw(path, start);
1701 self.hw.as_ref().map(|_| {
1702 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("decode backend: hardware (VA-API plugin)"); }
1703 false
1704 })
1705 }
1706}
1707
1708/// One span on a worker's thread: position the decoder, decode
1709/// `[start, end)`, send the pictures. Every opener ends here -- the sync one,
1710/// which demuxed on the caller's thread, the deferred one, which demuxes on
1711/// this one, and every reseek after them -- so there is exactly one description
1712/// of what a decode worker does.
1713fn run_span(
1714 path: &Path,
1715 source: &mut Option<Source>,
1716 cmd: SpanCmd,
1717 abort: &Abort,
1718 backend: &BackendCell,
1719 worker_failure: &DecodeFailure,
1720) {
1721 let SpanCmd {
1722 start,
1723 end,
1724 color,
1725 transform,
1726 canvas,
1727 tone,
1728 speed,
1729 deint,
1730 tx,
1731 ..
1732 } = cmd;
1733 // Where the software seat starts: `start`, unless hardware dies mid-span and
1734 // hands the rest over from the picture it failed on.
1735 let mut start = start;
1736 // A span is a fresh question, so it starts from a clean answer: the
1737 // failure that stopped the span before this one was already reported, and
1738 // carrying it would keep saying a fault that this range may not have. Only
1739 // a span that is actually going to run clears it -- a span superseded on its
1740 // way through the queue decoded nothing and has nothing to say.
1741 worker_failure.clear();
1742 let opened = match source {
1743 Some(opened) => opened,
1744 None => {
1745 let Some(fresh) = Source::open(path) else {
1746 backend.set(Backend::Gap);
1747 worker_failure.set(format!(
1748 "{}: could not be opened for decoding",
1749 path.display()
1750 ));
1751 return;
1752 };
1753 source.insert(fresh)
1754 }
1755 };
1756 // The clamp the sync opener does with the metadata it read on the caller's
1757 // thread; here the metadata arrives first.
1758 let deint = effective_deint(deint, &opened.meta, &opened.demuxer);
1759 let end = match opened.demuxer.path() {
1760 Some(path) => end.min(crate::deinterlace::counted_frames(deint, path, opened.meta.frame_count)),
1761 None => end.min(opened.meta.frame_count * deint_units(deint)),
1762 };
1763 // An empty range decodes nothing and must send nothing: `run_hw` counts a
1764 // frame *out* before it compares, so without this a zero-length span would
1765 // emit one picture.
1766 if end <= start {
1767 return;
1768 }
1769 // The stream's own colour and peak brightness: properties of the stream, so
1770 // neither can change while one range decodes -- but the grade, the canvas
1771 // and the rendition are the *span's*, so this is built per span.
1772 let mut render = Render::new(
1773 color,
1774 transform,
1775 opened.meta.rotation,
1776 opened.meta.pixel_aspect,
1777 opened.meta.color,
1778 canvas,
1779 tone,
1780 opened.peak,
1781 );
1782 if let Some(reused) = opened.position_hw(path, start) {
1783 // Cancelled during the init (or the seek): leave without decoding.
1784 if abort.hit() {
1785 return;
1786 }
1787 backend.set(Backend::Hardware);
1788 let mut ended = run_hw(
1789 opened.hw.as_mut().expect("positioned above"),
1790 Pass {
1791 tx: &tx,
1792 start_frame: start,
1793 end_frame: end,
1794 render: &mut render,
1795 abort,
1796 speed,
1797 failure: worker_failure,
1798 deint,
1799 },
1800 );
1801 // A *reused* session that produced nothing may simply be one this
1802 // reseek left where the driver would not follow; a session opened fresh
1803 // at the same frame is the honest second question, and only its silence
1804 // is a software fallback. Without this a single unfollowed seek would
1805 // collapse the rest of the file to software.
1806 if ended == HwEnd::Refused && reused {
1807 eprintln!(
1808 "hardware decode produced nothing after a reseek; reopening at frame {start}"
1809 );
1810 opened.hw = open_hw(path, start);
1811 if let Some(hw) = opened.hw.as_mut() {
1812 ended = run_hw(
1813 hw,
1814 Pass {
1815 tx: &tx,
1816 start_frame: start,
1817 end_frame: end,
1818 render: &mut render,
1819 abort,
1820 speed,
1821 failure: worker_failure,
1822 deint,
1823 },
1824 );
1825 }
1826 }
1827 match ended {
1828 HwEnd::Done => return,
1829 // A driver that opens but cannot decode a single frame is still a
1830 // fallback case, not a dead session.
1831 HwEnd::Refused => {
1832 opened.hw = None;
1833 if std::env::var_os("EDITH_DEBUG").is_some() {
1834 eprintln!("hardware decode failed before any frame, falling back to software");
1835 }
1836 }
1837 // The GPU failed part-way (a hung ring, a reset context): the
1838 // pictures before `index` are out, and the software seat is put at
1839 // `index` below, so the span carries on as a software decode would
1840 // have. The session is dropped -- its context is gone.
1841 HwEnd::FellBackAt(index) => {
1842 opened.hw = None;
1843 start = index;
1844 }
1845 }
1846 }
1847 // ...and every codec has one to fall back to: H.264, HEVC, AV1, VP9 and VP8
1848 // each have one of this project's own here (`ec-h264`, `ec-h265`, `ec-av1`,
1849 // `ec-vp9`, `ec-vp8`), so no stream reaches a seat it cannot decode.
1850 match opened.meta.codec {
1851 Codec::H264 => {
1852 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("decode backend: software (ec-h264)"); }
1853 backend.set(Backend::Software);
1854 run(
1855 &mut opened.demuxer,
1856 Pass {
1857 tx: &tx,
1858 start_frame: start,
1859 end_frame: end,
1860 render: &mut render,
1861 abort,
1862 speed,
1863 failure: worker_failure,
1864 deint,
1865 },
1866 );
1867 }
1868 Codec::Av1 => {
1869 if std::env::var_os("EDITH_DEBUG").is_some() { eprintln!("decode backend: software (ec-av1)"); }
1870 backend.set(Backend::Software);
1871 run_av1(
1872 &mut opened.demuxer,
1873 Pass {
1874 tx: &tx,
1875 start_frame: start,
1876 end_frame: end,
1877 render: &mut render,
1878 abort,
1879 speed,
1880 failure: worker_failure,
1881 deint,
1882 },
1883 );
1884 }
1885 Codec::Vp9 => {
1886 eprintln!("decode backend: software (ec-vp9)");
1887 backend.set(Backend::Software);
1888 run_vp9(
1889 &mut opened.demuxer,
1890 &tx,
1891 start,
1892 end,
1893 &mut render,
1894 abort,
1895 speed,
1896 worker_failure,
1897 );
1898 }
1899 Codec::Vp8 => {
1900 eprintln!("decode backend: software (ec-vp8)");
1901 backend.set(Backend::Software);
1902 run_vp8(
1903 &mut opened.demuxer,
1904 &tx,
1905 start,
1906 end,
1907 &mut render,
1908 abort,
1909 speed,
1910 worker_failure,
1911 );
1912 }
1913 Codec::ProRes => {
1914 eprintln!("decode backend: software (ec-prores)");
1915 backend.set(Backend::Software);
1916 intra::run::<prores::ProResSeat>(
1917 &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure,
1918 );
1919 }
1920 Codec::Dnxhd => {
1921 eprintln!("decode backend: software (ec-dnxhd)");
1922 backend.set(Backend::Software);
1923 intra::run::<dnxhd::DnxhdSeat>(
1924 &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure,
1925 );
1926 }
1927 Codec::Mjpeg => {
1928 eprintln!("decode backend: software (ec-mjpeg)");
1929 backend.set(Backend::Software);
1930 intra::run::<mjpeg::MjpegSeat>(
1931 &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure,
1932 );
1933 }
1934 Codec::Dv => {
1935 eprintln!("decode backend: software (ec-dv)");
1936 backend.set(Backend::Software);
1937 intra::run::<dv::DvSeat>(
1938 &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure,
1939 );
1940 }
1941 Codec::Raw => {
1942 eprintln!("decode backend: software (raw video)");
1943 backend.set(Backend::Software);
1944 intra::run::<raw::RawSeat>(
1945 &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure,
1946 );
1947 }
1948 Codec::Mpeg4 | Codec::MsMpeg4 => {
1949 eprintln!("decode backend: software (ec-mpeg4)");
1950 backend.set(Backend::Software);
1951 run_mpeg4(
1952 &mut opened.demuxer, &tx, start, end, &mut render, abort, speed, worker_failure,
1953 );
1954 }
1955 Codec::Mpeg2 => {
1956 eprintln!("decode backend: software (ec-mpeg2)");
1957 backend.set(Backend::Software);
1958 run_mpeg2(
1959 &mut opened.demuxer,
1960 &tx,
1961 start,
1962 end,
1963 &mut render,
1964 abort,
1965 speed,
1966 worker_failure,
1967 deint,
1968 );
1969 }
1970 Codec::Hevc => {
1971 eprintln!("decode backend: software (ec-h265)");
1972 backend.set(Backend::Software);
1973 run_hevc(
1974 &mut opened.demuxer,
1975 &tx,
1976 start,
1977 end,
1978 &mut render,
1979 abort,
1980 speed,
1981 worker_failure,
1982 );
1983 }
1984 }
1985}
1986
1987/// One clip's pictures on their way to the renderer: graded, placed on the
1988/// project canvas, converted. Both decode loops go through it, so hardware and
1989/// software cannot show two different pictures.
1990///
1991/// The order is grade, then place (see [`Composer`]): a grade is the clip's own,
1992/// applied at the resolution it was shot at, and the letterbox bars around it
1993/// are not the clip -- a brightness grade must not lift them off black.
1994///
1995/// A project at the media's own resolution never reaches any of that: it takes
1996/// the fused graded conversion, the one path this engine had before there was a
1997/// project resolution, byte for byte and allocation for allocation.
1998pub(crate) struct Render {
1999 color: ColorParams,
2000 /// This clip's placement, on top of whatever the canvas's own fit policy
2001 /// already does ([`crate::scale::Composer::place_transformed`]).
2002 transform: TransformParams,
2003 /// How far the *file* asks its picture to be turned before anything else
2004 /// happens to it ([`crate::demux::Rotation`]): the phone-portrait turn,
2005 /// made here so the grade, the canvas and the preview's own renderer all
2006 /// see the picture the way it is meant to be seen. [`Rotation::None`] for
2007 /// every file that states no turn, which is the whole of an ordinary
2008 /// library.
2009 rotation: Rotation,
2010 /// The ratio one coded pixel is drawn at ([`crate::demux::PixelAspect`]):
2011 /// the file's sample aspect ratio, applied exactly once, at this one
2012 /// conversion to the square-pixel raster -- the same place ffmpeg's swscale
2013 /// applies it, and nowhere else. Square for every file that states no
2014 /// aspect, which takes the branch by a bool and touches no byte.
2015 pixel_aspect: PixelAspect,
2016 /// What the source's samples mean -- the stream's own matrix and range,
2017 /// which is what the conversion below is done in rather than the BT.601 it
2018 /// used to assume of every file.
2019 desc: ColorDescription,
2020 canvas: Composer,
2021 /// This stream's HDR-to-SDR map, built once here because building it is
2022 /// float work over 9 537 grid nodes and the transfer is a property of the
2023 /// stream. `None` for an SDR stream, which is what keeps that path exactly
2024 /// the one it was.
2025 tone: Option<ToneMapper>,
2026 /// The working copy of the source planes, refilled per frame and kept
2027 /// across the worker's whole range. Empty unless the clip needs one: it is
2028 /// tone-mapped in place, graded in place, or both.
2029 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
2030 /// The same, for the display-matrix turn above: empty for every file that
2031 /// asks for none, and resized once for one that does -- a steady-state
2032 /// buffer rather than three plane allocations per decoded frame.
2033 turned: (Vec<u8>, Vec<u8>, Vec<u8>),
2034 /// The same, for the pixel-aspect stretch: the coded picture widened to
2035 /// the displayed width, empty for every square-pixel file and sized once
2036 /// for one that is not.
2037 stretched: (Vec<u8>, Vec<u8>, Vec<u8>),
2038 /// Where [`Composer::place_transformed`]'s owned picture lands, so a
2039 /// transformed frame's planes live as long as `self` -- matching what
2040 /// [`Composer::place`] already hands back by borrowing `self.canvas`.
2041 placed: (Vec<u8>, Vec<u8>, Vec<u8>),
2042}
2043
2044/// What [`Render::frame`] converts a tone-mapped picture in: the tone map's
2045/// output contract ([`crate::tonemap`]), and no longer the HDR space the file
2046/// declared.
2047const TONE_MAPPED: ColorDescription = ColorDescription {
2048 matrix: Matrix::Bt709,
2049 transfer: Transfer::Sdr,
2050 full_range: false,
2051};
2052
2053impl Render {
2054 /// `peak` is what the file declared about its own brightness
2055 /// ([`Demuxer::light`]), which only an HDR stream has and only the
2056 /// reference rendition reads (see [`tonemap::Preset`]).
2057 #[allow(
2058 clippy::too_many_arguments,
2059 reason = "one argument per field, passed straight through at its three construction sites"
2060 )]
2061 fn new(
2062 color: ColorParams,
2063 transform: TransformParams,
2064 rotation: Rotation,
2065 pixel_aspect: PixelAspect,
2066 desc: ColorDescription,
2067 canvas: Composer,
2068 preset: tonemap::Preset,
2069 peak: Option<f32>,
2070 ) -> Self {
2071 Self {
2072 color,
2073 transform,
2074 rotation,
2075 pixel_aspect,
2076 desc,
2077 canvas,
2078 // corner-cut: the ceiling is that the map reads limited-range codes
2079 // (`tonemap`'s input contract), so a full-range PQ file -- which
2080 // no encoder writes and no camera produces -- is mapped as if it
2081 // were limited and comes out slightly crushed. The upgrade is a
2082 // range argument to `ToneMapper::new`.
2083 tone: match desc.transfer {
2084 Transfer::Sdr => None,
2085 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, peak)),
2086 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)),
2087 },
2088 graded: (Vec::new(), Vec::new(), Vec::new()),
2089 turned: (Vec::new(), Vec::new(), Vec::new()),
2090 stretched: (Vec::new(), Vec::new(), Vec::new()),
2091 placed: (Vec::new(), Vec::new(), Vec::new()),
2092 }
2093 }
2094
2095 pub(crate) fn frame(
2096 &mut self,
2097 index: u32,
2098 y: &[u8],
2099 u: &[u8],
2100 v: &[u8],
2101 width: u32,
2102 height: u32,
2103 ) -> Frame {
2104 // The pixel aspect, applied exactly once -- the single conversion to
2105 // the square-pixel raster this engine makes, where ffmpeg's swscale
2106 // makes its own -- *before* the display-matrix turn. The ratio belongs
2107 // to the axis that was horizontal before the turn: the coded width is
2108 // stretched by h/v and the turn then swaps the stretched pair, which
2109 // is the composition the probe declares (a 1440x1080 SAR-4/3 file
2110 // turned 90° displays 1080x1920, DAR 9:16). Stretching after the turn
2111 // instead lands the ratio on the coded height and renders a
2112 // 1440x1440 square into a 9:16 canvas -- letterboxed, and the bars
2113 // baked into any export. Only a file whose samples are not square
2114 // reaches the resample: a square one takes the branch by a bool and
2115 // not one byte is touched, which is what keeps every existing picture
2116 // identical to the day before anamorphic sources existed.
2117 let (y, u, v, width, height) = if self.pixel_aspect.is_square() {
2118 (y, u, v, width, height)
2119 } else {
2120 // The aspect widens the *width*, always: 4:3 SAR over 1440x1080
2121 // shows 1920x1080. `width_factor` lands on the even grid 4:2:0
2122 // composes on, and a height is never touched by it.
2123 let display_width = self.pixel_aspect.width_factor(width);
2124 let (sy, su, sv) = &mut self.stretched;
2125 // Sized for `scale_i420`'s exact-planes assertion, once for the
2126 // worker's whole range: steady-state buffers, not per-frame
2127 // allocations ([`turned`]'s reason).
2128 let (dcw, dch) = (
2129 display_width.div_ceil(2) as usize,
2130 height.div_ceil(2) as usize,
2131 );
2132 sy.resize(display_width as usize * height as usize, 0);
2133 su.resize(dcw * dch, 0);
2134 sv.resize(dcw * dch, 0);
2135 crate::scale::scale_i420(
2136 y,
2137 u,
2138 v,
2139 width as usize,
2140 height as usize,
2141 sy,
2142 su,
2143 sv,
2144 display_width as usize,
2145 height as usize,
2146 );
2147 (
2148 &sy[..display_width as usize * height as usize],
2149 &su[..display_width.div_ceil(2) as usize * height.div_ceil(2) as usize],
2150 &sv[..display_width.div_ceil(2) as usize * height.div_ceil(2) as usize],
2151 display_width,
2152 height,
2153 )
2154 };
2155 // The file's own turn, after the stretch: a phone's portrait video
2156 // arrives as landscape planes, and the grade, the canvas and the
2157 // conversion below all have to see the picture the way it is meant to
2158 // be seen. Nothing here at all for the ordinary file that states no
2159 // turn -- `Rotation::None` takes the planes by reference and not one
2160 // byte is copied.
2161 let (y, u, v, width, height) = match self.rotation.is_none() {
2162 true => (y, u, v, width, height),
2163 false => {
2164 let steps = self.rotation.steps();
2165 let (rw, rh) = crate::scale::rotate_i420_90s_into(
2166 y,
2167 u,
2168 v,
2169 width,
2170 height,
2171 steps,
2172 &mut self.turned,
2173 );
2174 (
2175 &self.turned.0[..],
2176 &self.turned.1[..],
2177 &self.turned.2[..],
2178 rw,
2179 rh,
2180 )
2181 }
2182 };
2183 let passthrough = self.canvas.is_passthrough(width, height);
2184 // A transform still has a picture to place even where the canvas
2185 // itself would hand this size back untouched -- moving, scaling,
2186 // rotating or cropping a passthrough-sized clip is still a placement,
2187 // and must not be silently dropped by the fused conversion below.
2188 let transform_active = !self.transform.is_identity();
2189 let skip_placement = passthrough && !transform_active;
2190 // Everything that has to happen to the samples before the canvas sees
2191 // them, on one copy: the tone map (HDR streams only) and, unless the
2192 // conversion below can fuse it, the grade. An SDR stream that is either
2193 // ungraded or passing through takes neither and never allocates.
2194 //
2195 // The grade lands *after* the map on purpose: it is a look on the
2196 // picture a viewer is shown, so its brightness and saturation mean what
2197 // they say in the SDR the tone map just produced, not in the 10-stop
2198 // HDR the file was in.
2199 let (y, u, v, desc) =
2200 if self.tone.is_some() || (!skip_placement && !self.color.is_identity()) {
2201 let (gy, gu, gv) = &mut self.graded;
2202 gy.clear();
2203 gy.extend_from_slice(y);
2204 gu.clear();
2205 gu.extend_from_slice(u);
2206 gv.clear();
2207 gv.extend_from_slice(v);
2208 if let Some(tone) = &self.tone {
2209 tone.map(gy, gu, gv, width as usize, height as usize);
2210 }
2211 // The same terms the branch was entered on: anywhere the fused
2212 // conversion below will not apply the grade (a placement is
2213 // happening, so the canvas conversion is plain), it lands here --
2214 // including the passthrough-sized clip a transform moves, whose
2215 // grade used to be dropped on the floor between these two guards.
2216 if !skip_placement && !self.color.is_identity() {
2217 crate::color::apply_yuv(&self.color, gy, gu, gv, width as usize, self.tone.is_none() && self.desc.full_range);
2218 }
2219 let desc = if self.tone.is_some() {
2220 TONE_MAPPED
2221 } else {
2222 self.desc
2223 };
2224 (&gy[..], &gu[..], &gv[..], desc)
2225 } else {
2226 (y, u, v, self.desc)
2227 };
2228 if skip_placement {
2229 return Frame {
2230 index,
2231 width,
2232 height,
2233 bgra: i420_to_bgra_with(
2234 &desc,
2235 &self.color,
2236 y,
2237 u,
2238 v,
2239 width as usize,
2240 height as usize,
2241 ),
2242 };
2243 }
2244 let (y, u, v, width, height) = if transform_active {
2245 let (py, pu, pv, w, h) =
2246 self.canvas
2247 .place_transformed(y, u, v, width, height, &self.transform);
2248 self.placed = (py, pu, pv);
2249 (
2250 &self.placed.0[..],
2251 &self.placed.1[..],
2252 &self.placed.2[..],
2253 w,
2254 h,
2255 )
2256 } else {
2257 self.canvas.place(y, u, v, width, height)
2258 };
2259 Frame {
2260 index,
2261 width,
2262 height,
2263 // Ungraded on purpose: the grade is already in the pixels above and
2264 // the canvas around them must stay the black it was filled with.
2265 bgra: i420_to_bgra(&desc, y, u, v, width as usize, height as usize),
2266 }
2267 }
2268}
2269
2270/// One still image, decoded to tightly packed I420 -- the shape every other
2271/// source arrives in, so a placed image goes through the same grade, the same
2272/// canvas and the same conversion as a decoded picture and there is no second
2273/// pixel path to keep in step.
2274///
2275/// Held whole rather than streamed: an image *is* one picture, and the file is
2276/// read once per span that plays it.
2277pub(crate) struct Still {
2278 pub(crate) y: Vec<u8>,
2279 pub(crate) u: Vec<u8>,
2280 pub(crate) v: Vec<u8>,
2281 /// The picture as it is *shown*, which for a phone's portrait photo is not
2282 /// the picture as it was stored: the turn its EXIF block asks for was made
2283 /// in [`Still::open`] before these planes were written, exactly where the
2284 /// video doors make a display matrix, so the pair every reader takes is
2285 /// the displayed one ([`crate::demux::Rotation`]'s own contract).
2286 pub(crate) width: u32,
2287 pub(crate) height: u32,
2288 /// An animated generator ([`crate::generate`]) and the source frame its next picture is.
2289 /// `None` for a file and for a generator that is the same on every frame.
2290 anim: Option<(crate::generate::Gen, u32)>,
2291 /// A numbered run ([`crate::sequence`]): the frame the planes hold, read again for each
2292 /// picture that follows. `None` for a file and for a generator.
2293 seq: Option<SeqCursor>,
2294}
2295
2296/// Where a [`Still`] read from a numbered run is: the run, and which of its frames the planes
2297/// hold. `handed` is set once the planes have been handed out, so the next call moves on.
2298#[derive(Debug, Clone)]
2299pub(crate) struct SeqCursor {
2300 run: crate::sequence::Run,
2301 at: u32,
2302 handed: bool,
2303}
2304
2305/// A still whose EXIF orientation is not a quarter turn: values 2, 4, 5 and 7
2306/// are mirrorings, and this engine has no flip anywhere in its pipeline -- not
2307/// in [`crate::scale::rotate_i420_90s`], not in [`Render`], not in an export's
2308/// `place_picture`. Refused **by name** at the door, for
2309/// [`crate::demux::UnsupportedRotation`]'s reason: showing a mirrored photo the
2310/// wrong way round is a wrong picture rather than a missing feature, and
2311/// quietly treating a mirror as a turn is exactly the bug this door exists to
2312/// stop. The `Display` is what a user is refused by.
2313#[derive(Debug)]
2314pub struct UnsupportedStillOrientation {
2315 /// The EXIF value the file states, which is what the sentence names: the
2316 /// eight legal values are 1 (upright) through 8, and the four mirrorings
2317 /// are the even-odd pairs.
2318 pub exif: u8,
2319}
2320
2321impl std::fmt::Display for UnsupportedStillOrientation {
2322 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2323 write!(
2324 f,
2325 "this picture's EXIF orientation is {}, which is a mirror and not a turn; only \
2326 upright, 90°, 180° and 270° can be straightened here",
2327 self.exif
2328 )
2329 }
2330}
2331
2332impl std::error::Error for UnsupportedStillOrientation {}
2333
2334impl UnsupportedStillOrientation {
2335 /// Whether `error` is one of these, however deep in a `Box` it is --
2336 /// [`crate::demux::UnsupportedRotation::is_it`]'s twin.
2337 pub fn is_it(error: &crate::Error) -> bool {
2338 error.downcast_ref::<Self>().is_some()
2339 }
2340}
2341
2342/// The quarter turns an EXIF orientation asks for, as the one
2343/// [`Rotation`] every other door in this engine already uses -- no second
2344/// shape mechanism for a still, so the same turn is made by the same code
2345/// that makes a video's display matrix turn.
2346///
2347/// EXIF 1, 6, 8 and 3 are the four quarter turns; **2, 4, 5 and 7 are
2348/// mirrorings** and are refused ([`UnsupportedStillOrientation`]) rather than
2349/// approximated by the nearest rotation. Any other value (0, or above 8) is
2350/// not a legal orientation and reads as upright, as `ec_image` reports it.
2351fn rotation_of_exif(orientation: u8) -> crate::Result<Rotation> {
2352 Ok(match orientation {
2353 6 => Rotation::Cw90,
2354 3 => Rotation::Cw180,
2355 8 => Rotation::Cw270,
2356 // A mirror is refused by its own EXIF number, so the sentence names
2357 // what the file says rather than a guess at the nearest turn.
2358 2 | 4 | 5 | 7 => {
2359 return Err(UnsupportedStillOrientation { exif: orientation }.into());
2360 }
2361 _ => Rotation::None,
2362 })
2363}
2364
2365/// The header of the picture at `path`, read through the first
2366/// [`ec_image::PROBE_LIMIT`] bytes and no further: no pixel is decoded, and
2367/// the file is never read whole. Shared by [`image_orientation`] and
2368/// [`image_size`] so a library row costs one bounded read.
2369fn probe_header(path: &Path) -> crate::Result<ec_image::Info> {
2370 // A numbered run's spelling is not a file: its size and turn are its first frame's.
2371 let path = crate::sequence::first_frame(path);
2372 let file = std::fs::File::open(&path)?;
2373 ec_image::probe_reader(file).map_err(|e| format!("{}: {e}", path.display()).into())
2374}
2375
2376/// What turn `path` asks for, read off its **header** alone -- what a library
2377/// row says about a file it has not placed anywhere, and what
2378/// [`image_size`] needs to report the size the picture is shown at.
2379///
2380/// Header-only on purpose: the whole file is not decoded, exactly as
2381/// [`image_size`] has always been. The probe reads the container's header
2382/// and EXIF block and stops; the pixels are never touched.
2383pub fn image_orientation(path: &Path) -> crate::Result<Rotation> {
2384 if crate::generate::is_generated(path) {
2385 return Ok(Rotation::None);
2386 }
2387 // The refusal is handed on **unchanged**, not folded into a sentence with
2388 // the file's name: a `String` is not an error a caller can downcast, and
2389 // `is_it` is how a front-end tells this refusal from any other failure.
2390 // The path is not lost -- every caller that has one puts it in front.
2391 rotation_of_exif(probe_header(path)?.orientation)
2392}
2393
2394impl Still {
2395 /// Decodes `path`. Refused by name for a picture that is not one
2396 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project
2397 /// file are both held to cannot be walked around by a 30000-pixel-wide PNG.
2398 ///
2399 /// Alpha is *dropped*, not composited: `to_rgb8` discards the channel, so a
2400 /// transparent PNG arrives fully opaque over its own colours rather than
2401 /// over the clip beneath it. I420 has nowhere to carry it and this engine
2402 /// composes one picture per frame (topmost lane wins), so there is nothing
2403 /// for a blend to blend with.
2404 ///
2405 /// corner-cut: the ceiling is a logo with a transparent background, which
2406 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and
2407 /// giving `scale::Composer` a blend over the lane below.
2408 pub(crate) fn open(path: &Path) -> crate::Result<Self> {
2409 Self::open_at(path, 0)
2410 }
2411
2412 /// [`Still::open`] for a span that starts at source frame `start`: only an animated
2413 /// generator ([`crate::generate::Gen::animated`]) cares, and then each [`Still::picture`]
2414 /// is the next frame of it.
2415 pub(crate) fn open_at(path: &Path, start: u32) -> crate::Result<Self> {
2416 if let Some(g) = crate::generate::Gen::parse(path) {
2417 let (y, u, v) = rgb_to_i420(&g.rgb(start), g.width as usize, g.height as usize);
2418 return Ok(Self { y, u, v, width: g.width, height: g.height, anim: g.animated().then_some((g, start)), seq: None });
2419 }
2420 // A numbered run opens at its frame `start`, and each later picture is the frame after it.
2421 let run = crate::sequence::Run::parse(path);
2422 let file = match &run {
2423 Some(run) => run.frame(start),
2424 None => path.to_path_buf(),
2425 };
2426 let path = file.as_path();
2427 // The turn is read and made **here**, once, before a single pair of
2428 // numbers leaves this function: `image`'s decoder keeps an EXIF
2429 // orientation in its own field and applies nothing, so a portrait
2430 // phone photo arrived as landscape planes and every consumer below --
2431 // the `Render`, the `VideoMeta`, `image_size` -- reported the shape the
2432 // camera stored rather than the one it was shot at. This is the same
2433 // step the video doors make, at the same place in the pipeline
2434 // (before the grade, the canvas and the conversion all see the
2435 // picture), and it uses the same [`Rotation`].
2436 // The turn comes from the same probe `image_size` makes, so a library
2437 // row and a placed still agree on what a picture's turn is.
2438 let rotation = image_orientation(path)?;
2439 let decoded = ec_image::open(path).map_err(|e| format!("{}: {e}", path.display()))?;
2440 let (coded_width, coded_height) = decoded.dimensions();
2441 // Turned here rather than left to each consumer, so there is exactly
2442 // one place the turn is made and no consumer can be forgotten: the
2443 // planes handed out below are the *shown* picture, so the `Render`, the
2444 // `VideoMeta`, an export's `place_picture` and `image_size` all agree
2445 // without any of them re-deriving it. A file that states no turn takes
2446 // the branch by a bool and not one byte is copied.
2447 let (width, height, rgb) = match rotation.is_none() {
2448 true => (coded_width, coded_height, decoded.to_rgb8()),
2449 false => turn_rgb(
2450 &decoded.to_rgb8(),
2451 coded_width,
2452 coded_height,
2453 rotation.steps(),
2454 )
2455 .map_err(|e| format!("{}: {e}", path.display()))?,
2456 };
2457 if !crate::is_resolution(width, height) {
2458 return Err(format!(
2459 "{} is {width}x{height}, which is not a picture this engine composes",
2460 path.display()
2461 )
2462 .into());
2463 }
2464 let (y, u, v) = rgb_to_i420(&rgb, width as usize, height as usize);
2465 Ok(Self {
2466 y,
2467 u,
2468 v,
2469 width,
2470 height,
2471 anim: None,
2472 seq: run.map(|run| SeqCursor { run, at: start, handed: false }),
2473 })
2474 }
2475
2476 /// The planes as an export's decoder hands them over, so a still and a
2477 /// decoded picture are the same value to `export::run` -- and, for a
2478 /// turned still, the same value in the only sense that matters: the turn
2479 /// is already in them, so an export places what the preview showed without
2480 /// being told a second time.
2481 pub(crate) fn picture(&mut self) -> (&[u8], &[u8], &[u8], u32, u32) {
2482 // A numbered run hands out its frames in turn, each one read now: a frame that will
2483 // not decode keeps the picture before it, so a run deleted under a playing clip holds
2484 // its last good frame instead of tearing the timeline down.
2485 if let Some(cur) = &mut self.seq {
2486 if cur.handed {
2487 let next = (cur.at + 1).min(cur.run.count - 1);
2488 if next != cur.at && let Ok(still) = Still::open_at(&cur.run.frame(next), 0) {
2489 (self.y, self.u, self.v, self.width, self.height) = (still.y, still.u, still.v, still.width, still.height);
2490 cur.at = next;
2491 }
2492 }
2493 cur.handed = true;
2494 }
2495 // An animated generator hands out its frames in turn: the one drawn at open first.
2496 if let Some((g, next)) = &mut self.anim {
2497 if *next > 0 || self.y.is_empty() {
2498 (self.y, self.u, self.v) = rgb_to_i420(&g.rgb(*next), self.width as usize, self.height as usize);
2499 }
2500 *next += 1;
2501 }
2502 (&self.y, &self.u, &self.v, self.width, self.height)
2503 }
2504}
2505
2506/// `steps` quarter turns clockwise over a packed RGB8 picture of `width` by
2507/// `height` -- the same direction and the same count
2508/// [`crate::scale::rotate_i420_90s`] takes, on the still's own buffer rather
2509/// than on its planes: a still is turned exactly once in its whole life, so
2510/// there is no steady-state cost to make the allocating call the one that
2511/// happens. Returns the turned picture's `(width, height, pixels)`.
2512fn turn_rgb(
2513 rgb: &[u8],
2514 width: u32,
2515 height: u32,
2516 steps: u8,
2517) -> Result<(u32, u32, Vec<u8>), ec_core::Error> {
2518 use ec_image::transform::{Layout, rotate90, rotate180, rotate270};
2519 let layout = Layout::Rgb8;
2520 Ok(match steps % 4 {
2521 1 => (height, width, rotate90(layout, width, height, rgb)?),
2522 2 => (width, height, rotate180(layout, width, height, rgb)?),
2523 3 => (height, width, rotate270(layout, width, height, rgb)?),
2524 _ => (width, height, rgb.to_vec()),
2525 })
2526}
2527
2528/// How big the picture in `path` is as it is **shown**, from its header alone --
2529/// what a library row says about a file it has not placed anywhere. The whole
2530/// file is not decoded.
2531///
2532/// The turn is applied to the answer for the same reason
2533/// [`DecodeSession::open_still`]'s is: a portrait phone photo stores landscape
2534/// and says so in its EXIF block, and a row that answered 4000x3000 for a
2535/// picture that is shown 3000x4000 states the wrong shape on the one surface
2536/// that exists before anything places the file. Header-only still --
2537/// `into_decoder` parses the container and stops.
2538pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {
2539 if let Some(g) = crate::generate::Gen::parse(path) {
2540 return Ok((g.width, g.height));
2541 }
2542 let header = probe_header(path)?;
2543 let rotation = rotation_of_exif(header.orientation)?;
2544 let (width, height) = (header.width, header.height);
2545 Ok(match rotation.swaps_axes() {
2546 true => (height, width),
2547 false => (width, height),
2548 })
2549}
2550
2551/// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse
2552/// of [`crate::convert::i420_to_bgra`] *in that matrix*, which is why
2553/// [`DecodeSession::open_still`] hands the renderer a BT.601 description and
2554/// not the timeline's. A still has no stream to be tagged by; it round-trips to
2555/// the colour it was authored in through this pair and nothing else sees these
2556/// planes (`images::still_pixels_match_the_source_image` measures it).
2557///
2558/// Chroma is the 2x2 box average, and an odd edge averages the samples it has --
2559/// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape
2560/// [`crate::scale::Composer::place`] panics on anything else for.
2561fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2562 let (cw, ch) = crate::scale::chroma_dims(width, height);
2563 let mut y = vec![0u8; width * height];
2564 let mut u = vec![0u8; cw * ch];
2565 let mut v = vec![0u8; cw * ch];
2566 for row in 0..height {
2567 for col in 0..width {
2568 let p = (row * width + col) * 3;
2569 let (r, g, b) = (rgb[p] as i32, rgb[p + 1] as i32, rgb[p + 2] as i32);
2570 y[row * width + col] = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8;
2571 }
2572 }
2573 for crow in 0..ch {
2574 for ccol in 0..cw {
2575 let (mut sr, mut sg, mut sb, mut n) = (0i32, 0i32, 0i32, 0i32);
2576 for row in crow * 2..(crow * 2 + 2).min(height) {
2577 for col in ccol * 2..(ccol * 2 + 2).min(width) {
2578 let p = (row * width + col) * 3;
2579 sr += rgb[p] as i32;
2580 sg += rgb[p + 1] as i32;
2581 sb += rgb[p + 2] as i32;
2582 n += 1;
2583 }
2584 }
2585 let n = n.max(1);
2586 let (r, g, b) = (sr / n, sg / n, sb / n);
2587 u[crow * cw + ccol] = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8;
2588 v[crow * cw + ccol] = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8;
2589 }
2590 }
2591 (y, u, v)
2592}
2593
2594/// Peak buckets per second the visualizer paints from, shared by the one
2595/// caller that decodes them ([`DecodeSession::open_visualizer`], preview and
2596/// export both) and the painter that reads them.
2597pub(crate) const VIZ_BUCKETS_PER_SEC: u32 = 4000;
2598/// Bits 1-2: which picture this visualizer paints. Mutually exclusive —
2599/// a picker, not independent toggles.
2600pub const VIZ_STYLE_FILL: u8 = 0;
2601pub const VIZ_STYLE_RIBBON: u8 = 1;
2602pub const VIZ_STYLE_RING: u8 = 2;
2603pub const VIZ_STYLE_WAVE: u8 = 3;
2604pub const VIZ_FAST: u8 = 1 << 3;
2605
2606pub fn viz_style(flags: u8) -> u8 {
2607 (flags >> 1) & 3
2608}
2609
2610pub fn with_viz_style(flags: u8, style: u8) -> u8 {
2611 (flags & !0b0110) | ((style & 3) << 1)
2612}
2613
2614/// Azure + sat 160 + 8 strands + glow 2. What `viz_paint == 0` means.
2615pub const VIZ_PAINT_AZURE: u64 = 150 | (160 << 8) | (8 << 16) | (2 << 24);
2616
2617/// Where the strand colour sits above the clip's own four bytes: hue at 32
2618/// and sat at 40, with bit 63 as the flag that says a clip chose one
2619/// ([`viz_strand_set`]). A clear flag means the automatic complement the
2620/// ring has always painted -- so a v22 value, whose top half is empty, is
2621/// nothing new.
2622const VIZ_STRAND_HUE_SHIFT: u32 = 32;
2623const VIZ_STRAND_SAT_SHIFT: u32 = 40;
2624const VIZ_STRAND_CHOSEN: u64 = 1 << 63;
2625
2626pub fn viz_materialize(paint: u64) -> u64 {
2627 if paint == 0 { VIZ_PAINT_AZURE } else { paint }
2628}
2629
2630pub fn viz_ink_from_paint(paint: u64) -> (u8, u8, u8) {
2631 let p = viz_materialize(paint);
2632 let hue = (p & 0xFF) as f32 * 360.0 / 256.0;
2633 let sat = f32::from(((p >> 8) & 0xFF) as u8) / 255.0;
2634 hsv_to_rgb(hue, sat, 0.84)
2635}
2636
2637pub fn viz_strands_of(paint: u64) -> u8 {
2638 (((viz_materialize(paint) >> 16) & 0xFF) as u8).clamp(1, 32)
2639}
2640
2641pub fn viz_glow_of(paint: u64) -> u8 {
2642 ((viz_materialize(paint) >> 24) & 0xFF) as u8
2643}
2644
2645pub fn with_viz_paint_hue(paint: u64, hue: u8) -> u64 {
2646 (viz_materialize(paint) & !0xFF) | u64::from(hue)
2647}
2648
2649pub fn with_viz_paint_sat(paint: u64, sat: u8) -> u64 {
2650 (viz_materialize(paint) & !(0xFF << 8)) | (u64::from(sat) << 8)
2651}
2652
2653pub fn with_viz_paint_strands(paint: u64, n: u8) -> u64 {
2654 (viz_materialize(paint) & !(0xFF << 16)) | (u64::from(n.clamp(1, 32)) << 16)
2655}
2656
2657pub fn with_viz_paint_glow(paint: u64, n: u8) -> u64 {
2658 (viz_materialize(paint) & !(0xFF << 24)) | (u64::from(n.min(16)) << 24)
2659}
2660
2661pub fn viz_hue_ui(paint: u64) -> u8 {
2662 if paint == 0 {
2663 150
2664 } else {
2665 (paint & 0xFF) as u8
2666 }
2667}
2668
2669pub fn viz_sat_ui(paint: u64) -> u8 {
2670 if paint == 0 {
2671 160
2672 } else {
2673 match ((paint >> 8) & 0xFF) as u8 {
2674 0 => 160,
2675 s => s,
2676 }
2677 }
2678}
2679
2680/// Whether the clip chose a strand colour of its own (the top bit), rather
2681/// than taking the automatic complement a ring's dual half has always
2682/// painted.
2683pub fn viz_strand_set(paint: u64) -> bool {
2684 paint & VIZ_STRAND_CHOSEN != 0
2685}
2686
2687/// The chosen strand hue, 0-255 on the wheel [`viz_hue_ui`] reads.
2688pub fn viz_strand_hue_ui(paint: u64) -> u8 {
2689 ((paint >> VIZ_STRAND_HUE_SHIFT) & 0xFF) as u8
2690}
2691
2692/// The chosen strand sat, 0-255. A stored zero stays zero here, unlike
2693/// [`viz_sat_ui`]'s: a grey strand is a colour someone picked, and the flag
2694/// -- not the byte -- is what says whether there is one.
2695pub fn viz_strand_sat_ui(paint: u64) -> u8 {
2696 ((paint >> VIZ_STRAND_SAT_SHIFT) & 0xFF) as u8
2697}
2698
2699/// Set the strand hue and mark the colour chosen, so a ring's dual half
2700/// inks it instead of the automatic complement.
2701pub fn with_viz_paint_strand_hue(paint: u64, hue: u8) -> u64 {
2702 let p = viz_materialize(paint) & !(0xFF_u64 << VIZ_STRAND_HUE_SHIFT);
2703 (p | (u64::from(hue) << VIZ_STRAND_HUE_SHIFT)) | VIZ_STRAND_CHOSEN
2704}
2705
2706/// Set the strand sat and mark the colour chosen, as
2707/// [`with_viz_paint_strand_hue`] does.
2708pub fn with_viz_paint_strand_sat(paint: u64, sat: u8) -> u64 {
2709 let p = viz_materialize(paint) & !(0xFF_u64 << VIZ_STRAND_SAT_SHIFT);
2710 (p | (u64::from(sat) << VIZ_STRAND_SAT_SHIFT)) | VIZ_STRAND_CHOSEN
2711}
2712
2713/// Drop the chosen strand colour: the dual half of a ring goes back to the
2714/// automatic complement, and both strand bytes go with the flag.
2715pub fn viz_strand_clear(paint: u64) -> u64 {
2716 paint
2717 & !(VIZ_STRAND_CHOSEN
2718 | (0xFF_u64 << VIZ_STRAND_HUE_SHIFT)
2719 | (0xFF_u64 << VIZ_STRAND_SAT_SHIFT))
2720}
2721
2722/// `#RRGGBB` for an ink, at the same fixed value the painter draws at, so
2723/// the swatch a front-end shows is the colour that reaches the picture.
2724/// The inverse of [`viz_color_from_text`] for the colours a round trip
2725/// through bytes can carry back.
2726pub fn viz_color_hex(hue: u8, sat: u8) -> String {
2727 let (r, g, b) = hsv_to_rgb(f32::from(hue) * 360.0 / 256.0, f32::from(sat) / 255.0, 0.84);
2728 format!("#{r:02X}{g:02X}{b:02X}")
2729}
2730
2731/// A colour someone typed -- `#4F8FD6`, `4f8fd6`, `rgb(79,143,214)` or
2732/// `rgba(79,143,214,255)`, any case, commas or `/` between the channels,
2733/// alpha ignored -- as the `(hue, sat)` pair the sliders and the paint
2734/// field speak. `None` for everything else rather than a guess: the wrong
2735/// number of digits, a channel outside 0-255, parentheses missing.
2736///
2737/// Brightness is dropped, not carried: the painter draws every ink at its
2738/// own fixed value, so a typed colour is kept by its hue and saturation.
2739pub fn viz_color_from_text(text: &str) -> Option<(u8, u8)> {
2740 let t = text.trim();
2741 let (r, g, b) = if let Some(inner) = t.strip_suffix(')') {
2742 let body = if starts_ci(inner, b"rgb(") {
2743 &inner[4..]
2744 } else if starts_ci(inner, b"rgba(") {
2745 &inner[5..]
2746 } else {
2747 return None;
2748 };
2749 let mut channels = body.split(['/', ',']).map(str::trim);
2750 let r = channel(channels.next()?)?;
2751 let g = channel(channels.next()?)?;
2752 let b = channel(channels.next()?)?;
2753 // Alpha, when it is spelled: read so a bad one is refused like a
2754 // channel is, and dropped -- the paint field has no room for it.
2755 if let Some(a) = channels.next() {
2756 channel(a)?;
2757 }
2758 if channels.next().is_some() {
2759 return None;
2760 }
2761 (r, g, b)
2762 } else {
2763 let hex = t.strip_prefix('#').unwrap_or(t);
2764 if hex.len() != 6 || !hex.bytes().all(|c| c.is_ascii_hexdigit()) {
2765 return None;
2766 }
2767 (
2768 u8::from_str_radix(&hex[0..2], 16).ok()?,
2769 u8::from_str_radix(&hex[2..4], 16).ok()?,
2770 u8::from_str_radix(&hex[4..6], 16).ok()?,
2771 )
2772 };
2773 Some(rgb_to_hue_sat(r, g, b))
2774}
2775
2776fn starts_ci(text: &str, prefix: &[u8]) -> bool {
2777 text.len() >= prefix.len() && text.as_bytes()[..prefix.len()].eq_ignore_ascii_case(prefix)
2778}
2779
2780/// One 0-255 channel of a typed colour: digits only, so neither a sign nor
2781/// an exponent slips in the way `u8`'s own parse would take them.
2782fn channel(text: &str) -> Option<u8> {
2783 if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
2784 return None;
2785 }
2786 text.parse().ok()
2787}
2788
2789/// What a byte RGB is on the paint field's wheel: hue on [`viz_hue_ui`]'s
2790/// 0-255 scale, sat 0-255, brightness dropped for the same reason
2791/// [`viz_color_from_text`] drops the typed one.
2792fn rgb_to_hue_sat(r: u8, g: u8, b: u8) -> (u8, u8) {
2793 let (r, g, b) = (f32::from(r), f32::from(g), f32::from(b));
2794 let (max, min) = (r.max(g).max(b), r.min(g).min(b));
2795 let delta = max - min;
2796 let hue = if delta == 0.0 {
2797 0.0
2798 } else if max == r {
2799 60.0 * ((g - b) / delta).rem_euclid(6.0)
2800 } else if max == g {
2801 60.0 * ((b - r) / delta + 2.0)
2802 } else {
2803 60.0 * ((r - g) / delta + 4.0)
2804 };
2805 let hue = ((hue * 256.0 / 360.0).round() as i64).rem_euclid(256) as u8;
2806 let sat = if max == 0.0 { 0.0 } else { delta / max };
2807 (hue, (sat * 255.0).round() as u8)
2808}
2809
2810pub fn viz_hsv_rgb(h: f32, s: f32, v: f32) -> (u8, u8, u8) {
2811 hsv_to_rgb(h, s, v)
2812}
2813
2814fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (u8, u8, u8) {
2815 let h = ((h % 360.0) + 360.0) % 360.0;
2816 let c = v * s;
2817 let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
2818 let m = v - c;
2819 let (r, g, b) = match (h / 60.0) as i32 {
2820 0 => (c, x, 0.0),
2821 1 => (x, c, 0.0),
2822 2 => (0.0, c, x),
2823 3 => (0.0, x, c),
2824 4 => (x, 0.0, c),
2825 _ => (c, 0.0, x),
2826 };
2827 (
2828 ((r + m) * 255.0).round() as u8,
2829 ((g + m) * 255.0).round() as u8,
2830 ((b + m) * 255.0).round() as u8,
2831 )
2832}
2833
2834fn rgb_yuv(r: i32, g: i32, b: i32) -> (u8, u8, u8) {
2835 let y = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8;
2836 let u = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8;
2837 let v = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8;
2838 (y, u, v)
2839}
2840
2841/// How much sound one visualizer frame shows, centered on the frame's own
2842/// time. Two seconds by default; [`VIZ_FAST`] is a fifth of a second, the
2843/// zoom that makes an Audacity-style trace readable as a line.
2844const VIZ_WINDOW_SECS: f64 = 2.0;
2845const VIZ_FAST_SECS: f64 = 0.2;
2846
2847#[allow(
2848 clippy::too_many_arguments,
2849 reason = "the plane triple and its dimensions are threaded positionally through every painter's stamp calls; a planes struct would restructure all of them"
2850)]
2851fn viz_stamp(
2852 y: &mut [u8],
2853 u: &mut [u8],
2854 v: &mut [u8],
2855 w: usize,
2856 h: usize,
2857 cw: usize,
2858 ch: usize,
2859 x: i32,
2860 row: i32,
2861 fall: f32,
2862 bg_y: u8,
2863 ink_y: u8,
2864 ink_u: u8,
2865 ink_v: u8,
2866) {
2867 if x < 0 || row < 0 || x >= w as i32 || row >= h as i32 {
2868 return;
2869 }
2870 let lum = (f32::from(bg_y) + (f32::from(ink_y) - f32::from(bg_y)) * fall.clamp(0.0, 1.0)) as u8;
2871 let idx = row as usize * w + x as usize;
2872 if lum > y[idx] {
2873 y[idx] = lum;
2874 }
2875 if fall > 0.6 {
2876 let cx = x as usize / 2;
2877 let cy = row as usize / 2;
2878 if cy < ch && cx < cw {
2879 u[cy * cw + cx] = ink_u;
2880 v[cy * cw + cx] = ink_v;
2881 }
2882 }
2883}
2884
2885#[allow(
2886 clippy::too_many_arguments,
2887 reason = "forwards the same plane triple and ink as viz_stamp, positionally"
2888)]
2889fn viz_span(
2890 y: &mut [u8],
2891 u: &mut [u8],
2892 v: &mut [u8],
2893 w: usize,
2894 h: usize,
2895 cw: usize,
2896 ch: usize,
2897 x: i32,
2898 top: i32,
2899 bot: i32,
2900 bg_y: u8,
2901 ink_y: u8,
2902 ink_u: u8,
2903 ink_v: u8,
2904) {
2905 let (a, b) = if top <= bot { (top, bot) } else { (bot, top) };
2906 for row in a..=b {
2907 viz_stamp(
2908 y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v,
2909 );
2910 }
2911}
2912
2913/// What one frame's painting borrows instead of allocating, owned by whoever
2914/// paints a *stream* of frames -- the visualizer worker's own thread, an
2915/// export seat, a test -- and reused for every strand of every frame. Eight
2916/// `Vec`s, against the twenty-seven a fresh set per strand cost a ring at
2917/// eight strands.
2918#[derive(Default)]
2919pub(crate) struct VizScratch {
2920 /// The frame's own columns, kept across frames to the widest picture yet.
2921 lo: Vec<f32>,
2922 hi: Vec<f32>,
2923 sig: Vec<f32>,
2924 /// One strand's sampled positions, the cells its Bresenham runs cover,
2925 /// the chain's rows, the row band's candidates and their lower hull.
2926 pts: Vec<(i32, i32)>,
2927 chain: Vec<(i32, i32)>,
2928 rows: Vec<(i32, usize, usize)>,
2929 cand: Vec<(i32, i32)>,
2930 hull: Vec<usize>,
2931}
2932
2933/// One segment's glow as its own disc, stamped at every Bresenham cell: what
2934/// a chain was painted by before [`viz_chain`], and still the cheaper of the
2935/// two when the chain is long ([`viz_discs_are_cheaper`]).
2936#[allow(clippy::too_many_arguments)]
2937fn viz_line(
2938 y: &mut [u8],
2939 u: &mut [u8],
2940 v: &mut [u8],
2941 w: usize,
2942 h: usize,
2943 cw: usize,
2944 ch: usize,
2945 mut x0: i32,
2946 mut y0: i32,
2947 x1: i32,
2948 y1: i32,
2949 bg_y: u8,
2950 ink_y: u8,
2951 ink_u: u8,
2952 ink_v: u8,
2953 glow: u8,
2954) {
2955 let dx = (x1 - x0).abs();
2956 let dy = -(y1 - y0).abs();
2957 let sx = if x0 < x1 { 1 } else { -1 };
2958 let sy = if y0 < y1 { 1 } else { -1 };
2959 let mut err = dx + dy;
2960 let g = i32::from(glow);
2961 loop {
2962 for oy in -g..=g {
2963 for ox in -g..=g {
2964 if ox * ox + oy * oy > g * g {
2965 continue;
2966 }
2967 let fall = if ox == 0 && oy == 0 {
2968 1.0
2969 } else {
2970 let d2 = (ox * ox + oy * oy) as f32;
2971 (-0.45 * d2 / (g * g).max(1) as f32).exp()
2972 };
2973 viz_stamp(
2974 y,
2975 u,
2976 v,
2977 w,
2978 h,
2979 cw,
2980 ch,
2981 x0 + ox,
2982 y0 + oy,
2983 fall,
2984 bg_y,
2985 ink_y,
2986 ink_u,
2987 ink_v,
2988 );
2989 }
2990 }
2991 if x0 == x1 && y0 == y1 {
2992 break;
2993 }
2994 let e2 = 2 * err;
2995 if e2 >= dy {
2996 err += dy;
2997 x0 += sx;
2998 }
2999 if e2 <= dx {
3000 err += dx;
3001 y0 += sy;
3002 }
3003 }
3004}
3005
3006/// Which of the two passes paints a chain, by what each of them visits. Both
3007/// paint the same bytes, and the tests hold them to it; they are not alike in
3008/// what they cost. The discs visit `samples * pi * glow^2` cells whatever the
3009/// envelope is doing, while the chain visits each of its own cells once per
3010/// row of its band -- `cells * (2 * glow + 1)`. So a *smooth* trace (a chain
3011/// cell per sample, near enough) is the chain's by a wide margin, and a
3012/// *jagged* one, whose samples are Bresenham runs of dozens of cells, is the
3013/// discs' while the glow is small. A song's own ring at 1080p crossed between
3014/// glow 3 and 4 (31 ms against 44 ms there, and 60 against 52 at glow 4),
3015/// which is exactly what this comparison says.
3016fn viz_discs_are_cheaper(samples: usize, cells: usize, glow: u8) -> bool {
3017 (samples as u64) * (2 * u64::from(glow) + 1) < cells as u64
3018}
3019
3020/// How many cells [`viz_walk`] would push for these samples, without walking
3021/// them: one per iteration of that loop, and it iterates `max(dx, dy) + 1`
3022/// times a segment.
3023fn chain_cells(pts: &[(i32, i32)]) -> usize {
3024 pts.windows(2)
3025 .map(|w| {
3026 let (dx, dy) = ((w[1].0 - w[0].0).abs(), (w[1].1 - w[0].1).abs());
3027 dx.max(dy) as usize + 1
3028 })
3029 .sum()
3030}
3031
3032/// The Bresenham cells of one segment, collected rather than stamped: the same
3033/// walk [`viz_line`] used to rasterise, kept for [`viz_chain`] to paint the
3034/// whole chain from.
3035fn viz_walk(mut x0: i32, mut y0: i32, x1: i32, y1: i32, chain: &mut Vec<(i32, i32)>) {
3036 let dx = (x1 - x0).abs();
3037 let dy = -(y1 - y0).abs();
3038 let sx = if x0 < x1 { 1 } else { -1 };
3039 let sy = if y0 < y1 { 1 } else { -1 };
3040 let mut err = dx + dy;
3041 loop {
3042 chain.push((x0, y0));
3043 if x0 == x1 && y0 == y1 {
3044 break;
3045 }
3046 let e2 = 2 * err;
3047 if e2 >= dy {
3048 err += dy;
3049 x0 += sx;
3050 }
3051 if e2 <= dx {
3052 err += dx;
3053 y0 += sy;
3054 }
3055 }
3056}
3057
3058/// Paints a whole chain in one pass: every cell within `glow` of a chain cell
3059/// takes the falloff of the **nearest** one, and the ink with it.
3060///
3061/// Byte-for-byte what the per-point discs left behind, and the reason is in the
3062/// write: luma is a `max`, so of every disc covering a cell only the closest one
3063/// can decide it, and a glow disc's chroma is written at *every* step of it --
3064/// [`viz_stamp`]`s threshold (0.6) is under the falloff of the rim
3065/// (`exp(-0.45) = 0.64`), which is what makes the whole disc the ink's own.
3066/// What changes is the cost: discs visit `steps * pi * glow^2` cells
3067/// (`VIZ_STYLE_RING`'s 7680 steps measured 296 ms for one 1080p frame at glow
3068/// 16, eight strands), while this visits each covered cell once and finds its
3069/// nearest chain cell by walking outward from it through the chain cells of its
3070/// own row band.
3071#[allow(clippy::too_many_arguments)]
3072fn viz_chain(
3073 y: &mut [u8],
3074 u: &mut [u8],
3075 v: &mut [u8],
3076 w: usize,
3077 h: usize,
3078 cw: usize,
3079 ch: usize,
3080 scratch: &mut VizScratch,
3081 bg_y: u8,
3082 ink_y: u8,
3083 ink_u: u8,
3084 ink_v: u8,
3085 glow: u8,
3086) {
3087 let VizScratch {
3088 pts,
3089 chain,
3090 rows,
3091 cand,
3092 hull,
3093 ..
3094 } = scratch;
3095 chain.clear();
3096 for pair in pts.windows(2) {
3097 viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, chain);
3098 }
3099 if chain.is_empty() {
3100 return;
3101 }
3102 if glow == 0 {
3103 // Nothing to decide: with no glow the cells are the chain itself, at
3104 // full ink -- which is exactly what the row/by/band machinery below
3105 // works out, one sort later.
3106 for &(x, row) in chain.iter() {
3107 viz_stamp(
3108 y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v,
3109 );
3110 }
3111 return;
3112 }
3113 let g = i32::from(glow);
3114 // By (row, x) -- the tuple is (x, row) -- so a row's band is a contiguous
3115 // slice of this: a chain revisits cells (the ring is sampled several times
3116 // a pixel) and a repeat is the same candidate.
3117 chain.sort_unstable_by_key(|&(x, row)| (row, x));
3118 chain.dedup();
3119 rows.clear();
3120 let mut i = 0;
3121 while i < chain.len() {
3122 let row = chain[i].1;
3123 let start = i;
3124 while i < chain.len() && chain[i].1 == row {
3125 i += 1;
3126 }
3127 rows.push((row, start, i));
3128 }
3129 let first = (rows[0].0 - g).max(0);
3130 let last = (rows[rows.len() - 1].0 + g).min(h as i32 - 1);
3131 let mut band = 0usize;
3132 // `(x, dy^2)` -- a candidate's horizontal offset is left to the cell that
3133 // asks, its vertical one is its own.
3134 // ...and the candidates a run's cells are decided by, once the ones that
3135 // can never be nearest are off ([`viz_chain`]'s own note).
3136 for row in first..=last {
3137 while band < rows.len() && rows[band].0 < row - g {
3138 band += 1;
3139 }
3140 cand.clear();
3141 let mut k = band;
3142 while k < rows.len() && rows[k].0 <= row + g {
3143 let dy = rows[k].0 - row;
3144 let dy2 = dy * dy;
3145 for &(x, _) in &chain[rows[k].1..rows[k].2] {
3146 cand.push((x, dy2));
3147 }
3148 k += 1;
3149 }
3150 if cand.is_empty() {
3151 continue;
3152 }
3153 cand.sort_unstable_by_key(|&(x, _)| x);
3154 // One candidate per column: the nearest in y is the only one that can
3155 // decide a cell -- the others are further on both axes.
3156 let mut kept = 0usize;
3157 for j in 0..cand.len() {
3158 if kept > 0 && cand[kept - 1].0 == cand[j].0 {
3159 if cand[j].1 < cand[kept - 1].1 {
3160 cand[kept - 1] = cand[j];
3161 }
3162 } else {
3163 cand[kept] = cand[j];
3164 kept += 1;
3165 }
3166 }
3167 cand.truncate(kept);
3168 // The stretches of x the discs reach, one run at a time: the hole in
3169 // the middle of a ring is not walked at all.
3170 let mut j = 0usize;
3171 while j < cand.len() {
3172 let run_lo = cand[j].0 - g;
3173 let mut run_hi = cand[j].0 + g;
3174 let first = j;
3175 while j + 1 < cand.len() && cand[j + 1].0 - g <= run_hi + 1 {
3176 j += 1;
3177 run_hi = run_hi.max(cand[j].0 + g);
3178 }
3179 let end = j + 1; // exclusive
3180 j += 1;
3181 let x_lo = run_lo.max(0);
3182 let x_hi = run_hi.min(w as i32 - 1);
3183 if x_lo > x_hi {
3184 continue;
3185 }
3186 // What is left of a candidate at cell `x` is
3187 // `x^2 - 2*cx*x + (cx^2 + dy^2)`: the `x^2` is common to every
3188 // candidate, so the nearest one is the lowest line of the rest --
3189 // and only the lower hull of those lines is ever the lowest, at any
3190 // x. On the hull the nearest one only ever moves forward as x
3191 // does, which is what makes this a walk over the cells instead of a
3192 // search per cell.
3193 let line = |c: usize| {
3194 let (cx, dy2) = cand[c];
3195 let cx = i64::from(cx);
3196 (-2 * cx, cx * cx + i64::from(dy2))
3197 };
3198 let value = |c: usize, x: i32| {
3199 let (m, b) = line(c);
3200 m * i64::from(x) + b
3201 };
3202 hull.clear();
3203 for c in first..end {
3204 let (m, b) = line(c);
3205 while hull.len() >= 2 {
3206 let (m1, b1) = line(hull[hull.len() - 2]);
3207 let (m2, b2) = line(hull[hull.len() - 1]);
3208 // The middle line is never the lowest: its two crossings
3209 // are the wrong way round.
3210 if (b2 - b1) * (m2 - m) >= (b - b2) * (m1 - m2) {
3211 hull.pop();
3212 } else {
3213 break;
3214 }
3215 }
3216 hull.push(c);
3217 }
3218 // Only the hull's last two entries can change places as x moves
3219 // forward, so this is a walk and not a search -- and `value` is
3220 // asked of those two alone.
3221 let mut hp = 0usize;
3222 for x in x_lo..=x_hi {
3223 while hp + 1 < hull.len() && value(hull[hp + 1], x) <= value(hull[hp], x) {
3224 hp += 1;
3225 }
3226 let (cx, dy2) = cand[hull[hp]];
3227 let d = x - cx;
3228 let d2 = d * d + dy2;
3229 if d2 <= g * g {
3230 let fall = if d2 == 0 {
3231 1.0
3232 } else {
3233 (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp()
3234 };
3235 viz_stamp(
3236 y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v,
3237 );
3238 }
3239 }
3240 }
3241 }
3242}
3243
3244/// One visualizer picture in tightly packed I420. Three looks, picked by
3245/// [`viz_style`]: a bipolar sample trace (Audacity), a filled min/max
3246/// envelope at pixel resolution, or a multi-strand ribbon. Ink is
3247/// [`viz_ink_from_paint`]. A frame always exists; silence is the zero line.
3248///
3249/// This is the whole-envelope entry: it is handed the file's envelope and
3250/// paints from it ([`VizView::whole`]). The seat paints from a *window* of one
3251/// instead ([`visualizer_window_i420`], [`crate::waveform::viz_envelope`]).
3252pub(crate) fn visualizer_i420(
3253 scratch: &mut VizScratch,
3254 peaks: &[(f32, f32)],
3255 t_secs: f64,
3256 width: u32,
3257 height: u32,
3258 flags: u8,
3259 paint: u64,
3260) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
3261 visualizer_window_i420(
3262 scratch,
3263 &VizView::whole(peaks),
3264 t_secs,
3265 width,
3266 height,
3267 flags,
3268 paint,
3269 )
3270}
3271
3272/// The envelope a visualizer frame is painted from: the whole file, or one
3273/// *window* of it -- which is what the seat holds, because a film's own
3274/// envelope is past the memo's ceiling ([`crate::waveform::viz_envelope`]).
3275///
3276/// `peaks[i]` is the bucket at absolute index `first + i`, so the painter's
3277/// index arithmetic is the same whether it was handed a slice of thirty
3278/// seconds or of two hours. `total` is the *file's* own bucket count, which is
3279/// what "past the end of the file" is measured against -- a window that
3280/// measured it against itself would draw the file's end wherever the window
3281/// ended -- and `peak` is the file's loudest bucket, which every column is
3282/// scaled by: no window can derive that from itself.
3283///
3284/// `per_sec` is the rate *this* envelope was drawn at, in buckets per second,
3285/// and it is carried rather than assumed: the slice is indexed at it, so an
3286/// envelope drawn at another rate under a painter that hard-coded the
3287/// visualizer's own would read a tenth of a second of sound as a second. The
3288/// whole-file constructor is the one place the visualizer's rate is named.
3289pub(crate) struct VizView<'a> {
3290 pub(crate) peaks: &'a [(f32, f32)],
3291 pub(crate) first: usize,
3292 pub(crate) total: usize,
3293 pub(crate) peak: f32,
3294 pub(crate) per_sec: f64,
3295}
3296
3297impl<'a> VizView<'a> {
3298 /// The whole envelope, which is what every caller but the seat has.
3299 pub(crate) fn whole(peaks: &'a [(f32, f32)]) -> Self {
3300 Self {
3301 peaks,
3302 first: 0,
3303 total: peaks.len(),
3304 peak: crate::waveform::peak_of(peaks),
3305 per_sec: f64::from(VIZ_BUCKETS_PER_SEC),
3306 }
3307 }
3308
3309 /// One window of an envelope: `peaks` starts at absolute bucket `first`,
3310 /// `total` and `peak` are the whole file's, and `per_sec` is the rate the
3311 /// file's envelope was drawn at.
3312 pub(crate) fn window(
3313 peaks: &'a [(f32, f32)],
3314 first: usize,
3315 total: usize,
3316 peak: f32,
3317 per_sec: f64,
3318 ) -> Self {
3319 Self {
3320 peaks,
3321 first,
3322 total,
3323 peak,
3324 per_sec,
3325 }
3326 }
3327
3328 /// The bucket at absolute index `abs`, when this view carries it: the
3329 /// window's own edges are not the file's, and a frame asked for one of
3330 /// them draws silence rather than a bucket that is only half decoded.
3331 pub(crate) fn at(&self, abs: usize) -> Option<(f32, f32)> {
3332 abs.checked_sub(self.first)
3333 .and_then(|i| self.peaks.get(i))
3334 .copied()
3335 }
3336
3337 fn is_empty(&self) -> bool {
3338 self.peaks.is_empty()
3339 }
3340}
3341
3342/// [`visualizer_i420`] from a view, which is how the seat paints: `peaks` may
3343/// be a window rather than the file's own envelope, and `t_secs` is the
3344/// frame's own time either way -- the view knows where its slice starts.
3345pub(crate) fn visualizer_window_i420(
3346 scratch: &mut VizScratch,
3347 view: &VizView,
3348 t_secs: f64,
3349 width: u32,
3350 height: u32,
3351 flags: u8,
3352 paint: u64,
3353) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
3354 let width = width & !1;
3355 let height = height & !1;
3356 // A canvas with no size asks for no picture, and must be told so: the zero
3357 // line's row is derived from the height (`h - 1`), and a height of zero has
3358 // no row to put it on -- `clamp` answers that by panicking, which on this
3359 // path is a dead worker thread and a span the export aborts on. A
3360 // `Composer::passthrough()` canvas is exactly this size and says as much
3361 // (`places_nothing`), and a 1-pixel-high canvas floors to it (planes are
3362 // even), so both take the empty picture they asked for.
3363 if width == 0 || height == 0 {
3364 return (Vec::new(), Vec::new(), Vec::new());
3365 }
3366 let (w, h) = (width as usize, height as usize);
3367 let (cw, ch) = crate::scale::chroma_dims(w, h);
3368 let (bg_y, bg_u, bg_v) = rgb_yuv(8, 12, 22);
3369 let mut y = vec![bg_y; w * h];
3370 let mut u = vec![bg_u; cw * ch];
3371 let mut v = vec![bg_v; cw * ch];
3372 let (ink_r, ink_g, ink_b) = viz_ink_from_paint(paint);
3373 let (ink_y, ink_u, ink_v) = rgb_yuv(ink_r as i32, ink_g as i32, ink_b as i32);
3374 let center = h as f32 / 2.0;
3375 let half = h as f32 * 0.42;
3376 let t_secs = if t_secs.is_finite() { t_secs } else { 0.0 };
3377
3378 let z = (center.round() as isize).clamp(0, h as isize - 1) as usize;
3379 for col in 0..w {
3380 y[z * w + col] = y[z * w + col].max(bg_y.saturating_add(18));
3381 }
3382
3383 scratch.lo.clear();
3384 scratch.lo.resize(w, 0.0);
3385 scratch.hi.clear();
3386 scratch.hi.resize(w, 0.0);
3387 scratch.sig.clear();
3388 scratch.sig.resize(w, 0.0);
3389 if !view.is_empty() && view.total != 0 {
3390 let duration = view.total as f64 / view.per_sec;
3391 let per_sec = view.per_sec;
3392 let window = if flags & VIZ_FAST != 0 {
3393 VIZ_FAST_SECS
3394 } else {
3395 VIZ_WINDOW_SECS
3396 };
3397 // Fixed window length, silence outside the file: shrinking the span
3398 // to the samples that exist stretched a bump as it entered (2s) and
3399 // Fast (0.2s) rarely hit the edge. Column x always maps to
3400 // t - window/2 + x/w * window.
3401 let origin = t_secs - window / 2.0;
3402 let pair_at = |t: f64| -> (f32, f32) {
3403 if !t.is_finite() || t < 0.0 || t > duration {
3404 return (0.0, 0.0);
3405 }
3406 let pos = (t * per_sec).clamp(0.0, (view.total - 1) as f64);
3407 let i = pos.floor() as usize;
3408 let f = (pos - i as f64) as f32;
3409 // Silence where the slice does not reach: a view that is a window
3410 // is only handed the buckets the frame can ask for, so this is the
3411 // file's own ends and nothing else.
3412 let (Some((lo0, hi0)), Some((lo1, hi1))) =
3413 (view.at(i), view.at((i + 1).min(view.total - 1)))
3414 else {
3415 return (0.0, 0.0);
3416 };
3417 (
3418 (lo0 + (lo1 - lo0) * f).clamp(-1.0, 0.0),
3419 (hi0 + (hi1 - hi0) * f).clamp(0.0, 1.0),
3420 )
3421 };
3422 let signed_at = |t: f64| {
3423 let (a, b) = pair_at(t);
3424 if b.abs() >= a.abs() { b } else { a }
3425 };
3426 for col in 0..w {
3427 let t0 = origin + col as f64 / w as f64 * window;
3428 let t1 = origin + (col + 1) as f64 / w as f64 * window;
3429 let (mut mn, mut mx) = (0.0f32, 0.0f32);
3430 let samples = 4;
3431 for k in 0..samples {
3432 let t = t0 + (t1 - t0) * (k as f64 + 0.5) / samples as f64;
3433 let (l, h) = pair_at(t);
3434 mn = mn.min(l);
3435 mx = mx.max(h);
3436 }
3437 scratch.lo[col] = mn;
3438 scratch.hi[col] = mx;
3439 scratch.sig[col] = signed_at(origin + (col as f64 + 0.5) / w as f64 * window);
3440 }
3441 // Whole-file peak, not the window's: a 2s window that gains or loses
3442 // a loud hit used to rescale every column, so the same bump changed
3443 // height as it entered and left the picture. A view carries that peak
3444 // with it ([`VizView`]), because a window of a film could not compute
3445 // it from the megabyte it holds.
3446 let peak = view.peak;
3447 if peak > 1e-4 {
3448 for i in 0..w {
3449 scratch.lo[i] /= peak;
3450 scratch.hi[i] /= peak;
3451 scratch.sig[i] /= peak;
3452 }
3453 }
3454 }
3455
3456 match viz_style(flags) {
3457 VIZ_STYLE_RIBBON => {
3458 let tau = std::f64::consts::TAU;
3459 let travel = t_secs * 1.35;
3460 for col in 0..w {
3461 let env = scratch.lo[col].abs().max(scratch.hi[col]).max(0.06);
3462 let x_phase = (col as f64 / w.max(1) as f64) * 2.15 * tau;
3463 for s in 0..u32::from(viz_strands_of(paint)).max(1) {
3464 let frac = s as f32 / (viz_strands_of(paint).max(2) as f32 - 1.0);
3465 let scale = 0.28 + 0.72 * frac;
3466 let wave = (x_phase + travel + s as f64 * 0.05).sin() as f32;
3467 let row = (center + half * env * scale * wave).round() as i32;
3468 let glow = i32::from(viz_glow_of(paint));
3469 viz_stamp(
3470 &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row, 1.0, bg_y, ink_y,
3471 ink_u, ink_v,
3472 );
3473 for dy in 1..=glow {
3474 let fall = 0.5 / dy as f32;
3475 viz_stamp(
3476 &mut y,
3477 &mut u,
3478 &mut v,
3479 w,
3480 h,
3481 cw,
3482 ch,
3483 col as i32,
3484 row - dy,
3485 fall,
3486 bg_y,
3487 ink_y,
3488 ink_u,
3489 ink_v,
3490 );
3491 viz_stamp(
3492 &mut y,
3493 &mut u,
3494 &mut v,
3495 w,
3496 h,
3497 cw,
3498 ch,
3499 col as i32,
3500 row + dy,
3501 fall,
3502 bg_y,
3503 ink_y,
3504 ink_u,
3505 ink_v,
3506 );
3507 }
3508 }
3509 }
3510 }
3511 VIZ_STYLE_RING => {
3512 let cx = w as f32 / 2.0;
3513 let cy = h as f32 / 2.0;
3514 let r0 = (w.min(h) as f32) * 0.28;
3515 let amp = (w.min(h) as f32) * 0.18;
3516 let tau = std::f32::consts::TAU;
3517 let steps = w.max(h) * 4;
3518 let strands = viz_strands_of(paint);
3519 let glow = viz_glow_of(paint);
3520 for strand in 0..strands {
3521 let dual = strands >= 2 && strand >= strands / 2;
3522 // The dual half takes the clip's own strand colour when it
3523 // chose one; without one it is the wheel half a turn from
3524 // the clip's hue, at the clip's own saturation, which is
3525 // the complement every earlier project paints.
3526 let (ir, ig, ib) = if dual && viz_strand_set(paint) {
3527 let hue = f32::from(viz_strand_hue_ui(paint)) * 360.0 / 256.0;
3528 let sat = f32::from(viz_strand_sat_ui(paint)) / 255.0;
3529 hsv_to_rgb(hue, sat, 0.84)
3530 } else if dual {
3531 viz_ink_from_paint(with_viz_paint_hue(
3532 paint,
3533 viz_hue_ui(paint).wrapping_add(128),
3534 ))
3535 } else {
3536 viz_ink_from_paint(paint)
3537 };
3538 let (iy, iu, iv) = rgb_yuv(ir as i32, ig as i32, ib as i32);
3539 let scale = 0.65 + 0.35 * f32::from(strand % 4) / 3.0;
3540 let phase = f32::from(strand) * 0.35;
3541 scratch.pts.clear();
3542 for i in 0..=steps {
3543 let t = i as f32 / steps as f32;
3544 let theta = t * tau + t_secs as f32 * 1.1 + phase;
3545 let col = ((t * w as f32) as usize).min(w.saturating_sub(1));
3546 let env = scratch.lo[col].abs().max(scratch.hi[col]);
3547 let wobble = (theta * 3.0 + phase).sin() * 0.12 * env;
3548 let r = r0 + amp * env * scale + amp * wobble;
3549 let x = (cx + r * theta.cos()).round() as i32;
3550 let row = (cy + r * theta.sin()).round() as i32;
3551 scratch.pts.push((x, row));
3552 }
3553 if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) {
3554 for pair in scratch.pts.windows(2) {
3555 viz_line(
3556 &mut y, &mut u, &mut v, w, h, cw, ch, pair[0].0, pair[0].1, pair[1].0,
3557 pair[1].1, bg_y, iy, iu, iv, glow,
3558 );
3559 }
3560 } else {
3561 viz_chain(
3562 &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, iy, iu, iv, glow,
3563 );
3564 }
3565 }
3566 }
3567 VIZ_STYLE_WAVE => {
3568 scratch.pts.clear();
3569 for col in 0..w {
3570 scratch.pts.push((
3571 col as i32,
3572 (center - scratch.sig[col] * half).round() as i32,
3573 ));
3574 }
3575 let glow = viz_glow_of(paint);
3576 if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) {
3577 for pair in scratch.pts.windows(2) {
3578 viz_line(
3579 &mut y, &mut u, &mut v, w, h, cw, ch, pair[0].0, pair[0].1, pair[1].0,
3580 pair[1].1, bg_y, ink_y, ink_u, ink_v, glow,
3581 );
3582 }
3583 } else {
3584 viz_chain(
3585 &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v, glow,
3586 );
3587 }
3588 }
3589 _ => {
3590 // Timeline envelope: one filled body, tops then bottoms, after
3591 // the fold+smooth above. Default look.
3592 let glow = i32::from(viz_glow_of(paint));
3593 for col in 0..w {
3594 let top = (center - scratch.hi[col] * half).round() as i32;
3595 let bot = (center - scratch.lo[col] * half).round() as i32;
3596 viz_span(
3597 &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, top, bot, bg_y, ink_y, ink_u,
3598 ink_v,
3599 );
3600 for dy in 1..=glow {
3601 let fall = 0.55 / dy as f32;
3602 viz_stamp(
3603 &mut y,
3604 &mut u,
3605 &mut v,
3606 w,
3607 h,
3608 cw,
3609 ch,
3610 col as i32,
3611 top - dy,
3612 fall,
3613 bg_y,
3614 ink_y,
3615 ink_u,
3616 ink_v,
3617 );
3618 viz_stamp(
3619 &mut y,
3620 &mut u,
3621 &mut v,
3622 w,
3623 h,
3624 cw,
3625 ch,
3626 col as i32,
3627 bot + dy,
3628 fall,
3629 bg_y,
3630 ink_y,
3631 ink_u,
3632 ink_v,
3633 );
3634 }
3635 }
3636 }
3637 }
3638 (y, u, v)
3639}
3640
3641/// `None` when the software path must be used: forced by `VE_SW=1`, or the
3642/// plugin is absent/broken/unable to open this particular file.
3643pub(crate) fn open_hw(path: &Path, start_frame: u32) -> Option<HwSession> {
3644 if crate::envcfg::var_os("VE_SW").is_some_and(|v| v == "1") {
3645 return None;
3646 }
3647 // A VP9 stream the GPU cannot take goes straight to the ec-vp9 software seat.
3648 if vp9_off_gpu(path).is_some() || h264_software_only(path) {
3649 return None;
3650 }
3651 HwSession::open_at(path, start_frame)
3652}
3653
3654/// Whether a VP9 stream of this profile and chroma is one the VA-API plugin cannot
3655/// take: the GPU decodes profiles 0 and 2 only, which are 4:2:0. Profiles 1 and 3
3656/// are the 4:2:2 and 4:4:4 ones. Used by both the import probe and the decode
3657/// open, through [`hw_decodes`] and [`open_hw`], so the two cannot disagree.
3658fn vp9_needs_420_for_vaapi(profile: u8, chroma: Chroma) -> bool {
3659 matches!(profile, 1 | 3) && chroma != Chroma::C420
3660}
3661
3662/// The VP9 profile and chroma of `path` when it is a stream the GPU cannot take
3663/// ([`vp9_needs_420_for_vaapi`]), `None` for every other file. Not a refusal: such
3664/// a stream plays on the ec-vp9 software seat, which takes all four profiles.
3665fn vp9_off_gpu(path: &Path) -> Option<(u8, Chroma)> {
3666 let (meta, demuxer) = Demuxer::open(path).ok()?;
3667 if meta.codec != Codec::Vp9 {
3668 return None;
3669 }
3670 let chroma = demuxer.chroma()?;
3671 // Profile 1 is 8-bit and profile 3 is 10-bit (12-bit is refused by the demuxer),
3672 // so the depth names the profile without the header keeping a second field.
3673 let profile = if demuxer.bit_depth() == 10 { 3 } else { 1 };
3674 vp9_needs_420_for_vaapi(profile, chroma).then_some((profile, chroma))
3675}
3676
3677/// A [`Render`] as a span over `demuxer`'s file builds it, for tests that need
3678/// the plain conversion of a picture a decoder handed over.
3679#[cfg(test)]
3680pub(crate) fn test_render(meta: VideoMeta, demuxer: &Demuxer) -> Render {
3681 Render::new(
3682 ColorParams::default(),
3683 TransformParams::default(),
3684 meta.rotation,
3685 meta.pixel_aspect,
3686 meta.color,
3687 Composer::passthrough(),
3688 tonemap::Preset::default(),
3689 demuxer.light().peak(),
3690 )
3691}
3692
3693/// The clip's deinterlace setting as it applies to this stream: `Frame` for
3694/// anything that is not interlaced H.264, which ignores the setting.
3695fn effective_deint(
3696 deint: crate::project::Deinterlace,
3697 meta: &VideoMeta,
3698 demuxer: &Demuxer,
3699) -> crate::project::Deinterlace {
3700 if matches!(deint, crate::project::Deinterlace::IvtcAuto | crate::project::Deinterlace::Ivtc) {
3701 // Resolved against the file: `Ivtc` when it has a cadence, else `Frame`.
3702 demuxer.path().map_or(crate::project::Deinterlace::Frame, |p| crate::deinterlace::effective(deint, p))
3703 } else if meta.codec == Codec::H264 && demuxer.h264_interlaced() {
3704 deint
3705 } else {
3706 crate::project::Deinterlace::Frame
3707 }
3708}
3709
3710/// Pictures per frame of the file: 2 in field mode, where the numbers are fields.
3711fn deint_units(deint: crate::project::Deinterlace) -> u32 {
3712 if deint == crate::project::Deinterlace::Field { 2 } else { 1 }
3713}
3714
3715/// Whether `path` is H.264 the GPU is never offered: above 8 bits (High 10, which
3716/// VA-API has no profile for), 4:4:4 / monochrome / High 4:4:4 Predictive, or interlaced (PAFF and MBAFF, whose field order
3717/// and picture order this engine reads off `ec-h264`'s own pictures and
3718/// deinterlaces with their neighbours, see [`crate::deinterlace`]). Both play on
3719/// the ec-h264 software seat.
3720fn h264_software_only(path: &Path) -> bool {
3721 Demuxer::open(path)
3722 .is_ok_and(|(meta, d)| {
3723 meta.codec == Codec::H264
3724 && (d.bit_depth() > 8
3725 || d.h264_interlaced()
3726 // High 4:4:4 Predictive / CAVLC 4:4:4 Intra (also 4:2:0 lossless
3727 // under them), 4:4:4 and monochrome: no VA-API H.264 profile.
3728 || matches!(d.chroma(), Some(Chroma::C444 | Chroma::Gray))
3729 || d.profile().is_some_and(|p| p.contains("4:4:4")))
3730 })
3731}
3732
3733/// Why a VP9 stream [`vp9_off_gpu`] names is on the software seat: the profile, its
3734/// chroma, and where it plays. Named so the probe's reason can be read off it.
3735fn vp9_software_route(profile: u8, chroma: Chroma) -> String {
3736 let format = match chroma {
3737 Chroma::C422 => "4:2:2",
3738 Chroma::C444 => "4:4:4",
3739 Chroma::Gray => "grey",
3740 Chroma::C420 => "4:2:0",
3741 };
3742 format!(
3743 "VP9 profile {profile} ({format}) is not 4:2:0, which the GPU does not take: it plays on the ec-vp9 software seat"
3744 )
3745}
3746
3747/// `Ok` when the plugin really decodes this file: it opens *and* hands back a
3748/// first picture. Opening only reads the container -- a stream the vendored
3749/// bitstream parser dies on (a 2160p wavefront HEVC did, for one) opens fine and
3750/// then produces nothing, which reaches the user as a black picture with an
3751/// instant `eof` unless the door asks for that first frame. Costs one decoded
3752/// frame per probe.
3753///
3754/// The `Err` says which half failed, because "there is no decoder for this
3755/// codec" and "the decoder here would not take this stream" are different
3756/// refusals and a user acts on them differently.
3757fn hw_decodes(path: &Path, start_frame: u32, codec: Codec) -> Result<(), String> {
3758 // The plugin's VA-API path takes Main, Main 10, Main Still and SCC (profile
3759 // 1, 2, 3, 9). A range-extensions stream (profile 4 and up: 4:2:2, 4:4:4,
3760 // 12-bit) reaches an `unimplemented!` in the vendored decoder, which panics.
3761 // Refused by name here instead, before the plugin is asked for anything.
3762 if codec == Codec::Hevc
3763 && let Ok((_, demuxer)) = Demuxer::open(path)
3764 && let Some(profile) = demuxer.hevc_profile().filter(|p| !matches!(p, 1 | 2 | 3 | 9))
3765 {
3766 // Named by the chroma the stream states, in the words `demux` uses for
3767 // the same refusal at open, so probe and import say one thing.
3768 let what = match demuxer.chroma() {
3769 Some(Chroma::C422) => "HEVC 4:2:2".to_string(),
3770 Some(Chroma::C444) => "HEVC 4:4:4".to_string(),
3771 Some(Chroma::Gray) => "HEVC 4:0:0".to_string(),
3772 _ => format!("HEVC profile {profile}"),
3773 };
3774 return Err(format!(
3775 "{what} (HEVC profile {profile}) is not offered to VA-API, which takes Main and Main 10 only: it plays on the ec-h265 software seat"
3776 ));
3777 }
3778 // VP9 profiles 1 and 3 are the 4:2:2 and 4:4:4 ones; the GPU takes 4:2:0 only, so
3779 // such a stream is not the plugin's: it is routed to the ec-vp9 software seat.
3780 if codec == Codec::Mpeg2 {
3781 return Err("MPEG-2 video has no VA-API path here: it plays on the ec-mpeg2 software seat".into());
3782 }
3783 if matches!(codec, Codec::ProRes | Codec::Dnxhd | Codec::Mjpeg | Codec::Dv | Codec::Mpeg4 | Codec::MsMpeg4 | Codec::Raw) {
3784 return Err(format!("{} has no VA-API path: it plays on its own software seat", codec.name()));
3785 }
3786 if codec == Codec::Vp9
3787 && let Some((profile, chroma)) = vp9_off_gpu(path)
3788 {
3789 return Err(vp9_software_route(profile, chroma));
3790 }
3791 if codec == Codec::H264 && h264_software_only(path) {
3792 return Err("H.264 High 10, 4:4:4, monochrome and interlaced H.264 are not offered to VA-API: they play on the ec-h264 software seat, deinterlaced".into());
3793 }
3794 let Some(mut hw) = open_hw(path, start_frame) else {
3795 return Err(format!("the VA-API plugin did not open this {} stream", codec.name()));
3796 };
3797 // End of stream counts as a refusal, not as a pass: a session that hands
3798 // back no picture at all is exactly the black-frame-and-instant-eof this
3799 // probe exists to catch, and `Ok(None)` is how the plugin says it.
3800 match hw.next_frame() {
3801 Ok(Some(_)) => Ok(()),
3802 _ => Err(codec.undecodable()),
3803 }
3804}
3805
3806/// One software or hardware pass over a span: the frames `start_frame..end_frame`
3807/// go to `tx`, drawn through `render`, and the pass ends early on `abort`.
3808/// `speed` and `failure` are the session's own.
3809struct Pass<'a> {
3810 tx: &'a SyncSender<Frame>,
3811 start_frame: u32,
3812 end_frame: u32,
3813 render: &'a mut Render,
3814 abort: &'a Abort<'a>,
3815 speed: Speed,
3816 failure: &'a DecodeFailure,
3817 /// The clip's deinterlace setting, already narrowed to what applies to the
3818 /// stream (`Frame` for anything not interlaced).
3819 deint: crate::project::Deinterlace,
3820}
3821
3822/// How a hardware pass over a span ended.
3823#[derive(Clone, Copy, Debug, PartialEq, Eq)]
3824enum HwEnd {
3825 /// The span was decoded to its end, or its consumer or abort stopped it.
3826 Done,
3827 /// Hardware gave nothing at all before the first picture, so software takes
3828 /// the whole span.
3829 Refused,
3830 /// Hardware failed after the first picture, at this display index: software
3831 /// takes the span from there.
3832 FellBackAt(u32),
3833}
3834
3835/// Reports how the pass ended: [`HwEnd::Refused`] only when hardware decode
3836/// failed without emitting a single frame, [`HwEnd::FellBackAt`] when it failed
3837/// after some, so software can take over either way.
3838///
3839/// The plugin already positioned itself at `start_frame`, so indices are
3840/// counted from there (a stream whose very first sample is not a sync sample
3841/// cannot be decoded from its start at all, and is not accounted for).
3842fn run_hw(hw: &mut HwSession, pass: Pass) -> HwEnd {
3843 let Pass {
3844 tx,
3845 start_frame,
3846 end_frame,
3847 render,
3848 abort,
3849 speed,
3850 failure: _,
3851 deint: _,
3852 } = pass;
3853 let mut index = start_frame;
3854 // Pictures dropped for being late since the last one handed over; see
3855 // [`LATE_RUN`].
3856 let mut skipped = 0;
3857 loop {
3858 if abort.hit() {
3859 return HwEnd::Done;
3860 }
3861 match hw.next_frame() {
3862 Ok(Some((y, u, v, width, height))) => {
3863 let due = index;
3864 index += 1;
3865 if abort.late(due) {
3866 if skipped < LATE_RUN {
3867 skipped += 1;
3868 } else {
3869 skipped = 0;
3870 let frame = render.frame(due, y, u, v, width, height);
3871 if tx.send(frame).is_err() {
3872 return HwEnd::Done; // consumer went away
3873 }
3874 }
3875 } else if skip_for_speed(speed, start_frame, due, end_frame) {
3876 // Redundant by construction, not by lateness: no run limit
3877 // needed (see `skip_for_speed`).
3878 } else {
3879 skipped = 0;
3880 let frame = render.frame(due, y, u, v, width, height);
3881 if tx.send(frame).is_err() {
3882 return HwEnd::Done; // consumer went away
3883 }
3884 }
3885 if index >= end_frame {
3886 return HwEnd::Done; // end of the requested range
3887 }
3888 }
3889 // End of stream before the first picture is the same signal as an
3890 // error there: the plugin opened and gave nothing, and software
3891 // takes the span. A mid-GOP start on AV1 does exactly this -- the
3892 // plugin's seek leaves the leading inter frames undecodable and the
3893 // stream then ends with no picture.
3894 Ok(None) if index == start_frame => return HwEnd::Refused,
3895 Ok(None) => return HwEnd::Done,
3896 Err(e) => {
3897 // Before the first picture this is not a failure to report but
3898 // the signal that software should take over, and it is reported
3899 // by the caller that does the falling back -- saying it here as
3900 // well would put a fault on the strip for a span that is about
3901 // to decode cleanly.
3902 if index == start_frame {
3903 return HwEnd::Refused;
3904 }
3905 // Mid-span: not a fault to report, because the software seat
3906 // takes the rest of the span from `index`.
3907 eprintln!("hardware decode error at frame {index}: {e}; continuing in software");
3908 return HwEnd::FellBackAt(index);
3909 }
3910 }
3911 }
3912}
3913
3914/// Converts one decoded picture and queues it. `true` when the consumer went
3915/// away, so the span stops rather than keeps decoding into a void.
3916fn send_picture(
3917 pic: &VideoFrame,
3918 due: u32,
3919 render: &mut Render,
3920 tx: &SyncSender<Frame>,
3921 deep: &mut Deep,
3922) -> bool {
3923 // A High 10 picture is narrowed to the 8-bit planes below first.
3924 deep.load(pic, false);
3925 if deep.on {
3926 let n = &deep.narrow;
3927 let frame = render.frame(due, &n.y, &n.u, &n.v, n.width, n.height);
3928 return tx.send(frame).is_err();
3929 }
3930 // The decoder crops each picture into tightly packed planes, the shape
3931 // every converter below takes. A padded plane would render skewed rather
3932 // than subtly wrong, so the assumption is pinned where it is relied on --
3933 // free in a release build.
3934 let (y, u, v) = (&pic.planes[0], &pic.planes[1], &pic.planes[2]);
3935 debug_assert_eq!(y.stride, pic.width as usize, "padded luma plane");
3936 debug_assert_eq!(
3937 u.stride,
3938 pic.width.div_ceil(2) as usize,
3939 "padded chroma plane"
3940 );
3941 let frame = render.frame(due, &y.data, &u.data, &v.data, pic.width, pic.height);
3942 tx.send(frame).is_err()
3943}
3944
3945fn run(demuxer: &mut Demuxer, pass: Pass) {
3946 let Pass {
3947 tx,
3948 start_frame,
3949 end_frame,
3950 render,
3951 abort,
3952 speed,
3953 failure,
3954 deint: mode,
3955 } = pass;
3956 // A decoder per span, and cheap: it is a parameter-set map and a picture
3957 // buffer, while the *demuxer* -- whose index cost seconds to build -- is the
3958 // one this worker keeps.
3959 let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264))
3960 .expect("ec-h264 takes its own codec id");
3961 // Decoding has to restart at a sync sample, so pictures between it and
3962 // `start_frame` are decoded (the target frame references them) but never
3963 // converted or sent. Signed, because the landing sync sample can sit inside
3964 // what the file's edit list trims, i.e. *before* frame 0.
3965 //
3966 // An interlaced stream is deinterlaced against the picture before and the
3967 // picture after each one ([`crate::deinterlace`]), so a seek lands one
3968 // picture earlier: the target's predecessor is decoded too, and the first
3969 // picture shown is filtered from the same neighbours a sequential decode
3970 // gave it.
3971 let interlaced = demuxer.h264_interlaced();
3972 let mut deint = crate::deinterlace::Deinterlacer::with_mode(
3973 mode,
3974 interlaced,
3975 i64::from(start_frame),
3976 ec_core::frame::Interlace::Progressive,
3977 )
3978 .cadenced(mode, demuxer);
3979 // In field mode `start_frame`, `end_frame` and every `due` below are field
3980 // numbers; the demuxer lands on the frame holding the first one.
3981 let mut index = demuxer.seek_to_sync_at_or_before(deint.landing(start_frame));
3982 let mut pending = std::collections::VecDeque::new();
3983 // Pictures leave the decoder in display order -- clause C.4.5.3 bumps the
3984 // decoded picture buffer -- and the landing index above is a display index
3985 // by the demuxer's own contract, so the two count one to one. The decode
3986 // order this loop used to emit was a corner-cut that only held for
3987 // Baseline: a stream with B pictures arrived scrambled and mislabelled,
3988 // and every reader of `index` (the transport's playhead, `skip_for_speed`,
3989 // the export's frame map) reads it as a timeline position.
3990 let mut skipped = 0;
3991 let mut deep = Deep::default();
3992 // Set once the demuxer runs dry: `flush` makes the decoder release every
3993 // picture its reorder delay still holds, and the drain below ends on
3994 // `Error::Eof` once they are out.
3995 let mut flushed = false;
3996 // Every way this span ends: abort, consumer gone, end of the requested
3997 // range, end of stream.
3998 let mut done = false;
3999 while !done {
4000 if abort.hit() {
4001 break;
4002 }
4003 // One access unit is one packet. No timestamps travel with it: the
4004 // presentation order comes out of the bitstream's own POC, and `index`
4005 // is counted off the pictures as the decoder releases them.
4006 match demuxer.next_access_unit() {
4007 Ok(Some(au)) => {
4008 let packet = Packet::new(0, TimeBase::new(1, 1), au);
4009 if let Err(e) = decoder.send_packet(&packet) {
4010 failure.set(format!("decode error at access unit {index}: {e}"));
4011 break;
4012 }
4013 }
4014 Ok(None) => {
4015 flushed = true;
4016 if let Err(e) = decoder.flush() {
4017 failure.set(format!("decode error at end of stream: {e}"));
4018 break;
4019 }
4020 }
4021 Err(e) => {
4022 failure.set(format!("demux error: {e}"));
4023 break;
4024 }
4025 }
4026 // Take everything the packet released; `NeedMore` is the signal to go
4027 // back for the next access unit.
4028 loop {
4029 let (due, pic) = match pending.pop_front() {
4030 Some(ready) => ready,
4031 None => match decoder.receive_frame() {
4032 Ok(ec_core::frame::Frame::Video(pic)) => {
4033 let tag = index;
4034 index += 1;
4035 // A disabled stage hands the picture straight back; an
4036 // interlaced stream's comes one picture late (two,
4037 // fields, in field mode), and nothing while it primes
4038 // or for a picture below the target.
4039 pending.extend(deint.push_all(tag, pic));
4040 continue;
4041 }
4042 Ok(_) => continue,
4043 Err(e) if e.is_need_more() || e.is_eof() => {
4044 // The end of the stream releases the picture the stage
4045 // was holding for a successor.
4046 if flushed {
4047 pending.extend(deint.finish_all());
4048 }
4049 if pending.is_empty() {
4050 break;
4051 }
4052 continue;
4053 }
4054 Err(e) => {
4055 failure.set(format!("decode error at access unit {index}: {e}"));
4056 break;
4057 }
4058 },
4059 };
4060 if due < i64::from(start_frame) {
4061 continue;
4062 }
4063 let due = due as u32;
4064 if abort.late(due) {
4065 if skipped < LATE_RUN {
4066 skipped += 1;
4067 } else {
4068 skipped = 0;
4069 if send_picture(&pic, due, render, tx, &mut deep) {
4070 done = true; // consumer went away
4071 break;
4072 }
4073 }
4074 } else if skip_for_speed(speed, start_frame, due, end_frame) {
4075 // Redundant by construction, not by lateness: no run limit
4076 // needed (see `skip_for_speed`).
4077 } else {
4078 skipped = 0;
4079 if send_picture(&pic, due, render, tx, &mut deep) {
4080 done = true; // consumer went away
4081 break;
4082 }
4083 }
4084 if due + 1 >= end_frame {
4085 done = true; // end of the requested range
4086 break;
4087 }
4088 }
4089 if flushed {
4090 done = true;
4091 }
4092 }
4093}
4094
4095/// Whether an access unit leads with a sequence header OBU, which is how both
4096/// containers mark a random-access point for AV1: the demuxer prepends the
4097/// `av1C`/`CodecPrivate` record (itself one sequence header OBU) ahead of every
4098/// sync sample, so the marker rides on the same bytes the decoder needs. Type 1
4099/// in bits 6..3 of the first OBU header byte.
4100pub(crate) fn leads_with_sequence_header(au: &[u8]) -> bool {
4101 matches!(au.first(), Some(&first) if first >> 3 & 0xF == 1)
4102}
4103
4104/// One [`Av1Picture`] down to the tightly packed 8-bit I420 every converter
4105/// here takes. 8-bit samples arrive as `u16` in `0..=255` and narrow losslessly;
4106/// a 10-bit stream's `0..=1023` downshifts by two and a 12-bit one's by four,
4107/// the same truncation the hardware seat's P010 read-back performs when it
4108/// takes the high byte of each pair (`p010_to_i420`, engine-hw) -- so the two
4109/// seats hand the renderer byte-identical planes off the same file.
4110///
4111/// `depth` is the stream's bits per luma sample. A 4:2:2 or 4:4:4 picture
4112/// (profiles 1 and 2) has its chroma averaged down to 4:2:0 first, rounding to
4113/// nearest, at the depth it was decoded in: a pair of rows for 4:2:2, a 2x2 box
4114/// for 4:4:4 (the export's [`crate::export::chroma_420`], which the export seat
4115/// has applied already when the planes arrive here at 4:2:0).
4116pub(crate) fn narrow_av1(
4117 picture: &Av1Picture,
4118 depth: u8,
4119 y: &mut Vec<u8>,
4120 u: &mut Vec<u8>,
4121 v: &mut Vec<u8>,
4122) {
4123 let shift = depth.saturating_sub(8);
4124 let plane = |src: &[u16], dst: &mut Vec<u8>| {
4125 dst.clear();
4126 dst.extend(src.iter().map(|&sample| (sample >> shift) as u8));
4127 };
4128 plane(&picture.y, y);
4129 let (w, h) = (picture.width, picture.height);
4130 let (ow, oh) = (w.div_ceil(2), h.div_ceil(2));
4131 match crate::export::chroma_shape(picture.u.len(), w, h) {
4132 Some((cw, ch)) if (cw, ch) != (ow, oh) => {
4133 let down = |src: &[u16], dst: &mut Vec<u8>| {
4134 dst.clear();
4135 dst.extend(
4136 crate::export::chroma_420(src, cw, ch, ow, oh)
4137 .into_iter()
4138 .map(|s| (s >> shift) as u8),
4139 );
4140 };
4141 down(&picture.u, u);
4142 down(&picture.v, v);
4143 }
4144 _ => {
4145 plane(&picture.u, u);
4146 plane(&picture.v, v);
4147 }
4148 }
4149}
4150
4151/// Narrows one [`Av1Picture`] ([`narrow_av1`]) and queues it through the same
4152/// [`Render`] every other seat's pictures go through. `true` when the consumer
4153/// went away, so the span stops rather than keeps decoding into a void.
4154fn send_av1(
4155 picture: &Av1Picture,
4156 due: u32,
4157 depth: u8,
4158 render: &mut Render,
4159 tx: &SyncSender<Frame>,
4160 (y, u, v): (&mut Vec<u8>, &mut Vec<u8>, &mut Vec<u8>),
4161) -> bool {
4162 narrow_av1(picture, depth, y, u, v);
4163 let frame = render.frame(due, y, u, v, picture.width as u32, picture.height as u32);
4164 tx.send(frame).is_err()
4165}
4166
4167/// The AV1 software seat: one span of [`ec_av1`] through the same loop
4168/// [`run`] drives `ec-h264` through. A decoder per span, and cheap -- it is the
4169/// reference bank and one output picture, while the *demuxer* is the one this
4170/// worker keeps. `ec-av1` has no packet-by-packet door; it takes one whole OBU
4171/// stream, so the span is fed as it is built: every access unit from the landing
4172/// sync sample up to (not including) the next one is one chunk, and a chunk is
4173/// a legal random-access stream on its own -- it leads with the sequence header
4174/// and a key frame, which is exactly what makes the chunk boundary detectable
4175/// here ([`leads_with_sequence_header`]). A stream whose inter frames carried
4176/// an in-band sequence header would be cut mid-GOP and refused by name below,
4177/// never silently misread; container storage keeps the sequence header in the
4178/// config record precisely so that does not happen.
4179///
4180/// Chunks decode to their end, so the reorder window of the chunk the span
4181/// ends in always drains: hidden frames (`show_frame == 0`) are references
4182/// and arrive at the sink with `shown == false`, and the frames they hold
4183/// back in output order are the tail the sink still has to see.
4184///
4185/// A refusal out of `ec-av1` -- a real-world stream hitting a shape the
4186/// decoder does not reconstruct -- fails the span in words, mid-film, the way
4187/// the hardware seat's errors do: named on stderr, the pictures decoded so
4188/// far stand, and no garbage is sent. The same sentinel ends a span that has
4189/// delivered everything asked of it without decoding the rest of its last
4190/// chunk.
4191fn run_av1(demuxer: &mut Demuxer, pass: Pass) {
4192 let Pass {
4193 tx,
4194 start_frame,
4195 end_frame,
4196 render,
4197 abort,
4198 speed,
4199 failure,
4200 deint: _,
4201 } = pass;
4202 // Signed, for the same reason [`run`]'s is: the landing sync sample can
4203 // sit inside what an mp4's edit list trims, i.e. before frame 0.
4204 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
4205 // Reusable plane buffers: one allocation each for the whole span, refilled
4206 // per picture by [`narrow_av1`].
4207 let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new());
4208 let mut skipped = 0;
4209 // Every way this span ends: abort, consumer gone, the requested range
4210 // delivered, the demuxer dry, or a refusal out of the decoder.
4211 let mut done = false;
4212 let mut demux_dry = false;
4213 // An access unit read past a chunk boundary, waiting to head the next one.
4214 let mut pending: Option<Vec<u8>> = None;
4215 while !done && !demux_dry {
4216 if abort.hit() {
4217 break;
4218 }
4219 // One chunk: the access units from a sync sample up to the next one.
4220 let mut stream = pending.take().unwrap_or_default();
4221 while !demux_dry && pending.is_none() {
4222 match demuxer.next_access_unit() {
4223 Ok(Some(au)) => {
4224 if !stream.is_empty() && leads_with_sequence_header(&au) {
4225 pending = Some(au);
4226 } else {
4227 stream.extend_from_slice(&au);
4228 }
4229 }
4230 Ok(None) => demux_dry = true,
4231 Err(e) => {
4232 failure.set(format!("demux error: {e}"));
4233 return;
4234 }
4235 }
4236 }
4237 let depth = demuxer.bit_depth();
4238 let decode = decode_stream_with(&stream, |picture, _, shown| {
4239 // Hidden frames are references: they take no display slot and
4240 // are never sent, but they do hold the chunk's output order
4241 // back, which is why the chunk decodes to its end.
4242 if !shown {
4243 return Ok(());
4244 }
4245 let due = index;
4246 index += 1;
4247 if due < i64::from(start_frame) {
4248 return Ok(());
4249 }
4250 let due = due as u32;
4251 // The three ends [`run`] reaches per picture, in its own shape:
4252 // late for the playhead (one in [`LATE_RUN`] still goes through),
4253 // redundant by construction at speed, or a conversion and a send.
4254 let sent = if abort.late(due) {
4255 if skipped < LATE_RUN {
4256 skipped += 1;
4257 false
4258 } else {
4259 skipped = 0;
4260 send_av1(picture, due, depth, render, tx, (&mut y, &mut u, &mut v))
4261 }
4262 } else if skip_for_speed(speed, start_frame, due, end_frame) {
4263 // Redundant by construction, not by lateness: no run limit
4264 // needed (see `skip_for_speed`).
4265 false
4266 } else {
4267 skipped = 0;
4268 send_av1(picture, due, depth, render, tx, (&mut y, &mut u, &mut v))
4269 };
4270 if sent {
4271 done = true; // consumer went away
4272 }
4273 if done || i64::from(due) + 1 >= i64::from(end_frame) {
4274 done = true; // the range is out, or nobody is left to take it
4275 // Stops the decode inside the chunk: everything the span
4276 // asked for has been sent, and the chunk's remaining coded
4277 // frames are references for pictures nobody asked for.
4278 return Err(Av1Error::Eof);
4279 }
4280 Ok(())
4281 });
4282 // `done` was set by the sink itself for the `Eof` it returns -- the
4283 // sentinel, not a refusal. Any other `Err` is a refusal out of the
4284 // decoder, named where the hardware seat's decode errors are named;
4285 // the pictures decoded so far stand and the span ends.
4286 if let Err(e) = decode
4287 && !done
4288 {
4289 failure.set(format!("software AV1 decode failed at frame {index}: {e}"));
4290 done = true;
4291 }
4292 }
4293}
4294
4295#[cfg(test)]
4296mod tests {
4297 use super::*;
4298 use std::sync::mpsc::RecvTimeoutError;
4299 use std::time::{Duration, Instant};
4300
4301 fn asset(name: &str) -> PathBuf {
4302 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
4303 .join("../../assets")
4304 .join(name)
4305 }
4306
4307 /// Drops `path` from the page cache, so the open below really goes to disk
4308 /// -- the case the deferred opener exists for, and the one that costs
4309 /// seconds on a 25 GB film. Unprivileged (`posix_fadvise(DONTNEED)`), and a
4310 /// no-op wherever `python3` is not around: the assertions hold either way,
4311 /// the numbers printed are simply the warm ones.
4312 fn evict(path: &Path) {
4313 let _ = std::process::Command::new("python3")
4314 .arg("-c")
4315 .arg(
4316 "import os,sys\n\
4317 fd=os.open(sys.argv[1],os.O_RDONLY)\n\
4318 os.posix_fadvise(fd,0,0,os.POSIX_FADV_DONTNEED)\n\
4319 os.close(fd)",
4320 )
4321 .arg(path)
4322 .status();
4323 }
4324
4325 /// The whole point of [`DecodeSession::open_worker_deferred`]: the caller
4326 /// gets its stream back in the time a thread takes to spawn, and the file
4327 /// is opened behind it -- so the first frame necessarily arrives *after*
4328 /// the call returned, and the sync opener on the same cold file pays on the
4329 /// calling thread what this one does not.
4330 #[test]
4331 fn a_deferred_open_costs_the_caller_a_thread_and_not_a_demux() {
4332 let path = asset("test_baseline.mp4");
4333 // One cold deferred open: how long the call took, the stream's first
4334 // frame, and when that arrived.
4335 let deferred = || {
4336 evict(&path);
4337 let start = Instant::now();
4338 let stream = DecodeSession::open_worker_deferred(
4339 &path,
4340 0,
4341 u32::MAX,
4342 ColorParams::default(),
4343 TransformParams::default(),
4344 Composer::passthrough(),
4345 tonemap::Preset::default(),
4346 Speed::NORMAL,
4347 );
4348 let returned = start.elapsed();
4349 let frame = stream
4350 .frames
4351 .recv_timeout(Duration::from_secs(10))
4352 .expect("first frame");
4353 (returned, frame, start.elapsed())
4354 };
4355 // The call's cost is a wall-clock sample, and a thread spawn on a
4356 // machine under a parallel build can be descheduled for tens of ms --
4357 // the fastest of a few tries is the cost the code itself has, as the
4358 // tonemap perf gate does. A real read-before-return costs every try.
4359 let (mut returned, frame, mut first_frame) = deferred();
4360 for _ in 0..7 {
4361 if returned < Duration::from_millis(10) {
4362 break;
4363 }
4364 let (r, _, f) = deferred();
4365 if r < returned {
4366 (returned, first_frame) = (r, f);
4367 }
4368 }
4369
4370 // The same file, equally cold, through the door the import path keeps:
4371 // that one hands back metadata, and the demux it reads to do so is on
4372 // this thread.
4373 evict(&path);
4374 let sync_start = Instant::now();
4375 let sync = DecodeSession::open_worker(
4376 &path,
4377 0,
4378 u32::MAX,
4379 ColorParams::default(),
4380 TransformParams::default(),
4381 Composer::passthrough(),
4382 tonemap::Preset::default(),
4383 )
4384 .expect("sync open");
4385 let sync_returned = sync_start.elapsed();
4386 drop(sync);
4387
4388 eprintln!(
4389 "deferred open returned in {returned:?}, first frame at {first_frame:?}; \
4390 sync open returned in {sync_returned:?}"
4391 );
4392 assert_eq!(
4393 frame.index, 0,
4394 "the deferred worker starts where it is told"
4395 );
4396 assert!(
4397 returned < Duration::from_millis(10),
4398 "the caller waited {returned:?} -- something is still being read \
4399 from the file before this returns"
4400 );
4401 assert!(
4402 first_frame > returned,
4403 "the first frame arrived within the call ({first_frame:?} vs \
4404 {returned:?}), which cannot happen if the open is deferred"
4405 );
4406 // No `returned < sync_returned` here on purpose: on a loaded machine
4407 // a thread spawn (what the deferred open pays) can cost more wall
4408 // clock than a whole sync demux of a small fixture, and the race
4409 // flaked one run in three under a parallel build. The two asserts
4410 // above already pin the invariant -- the call returns in microseconds
4411 // territory and the demux happens after it, on the worker.
4412 let _ = sync_returned;
4413 }
4414
4415 /// The late-picture policy, at the one place it is decided. A worker told
4416 /// the playhead is already at frame 20 must not spend a conversion and a
4417 /// queue slot on the twenty pictures behind it -- they can never be shown --
4418 /// and it must not go silent either, which is what [`LATE_RUN`] bounds: a
4419 /// machine that cannot decode in real time is late on every picture, and one
4420 /// in nine still reaches the screen.
4421 ///
4422 /// Deterministic on purpose: the floor is set by hand rather than by a clock
4423 /// that would have to outrun a debug-build decoder to prove anything.
4424 #[test]
4425 fn a_worker_skips_the_pictures_the_playhead_has_gone_past() {
4426 let take = |floor: u32| {
4427 let stream = DecodeSession::open_worker_deferred(
4428 asset("test_baseline.mp4"),
4429 0,
4430 u32::MAX,
4431 ColorParams::default(),
4432 TransformParams::default(),
4433 Composer::passthrough(),
4434 tonemap::Preset::default(),
4435 Speed::NORMAL,
4436 );
4437 stream.worker.playhead(floor);
4438 let mut indices = Vec::new();
4439 while indices.len() < 4 {
4440 let frame = stream
4441 .frames
4442 .recv_timeout(Duration::from_secs(10))
4443 .expect("a picture");
4444 indices.push(frame.index);
4445 }
4446 indices
4447 };
4448
4449 // Nobody has moved: every picture of the range is owed, in order.
4450 assert_eq!(take(0), vec![0, 1, 2, 3]);
4451
4452 // The playhead is at 20, so the pictures before it are decoded (the ones
4453 // after reference them) and dropped unconverted -- all but the one in
4454 // nine [`LATE_RUN`] lets through, so the caller never goes blind.
4455 let caught_up = take(20);
4456 assert!(
4457 caught_up[0] > 0 && caught_up.windows(2).any(|w| w[1] > w[0] + 1),
4458 "nothing was skipped: {caught_up:?}"
4459 );
4460 assert!(
4461 caught_up.iter().any(|&i| i >= 20),
4462 "the playhead was never reached: {caught_up:?}"
4463 );
4464 assert!(
4465 caught_up.len() >= 4,
4466 "the worker went silent instead of dropping down to one in nine"
4467 );
4468 }
4469
4470 /// [`skip_for_speed`] on its own, with no worker or channel involved: at
4471 /// 2x every other source frame maps onto the same timeline frame
4472 /// ([`Speed::timeline_at`]), so `skip`/`keep` must alternate exactly, and
4473 /// the last frame of the span (the one [`crate::project::Span::source_len`]
4474 /// is built to land on) must never be skipped regardless of where the
4475 /// alternation lands.
4476 #[test]
4477 fn skip_for_speed_alternates_at_2x_and_never_drops_the_last_frame() {
4478 let speed = Speed::from_permille(2000);
4479 let start = 100;
4480 let end = 110;
4481
4482 let skips: Vec<bool> = (start..end)
4483 .map(|due| skip_for_speed(speed, start, due, end))
4484 .collect();
4485 // Alternation holds up to (but not including) the span's last frame,
4486 // which is special-cased below.
4487 for pair in (start..end - 2).zip(skips.windows(2)) {
4488 let (due, w) = pair;
4489 assert_eq!(
4490 w[0], !w[1],
4491 "frame {due} and its successor should alternate skip/keep at 2x: {skips:?}"
4492 );
4493 }
4494 assert!(
4495 !skip_for_speed(speed, start, end - 1, end),
4496 "the last frame of the span must never be skipped"
4497 );
4498 }
4499
4500 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
4501 /// The channel is bounded, so such a worker is parked in `send` within a
4502 /// few frames, and the only thing that can wake it is its receiver going
4503 /// away -- which is why the receiver is the first field and the join inside
4504 /// `Worker::drop` is the second. Swap those two fields and this hangs.
4505 ///
4506 /// This is the whole basis of every teardown path in the engine, so it is
4507 /// asserted rather than commented: the drop runs on a second thread and a
4508 /// regression fails in ten seconds instead of hanging the suite forever.
4509 #[test]
4510 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
4511 let (_meta, stream) = DecodeSession::open_worker(
4512 asset("test_baseline.mp4"),
4513 0,
4514 u32::MAX,
4515 ColorParams::default(),
4516 TransformParams::default(),
4517 Composer::passthrough(),
4518 tonemap::Preset::default(),
4519 )
4520 .expect("open");
4521 // Nothing is ever received: two frames fill the channel and the next
4522 // send parks the decode thread, exactly as a refused project load does.
4523 thread::sleep(Duration::from_millis(500));
4524
4525 let (done_tx, done_rx) = sync_channel(1);
4526 thread::spawn(move || {
4527 drop(stream);
4528 let _ = done_tx.send(());
4529 });
4530 assert!(
4531 done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout),
4532 "dropping a parked stream deadlocked: it joined a decode thread \
4533 while still holding the receiver that thread is waiting on"
4534 );
4535 }
4536
4537 /// The empty-peaks source -- a trackless file, or any peaks decode error
4538 /// (`peaks_shared(..).ok().flatten().unwrap_or_default()`) -- must paint
4539 /// the flat line, never panic: a visualizer frame always exists. The
4540 /// `pair_at` interpolator indexes `peaks[len() - 1]`, which is only
4541 /// reachable inside the `!peaks.is_empty()` guard, so the empty vec takes
4542 /// the early flat-line path and no column ever samples a bucket.
4543 #[test]
4544 fn empty_peaks_paint_the_flat_line() {
4545 let w = 320u32;
4546 let h = 180u32;
4547 let (y, _u, _v) = visualizer_i420(&mut VizScratch::default(), &[], 0.0, w, h, 1, 0);
4548 assert_eq!(
4549 (y.len(), _u.len(), _v.len()),
4550 (320 * 180, 160 * 90, 160 * 90)
4551 );
4552 // The ink's top and bottom row for a given peaks slice: one unbroken
4553 // band, and where it sits.
4554 let band = |peaks: &[(f32, f32)]| {
4555 let (y, _, _) = visualizer_i420(&mut VizScratch::default(), peaks, 0.0, w, h, 1, 0);
4556 let rows: Vec<usize> = (0..h as usize)
4557 .filter(|&row| y[row * 320..(row + 1) * 320].iter().any(|&p| p > 40))
4558 .collect();
4559 assert!(
4560 !rows.is_empty() && rows.len() == rows[rows.len() - 1] - rows[0] + 1,
4561 "the ink must be one unbroken band, not scattered rows: {rows:?}"
4562 );
4563 (rows[0], rows[rows.len() - 1])
4564 };
4565 // Silence is the zero line and nothing else: the band is on the middle
4566 // row and a line's thickness -- five rows here, the trace's own -- not
4567 // a picture's.
4568 let (first, last) = band(&[]);
4569 let zero = h as usize / 2;
4570 assert!(
4571 first <= zero && zero <= last,
4572 "the zero line itself must be inked: {first}..={last}"
4573 );
4574 assert!(
4575 last - first <= (h as usize) / 8,
4576 "a peaks-less source painted a {}-row band, not a line: {first}..={last}",
4577 last - first + 1
4578 );
4579 // ...and the same seat over full-scale peaks is a picture, which is
4580 // what makes the line above a claim about silence rather than about a
4581 // painter that never draws anything.
4582 let (loud_first, loud_last) = band(&[(-1.0, 1.0); 1200]);
4583 assert!(
4584 loud_last - loud_first > (last - first) * 3,
4585 "full-scale peaks painted {loud_first}..={loud_last}, no taller than silence's {first}..={last}"
4586 );
4587 }
4588
4589 /// A canvas with no size has no row to draw the zero line on. The row index
4590 /// is derived from the height (`h as isize - 1`), so a *height* of zero
4591 /// underflows into `clamp`'s `min <= max` assert and takes the worker
4592 /// thread with it. A `Composer::passthrough()` canvas is exactly this
4593 /// (`dims()` is `(0, 0)`, `places_nothing()` is true for it), and a
4594 /// one-pixel-high canvas floors to the same nothing, the planes being even.
4595 #[test]
4596 fn a_size_less_visualizer_canvas_paints_nothing() {
4597 let size_less = visualizer_i420(&mut VizScratch::default(), &[], 0.0, 0, 0, 0, 0);
4598 assert_eq!(size_less, (Vec::new(), Vec::new(), Vec::new()));
4599 let thin = visualizer_i420(&mut VizScratch::default(), &[(0.0, 1.0)], 0.0, 2, 1, 0, 0);
4600 assert!(
4601 thin.0.is_empty() && thin.1.is_empty() && thin.2.is_empty(),
4602 "a 2x1 canvas has no even-sized plane to paint on"
4603 );
4604 }
4605
4606 /// The same canvas, driven through the seat that really opens one: the
4607 /// worker thread is where a panic *is* the defect -- it closes the frame
4608 /// channel and the caller sees a span with no picture in it, which is what
4609 /// the export then aborts on.
4610 #[test]
4611 fn a_pass_through_canvas_visualizer_paints_nothing_and_stays_alive() {
4612 let transform = TransformParams {
4613 pos_x: 0.25,
4614 ..Default::default()
4615 };
4616 let stream = DecodeSession::open_visualizer(
4617 &asset("test_opus_51.mka"),
4618 0,
4619 0,
4620 2,
4621 30.0,
4622 ColorParams::default(),
4623 transform,
4624 Composer::passthrough(),
4625 VIZ_STYLE_WAVE,
4626 0,
4627 )
4628 .expect("open the visualizer");
4629 let frame = stream
4630 .frames
4631 .recv_timeout(Duration::from_secs(30))
4632 .expect("a picture, not a worker that died instead of painting one");
4633 assert_eq!((frame.width, frame.height), (0, 0));
4634 assert!(frame.bgra.is_empty());
4635 }
4636
4637 /// The same seat, at the two canvas sizes whose *declared* dims used to
4638 /// disagree with the planes the painter handed back: one pixel high (the
4639 /// planes floor to nothing) and odd (they floor to the even size below).
4640 /// The worker declares the size it renders at -- masked and floored the way
4641 /// the painter masks -- so the conversion below always has the chroma plane
4642 /// it indexes, and a picture arrives at the canvas's own size.
4643 #[test]
4644 fn a_thin_and_an_odd_visualizer_canvas_paint_through_the_seat() {
4645 for (w, h) in [(1920u32, 1u32), (1921, 1081)] {
4646 let stream = DecodeSession::open_visualizer(
4647 &asset("test_opus_51.mka"),
4648 0,
4649 0,
4650 2,
4651 30.0,
4652 ColorParams::default(),
4653 TransformParams::default(),
4654 Composer::new(w, h, crate::scale::FitPolicy::Fit),
4655 VIZ_STYLE_WAVE,
4656 0,
4657 )
4658 .unwrap_or_else(|e| panic!("open the visualizer at {w}x{h}: {e}"));
4659 let frame = stream
4660 .frames
4661 .recv_timeout(Duration::from_secs(30))
4662 .unwrap_or_else(|e| {
4663 panic!("a picture for a {w}x{h} canvas, not a worker that died instead: {e}")
4664 });
4665 assert_eq!(
4666 (frame.width, frame.height),
4667 (w, h),
4668 "a {w}x{h} canvas is handed back at its own size"
4669 );
4670 assert_eq!(
4671 frame.bgra.len(),
4672 (w * h * 4) as usize,
4673 "and converted across the whole canvas at {w}x{h}"
4674 );
4675 }
4676 }
4677
4678 /// Serialises the pins: `VE_SW` is process-wide and this file's unit tests
4679 /// share one process, so two pinned tests must not see each other's pin
4680 /// cleared under them.
4681 static SW_PIN: std::sync::Mutex<()> = std::sync::Mutex::new(());
4682
4683 /// The `VE_SW=1` pin, held for one test and put back as it was.
4684 struct SwPin {
4685 _lock: std::sync::MutexGuard<'static, ()>,
4686 was: Option<std::ffi::OsString>,
4687 }
4688
4689 impl SwPin {
4690 fn set() -> Self {
4691 let lock = SW_PIN
4692 .lock()
4693 .unwrap_or_else(|poisoned| poisoned.into_inner());
4694 let was = crate::envcfg::var_os("VE_SW");
4695 crate::envcfg::set("VE_SW", "1");
4696 Self { _lock: lock, was }
4697 }
4698 }
4699
4700 impl Drop for SwPin {
4701 fn drop(&mut self) {
4702 match &self.was {
4703 Some(was) => crate::envcfg::set("VE_SW", was),
4704 None => crate::envcfg::unset("VE_SW"),
4705 }
4706 }
4707 }
4708
4709 /// HEVC has a software seat of its own (`ec-h265`), so with the plugin off a
4710 /// span on it is on that seat: it reports `Software`, and decodes what it was
4711 /// asked for. Driven through [`run_span`] itself, the door the front-end's
4712 /// spans come through; `VE_SW=1` is what makes the plugin's absence
4713 /// box-independent; see [`SwPin`].
4714 #[test]
4715 fn an_hevc_span_with_no_hardware_takes_the_software_seat() {
4716 let _pin = SwPin::set();
4717 let path = asset("test_hevc.mp4");
4718 let mut source = None;
4719 let cancel = AtomicBool::new(false);
4720 let generation = AtomicU64::new(0);
4721 let floor = AtomicU32::new(0);
4722 let abort = Abort {
4723 cancel: &cancel,
4724 generation: &generation,
4725 mine: 0,
4726 floor: &floor,
4727 };
4728 let (tx, rx) = sync_channel(2);
4729 let cell = BackendCell::new(Backend::Opening);
4730 let failure = DecodeFailure::default();
4731 run_span(
4732 &path,
4733 &mut source,
4734 SpanCmd {
4735 generation: 0,
4736 start: 0,
4737 end: 2,
4738 color: ColorParams::default(),
4739 transform: TransformParams::default(),
4740 canvas: Composer::passthrough(),
4741 tone: tonemap::Preset::default(),
4742 speed: Speed::NORMAL,
4743 deint: Default::default(),
4744 tx,
4745 },
4746 &abort,
4747 &cell,
4748 &failure,
4749 );
4750 assert_eq!(
4751 cell.get(),
4752 Backend::Software,
4753 "an HEVC span with no hardware is on the software seat, not a gap"
4754 );
4755 assert_eq!(
4756 rx.try_iter().count(),
4757 2,
4758 "the software seat decodes the span's two pictures"
4759 );
4760 assert!(
4761 failure.reason().is_none(),
4762 "and a span that decoded what it was asked for says nothing went wrong"
4763 );
4764 }
4765
4766 #[test]
4767 fn visualizer_default_is_a_blue_envelope() {
4768 let mut peaks = vec![(0.0, 0.0); 12_000];
4769 for (i, p) in peaks.iter_mut().enumerate() {
4770 let a = ((i as f32 / 400.0) * std::f32::consts::TAU).sin() * 0.8;
4771 *p = (-a.abs(), a.abs());
4772 }
4773 let flags = 1u8;
4774 let (y, u, v) =
4775 visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0);
4776 let ink = y.iter().filter(|&&p| p > 40).count();
4777 assert!(ink > 200, "envelope missing: {ink}");
4778 assert!(
4779 ink < y.len() * 9 / 10,
4780 "solid frame, not an envelope: {ink}"
4781 );
4782 let mut blue = 0usize;
4783 for i in 0..u.len() {
4784 if u[i] > 145 && v[i] < 120 {
4785 blue += 1;
4786 }
4787 }
4788 assert!(blue > 10, "default ink was not timeline blue: {blue}");
4789
4790 let ring = with_viz_style(flags, VIZ_STYLE_RING);
4791 let (yr, _, _) =
4792 visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0);
4793 let ring_ink = yr.iter().filter(|&&p| p > 40).count();
4794 assert!(ring_ink > 80, "ring missing: {ring_ink}");
4795 assert!(ring_ink < ink, "ring should be a stroke, not a fill");
4796
4797 let hue_paint = with_viz_paint_hue(0, 40);
4798 let (_, u2, v2) = visualizer_i420(
4799 &mut VizScratch::default(),
4800 &peaks,
4801 1.0,
4802 64,
4803 32,
4804 flags,
4805 hue_paint,
4806 );
4807 let mut shifted = 0usize;
4808 for i in 0..u2.len() {
4809 if u2[i] < 120 && v2[i] > 130 {
4810 shifted += 1;
4811 }
4812 }
4813 assert!(shifted > 2, "hue 8 did not leave blue");
4814 }
4815
4816 /// The paint's byte layout: the strand colour lives above the clip's own
4817 /// four bytes and the top bit is the flag, so either strand setter marks
4818 /// the colour chosen and clearing drops both bytes with the flag.
4819 #[test]
4820 fn the_paint_packs_the_strand_colour_above_the_v22_halves() {
4821 let p = with_viz_paint_strand_sat(with_viz_paint_strand_hue(VIZ_PAINT_AZURE, 0xAB), 0xCD);
4822 assert_eq!(p & 0xFFFF_FFFF, VIZ_PAINT_AZURE, "the low half never moves");
4823 assert_eq!((p >> 32) & 0xFF, 0xAB);
4824 assert_eq!((p >> 40) & 0xFF, 0xCD);
4825 assert!(viz_strand_set(p));
4826 assert_eq!(viz_strand_hue_ui(p), 0xAB);
4827 assert_eq!(viz_strand_sat_ui(p), 0xCD);
4828 assert_eq!(viz_strand_clear(p), VIZ_PAINT_AZURE);
4829 assert!(!viz_strand_set(viz_strand_clear(p)));
4830 }
4831
4832 /// The shapes a colour is typed in all mean the same ink, and everything
4833 /// else is refused rather than guessed at.
4834 #[test]
4835 fn typed_colours_read_as_hex_rgb_and_rgba() {
4836 let want = viz_color_from_text("#4F8FD6").expect("a hex colour");
4837 assert_eq!(want, (150, 161), "hue and sat on the field's own scales");
4838 for text in [
4839 "#4F8FD6",
4840 "4f8fd6",
4841 " #4f8fd6 ",
4842 "rgb(79,143,214)",
4843 "rgb(79/143/214)",
4844 "RGBA(79, 143, 214, 255)",
4845 ] {
4846 assert_eq!(viz_color_from_text(text), Some(want), "{text}");
4847 }
4848 for text in [
4849 "#12345",
4850 "zz",
4851 "rgb(300,0,0)",
4852 "rgb(1,2)",
4853 "",
4854 "rgb 79,143,214)",
4855 "rgb(79,143,214",
4856 "#4F8FD",
4857 "#4F8FD67",
4858 "#GGGGGG",
4859 "rgb(79,143,214,255,0)",
4860 "rgb(79;143;214)",
4861 ] {
4862 assert_eq!(viz_color_from_text(text), None, "{text}");
4863 }
4864 }
4865
4866 /// A colour's hex is the ink the painter draws, and reading it back
4867 /// gives the sliders their own value again -- for the 47053 of the 65536
4868 /// hues and saturations a trip through bytes can carry. The rest land on
4869 /// a neighbour: their smallest channel rounds to a byte whose ratio is
4870 /// not the one that was asked for. Full saturation is where that channel
4871 /// is the one the value sets exactly, and it survives at every hue.
4872 #[test]
4873 fn a_sampled_palette_round_trips_through_its_hex() {
4874 for hue in (0..=255u8).step_by(8) {
4875 let hex = viz_color_hex(hue, 255);
4876 assert_eq!(viz_color_from_text(&hex), Some((hue, 255)), "{hex}");
4877 }
4878 // The achromatic end, where hue is not a colour at all.
4879 assert_eq!(viz_color_from_text(&viz_color_hex(0, 0)), Some((0, 0)));
4880 assert_eq!(viz_color_from_text(&viz_color_hex(200, 0)), Some((0, 0)));
4881 // ...and the whole grid, so a change that quietly shrinks what the
4882 // trip can carry cannot pass by leaving the sample above green.
4883 let exact = (0..=255u8)
4884 .flat_map(|hue| (0..=255u8).map(move |sat| (hue, sat)))
4885 .filter(|&(hue, sat)| viz_color_from_text(&viz_color_hex(hue, sat)) == Some((hue, sat)))
4886 .count();
4887 assert_eq!(exact, 47_053, "the colours a hex round trip keeps");
4888 }
4889
4890 /// The dual half of a ring takes the clip's own strand colour when it has
4891 /// one: a choice that names the automatic complement paints the same
4892 /// frame, another repaints the dual strands in it, and a paint whose flag
4893 /// is clear is the picture it has always been -- strand bytes or no.
4894 #[test]
4895 fn a_chosen_strand_colour_repaints_only_the_dual_half_of_a_ring() {
4896 let mut peaks = vec![(0.0, 0.0); 12_000];
4897 for (i, p) in peaks.iter_mut().enumerate() {
4898 let a = ((i as f32 / 400.0) * std::f32::consts::TAU).sin() * 0.8;
4899 *p = (-a.abs(), a.abs());
4900 }
4901 let ring = with_viz_style(1, VIZ_STYLE_RING);
4902 let auto = VIZ_PAINT_AZURE;
4903 let (y0, u0, v0) = visualizer_i420(
4904 &mut VizScratch::default(),
4905 &peaks,
4906 1.0,
4907 320,
4908 180,
4909 ring,
4910 auto,
4911 );
4912
4913 // The automatic dual is half a wheel from the clip's hue at the
4914 // clip's own saturation; choosing exactly that colour changes
4915 // nothing at all.
4916 let same = with_viz_paint_strand_sat(
4917 with_viz_paint_strand_hue(auto, viz_hue_ui(auto).wrapping_add(128)),
4918 viz_sat_ui(auto),
4919 );
4920 assert!(viz_strand_set(same));
4921 let (ys, us, vs) = visualizer_i420(
4922 &mut VizScratch::default(),
4923 &peaks,
4924 1.0,
4925 320,
4926 180,
4927 ring,
4928 same,
4929 );
4930 assert_eq!(
4931 ys, y0,
4932 "the automatic complement, spelled out, is the same frame"
4933 );
4934 assert_eq!(us, u0);
4935 assert_eq!(vs, v0);
4936
4937 // A colour of its own repaints the dual strands in it.
4938 let red = with_viz_paint_strand_sat(with_viz_paint_strand_hue(auto, 0), 255);
4939 let (_, u1, v1) =
4940 visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, red);
4941 let red_px = (0..u1.len())
4942 .filter(|&i| u1[i] < 110 && v1[i] > 200)
4943 .count();
4944 let auto_px = (0..u0.len())
4945 .filter(|&i| u0[i] < 110 && v0[i] > 200)
4946 .count();
4947 assert!(
4948 red_px > 20,
4949 "the chosen colour did not reach the frame: {red_px}"
4950 );
4951 assert_eq!(
4952 auto_px, 0,
4953 "the automatic ring already painted red: {auto_px}"
4954 );
4955
4956 // ...and the flag is what decides: strand bytes with it clear are
4957 // the unset picture, byte for byte.
4958 let stale = auto | (77u64 << 32) | (9u64 << 40);
4959 assert!(!viz_strand_set(stale));
4960 let (yt, ut, vt) = visualizer_i420(
4961 &mut VizScratch::default(),
4962 &peaks,
4963 1.0,
4964 320,
4965 180,
4966 ring,
4967 stale,
4968 );
4969 assert_eq!(yt, y0, "an unset strand colour is the frame it always was");
4970 assert_eq!(ut, u0);
4971 assert_eq!(vt, v0);
4972 }
4973 /// The look of a frame the glow pass was rewritten for, pinned byte for
4974 /// byte: [`viz_chain`] replaced the per-point discs under
4975 /// [`VIZ_STYLE_RING`] and [`VIZ_STYLE_WAVE`], whose glow cost `steps * pi *
4976 /// glow^2` cells per frame (295 ms of one 1080p ring frame at glow 16
4977 /// against 18 ms after), and this is what says the pictures did not move
4978 /// with it. FNV-1a over `y`, then `u`, then `v`, taken from the disc
4979 /// implementation that shipped before the rewrite; `fill` and `ribbon` are
4980 /// in the table because their planes share the frame with a chain's, and
4981 /// the row/run walk could still have reached them through a shared helper.
4982 ///
4983 /// Scope: eight strands (what [`VIZ_PAINT_AZURE`] carries) at four gloss
4984 /// including both ends. A strand count changes a chain's scale and phase,
4985 /// not the pass over it.
4986 #[test]
4987 fn the_glow_pass_paints_the_bytes_it_always_did() {
4988 const GOLDEN: &[(&str, u8, u64)] = &[
4989 ("fill", 0, 0xe141_5e51_fcc1_7ea1),
4990 ("fill", 2, 0x3842_fef4_d4ec_4239),
4991 ("fill", 8, 0xfaea_3e6f_9718_1d31),
4992 ("fill", 16, 0x6a09_31fe_e9f1_3069),
4993 ("ribbon", 0, 0x91fa_9b49_48d8_bcfe),
4994 ("ribbon", 2, 0xd4d2_bcce_3c32_14d8),
4995 ("ribbon", 8, 0xd23a_d502_17ac_697c),
4996 ("ribbon", 16, 0xd7de_425a_6737_11c3),
4997 ("ring", 0, 0xcfbe_55da_b222_0a1b),
4998 ("ring", 2, 0x5468_01eb_522e_21dc),
4999 ("ring", 8, 0xc08f_994e_4a19_c9f4),
5000 ("ring", 16, 0x8cee_6dcd_256c_d484),
5001 ("wave", 0, 0x2266_ba70_ab2a_06bd),
5002 ("wave", 2, 0xd05f_0a31_9264_b377),
5003 ("wave", 8, 0x2e50_7536_c5dd_6035),
5004 ("wave", 16, 0xf888_b09c_dae2_dd36),
5005 ];
5006 let peaks = benchmark_peaks((149.6 * f64::from(VIZ_BUCKETS_PER_SEC)) as usize);
5007 for &(name, glow, want) in GOLDEN {
5008 let style = match name {
5009 "fill" => VIZ_STYLE_FILL,
5010 "ribbon" => VIZ_STYLE_RIBBON,
5011 "ring" => VIZ_STYLE_RING,
5012 _ => VIZ_STYLE_WAVE,
5013 };
5014 let flags = with_viz_style(1, style);
5015 let paint = with_viz_paint_glow(VIZ_PAINT_AZURE, glow);
5016 let (y, u, v) = visualizer_i420(
5017 &mut VizScratch::default(),
5018 &peaks,
5019 37.5,
5020 1920,
5021 1080,
5022 flags,
5023 paint,
5024 );
5025 let mut hash = 0xcbf2_9ce4_8422_2325u64;
5026 for buf in [&y, &u, &v] {
5027 for &b in buf.iter() {
5028 hash ^= u64::from(b);
5029 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
5030 }
5031 }
5032 assert_eq!(
5033 hash, want,
5034 "{name} at glow {glow} paints different bytes than it always did ({hash:016x})"
5035 );
5036 }
5037 }
5038
5039 /// The envelope both of the tests above paint: loud enough that every
5040 /// column carries ink, and shaped so a ring's radii and a wave's trace
5041 /// differ from column to column.
5042 fn benchmark_peaks(n: usize) -> Vec<(f32, f32)> {
5043 let mut peaks = vec![(0.0f32, 0.0f32); n];
5044 for (i, p) in peaks.iter_mut().enumerate() {
5045 let t = i as f64 / f64::from(VIZ_BUCKETS_PER_SEC);
5046 let a = ((t * 0.7).sin() * 0.6 + (t * 5.3).sin() * 0.25 + 0.1) as f32;
5047 *p = (-a.abs(), a.abs());
5048 }
5049 peaks
5050 }
5051
5052 /// An AV1 clip of `pix_fmt` from ffmpeg's libaom-av1, in the temp dir.
5053 fn gen_av1(name: &str, pix_fmt: &str) -> PathBuf {
5054 let path = std::env::temp_dir().join(format!("{name}-{}.mkv", std::process::id()));
5055 let out = std::process::Command::new("ffmpeg")
5056 .args(["-v", "error", "-y", "-f", "lavfi", "-i"])
5057 .arg("testsrc2=size=128x96:rate=30:duration=1")
5058 .args(["-frames:v", "6", "-c:v", "libaom-av1", "-cpu-used", "8"])
5059 .args(["-crf", "20", "-b:v", "0", "-pix_fmt", pix_fmt])
5060 .arg(&path)
5061 .output()
5062 .expect("run ffmpeg");
5063 assert!(out.status.success(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
5064 path
5065 }
5066
5067 /// 4:2:2 at 8 bits, 4:4:4 at 10 and 4:2:0 at 12 open, decode every frame on
5068 /// the software seat's own narrowing, and land within 45 dB of ffmpeg's
5069 /// `-pix_fmt yuv420p` decode of the same file.
5070 #[test]
5071 fn non_420_and_12_bit_av1_decodes_within_45_db_of_ffmpeg() {
5072 let _pin = SwPin::set();
5073 for (pix, depth) in [("yuv422p", 8u8), ("yuv444p10le", 10), ("yuv420p12le", 12), ("yuv444p12le", 12)] {
5074 let clip = gen_av1(&format!("av1chroma-{pix}"), pix);
5075 let (meta, mut demuxer) = Demuxer::open(&clip).unwrap_or_else(|e| panic!("{pix}: {e}"));
5076 assert_eq!(demuxer.bit_depth(), depth, "{pix}");
5077 let mut stream = Vec::new();
5078 while let Some(au) = demuxer.next_access_unit().unwrap() {
5079 stream.extend_from_slice(&au);
5080 }
5081 let mut got = Vec::new();
5082 decode_stream_with(&stream, |picture, _, shown| {
5083 if shown {
5084 let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new());
5085 narrow_av1(picture, depth, &mut y, &mut u, &mut v);
5086 for p in [&y, &u, &v] {
5087 got.extend_from_slice(p);
5088 }
5089 }
5090 Ok(())
5091 })
5092 .unwrap_or_else(|e| panic!("{pix}: {e}"));
5093 let want = std::process::Command::new("ffmpeg")
5094 .args(["-v", "error", "-i"])
5095 .arg(&clip)
5096 .args(["-f", "rawvideo", "-pix_fmt", "yuv420p", "-fps_mode", "passthrough", "-"])
5097 .output()
5098 .expect("run ffmpeg")
5099 .stdout;
5100 let seat_frames = DecodeSession::open(&clip).map(|(_, rx)| rx.into_iter().count());
5101 let _ = std::fs::remove_file(&clip);
5102 assert_eq!(got.len(), want.len(), "{pix}: picture count");
5103 assert_eq!(got.len(), 128 * 96 * 3 / 2 * meta.frame_count as usize, "{pix}");
5104 let squared: f64 = got
5105 .iter()
5106 .zip(&want)
5107 .map(|(&a, &b)| (f64::from(a) - f64::from(b)).powi(2))
5108 .sum();
5109 let db = 10.0 * (255.0f64 * 255.0 * got.len() as f64 / squared.max(1e-9)).log10();
5110 eprintln!("AV1 {pix} -> 4:2:0 against ffmpeg yuv420p: {db:.2} dB");
5111 assert!(db >= 45.0, "{pix} is {db:.2} dB from ffmpeg, want 45");
5112 assert_eq!(seat_frames.unwrap(), meta.frame_count as usize, "{pix}: session frames");
5113 }
5114 }
5115
5116 /// A span whose file no seat can take -- nothing opens it and there is no
5117 /// software decoder for these bytes -- must report the *gap* it is. The cell
5118 /// used to be left claiming `Hardware`: the arm below the software fallback set
5119 /// it before the session that produced nothing, and the front-end then named a
5120 /// decoder that had decoded no frame.
5121 ///
5122 /// Every codec edith decodes now has a seat (VP8 included), so the gap is built
5123 /// from a file no seat takes: a 45-degree display matrix, which `Demuxer::open` refuses by name,
5124 /// so `Source::open` yields nothing and the span has no seat to report.
5125 /// Driven through [`run_span`] itself, the only door that reaches the arm.
5126 /// `VE_SW=1` keeps the test box-independent; see [`SwPin`].
5127 #[test]
5128 fn a_span_with_no_seat_at_all_reports_the_gap() {
5129 let _pin = SwPin::set();
5130 let path = asset("test_rotation45.mkv");
5131 let mut source = None;
5132 let cancel = AtomicBool::new(false);
5133 let generation = AtomicU64::new(0);
5134 let floor = AtomicU32::new(0);
5135 let abort = Abort {
5136 cancel: &cancel,
5137 generation: &generation,
5138 mine: 0,
5139 floor: &floor,
5140 };
5141 let (tx, rx) = sync_channel(2);
5142 let cell = BackendCell::new(Backend::Opening);
5143 let failure = DecodeFailure::default();
5144 run_span(
5145 &path,
5146 &mut source,
5147 SpanCmd {
5148 generation: 0,
5149 start: 0,
5150 end: 2,
5151 color: ColorParams::default(),
5152 transform: TransformParams::default(),
5153 canvas: Composer::passthrough(),
5154 tone: tonemap::Preset::default(),
5155 speed: Speed::NORMAL,
5156 deint: Default::default(),
5157 tx,
5158 },
5159 &abort,
5160 &cell,
5161 &failure,
5162 );
5163 assert_eq!(
5164 cell.get(),
5165 Backend::Gap,
5166 "a span no seat takes must report the gap, not a hardware seat"
5167 );
5168 assert!(
5169 rx.try_recv().is_err(),
5170 "a gap decodes nothing: no picture may come down the channel"
5171 );
5172 assert!(
5173 failure.reason().is_some(),
5174 "and it says why: a span that decoded nothing is the one case where \
5175 a closed channel is definitely not the end of the file"
5176 );
5177 }
5178
5179 /// The VA-API plugin takes 4:2:0 VP9 only: profiles 0 and 2 pass, and profiles 1
5180 /// and 3 pass only where the chroma is 4:2:0 (which no such profile writes).
5181 #[test]
5182 fn vp9_non_420_profiles_are_off_the_gpu() {
5183 assert!(vp9_needs_420_for_vaapi(1, Chroma::C444));
5184 assert!(vp9_needs_420_for_vaapi(1, Chroma::C422));
5185 assert!(vp9_needs_420_for_vaapi(3, Chroma::C444));
5186 assert!(vp9_needs_420_for_vaapi(3, Chroma::C422));
5187 assert!(!vp9_needs_420_for_vaapi(0, Chroma::C420));
5188 assert!(!vp9_needs_420_for_vaapi(2, Chroma::C420));
5189 assert!(!vp9_needs_420_for_vaapi(1, Chroma::C420));
5190 }
5191
5192 /// The route names the profile and its chroma, and says where the stream plays:
5193 /// the ec-vp9 software seat, not a refusal.
5194 #[test]
5195 fn vp9_non_420_route_names_profile_chroma_and_the_seat() {
5196 let text = vp9_software_route(1, Chroma::C444);
5197 assert_eq!(
5198 text,
5199 "VP9 profile 1 (4:4:4) is not 4:2:0, which the GPU does not take: it plays on the ec-vp9 software seat"
5200 );
5201 assert!(vp9_software_route(3, Chroma::C422).starts_with("VP9 profile 3 (4:2:2)"));
5202 }
5203}