forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7cb30bfTahinli2 months ago908 commits

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