forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8b784e6Tahinli2 months ago961 commits

decode.rs3588 lines, 146.3 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::Arc;
6use std::sync::atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering};
7use std::sync::mpsc::{Receiver, RecvTimeoutError, SyncSender, sync_channel};
8use std::thread;
9
10use ec_core::frame::VideoFrame;
11use ec_av1::encode::Picture as Av1Picture;
12use ec_av1::stream::decode_stream_with;
13use ec_core::registry::{CodecId, CodecParameters};
14use ec_core::registry::Decoder as _;
15use ec_core::{Error as Av1Error, Packet, TimeBase};
16use ec_h264::H264Decoder;
17
18use crate::color::ColorParams;
19use crate::colorspace::{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
28/// One decoded picture, ready to hand to a renderer.
29pub struct Frame {
30 /// Position in display order, starting at 0.
31 pub index: u32,
32 pub width: u32,
33 pub height: u32,
34 /// BGRA8, straight alpha, tightly packed.
35 pub bgra: Vec<u8>,
36}
37
38/// Which decoder a source is really running on. Read-only introspection: it
39/// decides nothing, it *reports* what [`DecodeSession::open_worker`] chose --
40/// a hardware session that opened and then failed before its first picture
41/// falls back to software and this says so, because it is written where the
42/// fallback happens rather than where it was hoped for.
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
44pub enum Backend {
45 /// The worker has not reached its decoder yet: the plugin's VA-API init is
46 /// ~90 ms, and this is what a caller reads in that window.
47 #[default]
48 Opening,
49 /// The VA-API plugin (`libengine_hw.so`).
50 Hardware,
51 /// This project's own software seat: `ec-h264` or `ec-av1`, in this
52 /// process.
53 Software,
54 /// A still image: one `image` decode, no stream and no decoder to pick.
55 Still,
56 /// A gap: black frames, nothing decoded at all.
57 Gap,
58 /// A waveform visualizer: the picture is painted from the audio's peaks
59 /// ([`visualizer_i420`]), no decoder seat and no stream of pictures at all.
60 Visualizer,
61}
62
63impl Backend {
64 /// Short enough for a library row and a transport line.
65 pub fn label(self) -> &'static str {
66 match self {
67 Self::Opening => "opening",
68 Self::Hardware => "HW",
69 Self::Software => "SW",
70 Self::Still => "still",
71 Self::Gap => "gap",
72 Self::Visualizer => "viz",
73 }
74 }
75
76 fn code(self) -> u8 {
77 match self {
78 Self::Opening => 0,
79 Self::Hardware => 1,
80 Self::Software => 2,
81 Self::Still => 3,
82 Self::Gap => 4,
83 Self::Visualizer => 5,
84 }
85 }
86
87 fn from_code(code: u8) -> Self {
88 match code {
89 1 => Self::Hardware,
90 2 => Self::Software,
91 3 => Self::Still,
92 4 => Self::Gap,
93 5 => Self::Visualizer,
94 _ => Self::Opening,
95 }
96 }
97}
98
99/// Where a worker publishes the decoder it opened, for whoever holds the other
100/// end of its channel. One atomic byte, written once at open (and once more if
101/// hardware hands the range back to software), read whenever a caller repaints
102/// -- never per frame on either side.
103#[derive(Clone, Default)]
104pub struct BackendCell(Arc<AtomicU8>);
105
106impl BackendCell {
107 pub(crate) fn new(backend: Backend) -> Self {
108 Self(Arc::new(AtomicU8::new(backend.code())))
109 }
110
111 fn set(&self, backend: Backend) {
112 self.0.store(backend.code(), Ordering::Relaxed);
113 }
114
115 pub fn get(&self) -> Backend {
116 Backend::from_code(self.0.load(Ordering::Relaxed))
117 }
118}
119
120/// Which decoder `path` would open, decided exactly as [`DecodeSession::open_worker`]
121/// decides it: the same `VE_SW` pin and the same plugin probe against this very
122/// file. What lets a front-end name the decoder *before* anything plays.
123///
124/// The codec is `None` for a still image, which has no coded stream. A stream
125/// no decoder here can take is an `Err` naming the plugin, exactly as opening
126/// it would be -- the same refusal, one VA-API init earlier.
127///
128/// Costs that one init (~90 ms) for a stream the plugin takes: ask it once per
129/// file, off a render thread, and keep the answer.
130pub fn probe(path: &Path) -> crate::Result<(Option<Codec>, Backend)> {
131 if crate::is_image(path) {
132 return Ok((None, Backend::Still));
133 }
134 let path = path.to_path_buf();
135 let (meta, _demuxer) = Demuxer::open(&path)?;
136 match hw_decodes(&path, 0, meta.codec) {
137 Ok(()) => return Ok((Some(meta.codec), Backend::Hardware)),
138 Err(e) if !matches!(meta.codec, Codec::H264 | Codec::Av1) => return Err(e.into()),
139 Err(_) => {}
140 }
141 Ok((Some(meta.codec), Backend::Software))
142}
143
144/// A running decode worker: the flag that stops it, and the handle to wait on.
145///
146/// Dropping one cancels *and joins*. A worker abandoned mid-`vaInitialize`
147/// outlives the process otherwise, and Mesa's `atexit` handlers free the state
148/// it is still reading -- a SIGSEGV at exit, long after the last test passed.
149pub(crate) struct Worker {
150 cancel: Arc<AtomicBool>,
151 /// `None` once detached, and for a range with nothing to decode: either way
152 /// there is no thread left to wait for.
153 handle: Option<thread::JoinHandle<()>>,
154 /// How a *later* span reaches this same thread ([`Worker::reseek`]), for the
155 /// workers that decode a file: the still, the gap and a detached worker have
156 /// no such door and are the one-span threads they always were.
157 reuse: Option<Reuse>,
158}
159
160/// The door a persistent decode worker is steered through: the file it has open,
161/// the channel its next span arrives on, and the generation counter that tells
162/// the span it is decoding *now* that nobody is waiting for it any more.
163///
164/// The point of all three is that a seek onto the same file costs a demuxer
165/// seek and a decoder flush ([`crate::hw::HwSession::seek`]) rather than a
166/// thread, a container parse and a VA-API initialisation (98 ms measured).
167struct Reuse {
168 path: PathBuf,
169 spans: std::sync::mpsc::Sender<SpanCmd>,
170 /// Bumped by every reseek and by [`Worker::abandon`]; the decode loop stops
171 /// the moment it no longer matches the span it was handed.
172 generation: Arc<AtomicU64>,
173 /// The worker's decoder, published once and read across every span it
174 /// decodes -- so a reseek onto a file already open says "hardware" from the
175 /// first repaint instead of going back through `opening`.
176 backend: BackendCell,
177 /// Where the caller's playhead stands, in this file's own frames
178 /// ([`Worker::playhead`]): the worker converts and sends nothing behind it.
179 /// Rewritten to the target by every reseek, so it can never carry one span's
180 /// position into the next.
181 floor: Arc<AtomicU32>,
182}
183
184/// One span asked of a persistent worker: the range in the file's own frames,
185/// everything a picture is graded, placed and mapped by, and the channel the
186/// pictures go down. Carries its generation, so a command already superseded on
187/// its way through the queue is dropped rather than decoded.
188struct SpanCmd {
189 generation: u64,
190 start: u32,
191 end: u32,
192 color: ColorParams,
193 transform: TransformParams,
194 canvas: Composer,
195 tone: tonemap::Preset,
196 /// The clip's own playback speed ([`crate::project::Clip::speed`]), for
197 /// [`skip_for_speed`]: at faster than real time several source frames in a
198 /// row land on the same timeline frame, and only the last of a run is ever
199 /// shown. [`Speed::NORMAL`] for a file-level open ([`DecodeSession::open`]
200 /// and friends), which has no clip and skips nothing.
201 speed: Speed,
202 tx: SyncSender<Frame>,
203}
204
205/// What stops a decode loop: the worker's terminal flag (the thread itself is
206/// going away) and the generation of the span it was handed (only *this* span is
207/// going away). One check, so every loop treats them alike.
208///
209/// ...and where the playhead has reached ([`Abort::late`]), which is the same
210/// question one picture at a time: a frame due before it is a frame nobody can
211/// be shown any more.
212struct Abort<'a> {
213 cancel: &'a AtomicBool,
214 generation: &'a AtomicU64,
215 mine: u64,
216 floor: &'a AtomicU32,
217}
218
219impl Abort<'_> {
220 fn hit(&self) -> bool {
221 self.cancel.load(Ordering::Relaxed) || self.generation.load(Ordering::Acquire) != self.mine
222 }
223
224 /// Whether the picture at source frame `index` is already past due: the
225 /// caller's playhead has gone by it, so converting it (a full BGRA pass over
226 /// 8 MB at 1080p) and queueing it would only push a picture nobody sees in
227 /// front of the one they are waiting for.
228 ///
229 /// It is still *decoded* -- the pictures after it reference it -- and the
230 /// floor only ever moves with the playhead the session publishes, so a
231 /// paused session (and every seek, which republishes its own target) drops
232 /// nothing at all.
233 fn late(&self, index: u32) -> bool {
234 self.floor.load(Ordering::Relaxed) > index
235 }
236}
237
238/// Whether the picture at source frame `due` (of a span starting at `start` and
239/// ending at `end`) is redundant *by construction* at `speed`, and its convert
240/// and send can be skipped without ever waiting on the playhead
241/// ([`Abort::late`]): at faster than real time several source frames in a row
242/// map to the same timeline frame ([`Speed::timeline_at`]), and only the last
243/// of such a run is ever shown -- the newest one always lands after the others
244/// in `try_frame`'s stamp comparison. Unlike a late drop this needs no run
245/// limit: the gap between two kept frames is at most `speed` source frames, so
246/// the picture stream this leaves is never silent, only sparser.
247///
248/// The last frame of the whole span is never skipped by this: it is the
249/// picture [`crate::project::Span::source_len`] was built to land exactly on,
250/// and this is what proves that promise here instead of trusting it blind.
251///
252/// corner-cut: `due` and `start` are the file's own frame numbers, so this
253/// is only correct when the file plays at the timeline's own rate
254/// ([`crate::project::Rate::is_real_time`]) -- callers pass [`Speed::NORMAL`]
255/// (never skip) otherwise. Upgrade path is composing `Rate` into this the way
256/// [`crate::project::Span::timeline_at`] does.
257fn skip_for_speed(speed: Speed, start: u32, due: u32, end: u32) -> bool {
258 if speed.is_normal() || due + 1 >= end {
259 return false;
260 }
261 let rel = due - start;
262 speed.timeline_at(rel) == speed.timeline_at(rel + 1)
263}
264
265impl Worker {
266 /// Stops the worker *and its thread* at their next check, without waiting.
267 /// Callers that replace a worker should do this first and drop the receiver
268 /// second: a worker parked in `send` only wakes on the disconnect, so the
269 /// join below would otherwise wait for a consumer that is never coming.
270 ///
271 /// The command channel goes with it, which is what wakes a persistent worker
272 /// parked between spans -- without that it would sit in `recv` forever and a
273 /// retired worker would never be reaped (nor joined at exit in any bounded
274 /// time, which is the Mesa `atexit` hazard this whole type exists for).
275 pub(crate) fn cancel(&mut self) {
276 self.cancel.store(true, Ordering::Release);
277 self.reuse = None;
278 }
279
280 /// Stops the span the worker is decoding, keeping the *thread* -- and with
281 /// it the open file and the open decoder -- for the span that follows. What
282 /// a seek does, since the next thing it says is [`Worker::reseek`].
283 ///
284 /// Falls back to [`cancel`](Self::cancel) for a worker with nothing to
285 /// reuse (a still, a gap, a detached one), where the two mean the same
286 /// thing: this worker has no next span.
287 pub(crate) fn abandon(&mut self) {
288 match &self.reuse {
289 Some(reuse) => {
290 reuse.generation.fetch_add(1, Ordering::Release);
291 }
292 None => self.cancel(),
293 }
294 }
295
296 /// Tells the worker where the caller's playhead stands, in the file's own
297 /// frames: it converts and queues nothing behind that, because a picture
298 /// whose moment has passed cannot be shown and would only delay the one that
299 /// can (see [`Abort::late`]). A worker with no reuse door -- a still, a gap
300 /// -- has nothing to tell, and this costs it nothing to say.
301 pub(crate) fn playhead(&self, source_frame: u32) {
302 if let Some(reuse) = &self.reuse {
303 reuse.floor.store(source_frame, Ordering::Relaxed);
304 }
305 }
306
307 /// Points this worker at another range of the file it already has open,
308 /// handing back the channel the new span's pictures arrive on and the cell
309 /// that says what is decoding them. `None` when this worker cannot take the
310 /// job -- another file, no reuse door, or a thread that has already returned
311 /// -- and the caller then opens a worker of its own, exactly as it always
312 /// did.
313 ///
314 /// The pictures of the *old* span are left in their own channel, which the
315 /// caller drops: that disconnect is what wakes this worker if it is parked
316 /// in `send`, and only then does it reach the command below. So the order at
317 /// the call site is unchanged -- install the new receiver, and the old
318 /// worker finds out by losing its consumer.
319 #[allow(clippy::too_many_arguments)]
320 pub(crate) fn reseek(
321 &mut self,
322 path: &Path,
323 start: u32,
324 end: u32,
325 color: ColorParams,
326 transform: TransformParams,
327 canvas: Composer,
328 tone: tonemap::Preset,
329 speed: Speed,
330 ) -> Option<(Receiver<Frame>, BackendCell)> {
331 let reuse = self.reuse.as_ref()?;
332 if reuse.path != path || self.is_finished() {
333 return None;
334 }
335 let (tx, rx) = sync_channel(canvas.queue_depth());
336 // The new span's own playhead, before its first picture is decoded: a
337 // floor left over from where the timeline *was* would drop every
338 // picture of a seek that went backwards.
339 reuse.floor.store(start, Ordering::Relaxed);
340 // Bumped before the command is queued, so the span running now stops at
341 // its next picture whatever order the two threads are scheduled in.
342 let generation = reuse.generation.fetch_add(1, Ordering::Release) + 1;
343 reuse
344 .spans
345 .send(SpanCmd {
346 generation,
347 start,
348 end,
349 color,
350 transform,
351 canvas,
352 tone,
353 speed,
354 tx,
355 })
356 .ok()?;
357 Some((rx, reuse.backend.clone()))
358 }
359
360 /// Whether the thread has already returned, i.e. dropping this would not
361 /// wait. `true` for a worker that never had a thread. What lets a caller
362 /// park cancelled workers and reap them without ever blocking.
363 pub(crate) fn is_finished(&self) -> bool {
364 self.handle
365 .as_ref()
366 .is_none_or(thread::JoinHandle::is_finished)
367 }
368
369 /// Lets the worker run on unwatched -- what the public API does, since it
370 /// hands out the flag alone.
371 ///
372 /// The reuse door goes with the handle: nothing can steer a worker nobody
373 /// holds, and dropping the command channel is what makes such a thread end
374 /// at its span rather than park waiting for a next one it can never be
375 /// given -- with a VA-API session open, into Mesa's `atexit`.
376 fn detach(mut self) -> Arc<AtomicBool> {
377 self.handle = None;
378 self.reuse = None;
379 Arc::clone(&self.cancel)
380 }
381}
382
383impl Drop for Worker {
384 fn drop(&mut self) {
385 if let Some(handle) = self.handle.take() {
386 // `cancel` drops the command channel too, so a worker parked between
387 // spans wakes on the disconnect and this join is bounded.
388 self.cancel();
389 let _ = handle.join();
390 }
391 }
392}
393
394/// A running worker and the frames it is sending, handed out as one value
395/// because they must be *dropped* as one, in this order: the receiver
396/// disconnects first, which is the only thing that wakes a worker parked in a
397/// full `send`, and the join inside [`Worker::drop`] runs second.
398///
399/// Rust drops fields in declaration order, so this struct *is* that rule, and
400/// it holds wherever the value goes: an early return out of a half-built
401/// session, an unwind, a caller not written yet. Two separate locals do not
402/// hold it -- they drop in reverse order of declaration, so the worker there
403/// joins a thread nobody will ever drain, which is a hang and not a slow path.
404pub(crate) struct FrameStream {
405 pub(crate) frames: Receiver<Frame>,
406 pub(crate) worker: Worker,
407 /// What this stream's pictures are being decoded by. Dropped last and read
408 /// by the caller, so it outlives nothing and blocks nothing.
409 pub(crate) backend: BackendCell,
410}
411
412pub struct DecodeSession;
413
414impl DecodeSession {
415 /// Opens `path`, returning stream metadata immediately and a receiver that
416 /// yields frames as the worker decodes them. The worker stops when the
417 /// receiver is dropped, at end of stream, or on the first decode error.
418 pub fn open(path: impl AsRef<Path>) -> crate::Result<(VideoMeta, Receiver<Frame>)> {
419 let (meta, rx, _cancel) = Self::open_at(path, 0)?;
420 Ok((meta, rx))
421 }
422
423 /// As [`DecodeSession::open`], but the first frame delivered is
424 /// `start_frame` (0-based display index; [`Frame::index`] stays absolute).
425 /// Setting the returned flag stops the worker at its next access unit,
426 /// which is how a caller abandons a session it no longer wants to drain.
427 pub fn open_at(
428 path: impl AsRef<Path>,
429 start_frame: u32,
430 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
431 // `u32::MAX` is clamped to the stream's frame count below, so this is
432 // "to the end of the file".
433 Self::open_range(path, start_frame, u32::MAX)
434 }
435
436 /// As [`DecodeSession::open_at`], but the worker also stops on its own
437 /// after sending `end_frame - 1`: the range is half-open `[start, end)` in
438 /// absolute source frames, which is what a clip of a longer file needs.
439 /// `end_frame` is capped at the stream's frame count, and an empty range
440 /// yields a receiver that is simply already disconnected.
441 pub fn open_range(
442 path: impl AsRef<Path>,
443 start_frame: u32,
444 end_frame: u32,
445 ) -> crate::Result<(VideoMeta, Receiver<Frame>, Arc<AtomicBool>)> {
446 // Ungraded: the public API opens a *file*, and a colour grade belongs to
447 // a clip of a timeline. `PlaybackSession` is what has one to pass.
448 let (meta, stream) = Self::open_worker(
449 path,
450 start_frame,
451 end_frame,
452 ColorParams::default(),
453 // No clip, no transform either: the file-level API hands back the
454 // pictures the file holds, untouched.
455 TransformParams::default(),
456 // No project, no canvas: the file-level API hands back the
457 // pictures the file holds, at the size it holds them.
458 Composer::passthrough(),
459 // ...and no project means no picked rendition either: an HDR file
460 // opened through this door is mapped the published way.
461 tonemap::Preset::default(),
462 )?;
463 // The public API hands out the flag alone, so the worker is detached and
464 // the receiver goes to the caller: nothing here joins anything.
465 Ok((meta, stream.frames, stream.worker.detach()))
466 }
467
468 /// A worker that decodes nothing and emits `len` black frames, indexed from
469 /// zero -- what a *gap* in the video lane looks like. It goes down the same
470 /// channel as decoded frames, so a gap costs the caller no branch at all
471 /// beyond choosing this opener: same bounded channel, same backpressure,
472 /// same cancel, same retire path.
473 pub(crate) fn open_black(width: u32, height: u32, len: u32) -> FrameStream {
474 let (tx, rx) = sync_channel(2);
475 let cancel = Arc::new(AtomicBool::new(false));
476 if len == 0 {
477 return FrameStream {
478 frames: rx,
479 worker: Worker {
480 cancel,
481 handle: None,
482 reuse: None,
483 },
484 backend: BackendCell::new(Backend::Gap),
485 };
486 }
487 let worker_cancel = Arc::clone(&cancel);
488 // One buffer, cloned per frame: opaque black is a constant, and the
489 // clone is a memcpy against a decode this replaces entirely.
490 let black = vec![[0u8, 0, 0, 255]; (width as usize) * (height as usize)].concat();
491 let handle = thread::Builder::new()
492 .name("black".into())
493 .spawn(move || {
494 for index in 0..len {
495 if worker_cancel.load(Ordering::Relaxed) {
496 return;
497 }
498 let frame = Frame {
499 index,
500 width,
501 height,
502 bgra: black.clone(),
503 };
504 if tx.send(frame).is_err() {
505 return; // caller moved on
506 }
507 }
508 })
509 .ok();
510 FrameStream {
511 frames: rx,
512 worker: Worker {
513 cancel,
514 handle,
515 reuse: None,
516 },
517 backend: BackendCell::new(Backend::Gap),
518 }
519 }
520
521 /// A worker for a still image ([`crate::is_image`]): the file is decoded
522 /// *once* and the same picture goes down the channel `len` times, indexed
523 /// from `start_frame` exactly as a decoder's pictures are -- so a placed
524 /// image is a clip like any other to everything downstream (`try_frame`
525 /// rewrites those indices, `next_clip` walks off the end of the range).
526 ///
527 /// Graded and placed on the canvas once too, before the repeat: a still is
528 /// the same pixels every frame, so the whole cost of one is one conversion
529 /// plus a memcpy per frame -- what [`open_black`](Self::open_black) pays.
530 pub(crate) fn open_still(
531 path: &Path,
532 start_frame: u32,
533 len: u32,
534 color: ColorParams,
535 transform: TransformParams,
536 canvas: Composer,
537 ) -> crate::Result<FrameStream> {
538 let still = Still::open(path)?;
539 let (tx, rx) = sync_channel(2);
540 let cancel = Arc::new(AtomicBool::new(false));
541 if len == 0 {
542 return Ok(FrameStream {
543 frames: rx,
544 worker: Worker {
545 cancel,
546 handle: None,
547 reuse: None,
548 },
549 backend: BackendCell::new(Backend::Still),
550 });
551 }
552 // The one conversion, on this thread: it is a few milliseconds and the
553 // error it could raise has already been raised by `Still::open`.
554 // BT.601 limited, because that is what `rgb_to_i420` above wrote these
555 // planes in: a still round-trips through the pair, not through the
556 // colour of whatever file is on the timeline beside it.
557 // No preset argument, and none wanted: a still is decoded into BT.601
558 // SDR planes, so the tone map is not built at all whichever rendition
559 // the project is watching.
560 let first = Render::new(
561 color,
562 transform,
563 // A still has no display matrix: what the file holds is what it is.
564 Rotation::None,
565 // ...and no sample aspect either: a still is authored square.
566 PixelAspect::SQUARE,
567 ColorDescription::default(),
568 canvas,
569 tonemap::Preset::default(),
570 // ...and no declared peak either, for the same reason: there is no
571 // tone map on this path to hand one to.
572 None,
573 )
574 .frame(
575 start_frame,
576 &still.y,
577 &still.u,
578 &still.v,
579 still.width,
580 still.height,
581 );
582 let worker_cancel = Arc::clone(&cancel);
583 let handle = thread::Builder::new()
584 .name("still".into())
585 .spawn(move || {
586 let (width, height, bgra) = (first.width, first.height, first.bgra);
587 for index in 0..len {
588 if worker_cancel.load(Ordering::Relaxed) {
589 return;
590 }
591 let frame = Frame {
592 index: start_frame + index,
593 width,
594 height,
595 bgra: bgra.clone(),
596 };
597 if tx.send(frame).is_err() {
598 return; // caller moved on
599 }
600 }
601 })
602 .ok();
603 Ok(FrameStream {
604 frames: rx,
605 worker: Worker {
606 cancel,
607 handle,
608 reuse: None,
609 },
610 backend: BackendCell::new(Backend::Still),
611 })
612 }
613
614 /// A worker for an audio file played as a *picture* ([`crate::is_audio`]):
615 /// the file's peaks are decoded **once** on the worker, and every picture
616 /// after that is painted -- a sliding visualizer
617 /// ([`visualizer_i420`]) at the canvas's own size, then graded, placed and
618 /// converted exactly like a decoded picture, so a grade, a transform and a
619 /// fit policy reach it the way they reach anything else on the timeline.
620 ///
621 /// `start_frame` and `len` are the file's own frames at `fps` -- which for
622 /// an audio source are also the timeline's
623 /// ([`crate::project::Rate::REAL_TIME`]) -- so `Frame::index` runs
624 /// `start_frame ..` like a decoder's output and a speed reaches it through
625 /// the same rewrite as any other clip.
626 pub(crate) fn open_visualizer(
627 path: &Path,
628 stream: usize,
629 start_frame: u32,
630 len: u32,
631 fps: f64,
632 color: ColorParams,
633 transform: TransformParams,
634 canvas: Composer,
635 flags: u8,
636 paint: u64,
637 ) -> crate::Result<FrameStream> {
638 let (tx, rx) = sync_channel(2);
639 let cancel = Arc::new(AtomicBool::new(false));
640 if len == 0 {
641 return Ok(FrameStream {
642 frames: rx,
643 worker: Worker {
644 cancel,
645 handle: None,
646 reuse: None,
647 },
648 backend: BackendCell::new(Backend::Visualizer),
649 });
650 }
651 // Painted at the canvas's own size, so the composite places nothing:
652 // the picture *is* the canvas, and whatever transform the clip
653 // carries still reaches it through the render below.
654 //
655 // Masked to even dimensions first: that is what the painter does to the
656 // planes it hands back, so a canvas it cannot divide evenly (an odd
657 // `resolution 1921 1081` line, or a one-pixel-high one) used to be
658 // *declared* at a size the picture never had -- and the conversion below
659 // then indexes a chroma plane that is not there (`index out of bounds`
660 // on a zero-length slice, in this worker, where no frame ever arrives
661 // and nothing catches it). No floor under the mask: a canvas with no
662 // size is asked for no picture, and the painter answers that with empty
663 // planes ([`visualizer_window_i420`]), which the declared size now
664 // matches.
665 let (canvas_w, canvas_h) = canvas.dims();
666 let (width, height) = (canvas_w & !1, canvas_h & !1);
667 let worker_cancel = Arc::clone(&cancel);
668 let path = path.to_path_buf();
669 let handle = thread::Builder::new()
670 .name("viz".into())
671 .spawn(move || {
672 // The envelope this span paints from, asked for once for the
673 // whole span: the memo's own handle when it holds one, and
674 // otherwise a *window* of the file's envelope per frame --
675 // which is what makes a rebuild cheap for a source whose whole
676 // envelope does not fit the memo at all ([`viz_envelope`]). A
677 // file that will not open -- and one with no track at all --
678 // paints the flat line, which is what its silence looks like
679 // anyway: a visualizer frame always exists, and is never worth
680 // failing a span over.
681 let mut envelope =
682 crate::waveform::viz_envelope(&path, stream, VIZ_BUCKETS_PER_SEC)
683 .unwrap_or(crate::waveform::VizEnvelope::Silent);
684 if worker_cancel.load(Ordering::Relaxed) {
685 return;
686 }
687 let fps = if fps.is_finite() && fps > 0.0 { fps } else { 30.0 };
688 // One frame's painting no longer allocates per strand per
689 // frame: this thread lives for the span.
690 let mut scratch = VizScratch::default();
691 let mut render = Render::new(
692 color,
693 transform,
694 // Painted here, at the canvas's own size: nothing turned it.
695 Rotation::None,
696 // ...and nothing drew it anamorphic: it is square by
697 // construction.
698 PixelAspect::SQUARE,
699 ColorDescription::default(),
700 canvas,
701 tonemap::Preset::default(),
702 None,
703 );
704 for index in 0..len {
705 if worker_cancel.load(Ordering::Relaxed) {
706 return;
707 }
708 let t = f64::from(start_frame + index) / fps;
709 // One window of the envelope about this frame's own time:
710 // the same window for every frame a sliding paint asks of
711 // the same thirty seconds, and no decode at all for the
712 // rebuilds of a look edit.
713 let view = envelope.view_at(t);
714 let (y, u, v) = visualizer_window_i420(
715 &mut scratch, &view, t, width, height, flags, paint,
716 );
717 let frame = render.frame(start_frame + index, &y, &u, &v, width, height);
718 if tx.send(frame).is_err() {
719 return; // caller moved on
720 }
721 }
722 })
723 .ok();
724 Ok(FrameStream {
725 frames: rx,
726 worker: Worker {
727 cancel,
728 handle,
729 reuse: None,
730 },
731 backend: BackendCell::new(Backend::Visualizer),
732 })
733 }
734
735 /// As [`DecodeSession::open_range`], but the caller gets the whole
736 /// [`Worker`] and can therefore *wait* for it, and the range is graded by
737 /// `color` -- the clip's own setting, folded into the conversion the frames
738 /// go through anyway (see [`i420_to_bgra_with`]). It is captured here rather
739 /// than read per frame because a worker *is* one clip's range: a grade
740 /// changed while this one runs reaches the picture when the session reseeks
741 /// onto the new one, which every edit does.
742 ///
743 /// In-process only: a caller that outlives its workers has to be able to
744 /// join them at exit.
745 ///
746 /// `canvas` is the project's own resolution and this clip's fit policy: the
747 /// frames come out at *that* size, whatever the file's is. A
748 /// [`Composer::passthrough`] (or one already the source's size) leaves every
749 /// picture exactly as it was decoded.
750 ///
751 /// `tone` is the project's HDR rendition ([`tonemap::Preset`]), captured
752 /// here for the reason the grade is: it is constant across one span, and a
753 /// preset picked while this worker runs reaches the picture when the session
754 /// reseeks onto the new one. An SDR source ignores it entirely.
755 pub(crate) fn open_worker(
756 path: impl AsRef<Path>,
757 start_frame: u32,
758 end_frame: u32,
759 color: ColorParams,
760 transform: TransformParams,
761 canvas: Composer,
762 tone: tonemap::Preset,
763 ) -> crate::Result<(VideoMeta, FrameStream)> {
764 let path = path.as_ref().to_path_buf();
765 let (meta, demuxer) = Demuxer::open(&path)?;
766 // No software HEVC, VP9 or VP8 decoder exists, so such a file the plugin will
767 // not take is refused *here*, where the caller still has somewhere to
768 // show it -- a worker that opened and then produced nothing is a black
769 // screen with no explanation. The probe session is opened, made to
770 // decode one picture and dropped: it costs one extra VA-API init
771 // (~90 ms) plus that frame, and only off the two codecs with a software
772 // seat of their own -- H.264 through `ec-h264`, AV1 through `ec-av1` --
773 // which fall back to it exactly where this probe would have refused.
774 if !matches!(meta.codec, Codec::H264 | Codec::Av1) {
775 hw_decodes(&path, start_frame, meta.codec)?;
776 }
777 let end_frame = end_frame.min(meta.frame_count);
778 if end_frame <= start_frame {
779 // Nothing to decode: a disconnected receiver and no thread at all,
780 // so the caller sees an immediate end of stream rather than an error.
781 let (_, rx) = sync_channel(1);
782 return Ok((
783 meta,
784 FrameStream {
785 frames: rx,
786 worker: Worker {
787 cancel: Arc::new(AtomicBool::new(false)),
788 handle: None,
789 reuse: None,
790 },
791 backend: BackendCell::default(),
792 },
793 ));
794 }
795 Ok((
796 meta,
797 span_worker(
798 path,
799 Some(Source::demuxed(demuxer, meta)),
800 start_frame,
801 end_frame,
802 color,
803 transform,
804 canvas,
805 tone,
806 // A file-level open has no clip and no speed to skip frames
807 // for: every picture in range is delivered, as it always was.
808 Speed::NORMAL,
809 ),
810 ))
811 }
812
813 /// As [`open_worker`](Self::open_worker), but the *file* is opened on the
814 /// worker too: nothing here touches the disk, so the caller pays a thread
815 /// spawn and not a demux -- 550-750 ms warm on a 25 GB film, seconds cold,
816 /// which is what a seek or a clip boundary used to cost the UI thread.
817 ///
818 /// The price is that there is no [`VideoMeta`] to return and no synchronous
819 /// refusal either: a file that will not open, and a codec no decoder here
820 /// takes (the plugin probe is skipped -- the worker's own refusal below
821 /// covers it), simply drop the sender. The disconnected receiver is what
822 /// carries a session on to the next span, which is exactly what a failed
823 /// open did on this path before. Callers that must *tell* the user why --
824 /// an import at the door -- keep the sync opener.
825 #[allow(clippy::too_many_arguments)]
826 pub(crate) fn open_worker_deferred(
827 path: impl AsRef<Path>,
828 start_frame: u32,
829 end_frame: u32,
830 color: ColorParams,
831 transform: TransformParams,
832 canvas: Composer,
833 tone: tonemap::Preset,
834 speed: Speed,
835 ) -> FrameStream {
836 span_worker(
837 path.as_ref().to_path_buf(),
838 None,
839 start_frame,
840 end_frame,
841 color,
842 transform,
843 canvas,
844 tone,
845 speed,
846 )
847 }
848}
849
850/// Spawns a decode worker over `path` and gives it its first span. The thread
851/// **outlives that span**: it parks on its command channel afterwards, so the
852/// next seek onto the same file reaches it through [`Worker::reseek`] and costs
853/// a demuxer seek and a decoder flush instead of a thread, a container parse and
854/// a VA-API initialisation (98 ms measured worst case).
855///
856/// `opened` is the file when the caller already read it (the sync opener, which
857/// demuxes on the caller's thread to have metadata to return); `None` is the
858/// deferred one, where the worker opens it and nothing here touches the disk.
859#[allow(clippy::too_many_arguments)]
860fn span_worker(
861 path: PathBuf,
862 opened: Option<Source>,
863 start_frame: u32,
864 end_frame: u32,
865 color: ColorParams,
866 transform: TransformParams,
867 canvas: Composer,
868 tone: tonemap::Preset,
869 speed: Speed,
870) -> FrameStream {
871 // The depth is the size of the pictures this worker will *emit*, which for a
872 // pass-through canvas is the stream's own -- and the sync opener has already
873 // read that on the caller's thread. Asking the canvas alone is how the file
874 // door came up with 2: every session opens pass-through (a freshly opened
875 // file *is* the project resolution), so a whole file would play at the
876 // decode-ahead this engine had before there was one, until the first seek
877 // built a real canvas.
878 let depth = match (&opened, canvas.places_nothing()) {
879 (Some(source), true) => crate::scale::queue_depth(source.meta.width, source.meta.height),
880 _ => canvas.queue_depth(),
881 };
882 let (tx, rx) = sync_channel(depth);
883 let cancel = Arc::new(AtomicBool::new(false));
884 // Written by the worker the moment it knows, so a caller reading it sees
885 // what opened rather than what was hoped for -- and kept across the spans
886 // that follow, since they are decoded by that very decoder.
887 let backend = BackendCell::default();
888 let generation = Arc::new(AtomicU64::new(0));
889 // The playhead starts where the span does: nothing is behind it yet.
890 let floor = Arc::new(AtomicU32::new(start_frame));
891 let (spans, commands) = std::sync::mpsc::channel();
892 let first = SpanCmd {
893 generation: 0,
894 start: start_frame,
895 end: end_frame,
896 color,
897 transform,
898 canvas,
899 tone,
900 speed,
901 tx,
902 };
903 let worker_cancel = Arc::clone(&cancel);
904 let worker_backend = backend.clone();
905 let worker_generation = Arc::clone(&generation);
906 let worker_floor = Arc::clone(&floor);
907 let worker_path = path.clone();
908 let handle = thread::Builder::new()
909 .name("decode".into())
910 .spawn(move || {
911 let mut source = opened;
912 let mut cmd = first;
913 loop {
914 let abort = Abort {
915 cancel: &worker_cancel,
916 generation: &worker_generation,
917 mine: cmd.generation,
918 floor: &worker_floor,
919 };
920 // Superseded (or cancelled) before this thread was even
921 // scheduled: do not open the file, and do not enter VA-API
922 // initialisation, which is the one stretch a cancel cannot
923 // interrupt. A scrub abandons spans by the dozen and this is
924 // where all but the last of them stop.
925 if !abort.hit() {
926 run_span(&worker_path, &mut source, cmd, &abort, &worker_backend);
927 }
928 // Parked between spans. A seek and a clip boundary arrive in
929 // milliseconds and find the decoder still open, which is the
930 // whole point of this thread -- but a session nobody comes back
931 // to (the timeline played out, the window was left alone) must
932 // not sit on the driver: it would hold a live libva thread into
933 // whatever exit path the process takes, which is the SIGSEGV in
934 // Mesa's `atexit` the retired pool exists to prevent, and
935 // holding it *while idle* would widen that from "quit during a
936 // decode" to "quit any time after opening a file".
937 //
938 // So the wait is in two halves: the fast one keeps everything,
939 // and past [`IDLE`] the hardware session is closed. The demuxer
940 // stays -- it is a file handle and an index, not driver state,
941 // and rebuilding it is what costs seconds on a big Matroska --
942 // so the reseek after a long pause pays one VA-API init and
943 // nothing else.
944 match commands.recv_timeout(IDLE) {
945 Ok(next) => cmd = next,
946 Err(RecvTimeoutError::Timeout) => {
947 if let Some(source) = &mut source
948 && source.hw.take().is_some()
949 {
950 eprintln!("decode worker idle: hardware session closed");
951 }
952 // The session dropped the command channel: this worker
953 // is retired (or was detached), so the file goes now.
954 match commands.recv() {
955 Ok(next) => cmd = next,
956 Err(_) => return,
957 }
958 }
959 Err(RecvTimeoutError::Disconnected) => return,
960 }
961 }
962 })
963 .ok();
964 FrameStream {
965 frames: rx,
966 worker: Worker {
967 cancel,
968 handle,
969 reuse: Some(Reuse {
970 path,
971 spans,
972 generation,
973 backend: backend.clone(),
974 floor,
975 }),
976 },
977 backend,
978 }
979}
980
981/// How long a parked worker keeps its hardware session before closing it. Long
982/// enough that a seek, a scrub step and a clip boundary all find the decoder
983/// where they left it -- and long enough for the think-time between two
984/// samples of a live slider drag (a colour or transform card nudge), which
985/// reseeks the very same worker and paid the *closed* half of this window
986/// every time a person paused a beat to look before nudging again: a session
987/// found the hardware gone and rebuilt it (measured seconds on a big file)
988/// for what should have cost one `hw.seek`. Short enough that a session left
989/// alone for real (the window switched away from, a scrub that stopped) is
990/// not holding libva when the process exits.
991const IDLE: std::time::Duration = std::time::Duration::from_secs(8);
992
993/// How many pictures in a row a worker may drop for being late before it hands
994/// one over regardless. The policy needs a floor of its own: a machine that
995/// cannot decode a file in real time is late on *every* picture, and dropping
996/// every picture is a black screen rather than a stutter -- so the slowest seat
997/// still gets one in nine, which is roughly what it could paint before (the
998/// front-end restarted the decoder once every two seconds to the same effect,
999/// and paid a VA-API init for each restart).
1000const LATE_RUN: u32 = 8;
1001
1002/// What a decode worker keeps **between** the spans it is asked for: the
1003/// container it read, what the stream says about itself, and the hardware
1004/// session -- the three things a seek used to throw away and buy again.
1005struct Source {
1006 meta: VideoMeta,
1007 /// What the film says its brightest picture is ([`Demuxer::light`]): the
1008 /// tone map's assumed peak on the reference rendition, so a 1759 cd/m^2
1009 /// grade is converted at 1759 rather than at the 1000 a file that declared
1010 /// nothing is assumed at. A property of the stream, read once with it.
1011 peak: Option<f32>,
1012 demuxer: Demuxer,
1013 /// The plugin's session, opened on this thread (its VA-API state is not
1014 /// `Send`-safe across a hand-off) and *kept*. `None` for software: forced by
1015 /// `VE_SW`, refused by the plugin, or handed back by a session that opened
1016 /// and then decoded nothing.
1017 hw: Option<HwSession>,
1018}
1019
1020impl Source {
1021 /// The file as the sync opener already read it.
1022 fn demuxed(demuxer: Demuxer, meta: VideoMeta) -> Self {
1023 Self {
1024 meta,
1025 peak: demuxer.light().peak(),
1026 demuxer,
1027 hw: None,
1028 }
1029 }
1030
1031 /// ...and as the deferred opener reads it, on the worker. `None` is a file
1032 /// that would not open: the caller drops the sender, and the disconnected
1033 /// receiver is the session's "walk on to the next span".
1034 fn open(path: &Path) -> Option<Self> {
1035 match Demuxer::open(path) {
1036 Ok((meta, demuxer)) => Some(Self::demuxed(demuxer, meta)),
1037 Err(e) => {
1038 eprintln!("video open failed: {e}");
1039 None
1040 }
1041 }
1042 }
1043
1044 /// Puts the hardware decoder at `start`, keeping the session open where the
1045 /// plugin can reposition it. `None` when there is no hardware here at all;
1046 /// otherwise whether the session was **reused** -- which is what lets the
1047 /// caller tell a driver that cannot decode this stream from one that merely
1048 /// did not follow a reseek.
1049 fn position_hw(&mut self, path: &Path, start: u32) -> Option<bool> {
1050 if let Some(hw) = &mut self.hw {
1051 if hw.seek(start) {
1052 eprintln!("decode backend: hardware (VA-API plugin, session kept, seek to {start})");
1053 return Some(true);
1054 }
1055 // A plugin too old to reposition, or a decoder that would not
1056 // flush: closed and opened again, which is what every seek did.
1057 self.hw = None;
1058 }
1059 self.hw = open_hw(path, start);
1060 self.hw.as_ref().map(|_| {
1061 eprintln!("decode backend: hardware (VA-API plugin)");
1062 false
1063 })
1064 }
1065}
1066
1067/// One span on a worker's thread: position the decoder, decode
1068/// `[start, end)`, send the pictures. Every opener ends here -- the sync one,
1069/// which demuxed on the caller's thread, the deferred one, which demuxes on
1070/// this one, and every reseek after them -- so there is exactly one description
1071/// of what a decode worker does.
1072fn run_span(
1073 path: &Path,
1074 source: &mut Option<Source>,
1075 cmd: SpanCmd,
1076 abort: &Abort,
1077 backend: &BackendCell,
1078) {
1079 let SpanCmd {
1080 start,
1081 end,
1082 color,
1083 transform,
1084 canvas,
1085 tone,
1086 speed,
1087 tx,
1088 ..
1089 } = cmd;
1090 let opened = match source {
1091 Some(opened) => opened,
1092 None => {
1093 let Some(fresh) = Source::open(path) else {
1094 backend.set(Backend::Gap);
1095 return;
1096 };
1097 source.insert(fresh)
1098 }
1099 };
1100 // The clamp the sync opener does with the metadata it read on the caller's
1101 // thread; here the metadata arrives first.
1102 let end = end.min(opened.meta.frame_count);
1103 // An empty range decodes nothing and must send nothing: `run_hw` counts a
1104 // frame *out* before it compares, so without this a zero-length span would
1105 // emit one picture.
1106 if end <= start {
1107 return;
1108 }
1109 // The stream's own colour and peak brightness: properties of the stream, so
1110 // neither can change while one range decodes -- but the grade, the canvas
1111 // and the rendition are the *span's*, so this is built per span.
1112 let mut render = Render::new(
1113 color,
1114 transform,
1115 opened.meta.rotation,
1116 opened.meta.pixel_aspect,
1117 opened.meta.color,
1118 canvas,
1119 tone,
1120 opened.peak,
1121 );
1122 if let Some(reused) = opened.position_hw(path, start) {
1123 // Cancelled during the init (or the seek): leave without decoding.
1124 if abort.hit() {
1125 return;
1126 }
1127 backend.set(Backend::Hardware);
1128 let mut decoded = run_hw(
1129 opened.hw.as_mut().expect("positioned above"),
1130 &tx,
1131 start,
1132 end,
1133 &mut render,
1134 abort,
1135 speed,
1136 );
1137 // A *reused* session that produced nothing may simply be one this
1138 // reseek left where the driver would not follow; a session opened fresh
1139 // at the same frame is the honest second question, and only its silence
1140 // is a software fallback. Without this a single unfollowed seek would
1141 // collapse the rest of the file to software.
1142 if !decoded && reused {
1143 eprintln!("hardware decode produced nothing after a reseek; reopening at frame {start}");
1144 opened.hw = open_hw(path, start);
1145 if let Some(hw) = opened.hw.as_mut() {
1146 decoded = run_hw(hw, &tx, start, end, &mut render, abort, speed);
1147 }
1148 }
1149 if decoded {
1150 return;
1151 }
1152 // A driver that opens but cannot decode a single frame is still a
1153 // fallback case, not a dead session.
1154 opened.hw = None;
1155 eprintln!("hardware decode failed before any frame, falling back to software");
1156 }
1157 // ...except where there is nothing to fall back to. Feeding HEVC, VP9 or
1158 // VP8 bytes to either software seat would be garbage, not a fallback --
1159 // VP8's decoder is `ec-vp8`, inside the plugin. H.264 and AV1 each
1160 // have one of this project's own here: `ec-h264`, `ec-av1`.
1161 match opened.meta.codec {
1162 Codec::H264 => {
1163 eprintln!("decode backend: software (ec-h264)");
1164 backend.set(Backend::Software);
1165 run(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed);
1166 }
1167 Codec::Av1 => {
1168 eprintln!("decode backend: software (ec-av1)");
1169 backend.set(Backend::Software);
1170 run_av1(&mut opened.demuxer, &tx, start, end, &mut render, abort, speed);
1171 }
1172 // Nothing decodes from here -- no software seat exists for this codec.
1173 // Say so: the cell was left claiming the hardware session that opened
1174 // and then produced nothing, and it reports what happened, not what
1175 // was hoped for.
1176 other => {
1177 backend.set(Backend::Gap);
1178 eprintln!("{}", other.needs_plugin());
1179 }
1180 }
1181}
1182
1183/// One clip's pictures on their way to the renderer: graded, placed on the
1184/// project canvas, converted. Both decode loops go through it, so hardware and
1185/// software cannot show two different pictures.
1186///
1187/// The order is grade, then place (see [`Composer`]): a grade is the clip's own,
1188/// applied at the resolution it was shot at, and the letterbox bars around it
1189/// are not the clip -- a brightness grade must not lift them off black.
1190///
1191/// A project at the media's own resolution never reaches any of that: it takes
1192/// the fused graded conversion, the one path this engine had before there was a
1193/// project resolution, byte for byte and allocation for allocation.
1194struct Render {
1195 color: ColorParams,
1196 /// This clip's placement, on top of whatever the canvas's own fit policy
1197 /// already does ([`crate::scale::Composer::place_transformed`]).
1198 transform: TransformParams,
1199 /// How far the *file* asks its picture to be turned before anything else
1200 /// happens to it ([`crate::demux::Rotation`]): the phone-portrait turn,
1201 /// made here so the grade, the canvas and the preview's own renderer all
1202 /// see the picture the way it is meant to be seen. [`Rotation::None`] for
1203 /// every file that states no turn, which is the whole of an ordinary
1204 /// library.
1205 rotation: Rotation,
1206 /// The ratio one coded pixel is drawn at ([`crate::demux::PixelAspect`]):
1207 /// the file's sample aspect ratio, applied exactly once, at this one
1208 /// conversion to the square-pixel raster -- the same place ffmpeg's swscale
1209 /// applies it, and nowhere else. Square for every file that states no
1210 /// aspect, which takes the branch by a bool and touches no byte.
1211 pixel_aspect: PixelAspect,
1212 /// What the source's samples mean -- the stream's own matrix and range,
1213 /// which is what the conversion below is done in rather than the BT.601 it
1214 /// used to assume of every file.
1215 desc: ColorDescription,
1216 canvas: Composer,
1217 /// This stream's HDR-to-SDR map, built once here because building it is
1218 /// float work over 9 537 grid nodes and the transfer is a property of the
1219 /// stream. `None` for an SDR stream, which is what keeps that path exactly
1220 /// the one it was.
1221 tone: Option<ToneMapper>,
1222 /// The working copy of the source planes, refilled per frame and kept
1223 /// across the worker's whole range. Empty unless the clip needs one: it is
1224 /// tone-mapped in place, graded in place, or both.
1225 graded: (Vec<u8>, Vec<u8>, Vec<u8>),
1226 /// The same, for the display-matrix turn above: empty for every file that
1227 /// asks for none, and resized once for one that does -- a steady-state
1228 /// buffer rather than three plane allocations per decoded frame.
1229 turned: (Vec<u8>, Vec<u8>, Vec<u8>),
1230 /// The same, for the pixel-aspect stretch: the coded picture widened to
1231 /// the displayed width, empty for every square-pixel file and sized once
1232 /// for one that is not.
1233 stretched: (Vec<u8>, Vec<u8>, Vec<u8>),
1234 /// Where [`Composer::place_transformed`]'s owned picture lands, so a
1235 /// transformed frame's planes live as long as `self` -- matching what
1236 /// [`Composer::place`] already hands back by borrowing `self.canvas`.
1237 placed: (Vec<u8>, Vec<u8>, Vec<u8>),
1238}
1239
1240/// What [`Render::frame`] converts a tone-mapped picture in: the tone map's
1241/// output contract ([`crate::tonemap`]), and no longer the HDR space the file
1242/// declared.
1243const TONE_MAPPED: ColorDescription = ColorDescription {
1244 matrix: Matrix::Bt709,
1245 transfer: Transfer::Sdr,
1246 full_range: false,
1247};
1248
1249impl Render {
1250 /// `peak` is what the file declared about its own brightness
1251 /// ([`Demuxer::light`]), which only an HDR stream has and only the
1252 /// reference rendition reads (see [`tonemap::Preset`]).
1253 fn new(
1254 color: ColorParams,
1255 transform: TransformParams,
1256 rotation: Rotation,
1257 pixel_aspect: PixelAspect,
1258 desc: ColorDescription,
1259 canvas: Composer,
1260 preset: tonemap::Preset,
1261 peak: Option<f32>,
1262 ) -> Self {
1263 Self {
1264 color,
1265 transform,
1266 rotation,
1267 pixel_aspect,
1268 desc,
1269 canvas,
1270 // corner-cut: the ceiling is that the map reads limited-range codes
1271 // (`tonemap`'s input contract), so a full-range PQ file -- which
1272 // no encoder writes and no camera produces -- is mapped as if it
1273 // were limited and comes out slightly crushed. The upgrade is a
1274 // range argument to `ToneMapper::new`.
1275 tone: match desc.transfer {
1276 Transfer::Sdr => None,
1277 Transfer::Pq => Some(ToneMapper::new(tonemap::Transfer::Pq, preset, peak)),
1278 Transfer::Hlg => Some(ToneMapper::new(tonemap::Transfer::Hlg, preset, peak)),
1279 },
1280 graded: (Vec::new(), Vec::new(), Vec::new()),
1281 turned: (Vec::new(), Vec::new(), Vec::new()),
1282 stretched: (Vec::new(), Vec::new(), Vec::new()),
1283 placed: (Vec::new(), Vec::new(), Vec::new()),
1284 }
1285 }
1286
1287 fn frame(
1288 &mut self,
1289 index: u32,
1290 y: &[u8],
1291 u: &[u8],
1292 v: &[u8],
1293 width: u32,
1294 height: u32,
1295 ) -> Frame {
1296 // The pixel aspect, applied exactly once -- the single conversion to
1297 // the square-pixel raster this engine makes, where ffmpeg's swscale
1298 // makes its own -- *before* the display-matrix turn. The ratio belongs
1299 // to the axis that was horizontal before the turn: the coded width is
1300 // stretched by h/v and the turn then swaps the stretched pair, which
1301 // is the composition the probe declares (a 1440x1080 SAR-4/3 file
1302 // turned 90° displays 1080x1920, DAR 9:16). Stretching after the turn
1303 // instead lands the ratio on the coded height and renders a
1304 // 1440x1440 square into a 9:16 canvas -- letterboxed, and the bars
1305 // baked into any export. Only a file whose samples are not square
1306 // reaches the resample: a square one takes the branch by a bool and
1307 // not one byte is touched, which is what keeps every existing picture
1308 // identical to the day before anamorphic sources existed.
1309 let (y, u, v, width, height) = if self.pixel_aspect.is_square() {
1310 (y, u, v, width, height)
1311 } else {
1312 // The aspect widens the *width*, always: 4:3 SAR over 1440x1080
1313 // shows 1920x1080. `width_factor` lands on the even grid 4:2:0
1314 // composes on, and a height is never touched by it.
1315 let display_width = self.pixel_aspect.width_factor(width);
1316 let (sy, su, sv) = &mut self.stretched;
1317 // Sized for `scale_i420`'s exact-planes assertion, once for the
1318 // worker's whole range: steady-state buffers, not per-frame
1319 // allocations ([`turned`]'s reason).
1320 let (dcw, dch) = (
1321 display_width.div_ceil(2) as usize,
1322 height.div_ceil(2) as usize,
1323 );
1324 sy.resize(display_width as usize * height as usize, 0);
1325 su.resize(dcw * dch, 0);
1326 sv.resize(dcw * dch, 0);
1327 crate::scale::scale_i420(
1328 y,
1329 u,
1330 v,
1331 width as usize,
1332 height as usize,
1333 sy,
1334 su,
1335 sv,
1336 display_width as usize,
1337 height as usize,
1338 );
1339 (
1340 &sy[..display_width as usize * height as usize],
1341 &su[..display_width.div_ceil(2) as usize * height.div_ceil(2) as usize],
1342 &sv[..display_width.div_ceil(2) as usize * height.div_ceil(2) as usize],
1343 display_width,
1344 height,
1345 )
1346 };
1347 // The file's own turn, after the stretch: a phone's portrait video
1348 // arrives as landscape planes, and the grade, the canvas and the
1349 // conversion below all have to see the picture the way it is meant to
1350 // be seen. Nothing here at all for the ordinary file that states no
1351 // turn -- `Rotation::None` takes the planes by reference and not one
1352 // byte is copied.
1353 let (y, u, v, width, height) = match self.rotation.is_none() {
1354 true => (y, u, v, width, height),
1355 false => {
1356 let steps = self.rotation.steps();
1357 let (rw, rh) = crate::scale::rotate_i420_90s_into(
1358 y,
1359 u,
1360 v,
1361 width,
1362 height,
1363 steps,
1364 &mut self.turned,
1365 );
1366 (
1367 &self.turned.0[..],
1368 &self.turned.1[..],
1369 &self.turned.2[..],
1370 rw,
1371 rh,
1372 )
1373 }
1374 };
1375 let passthrough = self.canvas.is_passthrough(width, height);
1376 // A transform still has a picture to place even where the canvas
1377 // itself would hand this size back untouched -- moving, scaling,
1378 // rotating or cropping a passthrough-sized clip is still a placement,
1379 // and must not be silently dropped by the fused conversion below.
1380 let transform_active = !self.transform.is_identity();
1381 let skip_placement = passthrough && !transform_active;
1382 // Everything that has to happen to the samples before the canvas sees
1383 // them, on one copy: the tone map (HDR streams only) and, unless the
1384 // conversion below can fuse it, the grade. An SDR stream that is either
1385 // ungraded or passing through takes neither and never allocates.
1386 //
1387 // The grade lands *after* the map on purpose: it is a look on the
1388 // picture a viewer is shown, so its brightness and saturation mean what
1389 // they say in the SDR the tone map just produced, not in the 10-stop
1390 // HDR the file was in.
1391 let (y, u, v, desc) = if self.tone.is_some()
1392 || (!skip_placement && !self.color.is_identity())
1393 {
1394 let (gy, gu, gv) = &mut self.graded;
1395 gy.clear();
1396 gy.extend_from_slice(y);
1397 gu.clear();
1398 gu.extend_from_slice(u);
1399 gv.clear();
1400 gv.extend_from_slice(v);
1401 if let Some(tone) = &self.tone {
1402 tone.map(gy, gu, gv, width as usize, height as usize);
1403 }
1404 // The same terms the branch was entered on: anywhere the fused
1405 // conversion below will not apply the grade (a placement is
1406 // happening, so the canvas conversion is plain), it lands here --
1407 // including the passthrough-sized clip a transform moves, whose
1408 // grade used to be dropped on the floor between these two guards.
1409 if !skip_placement && !self.color.is_identity() {
1410 crate::color::apply_yuv(&self.color, gy, gu, gv);
1411 }
1412 let desc = if self.tone.is_some() {
1413 TONE_MAPPED
1414 } else {
1415 self.desc
1416 };
1417 (&gy[..], &gu[..], &gv[..], desc)
1418 } else {
1419 (y, u, v, self.desc)
1420 };
1421 if skip_placement {
1422 return Frame {
1423 index,
1424 width,
1425 height,
1426 bgra: i420_to_bgra_with(
1427 &desc,
1428 &self.color,
1429 y,
1430 u,
1431 v,
1432 width as usize,
1433 height as usize,
1434 ),
1435 };
1436 }
1437 let (y, u, v, width, height) = if transform_active {
1438 let (py, pu, pv, w, h) = self
1439 .canvas
1440 .place_transformed(y, u, v, width, height, &self.transform);
1441 self.placed = (py, pu, pv);
1442 (&self.placed.0[..], &self.placed.1[..], &self.placed.2[..], w, h)
1443 } else {
1444 self.canvas.place(y, u, v, width, height)
1445 };
1446 Frame {
1447 index,
1448 width,
1449 height,
1450 // Ungraded on purpose: the grade is already in the pixels above and
1451 // the canvas around them must stay the black it was filled with.
1452 bgra: i420_to_bgra(&desc, y, u, v, width as usize, height as usize),
1453 }
1454 }
1455}
1456
1457/// One still image, decoded to tightly packed I420 -- the shape every other
1458/// source arrives in, so a placed image goes through the same grade, the same
1459/// canvas and the same conversion as a decoded picture and there is no second
1460/// pixel path to keep in step.
1461///
1462/// Held whole rather than streamed: an image *is* one picture, and the file is
1463/// read once per span that plays it.
1464pub(crate) struct Still {
1465 pub(crate) y: Vec<u8>,
1466 pub(crate) u: Vec<u8>,
1467 pub(crate) v: Vec<u8>,
1468 pub(crate) width: u32,
1469 pub(crate) height: u32,
1470}
1471
1472impl Still {
1473 /// Decodes `path`. Refused by name for a picture that is not one
1474 /// ([`crate::is_resolution`]): an 8K limit that a keystroke and a project
1475 /// file are both held to cannot be walked around by a 30000-pixel-wide PNG.
1476 ///
1477 /// Alpha is *dropped*, not composited: `to_rgb8` discards the channel, so a
1478 /// transparent PNG arrives fully opaque over its own colours rather than
1479 /// over the clip beneath it. I420 has nowhere to carry it and this engine
1480 /// composes one picture per frame (topmost lane wins), so there is nothing
1481 /// for a blend to blend with.
1482 ///
1483 /// corner-cut: the ceiling is a logo with a transparent background, which
1484 /// lands as a rectangle. Upgrade path is keeping the alpha plane here and
1485 /// giving `scale::Composer` a blend over the lane below.
1486 pub(crate) fn open(path: &Path) -> crate::Result<Self> {
1487 let reader = image::ImageReader::open(path)?.with_guessed_format()?;
1488 let rgb = reader
1489 .decode()
1490 .map_err(|e| format!("{}: {e}", path.display()))?
1491 .to_rgb8();
1492 let (width, height) = rgb.dimensions();
1493 if !crate::is_resolution(width, height) {
1494 return Err(format!(
1495 "{} is {width}x{height}, which is not a picture this engine composes",
1496 path.display()
1497 )
1498 .into());
1499 }
1500 let (y, u, v) = rgb_to_i420(&rgb, width as usize, height as usize);
1501 Ok(Self {
1502 y,
1503 u,
1504 v,
1505 width,
1506 height,
1507 })
1508 }
1509
1510 /// The planes as an export's decoder hands them over, so a still and a
1511 /// decoded picture are the same value to `export::run`.
1512 pub(crate) fn picture(&self) -> (&[u8], &[u8], &[u8], u32, u32) {
1513 (&self.y, &self.u, &self.v, self.width, self.height)
1514 }
1515}
1516
1517/// How big the picture in `path` is, from its header alone -- what a library row
1518/// says about a file it has not placed anywhere. The whole file is not decoded.
1519pub fn image_size(path: &Path) -> crate::Result<(u32, u32)> {
1520 Ok(image::ImageReader::open(path)?
1521 .with_guessed_format()?
1522 .into_dimensions()
1523 .map_err(|e| format!("{}: {e}", path.display()))?)
1524}
1525
1526/// Packed RGB8 -> tightly packed I420, BT.601 limited range: the exact inverse
1527/// of [`crate::convert::i420_to_bgra`] *in that matrix*, which is why
1528/// [`DecodeSession::open_still`] hands the renderer a BT.601 description and
1529/// not the timeline's. A still has no stream to be tagged by; it round-trips to
1530/// the colour it was authored in through this pair and nothing else sees these
1531/// planes (`images::still_pixels_match_the_source_image` measures it).
1532///
1533/// Chroma is the 2x2 box average, and an odd edge averages the samples it has --
1534/// the planes come out `(w + 1) / 2` by `(h + 1) / 2`, which is the shape
1535/// [`crate::scale::Composer::place`] panics on anything else for.
1536fn rgb_to_i420(rgb: &[u8], width: usize, height: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1537 let (cw, ch) = crate::scale::chroma_dims(width, height);
1538 let mut y = vec![0u8; width * height];
1539 let mut u = vec![0u8; cw * ch];
1540 let mut v = vec![0u8; cw * ch];
1541 for row in 0..height {
1542 for col in 0..width {
1543 let p = (row * width + col) * 3;
1544 let (r, g, b) = (rgb[p] as i32, rgb[p + 1] as i32, rgb[p + 2] as i32);
1545 y[row * width + col] = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8;
1546 }
1547 }
1548 for crow in 0..ch {
1549 for ccol in 0..cw {
1550 let (mut sr, mut sg, mut sb, mut n) = (0i32, 0i32, 0i32, 0i32);
1551 for row in crow * 2..(crow * 2 + 2).min(height) {
1552 for col in ccol * 2..(ccol * 2 + 2).min(width) {
1553 let p = (row * width + col) * 3;
1554 sr += rgb[p] as i32;
1555 sg += rgb[p + 1] as i32;
1556 sb += rgb[p + 2] as i32;
1557 n += 1;
1558 }
1559 }
1560 let n = n.max(1);
1561 let (r, g, b) = (sr / n, sg / n, sb / n);
1562 u[crow * cw + ccol] = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8;
1563 v[crow * cw + ccol] = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8;
1564 }
1565 }
1566 (y, u, v)
1567}
1568
1569/// Peak buckets per second the visualizer paints from, shared by the one
1570/// caller that decodes them ([`DecodeSession::open_visualizer`], preview and
1571/// export both) and the painter that reads them.
1572pub(crate) const VIZ_BUCKETS_PER_SEC: u32 = 4000;
1573/// Bits 1-2: which picture this visualizer paints. Mutually exclusive —
1574/// a picker, not independent toggles.
1575pub const VIZ_STYLE_FILL: u8 = 0;
1576pub const VIZ_STYLE_RIBBON: u8 = 1;
1577pub const VIZ_STYLE_RING: u8 = 2;
1578pub const VIZ_STYLE_WAVE: u8 = 3;
1579pub const VIZ_FAST: u8 = 1 << 3;
1580
1581pub fn viz_style(flags: u8) -> u8 {
1582 (flags >> 1) & 3
1583}
1584
1585pub fn with_viz_style(flags: u8, style: u8) -> u8 {
1586 (flags & !0b0110) | ((style & 3) << 1)
1587}
1588
1589/// Azure + sat 160 + 8 strands + glow 2. What `viz_paint == 0` means.
1590pub const VIZ_PAINT_AZURE: u64 = 150 | (160 << 8) | (8 << 16) | (2 << 24);
1591
1592/// Where the strand colour sits above the clip's own four bytes: hue at 32
1593/// and sat at 40, with bit 63 as the flag that says a clip chose one
1594/// ([`viz_strand_set`]). A clear flag means the automatic complement the
1595/// ring has always painted -- so a v22 value, whose top half is empty, is
1596/// nothing new.
1597const VIZ_STRAND_HUE_SHIFT: u32 = 32;
1598const VIZ_STRAND_SAT_SHIFT: u32 = 40;
1599const VIZ_STRAND_CHOSEN: u64 = 1 << 63;
1600
1601pub fn viz_materialize(paint: u64) -> u64 {
1602 if paint == 0 {
1603 VIZ_PAINT_AZURE
1604 } else {
1605 paint
1606 }
1607}
1608
1609pub fn viz_ink_from_paint(paint: u64) -> (u8, u8, u8) {
1610 let p = viz_materialize(paint);
1611 let hue = (p & 0xFF) as f32 * 360.0 / 256.0;
1612 let sat = f32::from(((p >> 8) & 0xFF) as u8) / 255.0;
1613 hsv_to_rgb(hue, sat, 0.84)
1614}
1615
1616pub fn viz_strands_of(paint: u64) -> u8 {
1617 (((viz_materialize(paint) >> 16) & 0xFF) as u8).clamp(1, 32)
1618}
1619
1620pub fn viz_glow_of(paint: u64) -> u8 {
1621 ((viz_materialize(paint) >> 24) & 0xFF) as u8
1622}
1623
1624pub fn with_viz_paint_hue(paint: u64, hue: u8) -> u64 {
1625 (viz_materialize(paint) & !0xFF) | u64::from(hue)
1626}
1627
1628pub fn with_viz_paint_sat(paint: u64, sat: u8) -> u64 {
1629 (viz_materialize(paint) & !(0xFF << 8)) | (u64::from(sat) << 8)
1630}
1631
1632pub fn with_viz_paint_strands(paint: u64, n: u8) -> u64 {
1633 (viz_materialize(paint) & !(0xFF << 16)) | (u64::from(n.clamp(1, 32)) << 16)
1634}
1635
1636pub fn with_viz_paint_glow(paint: u64, n: u8) -> u64 {
1637 (viz_materialize(paint) & !(0xFF << 24)) | (u64::from(n.min(16)) << 24)
1638}
1639
1640pub fn viz_hue_ui(paint: u64) -> u8 {
1641 if paint == 0 { 150 } else { (paint & 0xFF) as u8 }
1642}
1643
1644pub fn viz_sat_ui(paint: u64) -> u8 {
1645 if paint == 0 {
1646 160
1647 } else {
1648 match ((paint >> 8) & 0xFF) as u8 {
1649 0 => 160,
1650 s => s,
1651 }
1652 }
1653}
1654
1655/// Whether the clip chose a strand colour of its own (the top bit), rather
1656/// than taking the automatic complement a ring's dual half has always
1657/// painted.
1658pub fn viz_strand_set(paint: u64) -> bool {
1659 paint & VIZ_STRAND_CHOSEN != 0
1660}
1661
1662/// The chosen strand hue, 0-255 on the wheel [`viz_hue_ui`] reads.
1663pub fn viz_strand_hue_ui(paint: u64) -> u8 {
1664 ((paint >> VIZ_STRAND_HUE_SHIFT) & 0xFF) as u8
1665}
1666
1667/// The chosen strand sat, 0-255. A stored zero stays zero here, unlike
1668/// [`viz_sat_ui`]'s: a grey strand is a colour someone picked, and the flag
1669/// -- not the byte -- is what says whether there is one.
1670pub fn viz_strand_sat_ui(paint: u64) -> u8 {
1671 ((paint >> VIZ_STRAND_SAT_SHIFT) & 0xFF) as u8
1672}
1673
1674/// Set the strand hue and mark the colour chosen, so a ring's dual half
1675/// inks it instead of the automatic complement.
1676pub fn with_viz_paint_strand_hue(paint: u64, hue: u8) -> u64 {
1677 let p = viz_materialize(paint) & !(0xFF_u64 << VIZ_STRAND_HUE_SHIFT);
1678 (p | (u64::from(hue) << VIZ_STRAND_HUE_SHIFT)) | VIZ_STRAND_CHOSEN
1679}
1680
1681/// Set the strand sat and mark the colour chosen, as
1682/// [`with_viz_paint_strand_hue`] does.
1683pub fn with_viz_paint_strand_sat(paint: u64, sat: u8) -> u64 {
1684 let p = viz_materialize(paint) & !(0xFF_u64 << VIZ_STRAND_SAT_SHIFT);
1685 (p | (u64::from(sat) << VIZ_STRAND_SAT_SHIFT)) | VIZ_STRAND_CHOSEN
1686}
1687
1688/// Drop the chosen strand colour: the dual half of a ring goes back to the
1689/// automatic complement, and both strand bytes go with the flag.
1690pub fn viz_strand_clear(paint: u64) -> u64 {
1691 paint & !(VIZ_STRAND_CHOSEN
1692 | (0xFF_u64 << VIZ_STRAND_HUE_SHIFT)
1693 | (0xFF_u64 << VIZ_STRAND_SAT_SHIFT))
1694}
1695
1696/// `#RRGGBB` for an ink, at the same fixed value the painter draws at, so
1697/// the swatch a front-end shows is the colour that reaches the picture.
1698/// The inverse of [`viz_color_from_text`] for the colours a round trip
1699/// through bytes can carry back.
1700pub fn viz_color_hex(hue: u8, sat: u8) -> String {
1701 let (r, g, b) = hsv_to_rgb(f32::from(hue) * 360.0 / 256.0, f32::from(sat) / 255.0, 0.84);
1702 format!("#{r:02X}{g:02X}{b:02X}")
1703}
1704
1705/// A colour someone typed -- `#4F8FD6`, `4f8fd6`, `rgb(79,143,214)` or
1706/// `rgba(79,143,214,255)`, any case, commas or `/` between the channels,
1707/// alpha ignored -- as the `(hue, sat)` pair the sliders and the paint
1708/// field speak. `None` for everything else rather than a guess: the wrong
1709/// number of digits, a channel outside 0-255, parentheses missing.
1710///
1711/// Brightness is dropped, not carried: the painter draws every ink at its
1712/// own fixed value, so a typed colour is kept by its hue and saturation.
1713pub fn viz_color_from_text(text: &str) -> Option<(u8, u8)> {
1714 let t = text.trim();
1715 let (r, g, b) = if let Some(inner) = t.strip_suffix(')') {
1716 let body = if starts_ci(inner, b"rgb(") {
1717 &inner[4..]
1718 } else if starts_ci(inner, b"rgba(") {
1719 &inner[5..]
1720 } else {
1721 return None;
1722 };
1723 let mut channels = body.split(['/', ',']).map(str::trim);
1724 let r = channel(channels.next()?)?;
1725 let g = channel(channels.next()?)?;
1726 let b = channel(channels.next()?)?;
1727 // Alpha, when it is spelled: read so a bad one is refused like a
1728 // channel is, and dropped -- the paint field has no room for it.
1729 if let Some(a) = channels.next() {
1730 channel(a)?;
1731 }
1732 if channels.next().is_some() {
1733 return None;
1734 }
1735 (r, g, b)
1736 } else {
1737 let hex = t.strip_prefix('#').unwrap_or(t);
1738 if hex.len() != 6 || !hex.bytes().all(|c| c.is_ascii_hexdigit()) {
1739 return None;
1740 }
1741 (
1742 u8::from_str_radix(&hex[0..2], 16).ok()?,
1743 u8::from_str_radix(&hex[2..4], 16).ok()?,
1744 u8::from_str_radix(&hex[4..6], 16).ok()?,
1745 )
1746 };
1747 Some(rgb_to_hue_sat(r, g, b))
1748}
1749
1750fn starts_ci(text: &str, prefix: &[u8]) -> bool {
1751 text.len() >= prefix.len() && text.as_bytes()[..prefix.len()].eq_ignore_ascii_case(prefix)
1752}
1753
1754/// One 0-255 channel of a typed colour: digits only, so neither a sign nor
1755/// an exponent slips in the way `u8`'s own parse would take them.
1756fn channel(text: &str) -> Option<u8> {
1757 if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
1758 return None;
1759 }
1760 text.parse().ok()
1761}
1762
1763/// What a byte RGB is on the paint field's wheel: hue on [`viz_hue_ui`]'s
1764/// 0-255 scale, sat 0-255, brightness dropped for the same reason
1765/// [`viz_color_from_text`] drops the typed one.
1766fn rgb_to_hue_sat(r: u8, g: u8, b: u8) -> (u8, u8) {
1767 let (r, g, b) = (f32::from(r), f32::from(g), f32::from(b));
1768 let (max, min) = (r.max(g).max(b), r.min(g).min(b));
1769 let delta = max - min;
1770 let hue = if delta == 0.0 {
1771 0.0
1772 } else if max == r {
1773 60.0 * ((g - b) / delta).rem_euclid(6.0)
1774 } else if max == g {
1775 60.0 * ((b - r) / delta + 2.0)
1776 } else {
1777 60.0 * ((r - g) / delta + 4.0)
1778 };
1779 let hue = ((hue * 256.0 / 360.0).round() as i64).rem_euclid(256) as u8;
1780 let sat = if max == 0.0 { 0.0 } else { delta / max };
1781 (hue, (sat * 255.0).round() as u8)
1782}
1783
1784pub fn viz_hsv_rgb(h: f32, s: f32, v: f32) -> (u8, u8, u8) {
1785 hsv_to_rgb(h, s, v)
1786}
1787
1788fn hsv_to_rgb(h: f32, s: f32, v: f32) -> (u8, u8, u8) {
1789 let h = ((h % 360.0) + 360.0) % 360.0;
1790 let c = v * s;
1791 let x = c * (1.0 - ((h / 60.0) % 2.0 - 1.0).abs());
1792 let m = v - c;
1793 let (r, g, b) = match (h / 60.0) as i32 {
1794 0 => (c, x, 0.0),
1795 1 => (x, c, 0.0),
1796 2 => (0.0, c, x),
1797 3 => (0.0, x, c),
1798 4 => (x, 0.0, c),
1799 _ => (c, 0.0, x),
1800 };
1801 (
1802 ((r + m) * 255.0).round() as u8,
1803 ((g + m) * 255.0).round() as u8,
1804 ((b + m) * 255.0).round() as u8,
1805 )
1806}
1807
1808fn rgb_yuv(r: i32, g: i32, b: i32) -> (u8, u8, u8) {
1809 let y = (((66 * r + 129 * g + 25 * b + 128) >> 8) + 16) as u8;
1810 let u = (((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128) as u8;
1811 let v = (((112 * r - 94 * g - 18 * b + 128) >> 8) + 128) as u8;
1812 (y, u, v)
1813}
1814
1815/// How much sound one visualizer frame shows, centered on the frame's own
1816/// time. Two seconds by default; [`VIZ_FAST`] is a fifth of a second, the
1817/// zoom that makes an Audacity-style trace readable as a line.
1818const VIZ_WINDOW_SECS: f64 = 2.0;
1819const VIZ_FAST_SECS: f64 = 0.2;
1820
1821fn viz_stamp(
1822 y: &mut [u8],
1823 u: &mut [u8],
1824 v: &mut [u8],
1825 w: usize,
1826 h: usize,
1827 cw: usize,
1828 ch: usize,
1829 x: i32,
1830 row: i32,
1831 fall: f32,
1832 bg_y: u8,
1833 ink_y: u8,
1834 ink_u: u8,
1835 ink_v: u8,
1836) {
1837 if x < 0 || row < 0 || x >= w as i32 || row >= h as i32 {
1838 return;
1839 }
1840 let lum =
1841 (f32::from(bg_y) + (f32::from(ink_y) - f32::from(bg_y)) * fall.clamp(0.0, 1.0)) as u8;
1842 let idx = row as usize * w + x as usize;
1843 if lum > y[idx] {
1844 y[idx] = lum;
1845 }
1846 if fall > 0.6 {
1847 let cx = x as usize / 2;
1848 let cy = row as usize / 2;
1849 if cy < ch && cx < cw {
1850 u[cy * cw + cx] = ink_u;
1851 v[cy * cw + cx] = ink_v;
1852 }
1853 }
1854}
1855
1856fn viz_span(
1857 y: &mut [u8],
1858 u: &mut [u8],
1859 v: &mut [u8],
1860 w: usize,
1861 h: usize,
1862 cw: usize,
1863 ch: usize,
1864 x: i32,
1865 top: i32,
1866 bot: i32,
1867 bg_y: u8,
1868 ink_y: u8,
1869 ink_u: u8,
1870 ink_v: u8,
1871) {
1872 let (a, b) = if top <= bot { (top, bot) } else { (bot, top) };
1873 for row in a..=b {
1874 viz_stamp(y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v);
1875 }
1876}
1877
1878/// What one frame's painting borrows instead of allocating, owned by whoever
1879/// paints a *stream* of frames -- the visualizer worker's own thread, an
1880/// export seat, a test -- and reused for every strand of every frame. Eight
1881/// `Vec`s, against the twenty-seven a fresh set per strand cost a ring at
1882/// eight strands.
1883#[derive(Default)]
1884pub(crate) struct VizScratch {
1885 /// The frame's own columns, kept across frames to the widest picture yet.
1886 lo: Vec<f32>,
1887 hi: Vec<f32>,
1888 sig: Vec<f32>,
1889 /// One strand's sampled positions, the cells its Bresenham runs cover,
1890 /// the chain's rows, the row band's candidates and their lower hull.
1891 pts: Vec<(i32, i32)>,
1892 chain: Vec<(i32, i32)>,
1893 rows: Vec<(i32, usize, usize)>,
1894 cand: Vec<(i32, i32)>,
1895 hull: Vec<usize>,
1896}
1897
1898/// One segment's glow as its own disc, stamped at every Bresenham cell: what
1899/// a chain was painted by before [`viz_chain`], and still the cheaper of the
1900/// two when the chain is long ([`viz_discs_are_cheaper`]).
1901#[allow(clippy::too_many_arguments)]
1902fn viz_line(
1903 y: &mut [u8],
1904 u: &mut [u8],
1905 v: &mut [u8],
1906 w: usize,
1907 h: usize,
1908 cw: usize,
1909 ch: usize,
1910 mut x0: i32,
1911 mut y0: i32,
1912 x1: i32,
1913 y1: i32,
1914 bg_y: u8,
1915 ink_y: u8,
1916 ink_u: u8,
1917 ink_v: u8,
1918 glow: u8,
1919) {
1920 let dx = (x1 - x0).abs();
1921 let dy = -(y1 - y0).abs();
1922 let sx = if x0 < x1 { 1 } else { -1 };
1923 let sy = if y0 < y1 { 1 } else { -1 };
1924 let mut err = dx + dy;
1925 let g = i32::from(glow);
1926 loop {
1927 for oy in -g..=g {
1928 for ox in -g..=g {
1929 if ox * ox + oy * oy > g * g {
1930 continue;
1931 }
1932 let fall = if ox == 0 && oy == 0 {
1933 1.0
1934 } else {
1935 let d2 = (ox * ox + oy * oy) as f32;
1936 (-0.45 * d2 / (g * g).max(1) as f32).exp()
1937 };
1938 viz_stamp(y, u, v, w, h, cw, ch, x0 + ox, y0 + oy, fall, bg_y, ink_y, ink_u, ink_v);
1939 }
1940 }
1941 if x0 == x1 && y0 == y1 {
1942 break;
1943 }
1944 let e2 = 2 * err;
1945 if e2 >= dy {
1946 err += dy;
1947 x0 += sx;
1948 }
1949 if e2 <= dx {
1950 err += dx;
1951 y0 += sy;
1952 }
1953 }
1954}
1955
1956/// Which of the two passes paints a chain, by what each of them visits. Both
1957/// paint the same bytes, and the tests hold them to it; they are not alike in
1958/// what they cost. The discs visit `samples * pi * glow^2` cells whatever the
1959/// envelope is doing, while the chain visits each of its own cells once per
1960/// row of its band -- `cells * (2 * glow + 1)`. So a *smooth* trace (a chain
1961/// cell per sample, near enough) is the chain's by a wide margin, and a
1962/// *jagged* one, whose samples are Bresenham runs of dozens of cells, is the
1963/// discs' while the glow is small. A song's own ring at 1080p crossed between
1964/// glow 3 and 4 (31 ms against 44 ms there, and 60 against 52 at glow 4),
1965/// which is exactly what this comparison says.
1966fn viz_discs_are_cheaper(samples: usize, cells: usize, glow: u8) -> bool {
1967 (samples as u64) * (2 * u64::from(glow) + 1) < cells as u64
1968}
1969
1970/// How many cells [`viz_walk`] would push for these samples, without walking
1971/// them: one per iteration of that loop, and it iterates `max(dx, dy) + 1`
1972/// times a segment.
1973fn chain_cells(pts: &[(i32, i32)]) -> usize {
1974 pts.windows(2)
1975 .map(|w| {
1976 let (dx, dy) = ((w[1].0 - w[0].0).abs(), (w[1].1 - w[0].1).abs());
1977 dx.max(dy) as usize + 1
1978 })
1979 .sum()
1980}
1981
1982/// The Bresenham cells of one segment, collected rather than stamped: the same
1983/// walk [`viz_line`] used to rasterise, kept for [`viz_chain`] to paint the
1984/// whole chain from.
1985fn viz_walk(mut x0: i32, mut y0: i32, x1: i32, y1: i32, chain: &mut Vec<(i32, i32)>) {
1986 let dx = (x1 - x0).abs();
1987 let dy = -(y1 - y0).abs();
1988 let sx = if x0 < x1 { 1 } else { -1 };
1989 let sy = if y0 < y1 { 1 } else { -1 };
1990 let mut err = dx + dy;
1991 loop {
1992 chain.push((x0, y0));
1993 if x0 == x1 && y0 == y1 {
1994 break;
1995 }
1996 let e2 = 2 * err;
1997 if e2 >= dy {
1998 err += dy;
1999 x0 += sx;
2000 }
2001 if e2 <= dx {
2002 err += dx;
2003 y0 += sy;
2004 }
2005 }
2006}
2007
2008/// Paints a whole chain in one pass: every cell within `glow` of a chain cell
2009/// takes the falloff of the **nearest** one, and the ink with it.
2010///
2011/// Byte-for-byte what the per-point discs left behind, and the reason is in the
2012/// write: luma is a `max`, so of every disc covering a cell only the closest one
2013/// can decide it, and a glow disc's chroma is written at *every* step of it --
2014/// [`viz_stamp`]`s threshold (0.6) is under the falloff of the rim
2015/// (`exp(-0.45) = 0.64`), which is what makes the whole disc the ink's own.
2016/// What changes is the cost: discs visit `steps * pi * glow^2` cells
2017/// (`VIZ_STYLE_RING`'s 7680 steps measured 296 ms for one 1080p frame at glow
2018/// 16, eight strands), while this visits each covered cell once and finds its
2019/// nearest chain cell by walking outward from it through the chain cells of its
2020/// own row band.
2021#[allow(clippy::too_many_arguments)]
2022fn viz_chain(
2023 y: &mut [u8],
2024 u: &mut [u8],
2025 v: &mut [u8],
2026 w: usize,
2027 h: usize,
2028 cw: usize,
2029 ch: usize,
2030 scratch: &mut VizScratch,
2031 bg_y: u8,
2032 ink_y: u8,
2033 ink_u: u8,
2034 ink_v: u8,
2035 glow: u8,
2036) {
2037 let VizScratch { pts, chain, rows, cand, hull, .. } = scratch;
2038 chain.clear();
2039 for pair in pts.windows(2) {
2040 viz_walk(pair[0].0, pair[0].1, pair[1].0, pair[1].1, chain);
2041 }
2042 if chain.is_empty() {
2043 return;
2044 }
2045 if glow == 0 {
2046 // Nothing to decide: with no glow the cells are the chain itself, at
2047 // full ink -- which is exactly what the row/by/band machinery below
2048 // works out, one sort later.
2049 for &(x, row) in chain.iter() {
2050 viz_stamp(y, u, v, w, h, cw, ch, x, row, 1.0, bg_y, ink_y, ink_u, ink_v);
2051 }
2052 return;
2053 }
2054 let g = i32::from(glow);
2055 // By (row, x) -- the tuple is (x, row) -- so a row's band is a contiguous
2056 // slice of this: a chain revisits cells (the ring is sampled several times
2057 // a pixel) and a repeat is the same candidate.
2058 chain.sort_unstable_by_key(|&(x, row)| (row, x));
2059 chain.dedup();
2060 rows.clear();
2061 let mut i = 0;
2062 while i < chain.len() {
2063 let row = chain[i].1;
2064 let start = i;
2065 while i < chain.len() && chain[i].1 == row {
2066 i += 1;
2067 }
2068 rows.push((row, start, i));
2069 }
2070 let first = (rows[0].0 - g).max(0);
2071 let last = (rows[rows.len() - 1].0 + g).min(h as i32 - 1);
2072 let mut band = 0usize;
2073 // `(x, dy^2)` -- a candidate's horizontal offset is left to the cell that
2074 // asks, its vertical one is its own.
2075 // ...and the candidates a run's cells are decided by, once the ones that
2076 // can never be nearest are off ([`viz_chain`]'s own note).
2077 for row in first..=last {
2078 while band < rows.len() && rows[band].0 < row - g {
2079 band += 1;
2080 }
2081 cand.clear();
2082 let mut k = band;
2083 while k < rows.len() && rows[k].0 <= row + g {
2084 let dy = rows[k].0 - row;
2085 let dy2 = dy * dy;
2086 for &(x, _) in &chain[rows[k].1..rows[k].2] {
2087 cand.push((x, dy2));
2088 }
2089 k += 1;
2090 }
2091 if cand.is_empty() {
2092 continue;
2093 }
2094 cand.sort_unstable_by_key(|&(x, _)| x);
2095 // One candidate per column: the nearest in y is the only one that can
2096 // decide a cell -- the others are further on both axes.
2097 let mut kept = 0usize;
2098 for j in 0..cand.len() {
2099 if kept > 0 && cand[kept - 1].0 == cand[j].0 {
2100 if cand[j].1 < cand[kept - 1].1 {
2101 cand[kept - 1] = cand[j];
2102 }
2103 } else {
2104 cand[kept] = cand[j];
2105 kept += 1;
2106 }
2107 }
2108 cand.truncate(kept);
2109 // The stretches of x the discs reach, one run at a time: the hole in
2110 // the middle of a ring is not walked at all.
2111 let mut j = 0usize;
2112 while j < cand.len() {
2113 let run_lo = cand[j].0 - g;
2114 let mut run_hi = cand[j].0 + g;
2115 let first = j;
2116 while j + 1 < cand.len() && cand[j + 1].0 - g <= run_hi + 1 {
2117 j += 1;
2118 run_hi = run_hi.max(cand[j].0 + g);
2119 }
2120 let end = j + 1; // exclusive
2121 j += 1;
2122 let x_lo = run_lo.max(0);
2123 let x_hi = run_hi.min(w as i32 - 1);
2124 if x_lo > x_hi {
2125 continue;
2126 }
2127 // What is left of a candidate at cell `x` is
2128 // `x^2 - 2*cx*x + (cx^2 + dy^2)`: the `x^2` is common to every
2129 // candidate, so the nearest one is the lowest line of the rest --
2130 // and only the lower hull of those lines is ever the lowest, at any
2131 // x. On the hull the nearest one only ever moves forward as x
2132 // does, which is what makes this a walk over the cells instead of a
2133 // search per cell.
2134 let line = |c: usize| {
2135 let (cx, dy2) = cand[c];
2136 let cx = i64::from(cx);
2137 (-2 * cx, cx * cx + i64::from(dy2))
2138 };
2139 let value = |c: usize, x: i32| {
2140 let (m, b) = line(c);
2141 m * i64::from(x) + b
2142 };
2143 hull.clear();
2144 for c in first..end {
2145 let (m, b) = line(c);
2146 while hull.len() >= 2 {
2147 let (m1, b1) = line(hull[hull.len() - 2]);
2148 let (m2, b2) = line(hull[hull.len() - 1]);
2149 // The middle line is never the lowest: its two crossings
2150 // are the wrong way round.
2151 if (b2 - b1) * (m2 - m) >= (b - b2) * (m1 - m2) {
2152 hull.pop();
2153 } else {
2154 break;
2155 }
2156 }
2157 hull.push(c);
2158 }
2159 // Only the hull's last two entries can change places as x moves
2160 // forward, so this is a walk and not a search -- and `value` is
2161 // asked of those two alone.
2162 let mut hp = 0usize;
2163 for x in x_lo..=x_hi {
2164 while hp + 1 < hull.len() && value(hull[hp + 1], x) <= value(hull[hp], x) {
2165 hp += 1;
2166 }
2167 let (cx, dy2) = cand[hull[hp]];
2168 let d = x - cx;
2169 let d2 = d * d + dy2;
2170 if d2 <= g * g {
2171 let fall = if d2 == 0 {
2172 1.0
2173 } else {
2174 (-0.45 * d2 as f32 / (g * g).max(1) as f32).exp()
2175 };
2176 viz_stamp(y, u, v, w, h, cw, ch, x, row, fall, bg_y, ink_y, ink_u, ink_v);
2177 }
2178 }
2179 }
2180 }
2181}
2182
2183/// One visualizer picture in tightly packed I420. Three looks, picked by
2184/// [`viz_style`]: a bipolar sample trace (Audacity), a filled min/max
2185/// envelope at pixel resolution, or a multi-strand ribbon. Ink is
2186/// [`viz_ink_from_paint`]. A frame always exists; silence is the zero line.
2187///
2188/// This is the whole-envelope entry: it is handed the file's envelope and
2189/// paints from it ([`VizView::whole`]). The seat paints from a *window* of one
2190/// instead ([`visualizer_window_i420`], [`crate::waveform::viz_envelope`]).
2191pub(crate) fn visualizer_i420(
2192 scratch: &mut VizScratch,
2193 peaks: &[(f32, f32)],
2194 t_secs: f64,
2195 width: u32,
2196 height: u32,
2197 flags: u8,
2198 paint: u64,
2199) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2200 visualizer_window_i420(scratch, &VizView::whole(peaks), t_secs, width, height, flags, paint)
2201}
2202
2203/// The envelope a visualizer frame is painted from: the whole file, or one
2204/// *window* of it -- which is what the seat holds, because a film's own
2205/// envelope is past the memo's ceiling ([`crate::waveform::viz_envelope`]).
2206///
2207/// `peaks[i]` is the bucket at absolute index `first + i`, so the painter's
2208/// index arithmetic is the same whether it was handed a slice of thirty
2209/// seconds or of two hours. `total` is the *file's* own bucket count, which is
2210/// what "past the end of the file" is measured against -- a window that
2211/// measured it against itself would draw the file's end wherever the window
2212/// ended -- and `peak` is the file's loudest bucket, which every column is
2213/// scaled by: no window can derive that from itself.
2214///
2215/// `per_sec` is the rate *this* envelope was drawn at, in buckets per second,
2216/// and it is carried rather than assumed: the slice is indexed at it, so an
2217/// envelope drawn at another rate under a painter that hard-coded the
2218/// visualizer's own would read a tenth of a second of sound as a second. The
2219/// whole-file constructor is the one place the visualizer's rate is named.
2220pub(crate) struct VizView<'a> {
2221 pub(crate) peaks: &'a [(f32, f32)],
2222 pub(crate) first: usize,
2223 pub(crate) total: usize,
2224 pub(crate) peak: f32,
2225 pub(crate) per_sec: f64,
2226}
2227
2228impl<'a> VizView<'a> {
2229 /// The whole envelope, which is what every caller but the seat has.
2230 pub(crate) fn whole(peaks: &'a [(f32, f32)]) -> Self {
2231 Self {
2232 peaks,
2233 first: 0,
2234 total: peaks.len(),
2235 peak: crate::waveform::peak_of(peaks),
2236 per_sec: f64::from(VIZ_BUCKETS_PER_SEC),
2237 }
2238 }
2239
2240 /// One window of an envelope: `peaks` starts at absolute bucket `first`,
2241 /// `total` and `peak` are the whole file's, and `per_sec` is the rate the
2242 /// file's envelope was drawn at.
2243 pub(crate) fn window(
2244 peaks: &'a [(f32, f32)],
2245 first: usize,
2246 total: usize,
2247 peak: f32,
2248 per_sec: f64,
2249 ) -> Self {
2250 Self {
2251 peaks,
2252 first,
2253 total,
2254 peak,
2255 per_sec,
2256 }
2257 }
2258
2259 /// The bucket at absolute index `abs`, when this view carries it: the
2260 /// window's own edges are not the file's, and a frame asked for one of
2261 /// them draws silence rather than a bucket that is only half decoded.
2262 pub(crate) fn at(&self, abs: usize) -> Option<(f32, f32)> {
2263 abs.checked_sub(self.first)
2264 .and_then(|i| self.peaks.get(i))
2265 .copied()
2266 }
2267
2268 fn is_empty(&self) -> bool {
2269 self.peaks.is_empty()
2270 }
2271}
2272
2273/// [`visualizer_i420`] from a view, which is how the seat paints: `peaks` may
2274/// be a window rather than the file's own envelope, and `t_secs` is the
2275/// frame's own time either way -- the view knows where its slice starts.
2276pub(crate) fn visualizer_window_i420(
2277 scratch: &mut VizScratch,
2278 view: &VizView,
2279 t_secs: f64,
2280 width: u32,
2281 height: u32,
2282 flags: u8,
2283 paint: u64,
2284) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
2285 let width = width & !1;
2286 let height = height & !1;
2287 // A canvas with no size asks for no picture, and must be told so: the zero
2288 // line's row is derived from the height (`h - 1`), and a height of zero has
2289 // no row to put it on -- `clamp` answers that by panicking, which on this
2290 // path is a dead worker thread and a span the export aborts on. A
2291 // `Composer::passthrough()` canvas is exactly this size and says as much
2292 // (`places_nothing`), and a 1-pixel-high canvas floors to it (planes are
2293 // even), so both take the empty picture they asked for.
2294 if width == 0 || height == 0 {
2295 return (Vec::new(), Vec::new(), Vec::new());
2296 }
2297 let (w, h) = (width as usize, height as usize);
2298 let (cw, ch) = crate::scale::chroma_dims(w, h);
2299 let (bg_y, bg_u, bg_v) = rgb_yuv(8, 12, 22);
2300 let mut y = vec![bg_y; w * h];
2301 let mut u = vec![bg_u; cw * ch];
2302 let mut v = vec![bg_v; cw * ch];
2303 let (ink_r, ink_g, ink_b) = viz_ink_from_paint(paint);
2304 let (ink_y, ink_u, ink_v) = rgb_yuv(ink_r as i32, ink_g as i32, ink_b as i32);
2305 let center = h as f32 / 2.0;
2306 let half = h as f32 * 0.42;
2307 let t_secs = if t_secs.is_finite() { t_secs } else { 0.0 };
2308
2309 let z = (center.round() as isize).clamp(0, h as isize - 1) as usize;
2310 for col in 0..w {
2311 y[z * w + col] = y[z * w + col].max(bg_y.saturating_add(18));
2312 }
2313
2314 scratch.lo.clear();
2315 scratch.lo.resize(w, 0.0);
2316 scratch.hi.clear();
2317 scratch.hi.resize(w, 0.0);
2318 scratch.sig.clear();
2319 scratch.sig.resize(w, 0.0);
2320 if !view.is_empty() && view.total != 0 {
2321 let duration = view.total as f64 / view.per_sec;
2322 let per_sec = view.per_sec;
2323 let window = if flags & VIZ_FAST != 0 {
2324 VIZ_FAST_SECS
2325 } else {
2326 VIZ_WINDOW_SECS
2327 };
2328 // Fixed window length, silence outside the file: shrinking the span
2329 // to the samples that exist stretched a bump as it entered (2s) and
2330 // Fast (0.2s) rarely hit the edge. Column x always maps to
2331 // t - window/2 + x/w * window.
2332 let origin = t_secs - window / 2.0;
2333 let pair_at = |t: f64| -> (f32, f32) {
2334 if !t.is_finite() || t < 0.0 || t > duration {
2335 return (0.0, 0.0);
2336 }
2337 let pos = (t * per_sec).clamp(0.0, (view.total - 1) as f64);
2338 let i = pos.floor() as usize;
2339 let f = (pos - i as f64) as f32;
2340 // Silence where the slice does not reach: a view that is a window
2341 // is only handed the buckets the frame can ask for, so this is the
2342 // file's own ends and nothing else.
2343 let (Some((lo0, hi0)), Some((lo1, hi1))) =
2344 (view.at(i), view.at((i + 1).min(view.total - 1)))
2345 else {
2346 return (0.0, 0.0);
2347 };
2348 (
2349 (lo0 + (lo1 - lo0) * f).clamp(-1.0, 0.0),
2350 (hi0 + (hi1 - hi0) * f).clamp(0.0, 1.0),
2351 )
2352 };
2353 let signed_at = |t: f64| {
2354 let (a, b) = pair_at(t);
2355 if b.abs() >= a.abs() { b } else { a }
2356 };
2357 for col in 0..w {
2358 let t0 = origin + col as f64 / w as f64 * window;
2359 let t1 = origin + (col + 1) as f64 / w as f64 * window;
2360 let (mut mn, mut mx) = (0.0f32, 0.0f32);
2361 let samples = 4;
2362 for k in 0..samples {
2363 let t = t0 + (t1 - t0) * (k as f64 + 0.5) / samples as f64;
2364 let (l, h) = pair_at(t);
2365 mn = mn.min(l);
2366 mx = mx.max(h);
2367 }
2368 scratch.lo[col] = mn;
2369 scratch.hi[col] = mx;
2370 scratch.sig[col] = signed_at(origin + (col as f64 + 0.5) / w as f64 * window);
2371 }
2372 // Whole-file peak, not the window's: a 2s window that gains or loses
2373 // a loud hit used to rescale every column, so the same bump changed
2374 // height as it entered and left the picture. A view carries that peak
2375 // with it ([`VizView`]), because a window of a film could not compute
2376 // it from the megabyte it holds.
2377 let peak = view.peak;
2378 if peak > 1e-4 {
2379 for i in 0..w {
2380 scratch.lo[i] /= peak;
2381 scratch.hi[i] /= peak;
2382 scratch.sig[i] /= peak;
2383 }
2384 }
2385 }
2386
2387 match viz_style(flags) {
2388 VIZ_STYLE_RIBBON => {
2389 let tau = std::f64::consts::TAU;
2390 let travel = t_secs * 1.35;
2391 for col in 0..w {
2392 let env = scratch.lo[col].abs().max(scratch.hi[col]).max(0.06);
2393 let x_phase = (col as f64 / w.max(1) as f64) * 2.15 * tau;
2394 for s in 0..u32::from(viz_strands_of(paint)).max(1) {
2395 let frac = s as f32 / (viz_strands_of(paint).max(2) as f32 - 1.0);
2396 let scale = 0.28 + 0.72 * frac;
2397 let wave = (x_phase + travel + s as f64 * 0.05).sin() as f32;
2398 let row = (center + half * env * scale * wave).round() as i32;
2399 let glow = i32::from(viz_glow_of(paint));
2400 viz_stamp(
2401 &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row, 1.0, bg_y, ink_y,
2402 ink_u, ink_v,
2403 );
2404 for dy in 1..=glow {
2405 let fall = 0.5 / dy as f32;
2406 viz_stamp(
2407 &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row - dy, fall, bg_y,
2408 ink_y, ink_u, ink_v,
2409 );
2410 viz_stamp(
2411 &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, row + dy, fall, bg_y,
2412 ink_y, ink_u, ink_v,
2413 );
2414 }
2415 }
2416 }
2417 }
2418 VIZ_STYLE_RING => {
2419 let cx = w as f32 / 2.0;
2420 let cy = h as f32 / 2.0;
2421 let r0 = (w.min(h) as f32) * 0.28;
2422 let amp = (w.min(h) as f32) * 0.18;
2423 let tau = std::f32::consts::TAU;
2424 let steps = w.max(h) * 4;
2425 let strands = viz_strands_of(paint);
2426 let glow = viz_glow_of(paint);
2427 for strand in 0..strands {
2428 let dual = strands >= 2 && strand >= strands / 2;
2429 // The dual half takes the clip's own strand colour when it
2430 // chose one; without one it is the wheel half a turn from
2431 // the clip's hue, at the clip's own saturation, which is
2432 // the complement every earlier project paints.
2433 let (ir, ig, ib) = if dual && viz_strand_set(paint) {
2434 let hue = f32::from(viz_strand_hue_ui(paint)) * 360.0 / 256.0;
2435 let sat = f32::from(viz_strand_sat_ui(paint)) / 255.0;
2436 hsv_to_rgb(hue, sat, 0.84)
2437 } else if dual {
2438 viz_ink_from_paint(with_viz_paint_hue(
2439 paint,
2440 viz_hue_ui(paint).wrapping_add(128),
2441 ))
2442 } else {
2443 viz_ink_from_paint(paint)
2444 };
2445 let (iy, iu, iv) = rgb_yuv(ir as i32, ig as i32, ib as i32);
2446 let scale = 0.65 + 0.35 * f32::from(strand % 4) / 3.0;
2447 let phase = f32::from(strand) * 0.35;
2448 scratch.pts.clear();
2449 for i in 0..=steps {
2450 let t = i as f32 / steps as f32;
2451 let theta = t * tau + t_secs as f32 * 1.1 + phase;
2452 let col = ((t * w as f32) as usize).min(w.saturating_sub(1));
2453 let env = scratch.lo[col].abs().max(scratch.hi[col]);
2454 let wobble = (theta * 3.0 + phase).sin() * 0.12 * env;
2455 let r = r0 + amp * env * scale + amp * wobble;
2456 let x = (cx + r * theta.cos()).round() as i32;
2457 let row = (cy + r * theta.sin()).round() as i32;
2458 scratch.pts.push((x, row));
2459 }
2460 if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) {
2461 for pair in scratch.pts.windows(2) {
2462 viz_line(
2463 &mut y, &mut u, &mut v, w, h, cw, ch, pair[0].0, pair[0].1, pair[1].0,
2464 pair[1].1, bg_y, iy, iu, iv, glow,
2465 );
2466 }
2467 } else {
2468 viz_chain(
2469 &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, iy, iu, iv, glow,
2470 );
2471 }
2472 }
2473 }
2474 VIZ_STYLE_WAVE => {
2475 scratch.pts.clear();
2476 for col in 0..w {
2477 scratch
2478 .pts
2479 .push((col as i32, (center - scratch.sig[col] * half).round() as i32));
2480 }
2481 let glow = viz_glow_of(paint);
2482 if viz_discs_are_cheaper(scratch.pts.len(), chain_cells(&scratch.pts), glow) {
2483 for pair in scratch.pts.windows(2) {
2484 viz_line(
2485 &mut y, &mut u, &mut v, w, h, cw, ch, pair[0].0, pair[0].1, pair[1].0,
2486 pair[1].1, bg_y, ink_y, ink_u, ink_v, glow,
2487 );
2488 }
2489 } else {
2490 viz_chain(
2491 &mut y, &mut u, &mut v, w, h, cw, ch, scratch, bg_y, ink_y, ink_u, ink_v,
2492 glow,
2493 );
2494 }
2495 }
2496 _ => {
2497 // Timeline envelope: one filled body, tops then bottoms, after
2498 // the fold+smooth above. Default look.
2499 let glow = i32::from(viz_glow_of(paint));
2500 for col in 0..w {
2501 let top = (center - scratch.hi[col] * half).round() as i32;
2502 let bot = (center - scratch.lo[col] * half).round() as i32;
2503 viz_span(
2504 &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, top, bot, bg_y, ink_y, ink_u,
2505 ink_v,
2506 );
2507 for dy in 1..=glow {
2508 let fall = 0.55 / dy as f32;
2509 viz_stamp(
2510 &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, top - dy, fall, bg_y,
2511 ink_y, ink_u, ink_v,
2512 );
2513 viz_stamp(
2514 &mut y, &mut u, &mut v, w, h, cw, ch, col as i32, bot + dy, fall, bg_y,
2515 ink_y, ink_u, ink_v,
2516 );
2517 }
2518 }
2519 }
2520 }
2521 (y, u, v)
2522}
2523
2524/// `None` when the software path must be used: forced by `VE_SW=1`, or the
2525/// plugin is absent/broken/unable to open this particular file.
2526fn open_hw(path: &Path, start_frame: u32) -> Option<HwSession> {
2527 if std::env::var_os("VE_SW").is_some_and(|v| v == "1") {
2528 return None;
2529 }
2530 HwSession::open_at(path, start_frame)
2531}
2532
2533/// `Ok` when the plugin really decodes this file: it opens *and* hands back a
2534/// first picture. Opening only reads the container -- a stream the vendored
2535/// bitstream parser dies on (a 2160p wavefront HEVC did, for one) opens fine and
2536/// then produces nothing, which reaches the user as a black picture with an
2537/// instant `eof` unless the door asks for that first frame. Costs one decoded
2538/// frame per probe.
2539///
2540/// The `Err` says which half failed, because "there is no decoder for this
2541/// codec" and "the decoder here would not take this stream" are different
2542/// refusals and a user acts on them differently.
2543fn hw_decodes(path: &PathBuf, start_frame: u32, codec: Codec) -> Result<(), String> {
2544 let Some(mut hw) = open_hw(path, start_frame) else {
2545 return Err(codec.needs_plugin());
2546 };
2547 // End of stream counts as a refusal, not as a pass: a session that hands
2548 // back no picture at all is exactly the black-frame-and-instant-eof this
2549 // probe exists to catch, and `Ok(None)` is how the plugin says it.
2550 match hw.next_frame() {
2551 Ok(Some(_)) => Ok(()),
2552 _ => Err(codec.undecodable()),
2553 }
2554}
2555
2556/// Returns whether the session was handled; `false` only when hardware decode
2557/// failed without emitting a single frame, so software can still take over.
2558///
2559/// The plugin already positioned itself at `start_frame`, so indices are
2560/// counted from there (a stream whose very first sample is not a sync sample
2561/// cannot be decoded from its start at all, and is not accounted for).
2562fn run_hw(
2563 hw: &mut HwSession,
2564 tx: &SyncSender<Frame>,
2565 start_frame: u32,
2566 end_frame: u32,
2567 render: &mut Render,
2568 abort: &Abort,
2569 speed: Speed,
2570) -> bool {
2571 let mut index = start_frame;
2572 // Pictures dropped for being late since the last one handed over; see
2573 // [`LATE_RUN`].
2574 let mut skipped = 0;
2575 loop {
2576 if abort.hit() {
2577 return true;
2578 }
2579 match hw.next_frame() {
2580 Ok(Some((y, u, v, width, height))) => {
2581 let due = index;
2582 index += 1;
2583 if abort.late(due) {
2584 if skipped < LATE_RUN {
2585 skipped += 1;
2586 } else {
2587 skipped = 0;
2588 let frame = render.frame(due, y, u, v, width, height);
2589 if tx.send(frame).is_err() {
2590 return true; // consumer went away
2591 }
2592 }
2593 } else if skip_for_speed(speed, start_frame, due, end_frame) {
2594 // Redundant by construction, not by lateness: no run limit
2595 // needed (see `skip_for_speed`).
2596 } else {
2597 skipped = 0;
2598 let frame = render.frame(due, y, u, v, width, height);
2599 if tx.send(frame).is_err() {
2600 return true; // consumer went away
2601 }
2602 }
2603 if index >= end_frame {
2604 return true; // end of the requested range
2605 }
2606 }
2607 Ok(None) => return true,
2608 Err(e) => {
2609 if index == start_frame {
2610 return false;
2611 }
2612 eprintln!("hardware decode error at frame {index}: {e}");
2613 return true;
2614 }
2615 }
2616 }
2617}
2618
2619#[cfg(test)]
2620mod tests {
2621 use super::*;
2622 use std::sync::mpsc::RecvTimeoutError;
2623 use std::time::{Duration, Instant};
2624
2625 fn asset(name: &str) -> PathBuf {
2626 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2627 .join("../../assets")
2628 .join(name)
2629 }
2630
2631 /// Drops `path` from the page cache, so the open below really goes to disk
2632 /// -- the case the deferred opener exists for, and the one that costs
2633 /// seconds on a 25 GB film. Unprivileged (`posix_fadvise(DONTNEED)`), and a
2634 /// no-op wherever `python3` is not around: the assertions hold either way,
2635 /// the numbers printed are simply the warm ones.
2636 fn evict(path: &Path) {
2637 let _ = std::process::Command::new("python3")
2638 .arg("-c")
2639 .arg(
2640 "import os,sys\n\
2641 fd=os.open(sys.argv[1],os.O_RDONLY)\n\
2642 os.posix_fadvise(fd,0,0,os.POSIX_FADV_DONTNEED)\n\
2643 os.close(fd)",
2644 )
2645 .arg(path)
2646 .status();
2647 }
2648
2649 /// The whole point of [`DecodeSession::open_worker_deferred`]: the caller
2650 /// gets its stream back in the time a thread takes to spawn, and the file
2651 /// is opened behind it -- so the first frame necessarily arrives *after*
2652 /// the call returned, and the sync opener on the same cold file pays on the
2653 /// calling thread what this one does not.
2654 #[test]
2655 fn a_deferred_open_costs_the_caller_a_thread_and_not_a_demux() {
2656 let path = asset("test_baseline.mp4");
2657 evict(&path);
2658 let start = Instant::now();
2659 let stream = DecodeSession::open_worker_deferred(
2660 &path,
2661 0,
2662 u32::MAX,
2663 ColorParams::default(),
2664 TransformParams::default(),
2665 Composer::passthrough(),
2666 tonemap::Preset::default(),
2667 Speed::NORMAL,
2668 );
2669 let returned = start.elapsed();
2670 let frame = stream
2671 .frames
2672 .recv_timeout(Duration::from_secs(10))
2673 .expect("first frame");
2674 let first_frame = start.elapsed();
2675
2676 // The same file, equally cold, through the door the import path keeps:
2677 // that one hands back metadata, and the demux it reads to do so is on
2678 // this thread.
2679 evict(&path);
2680 let sync_start = Instant::now();
2681 let sync = DecodeSession::open_worker(
2682 &path,
2683 0,
2684 u32::MAX,
2685 ColorParams::default(),
2686 TransformParams::default(),
2687 Composer::passthrough(),
2688 tonemap::Preset::default(),
2689 )
2690 .expect("sync open");
2691 let sync_returned = sync_start.elapsed();
2692 drop(sync);
2693
2694 eprintln!(
2695 "deferred open returned in {returned:?}, first frame at {first_frame:?}; \
2696 sync open returned in {sync_returned:?}"
2697 );
2698 assert_eq!(frame.index, 0, "the deferred worker starts where it is told");
2699 assert!(
2700 returned < Duration::from_millis(10),
2701 "the caller waited {returned:?} -- something is still being read \
2702 from the file before this returns"
2703 );
2704 assert!(
2705 first_frame > returned,
2706 "the first frame arrived within the call ({first_frame:?} vs \
2707 {returned:?}), which cannot happen if the open is deferred"
2708 );
2709 // No `returned < sync_returned` here on purpose: on a loaded machine
2710 // a thread spawn (what the deferred open pays) can cost more wall
2711 // clock than a whole sync demux of a small fixture, and the race
2712 // flaked one run in three under a parallel build. The two asserts
2713 // above already pin the invariant -- the call returns in microseconds
2714 // territory and the demux happens after it, on the worker.
2715 let _ = sync_returned;
2716 }
2717
2718 /// The late-picture policy, at the one place it is decided. A worker told
2719 /// the playhead is already at frame 20 must not spend a conversion and a
2720 /// queue slot on the twenty pictures behind it -- they can never be shown --
2721 /// and it must not go silent either, which is what [`LATE_RUN`] bounds: a
2722 /// machine that cannot decode in real time is late on every picture, and one
2723 /// in nine still reaches the screen.
2724 ///
2725 /// Deterministic on purpose: the floor is set by hand rather than by a clock
2726 /// that would have to outrun a debug-build decoder to prove anything.
2727 #[test]
2728 fn a_worker_skips_the_pictures_the_playhead_has_gone_past() {
2729 let take = |floor: u32| {
2730 let stream = DecodeSession::open_worker_deferred(
2731 asset("test_baseline.mp4"),
2732 0,
2733 u32::MAX,
2734 ColorParams::default(),
2735 TransformParams::default(),
2736 Composer::passthrough(),
2737 tonemap::Preset::default(),
2738 Speed::NORMAL,
2739 );
2740 stream.worker.playhead(floor);
2741 let mut indices = Vec::new();
2742 while indices.len() < 4 {
2743 let frame = stream
2744 .frames
2745 .recv_timeout(Duration::from_secs(10))
2746 .expect("a picture");
2747 indices.push(frame.index);
2748 }
2749 indices
2750 };
2751
2752 // Nobody has moved: every picture of the range is owed, in order.
2753 assert_eq!(take(0), vec![0, 1, 2, 3]);
2754
2755 // The playhead is at 20, so the pictures before it are decoded (the ones
2756 // after reference them) and dropped unconverted -- all but the one in
2757 // nine [`LATE_RUN`] lets through, so the caller never goes blind.
2758 let caught_up = take(20);
2759 assert!(
2760 caught_up[0] > 0 && caught_up.windows(2).any(|w| w[1] > w[0] + 1),
2761 "nothing was skipped: {caught_up:?}"
2762 );
2763 assert!(
2764 caught_up.iter().any(|&i| i >= 20),
2765 "the playhead was never reached: {caught_up:?}"
2766 );
2767 assert!(
2768 caught_up.len() >= 4,
2769 "the worker went silent instead of dropping down to one in nine"
2770 );
2771 }
2772
2773 /// [`skip_for_speed`] on its own, with no worker or channel involved: at
2774 /// 2x every other source frame maps onto the same timeline frame
2775 /// ([`Speed::timeline_at`]), so `skip`/`keep` must alternate exactly, and
2776 /// the last frame of the span (the one [`crate::project::Span::source_len`]
2777 /// is built to land on) must never be skipped regardless of where the
2778 /// alternation lands.
2779 #[test]
2780 fn skip_for_speed_alternates_at_2x_and_never_drops_the_last_frame() {
2781 let speed = Speed::from_permille(2000);
2782 let start = 100;
2783 let end = 110;
2784
2785 let skips: Vec<bool> = (start..end)
2786 .map(|due| skip_for_speed(speed, start, due, end))
2787 .collect();
2788 // Alternation holds up to (but not including) the span's last frame,
2789 // which is special-cased below.
2790 for pair in (start..end - 2).zip(skips.windows(2)) {
2791 let (due, w) = pair;
2792 assert_eq!(
2793 w[0], !w[1],
2794 "frame {due} and its successor should alternate skip/keep at 2x: {skips:?}"
2795 );
2796 }
2797 assert!(
2798 !skip_for_speed(speed, start, end - 1, end),
2799 "the last frame of the span must never be skipped"
2800 );
2801 }
2802
2803 /// Dropping a [`FrameStream`] whose frames nobody ever took must not wait.
2804 /// The channel is bounded, so such a worker is parked in `send` within a
2805 /// few frames, and the only thing that can wake it is its receiver going
2806 /// away -- which is why the receiver is the first field and the join inside
2807 /// `Worker::drop` is the second. Swap those two fields and this hangs.
2808 ///
2809 /// This is the whole basis of every teardown path in the engine, so it is
2810 /// asserted rather than commented: the drop runs on a second thread and a
2811 /// regression fails in ten seconds instead of hanging the suite forever.
2812 #[test]
2813 fn dropping_a_frame_stream_never_waits_for_an_undrained_channel() {
2814 let (_meta, stream) = DecodeSession::open_worker(
2815 &asset("test_baseline.mp4"),
2816 0,
2817 u32::MAX,
2818 ColorParams::default(),
2819 TransformParams::default(),
2820 Composer::passthrough(),
2821 tonemap::Preset::default(),
2822 )
2823 .expect("open");
2824 // Nothing is ever received: two frames fill the channel and the next
2825 // send parks the decode thread, exactly as a refused project load does.
2826 thread::sleep(Duration::from_millis(500));
2827
2828 let (done_tx, done_rx) = sync_channel(1);
2829 thread::spawn(move || {
2830 drop(stream);
2831 let _ = done_tx.send(());
2832 });
2833 assert!(
2834 done_rx.recv_timeout(Duration::from_secs(10)) != Err(RecvTimeoutError::Timeout),
2835 "dropping a parked stream deadlocked: it joined a decode thread \
2836 while still holding the receiver that thread is waiting on"
2837 );
2838 }
2839
2840 /// The empty-peaks source -- a trackless file, or any peaks decode error
2841 /// (`peaks_shared(..).ok().flatten().unwrap_or_default()`) -- must paint
2842 /// the flat line, never panic: a visualizer frame always exists. The
2843 /// `pair_at` interpolator indexes `peaks[len() - 1]`, which is only
2844 /// reachable inside the `!peaks.is_empty()` guard, so the empty vec takes
2845 /// the early flat-line path and no column ever samples a bucket.
2846 #[test]
2847 fn empty_peaks_paint_the_flat_line() {
2848 let w = 320u32;
2849 let h = 180u32;
2850 let (y, _u, _v) = visualizer_i420(&mut VizScratch::default(), &[], 0.0, w, h, 1, 0);
2851 assert_eq!((y.len(), _u.len(), _v.len()), (320 * 180, 160 * 90, 160 * 90));
2852 // The ink's top and bottom row for a given peaks slice: one unbroken
2853 // band, and where it sits.
2854 let band = |peaks: &[(f32, f32)]| {
2855 let (y, _, _) = visualizer_i420(&mut VizScratch::default(), peaks, 0.0, w, h, 1, 0);
2856 let rows: Vec<usize> = (0..h as usize)
2857 .filter(|&row| y[row * 320..(row + 1) * 320].iter().any(|&p| p > 40))
2858 .collect();
2859 assert!(
2860 !rows.is_empty() && rows.len() == rows[rows.len() - 1] - rows[0] + 1,
2861 "the ink must be one unbroken band, not scattered rows: {rows:?}"
2862 );
2863 (rows[0], rows[rows.len() - 1])
2864 };
2865 // Silence is the zero line and nothing else: the band is on the middle
2866 // row and a line's thickness -- five rows here, the trace's own -- not
2867 // a picture's.
2868 let (first, last) = band(&[]);
2869 let zero = h as usize / 2;
2870 assert!(
2871 first <= zero && zero <= last,
2872 "the zero line itself must be inked: {first}..={last}"
2873 );
2874 assert!(
2875 last - first <= (h as usize) / 8,
2876 "a peaks-less source painted a {}-row band, not a line: {first}..={last}",
2877 last - first + 1
2878 );
2879 // ...and the same seat over full-scale peaks is a picture, which is
2880 // what makes the line above a claim about silence rather than about a
2881 // painter that never draws anything.
2882 let (loud_first, loud_last) = band(&[(-1.0, 1.0); 1200]);
2883 assert!(
2884 loud_last - loud_first > (last - first) * 3,
2885 "full-scale peaks painted {loud_first}..={loud_last}, no taller than silence's {first}..={last}"
2886 );
2887 }
2888
2889 /// A canvas with no size has no row to draw the zero line on. The row index
2890 /// is derived from the height (`h as isize - 1`), so a *height* of zero
2891 /// underflows into `clamp`'s `min <= max` assert and takes the worker
2892 /// thread with it. A `Composer::passthrough()` canvas is exactly this
2893 /// (`dims()` is `(0, 0)`, `places_nothing()` is true for it), and a
2894 /// one-pixel-high canvas floors to the same nothing, the planes being even.
2895 #[test]
2896 fn a_size_less_visualizer_canvas_paints_nothing() {
2897 let size_less = visualizer_i420(&mut VizScratch::default(), &[], 0.0, 0, 0, 0, 0);
2898 assert_eq!(size_less, (Vec::new(), Vec::new(), Vec::new()));
2899 let thin = visualizer_i420(&mut VizScratch::default(), &[(0.0, 1.0)], 0.0, 2, 1, 0, 0);
2900 assert!(
2901 thin.0.is_empty() && thin.1.is_empty() && thin.2.is_empty(),
2902 "a 2x1 canvas has no even-sized plane to paint on"
2903 );
2904 }
2905
2906 /// The same canvas, driven through the seat that really opens one: the
2907 /// worker thread is where a panic *is* the defect -- it closes the frame
2908 /// channel and the caller sees a span with no picture in it, which is what
2909 /// the export then aborts on.
2910 #[test]
2911 fn a_pass_through_canvas_visualizer_paints_nothing_and_stays_alive() {
2912 let transform = TransformParams {
2913 pos_x: 0.25,
2914 ..Default::default()
2915 };
2916 let stream = DecodeSession::open_visualizer(
2917 &asset("test_opus_51.mka"),
2918 0,
2919 0,
2920 2,
2921 30.0,
2922 ColorParams::default(),
2923 transform,
2924 Composer::passthrough(),
2925 VIZ_STYLE_WAVE,
2926 0,
2927 )
2928 .expect("open the visualizer");
2929 let frame = stream
2930 .frames
2931 .recv_timeout(Duration::from_secs(30))
2932 .expect("a picture, not a worker that died instead of painting one");
2933 assert_eq!((frame.width, frame.height), (0, 0));
2934 assert!(frame.bgra.is_empty());
2935 }
2936
2937 /// The same seat, at the two canvas sizes whose *declared* dims used to
2938 /// disagree with the planes the painter handed back: one pixel high (the
2939 /// planes floor to nothing) and odd (they floor to the even size below).
2940 /// The worker declares the size it renders at -- masked and floored the way
2941 /// the painter masks -- so the conversion below always has the chroma plane
2942 /// it indexes, and a picture arrives at the canvas's own size.
2943 #[test]
2944 fn a_thin_and_an_odd_visualizer_canvas_paint_through_the_seat() {
2945 for (w, h) in [(1920u32, 1u32), (1921, 1081)] {
2946 let stream = DecodeSession::open_visualizer(
2947 &asset("test_opus_51.mka"),
2948 0,
2949 0,
2950 2,
2951 30.0,
2952 ColorParams::default(),
2953 TransformParams::default(),
2954 Composer::new(w, h, crate::scale::FitPolicy::Fit),
2955 VIZ_STYLE_WAVE,
2956 0,
2957 )
2958 .unwrap_or_else(|e| panic!("open the visualizer at {w}x{h}: {e}"));
2959 let frame = stream
2960 .frames
2961 .recv_timeout(Duration::from_secs(30))
2962 .unwrap_or_else(|e| {
2963 panic!("a picture for a {w}x{h} canvas, not a worker that died instead: {e}")
2964 });
2965 assert_eq!(
2966 (frame.width, frame.height),
2967 (w, h),
2968 "a {w}x{h} canvas is handed back at its own size"
2969 );
2970 assert_eq!(
2971 frame.bgra.len(),
2972 (w * h * 4) as usize,
2973 "and converted across the whole canvas at {w}x{h}"
2974 );
2975 }
2976 }
2977
2978 /// The `VE_SW=1` pin, borrowed for one test and put back as it was: it is
2979 /// process-wide, and this file's unit tests share one process.
2980 struct SwPin(Option<std::ffi::OsString>);
2981
2982 impl SwPin {
2983 fn set() -> Self {
2984 let had = std::env::var_os("VE_SW");
2985 unsafe { std::env::set_var("VE_SW", "1") };
2986 Self(had)
2987 }
2988 }
2989
2990 impl Drop for SwPin {
2991 fn drop(&mut self) {
2992 match &self.0 {
2993 Some(was) => unsafe { std::env::set_var("VE_SW", was) },
2994 None => unsafe { std::env::remove_var("VE_SW") },
2995 }
2996 }
2997 }
2998
2999 /// A span whose codec has no seat at all -- the plugin never opened one and
3000 /// there is no software decoder for these bytes -- must report the *gap* it
3001 /// is. The cell used to be left claiming `Hardware`: the arm below the
3002 /// software fallback set it before the session that produced nothing, and
3003 /// the front-end then named a decoder that had decoded no frame.
3004 ///
3005 /// Driven through [`run_span`] itself, which is the only door that reaches
3006 /// the arm: every public one refuses a plugin-only codec at `hw_decodes`
3007 /// before a span exists (VP8, VP9 and HEVC all refuse on this machine), and
3008 /// the arm is for the box where the plugin was there and then was not.
3009 /// `VE_SW=1` is what makes that box-independent; see [`SwPin`].
3010 #[test]
3011 fn a_span_with_no_seat_at_all_reports_the_gap() {
3012 let _pin = SwPin::set();
3013 let path = asset("test_vp8.mp4");
3014 let mut source = None;
3015 let cancel = AtomicBool::new(false);
3016 let generation = AtomicU64::new(0);
3017 let floor = AtomicU32::new(0);
3018 let abort = Abort {
3019 cancel: &cancel,
3020 generation: &generation,
3021 mine: 0,
3022 floor: &floor,
3023 };
3024 let (tx, rx) = sync_channel(2);
3025 let cell = BackendCell::new(Backend::Opening);
3026 run_span(
3027 &path,
3028 &mut source,
3029 SpanCmd {
3030 generation: 0,
3031 start: 0,
3032 end: 2,
3033 color: ColorParams::default(),
3034 transform: TransformParams::default(),
3035 canvas: Composer::passthrough(),
3036 tone: tonemap::Preset::default(),
3037 speed: Speed::NORMAL,
3038 tx,
3039 },
3040 &abort,
3041 &cell,
3042 );
3043 assert_eq!(
3044 cell.get(),
3045 Backend::Gap,
3046 "a VP8 span with no hardware must report the gap, not a hardware seat"
3047 );
3048 assert!(
3049 rx.try_recv().is_err(),
3050 "a gap decodes nothing: no picture may come down the channel"
3051 );
3052 }
3053
3054 #[test]
3055 fn visualizer_default_is_a_blue_envelope() {
3056 let mut peaks = vec![(0.0, 0.0); 12_000];
3057 for (i, p) in peaks.iter_mut().enumerate() {
3058 let a = ((i as f32 / 400.0) * std::f32::consts::TAU).sin() * 0.8;
3059 *p = (-a.abs(), a.abs());
3060 }
3061 let flags = 1u8;
3062 let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, flags, 0);
3063 let ink = y.iter().filter(|&&p| p > 40).count();
3064 assert!(ink > 200, "envelope missing: {ink}");
3065 assert!(ink < y.len() * 9 / 10, "solid frame, not an envelope: {ink}");
3066 let mut blue = 0usize;
3067 for i in 0..u.len() {
3068 if u[i] > 145 && v[i] < 120 {
3069 blue += 1;
3070 }
3071 }
3072 assert!(blue > 10, "default ink was not timeline blue: {blue}");
3073
3074 let ring = with_viz_style(flags, VIZ_STYLE_RING);
3075 let (yr, _, _) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, 0);
3076 let ring_ink = yr.iter().filter(|&&p| p > 40).count();
3077 assert!(ring_ink > 80, "ring missing: {ring_ink}");
3078 assert!(ring_ink < ink, "ring should be a stroke, not a fill");
3079
3080 let hue_paint = with_viz_paint_hue(0, 40);
3081 let (_, u2, v2) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 64, 32, flags, hue_paint);
3082 let mut shifted = 0usize;
3083 for i in 0..u2.len() {
3084 if u2[i] < 120 && v2[i] > 130 {
3085 shifted += 1;
3086 }
3087 }
3088 assert!(shifted > 2, "hue 8 did not leave blue");
3089 }
3090
3091 /// The paint's byte layout: the strand colour lives above the clip's own
3092 /// four bytes and the top bit is the flag, so either strand setter marks
3093 /// the colour chosen and clearing drops both bytes with the flag.
3094 #[test]
3095 fn the_paint_packs_the_strand_colour_above_the_v22_halves() {
3096 let p = with_viz_paint_strand_sat(with_viz_paint_strand_hue(VIZ_PAINT_AZURE, 0xAB), 0xCD);
3097 assert_eq!(p & 0xFFFF_FFFF, VIZ_PAINT_AZURE, "the low half never moves");
3098 assert_eq!((p >> 32) & 0xFF, 0xAB);
3099 assert_eq!((p >> 40) & 0xFF, 0xCD);
3100 assert!(viz_strand_set(p));
3101 assert_eq!(viz_strand_hue_ui(p), 0xAB);
3102 assert_eq!(viz_strand_sat_ui(p), 0xCD);
3103 assert_eq!(viz_strand_clear(p), VIZ_PAINT_AZURE);
3104 assert!(!viz_strand_set(viz_strand_clear(p)));
3105 }
3106
3107 /// The shapes a colour is typed in all mean the same ink, and everything
3108 /// else is refused rather than guessed at.
3109 #[test]
3110 fn typed_colours_read_as_hex_rgb_and_rgba() {
3111 let want = viz_color_from_text("#4F8FD6").expect("a hex colour");
3112 assert_eq!(want, (150, 161), "hue and sat on the field's own scales");
3113 for text in [
3114 "#4F8FD6",
3115 "4f8fd6",
3116 " #4f8fd6 ",
3117 "rgb(79,143,214)",
3118 "rgb(79/143/214)",
3119 "RGBA(79, 143, 214, 255)",
3120 ] {
3121 assert_eq!(viz_color_from_text(text), Some(want), "{text}");
3122 }
3123 for text in [
3124 "#12345",
3125 "zz",
3126 "rgb(300,0,0)",
3127 "rgb(1,2)",
3128 "",
3129 "rgb 79,143,214)",
3130 "rgb(79,143,214",
3131 "#4F8FD",
3132 "#4F8FD67",
3133 "#GGGGGG",
3134 "rgb(79,143,214,255,0)",
3135 "rgb(79;143;214)",
3136 ] {
3137 assert_eq!(viz_color_from_text(text), None, "{text}");
3138 }
3139 }
3140
3141 /// A colour's hex is the ink the painter draws, and reading it back
3142 /// gives the sliders their own value again -- for the 47053 of the 65536
3143 /// hues and saturations a trip through bytes can carry. The rest land on
3144 /// a neighbour: their smallest channel rounds to a byte whose ratio is
3145 /// not the one that was asked for. Full saturation is where that channel
3146 /// is the one the value sets exactly, and it survives at every hue.
3147 #[test]
3148 fn a_sampled_palette_round_trips_through_its_hex() {
3149 for hue in (0..=255u8).step_by(8) {
3150 let hex = viz_color_hex(hue, 255);
3151 assert_eq!(viz_color_from_text(&hex), Some((hue, 255)), "{hex}");
3152 }
3153 // The achromatic end, where hue is not a colour at all.
3154 assert_eq!(viz_color_from_text(&viz_color_hex(0, 0)), Some((0, 0)));
3155 assert_eq!(viz_color_from_text(&viz_color_hex(200, 0)), Some((0, 0)));
3156 // ...and the whole grid, so a change that quietly shrinks what the
3157 // trip can carry cannot pass by leaving the sample above green.
3158 let exact = (0..=255u8)
3159 .flat_map(|hue| (0..=255u8).map(move |sat| (hue, sat)))
3160 .filter(|&(hue, sat)| viz_color_from_text(&viz_color_hex(hue, sat)) == Some((hue, sat)))
3161 .count();
3162 assert_eq!(exact, 47_053, "the colours a hex round trip keeps");
3163 }
3164
3165 /// The dual half of a ring takes the clip's own strand colour when it has
3166 /// one: a choice that names the automatic complement paints the same
3167 /// frame, another repaints the dual strands in it, and a paint whose flag
3168 /// is clear is the picture it has always been -- strand bytes or no.
3169 #[test]
3170 fn a_chosen_strand_colour_repaints_only_the_dual_half_of_a_ring() {
3171 let mut peaks = vec![(0.0, 0.0); 12_000];
3172 for (i, p) in peaks.iter_mut().enumerate() {
3173 let a = ((i as f32 / 400.0) * std::f32::consts::TAU).sin() * 0.8;
3174 *p = (-a.abs(), a.abs());
3175 }
3176 let ring = with_viz_style(1, VIZ_STYLE_RING);
3177 let auto = VIZ_PAINT_AZURE;
3178 let (y0, u0, v0) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, auto);
3179
3180 // The automatic dual is half a wheel from the clip's hue at the
3181 // clip's own saturation; choosing exactly that colour changes
3182 // nothing at all.
3183 let same = with_viz_paint_strand_sat(
3184 with_viz_paint_strand_hue(auto, viz_hue_ui(auto).wrapping_add(128)),
3185 viz_sat_ui(auto),
3186 );
3187 assert!(viz_strand_set(same));
3188 let (ys, us, vs) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, same);
3189 assert_eq!(ys, y0, "the automatic complement, spelled out, is the same frame");
3190 assert_eq!(us, u0);
3191 assert_eq!(vs, v0);
3192
3193 // A colour of its own repaints the dual strands in it.
3194 let red = with_viz_paint_strand_sat(with_viz_paint_strand_hue(auto, 0), 255);
3195 let (_, u1, v1) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, red);
3196 let red_px = (0..u1.len()).filter(|&i| u1[i] < 110 && v1[i] > 200).count();
3197 let auto_px = (0..u0.len()).filter(|&i| u0[i] < 110 && v0[i] > 200).count();
3198 assert!(red_px > 20, "the chosen colour did not reach the frame: {red_px}");
3199 assert_eq!(auto_px, 0, "the automatic ring already painted red: {auto_px}");
3200
3201 // ...and the flag is what decides: strand bytes with it clear are
3202 // the unset picture, byte for byte.
3203 let stale = auto | (77u64 << 32) | (9u64 << 40);
3204 assert!(!viz_strand_set(stale));
3205 let (yt, ut, vt) = visualizer_i420(&mut VizScratch::default(), &peaks, 1.0, 320, 180, ring, stale);
3206 assert_eq!(yt, y0, "an unset strand colour is the frame it always was");
3207 assert_eq!(ut, u0);
3208 assert_eq!(vt, v0);
3209 }
3210 /// The look of a frame the glow pass was rewritten for, pinned byte for
3211 /// byte: [`viz_chain`] replaced the per-point discs under
3212 /// [`VIZ_STYLE_RING`] and [`VIZ_STYLE_WAVE`], whose glow cost `steps * pi *
3213 /// glow^2` cells per frame (295 ms of one 1080p ring frame at glow 16
3214 /// against 18 ms after), and this is what says the pictures did not move
3215 /// with it. FNV-1a over `y`, then `u`, then `v`, taken from the disc
3216 /// implementation that shipped before the rewrite; `fill` and `ribbon` are
3217 /// in the table because their planes share the frame with a chain's, and
3218 /// the row/run walk could still have reached them through a shared helper.
3219 ///
3220 /// Scope: eight strands (what [`VIZ_PAINT_AZURE`] carries) at four gloss
3221 /// including both ends. A strand count changes a chain's scale and phase,
3222 /// not the pass over it.
3223 #[test]
3224 fn the_glow_pass_paints_the_bytes_it_always_did() {
3225 const GOLDEN: &[(&str, u8, u64)] = &[
3226 ("fill", 0, 0xe141_5e51_fcc1_7ea1),
3227 ("fill", 2, 0x3842_fef4_d4ec_4239),
3228 ("fill", 8, 0xfaea_3e6f_9718_1d31),
3229 ("fill", 16, 0x6a09_31fe_e9f1_3069),
3230 ("ribbon", 0, 0x91fa_9b49_48d8_bcfe),
3231 ("ribbon", 2, 0xd4d2_bcce_3c32_14d8),
3232 ("ribbon", 8, 0xd23a_d502_17ac_697c),
3233 ("ribbon", 16, 0xd7de_425a_6737_11c3),
3234 ("ring", 0, 0xcfbe_55da_b222_0a1b),
3235 ("ring", 2, 0x5468_01eb_522e_21dc),
3236 ("ring", 8, 0xc08f_994e_4a19_c9f4),
3237 ("ring", 16, 0x8cee_6dcd_256c_d484),
3238 ("wave", 0, 0x2266_ba70_ab2a_06bd),
3239 ("wave", 2, 0xd05f_0a31_9264_b377),
3240 ("wave", 8, 0x2e50_7536_c5dd_6035),
3241 ("wave", 16, 0xf888_b09c_dae2_dd36),
3242 ];
3243 let peaks = benchmark_peaks((149.6 * f64::from(VIZ_BUCKETS_PER_SEC)) as usize);
3244 for &(name, glow, want) in GOLDEN {
3245 let style = match name {
3246 "fill" => VIZ_STYLE_FILL,
3247 "ribbon" => VIZ_STYLE_RIBBON,
3248 "ring" => VIZ_STYLE_RING,
3249 _ => VIZ_STYLE_WAVE,
3250 };
3251 let flags = with_viz_style(1, style);
3252 let paint = with_viz_paint_glow(VIZ_PAINT_AZURE, glow);
3253 let (y, u, v) = visualizer_i420(&mut VizScratch::default(), &peaks, 37.5, 1920, 1080, flags, paint);
3254 let mut hash = 0xcbf2_9ce4_8422_2325u64;
3255 for buf in [&y, &u, &v] {
3256 for &b in buf.iter() {
3257 hash ^= u64::from(b);
3258 hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
3259 }
3260 }
3261 assert_eq!(
3262 hash, want,
3263 "{name} at glow {glow} paints different bytes than it always did ({hash:016x})"
3264 );
3265 }
3266 }
3267
3268 /// The envelope both of the tests above paint: loud enough that every
3269 /// column carries ink, and shaped so a ring's radii and a wave's trace
3270 /// differ from column to column.
3271 fn benchmark_peaks(n: usize) -> Vec<(f32, f32)> {
3272 let mut peaks = vec![(0.0f32, 0.0f32); n];
3273 for (i, p) in peaks.iter_mut().enumerate() {
3274 let t = i as f64 / f64::from(VIZ_BUCKETS_PER_SEC);
3275 let a = ((t * 0.7).sin() * 0.6 + (t * 5.3).sin() * 0.25 + 0.1) as f32;
3276 *p = (-a.abs(), a.abs());
3277 }
3278 peaks
3279 }
3280}
3281
3282fn run(
3283 demuxer: &mut Demuxer,
3284 tx: &SyncSender<Frame>,
3285 start_frame: u32,
3286 end_frame: u32,
3287 render: &mut Render,
3288 abort: &Abort,
3289 speed: Speed,
3290) {
3291 // A decoder per span, and cheap: it is a parameter-set map and a picture
3292 // buffer, while the *demuxer* -- whose index cost seconds to build -- is the
3293 // one this worker keeps.
3294 let mut decoder = H264Decoder::new(CodecParameters::new(CodecId::H264))
3295 .expect("ec-h264 takes its own codec id");
3296 // Decoding has to restart at a sync sample, so pictures between it and
3297 // `start_frame` are decoded (the target frame references them) but never
3298 // converted or sent. Signed, because the landing sync sample can sit inside
3299 // what the file's edit list trims, i.e. *before* frame 0.
3300 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
3301 // Pictures leave the decoder in display order -- clause C.4.5.3 bumps the
3302 // decoded picture buffer -- and the landing index above is a display index
3303 // by the demuxer's own contract, so the two count one to one. The decode
3304 // order this loop used to emit was a corner-cut that only held for
3305 // Baseline: a stream with B pictures arrived scrambled and mislabelled,
3306 // and every reader of `index` (the transport's playhead, `skip_for_speed`,
3307 // the export's frame map) reads it as a timeline position.
3308 let mut skipped = 0;
3309 // Set once the demuxer runs dry: `flush` makes the decoder release every
3310 // picture its reorder delay still holds, and the drain below ends on
3311 // `Error::Eof` once they are out.
3312 let mut flushed = false;
3313 // Every way this span ends: abort, consumer gone, end of the requested
3314 // range, end of stream.
3315 let mut done = false;
3316 while !done {
3317 if abort.hit() {
3318 break;
3319 }
3320 // One access unit is one packet. No timestamps travel with it: the
3321 // presentation order comes out of the bitstream's own POC, and `index`
3322 // is counted off the pictures as the decoder releases them.
3323 match demuxer.next_access_unit() {
3324 Ok(Some(au)) => {
3325 let packet = Packet::new(0, TimeBase::new(1, 1), au);
3326 if let Err(e) = decoder.send_packet(&packet) {
3327 eprintln!("decode error at access unit {index}: {e}");
3328 break;
3329 }
3330 }
3331 Ok(None) => {
3332 flushed = true;
3333 if let Err(e) = decoder.flush() {
3334 eprintln!("decode error at end of stream: {e}");
3335 break;
3336 }
3337 }
3338 Err(e) => {
3339 eprintln!("demux error: {e}");
3340 break;
3341 }
3342 }
3343 // Take everything the packet released; `NeedMore` is the signal to go
3344 // back for the next access unit.
3345 loop {
3346 let pic = match decoder.receive_frame() {
3347 Ok(pic) => pic,
3348 Err(e) if e.is_need_more() || e.is_eof() => break,
3349 Err(e) => {
3350 eprintln!("decode error at access unit {index}: {e}");
3351 break;
3352 }
3353 };
3354 let ec_core::frame::Frame::Video(pic) = pic else {
3355 continue;
3356 };
3357 if index < i64::from(start_frame) {
3358 index += 1;
3359 continue;
3360 }
3361 let due = index as u32;
3362 index += 1;
3363 if abort.late(due) {
3364 if skipped < LATE_RUN {
3365 skipped += 1;
3366 } else {
3367 skipped = 0;
3368 if send_picture(&pic, due, render, tx) {
3369 done = true; // consumer went away
3370 break;
3371 }
3372 }
3373 } else if skip_for_speed(speed, start_frame, due, end_frame) {
3374 // Redundant by construction, not by lateness: no run limit
3375 // needed (see `skip_for_speed`).
3376 } else {
3377 skipped = 0;
3378 if send_picture(&pic, due, render, tx) {
3379 done = true; // consumer went away
3380 break;
3381 }
3382 }
3383 if index >= i64::from(end_frame) {
3384 done = true; // end of the requested range
3385 break;
3386 }
3387 }
3388 if flushed {
3389 done = true;
3390 }
3391 }
3392}
3393
3394/// Whether an access unit leads with a sequence header OBU, which is how both
3395/// containers mark a random-access point for AV1: the demuxer prepends the
3396/// `av1C`/`CodecPrivate` record (itself one sequence header OBU) ahead of every
3397/// sync sample, so the marker rides on the same bytes the decoder needs. Type 1
3398/// in bits 6..3 of the first OBU header byte.
3399fn leads_with_sequence_header(au: &[u8]) -> bool {
3400 matches!(au.first(), Some(&first) if first >> 3 & 0xF == 1)
3401}
3402
3403/// One [`Av1Picture`] down to the tightly packed 8-bit I420 every converter
3404/// here takes. 8-bit samples arrive as `u16` in `0..=255` and narrow losslessly;
3405/// a 10-bit stream's `0..=1023` downshifts by two, the same truncation the
3406/// hardware seat's P010 read-back performs when it takes the high byte of each
3407/// pair (`p010_to_i420`, engine-hw) -- so the two seats hand the renderer
3408/// byte-identical planes off the same file. 12-bit never reaches a seat: the
3409/// demuxer refuses it at open, where `parse_av1c` reads the depth.
3410fn narrow_av1(
3411 picture: &Av1Picture,
3412 ten_bit: bool,
3413 y: &mut Vec<u8>,
3414 u: &mut Vec<u8>,
3415 v: &mut Vec<u8>,
3416) {
3417 let shift = u8::from(ten_bit) * 2;
3418 let plane = |src: &[u16], dst: &mut Vec<u8>| {
3419 dst.clear();
3420 dst.extend(src.iter().map(|&sample| (sample >> shift) as u8));
3421 };
3422 plane(&picture.y, y);
3423 plane(&picture.u, u);
3424 plane(&picture.v, v);
3425}
3426
3427/// Narrows one [`Av1Picture`] ([`narrow_av1`]) and queues it through the same
3428/// [`Render`] every other seat's pictures go through. `true` when the consumer
3429/// went away, so the span stops rather than keeps decoding into a void.
3430fn send_av1(
3431 picture: &Av1Picture,
3432 due: u32,
3433 ten_bit: bool,
3434 render: &mut Render,
3435 tx: &SyncSender<Frame>,
3436 y: &mut Vec<u8>,
3437 u: &mut Vec<u8>,
3438 v: &mut Vec<u8>,
3439) -> bool {
3440 narrow_av1(picture, ten_bit, y, u, v);
3441 let frame = render.frame(due, y, u, v, picture.width as u32, picture.height as u32);
3442 tx.send(frame).is_err()
3443}
3444
3445/// The AV1 software seat: one span of [`ec_av1`] through the same loop
3446/// [`run`] drives `ec-h264` through. A decoder per span, and cheap -- it is the
3447/// reference bank and one output picture, while the *demuxer* is the one this
3448/// worker keeps. `ec-av1` has no packet-by-packet door; it takes one whole OBU
3449/// stream, so the span is fed as it is built: every access unit from the landing
3450/// sync sample up to (not including) the next one is one chunk, and a chunk is
3451/// a legal random-access stream on its own -- it leads with the sequence header
3452/// and a key frame, which is exactly what makes the chunk boundary detectable
3453/// here ([`leads_with_sequence_header`]). A stream whose inter frames carried
3454/// an in-band sequence header would be cut mid-GOP and refused by name below,
3455/// never silently misread; container storage keeps the sequence header in the
3456/// config record precisely so that does not happen.
3457///
3458/// Chunks decode to their end, so the reorder window of the chunk the span
3459/// ends in always drains: hidden frames (`show_frame == 0`) are references
3460/// and arrive at the sink with `shown == false`, and the frames they hold
3461/// back in output order are the tail the sink still has to see.
3462///
3463/// A refusal out of `ec-av1` -- a real-world stream hitting a shape the
3464/// decoder does not reconstruct -- fails the span in words, mid-film, the way
3465/// the hardware seat's errors do: named on stderr, the pictures decoded so
3466/// far stand, and no garbage is sent. The same sentinel ends a span that has
3467/// delivered everything asked of it without decoding the rest of its last
3468/// chunk.
3469fn run_av1(
3470 demuxer: &mut Demuxer,
3471 tx: &SyncSender<Frame>,
3472 start_frame: u32,
3473 end_frame: u32,
3474 render: &mut Render,
3475 abort: &Abort,
3476 speed: Speed,
3477) {
3478 // Signed, for the same reason [`run`]'s is: the landing sync sample can
3479 // sit inside what an mp4's edit list trims, i.e. before frame 0.
3480 let mut index = demuxer.seek_to_sync_at_or_before(start_frame);
3481 // Reusable plane buffers: one allocation each for the whole span, refilled
3482 // per picture by [`narrow_av1`].
3483 let (mut y, mut u, mut v) = (Vec::new(), Vec::new(), Vec::new());
3484 let mut skipped = 0;
3485 // Every way this span ends: abort, consumer gone, the requested range
3486 // delivered, the demuxer dry, or a refusal out of the decoder.
3487 let mut done = false;
3488 let mut demux_dry = false;
3489 // An access unit read past a chunk boundary, waiting to head the next one.
3490 let mut pending: Option<Vec<u8>> = None;
3491 while !done && !demux_dry {
3492 if abort.hit() {
3493 break;
3494 }
3495 // One chunk: the access units from a sync sample up to the next one.
3496 let mut stream = pending.take().unwrap_or_default();
3497 while !demux_dry && pending.is_none() {
3498 match demuxer.next_access_unit() {
3499 Ok(Some(au)) => {
3500 if !stream.is_empty() && leads_with_sequence_header(&au) {
3501 pending = Some(au);
3502 } else {
3503 stream.extend_from_slice(&au);
3504 }
3505 }
3506 Ok(None) => demux_dry = true,
3507 Err(e) => {
3508 eprintln!("demux error: {e}");
3509 return;
3510 }
3511 }
3512 }
3513 let ten_bit = demuxer.bit_depth() == 10;
3514 let decode = decode_stream_with(&stream, |picture, _, shown| {
3515 // Hidden frames are references: they take no display slot and
3516 // are never sent, but they do hold the chunk's output order
3517 // back, which is why the chunk decodes to its end.
3518 if !shown {
3519 return Ok(());
3520 }
3521 let due = index;
3522 index += 1;
3523 if due < i64::from(start_frame) {
3524 return Ok(());
3525 }
3526 let due = due as u32;
3527 // The three ends [`run`] reaches per picture, in its own shape:
3528 // late for the playhead (one in [`LATE_RUN`] still goes through),
3529 // redundant by construction at speed, or a conversion and a send.
3530 let sent = if abort.late(due) {
3531 if skipped < LATE_RUN {
3532 skipped += 1;
3533 false
3534 } else {
3535 skipped = 0;
3536 send_av1(picture, due, ten_bit, render, tx, &mut y, &mut u, &mut v)
3537 }
3538 } else if skip_for_speed(speed, start_frame, due, end_frame) {
3539 // Redundant by construction, not by lateness: no run limit
3540 // needed (see `skip_for_speed`).
3541 false
3542 } else {
3543 skipped = 0;
3544 send_av1(picture, due, ten_bit, render, tx, &mut y, &mut u, &mut v)
3545 };
3546 if sent {
3547 done = true; // consumer went away
3548 }
3549 if done || i64::from(due) + 1 >= i64::from(end_frame) {
3550 done = true; // the range is out, or nobody is left to take it
3551 // Stops the decode inside the chunk: everything the span
3552 // asked for has been sent, and the chunk's remaining coded
3553 // frames are references for pictures nobody asked for.
3554 return Err(Av1Error::Eof);
3555 }
3556 Ok(())
3557 });
3558 // `done` was set by the sink itself for the `Eof` it returns -- the
3559 // sentinel, not a refusal. Any other `Err` is a refusal out of the
3560 // decoder, named where the hardware seat's decode errors are named;
3561 // the pictures decoded so far stand and the span ends.
3562 if let Err(e) = decode {
3563 if !done {
3564 eprintln!("software AV1 decode failed at frame {index}: {e}");
3565 done = true;
3566 }
3567 }
3568 }
3569
3570}
3571
3572/// Converts one decoded picture and queues it. `true` when the consumer went
3573/// away, so the span stops rather than keeps decoding into a void.
3574fn send_picture(pic: &VideoFrame, due: u32, render: &mut Render, tx: &SyncSender<Frame>) -> bool {
3575 // The decoder crops each picture into tightly packed planes, the shape
3576 // every converter below takes. A padded plane would render skewed rather
3577 // than subtly wrong, so the assumption is pinned where it is relied on --
3578 // free in a release build.
3579 let (y, u, v) = (&pic.planes[0], &pic.planes[1], &pic.planes[2]);
3580 debug_assert_eq!(y.stride, pic.width as usize, "padded luma plane");
3581 debug_assert_eq!(
3582 u.stride,
3583 pic.width.div_ceil(2) as usize,
3584 "padded chroma plane"
3585 );
3586 let frame = render.frame(due, &y.data, &u.data, &v.data, pic.width, pic.height);
3587 tx.send(frame).is_err()
3588}