//! One timeline over one or more files: the decode workers, the audio output //! and the master clock wired together so a front-end only has to render and //! call [`tick`]. //! //! [`tick`]: PlaybackSession::tick //! //! Everything degrades to silent-but-correct: no audio track, no plugin, no //! PipeWire daemon and an unusable format all end up in [`ClockSource::Wall`], //! where the video is paced by real time instead of by the device. //! //! Drift policy stays with the caller -- this type answers "what time is it", //! the renderer decides which frame that means. use std::borrow::Cow; use std::path::{Path, PathBuf}; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering}; use std::sync::mpsc::{Receiver, TryRecvError}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::{Duration, Instant}; use crate::ao::AoSession; use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; use crate::color::ColorParams; use crate::colorspace::{ColorDescription, ContentLight}; use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta}; use crate::eq::EqParams; use crate::project::{ Clip, Edge, GainKey, GapSweep, Lane, LaneKind, Project, ProjectSettings, Rate, RedoCheckpoint, Source, SourceWalls, Span, Speed, SubClip, TrimWalls, WallBound, STILL_DEFAULT_SECS, }; use crate::scale::{Composer, FitPolicy}; use crate::transform::TransformParams; /// How long the feeder waits out a full ring. The ring holds a second, so this /// only has to be short next to that; it costs one wakeup per 10 ms of audio. const RING_FULL_WAIT: Duration = Duration::from_millis(10); /// How long the feeder waits out a ring that took *nothing*: the flush of a /// restart, which only the device's own callback can clear (`engine-audio` /// refuses a write queued behind one). Short, because this is the gap at the /// head of every restart and the ear is in it -- one wakeup per millisecond, /// for the millisecond or two it lasts. const FLUSH_WAIT: Duration = Duration::from_millis(1); /// How long [`try_frame`](PlaybackSession::try_frame) blocks the caller /// waiting for B's first picture when the playhead lands in a dissolve /// window before B's eager-opened decoder ([`start_span`](PlaybackSession::start_span)) /// has one ready -- a seek straight into the window, mostly. Above the 98 ms /// worst-case VA-API init measured for a picture open, so an eager-opened B /// almost never actually waits the full budget; a source B cannot decode at /// all pays this once per span rather than freezing the preview outright. const DISSOLVE_B_TIMEOUT: Duration = Duration::from_millis(200); /// How long a dead output is left alone before another open is attempted. A /// PipeWire daemon restart takes a moment, and the ask that makes the attempt /// runs once per rendered frame: a second is long enough that a restart lands /// inside it, and short enough that a play pressed after one does not wait. const AUDIO_REARM_AFTER: Duration = Duration::from_secs(1); /// The reason a session gives for having gone quiet when its output dies /// ([`PlaybackSession::tick`]), through the same door a file's own refusal /// reaches a front-end by ([`PlaybackSession::audio_disabled_reason`]). /// /// That door is read where a notice is *built* -- at open and at load -- so this /// is fetchable rather than announced: the engine sets the reason and clears it /// again when the output comes back, and a front-end that reads the door after /// the session is open (a per-frame check, or one at the next load) is what /// shows it. Nothing here pushes a notice. const AUDIO_LOST: &str = "output device went away -- reconnecting the timeline's sound"; /// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 -- /// nothing was shot on it, so it is the canvas a *later* import meets rather /// than a description of the song. H.264 because it is the one codec that /// decodes without the plugin, 30 fps because a rounded-up audio length is what /// the frame count means and a whole number of frames per second keeps it /// honest; both are what a video imported onto such a timeline is held to /// ([`matches_timeline`]). /// /// corner-cut: a 25 fps video imported onto an audio-only timeline it could have /// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read /// through [`Rate`] like any other file shot at another rate rather than /// defining one. Upgrade path is adopting the first *picture's* rate and codec /// on import, which means retiming every audio clip already placed in frames. const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0); /// The frame rate a timeline scaffolded from a still image runs at, for /// [`AUDIO_ONLY_CANVAS`]'s reason: nothing was shot on it. The *size* is not /// invented the same way -- an image has a picture of its own, and that picture /// is the canvas a later import meets. const IMAGE_ONLY_RATE: f64 = 30.0; /// How long a still image *is*, in seconds: the wall a trim may drag its edge /// out to, since an image has no length of its own to be walled by. Ten /// minutes, which is a title card nobody will run out of and still a finite /// number -- a `u32::MAX` sentinel here would make [`Self::trim_room`] hand a /// drag a wall past what the timeline can hold. /// /// corner-cut: a still cannot be held longer than this. Upgrade path is a /// per-source length the project file carries, which every `counts` reader /// would then have to take from the document rather than from the file. const IMAGE_MAX_SECS: f64 = 600.0; /// The output half of a session: the device, plus what the feeder has handed it. /// Cloned into the feeder thread; every field that matters is shared. #[derive(Clone)] struct Audio { /// Shared because `write` runs on the feeder thread while `position` and /// `set_active` are called from the caller's. The plugin serialises those /// itself (atomics and a channel), but the lock is what makes it sayable in /// Rust and it is never held for more than a memcpy. ao: Arc>, sample_rate: u32, channels: u64, /// Interleaved samples accepted by the device so far. fed: Arc, /// The decoder ran out and `fed` is final. fed_all: Arc, /// The output plugin failed mid-stream. Its position is frozen from here on, /// so it can never satisfy [`Audio::played_out`] -- the flag is what lets /// [`PlaybackSession::tick`] hand the timeline to wall time instead. died: Arc, /// Bumped by every seek. A feeder only owns the device while this still /// matches the value it started with; see [`feed`]. epoch: Arc, /// The device position the *current* stream's first real sample was queued /// at, `-1` until the feeder has queued one. Written by the feeder under the /// device lock, read by [`tick`](PlaybackSession::tick). /// /// This is what keeps a restart out of the timeline. Between a flush and the /// first sample of the new stream the device plays silence -- a decoder open /// is tens of milliseconds -- and that silence is elapsed *device* time /// ([`crate::ao`] counts it, as it must: it really was played). It is not /// elapsed *timeline* time, and a clock anchored on the first poll after a /// seek counts it as such, which is a permanent offset between the picture /// and the sound, re-rolled by every edit made while playing. content_at: Arc, /// The monitoring gain this session's device is running at, as f32 bits. /// /// The device is the owner -- [`PlaybackSession::gain`] reads the level /// back out of it -- and this is the *only* reason a session knows what to /// restore: the device object is replaced from under the session whenever /// the output dies ([`Self::rearm_audio`]) or is armed late /// ([`Self::arm_audio`]), and a fresh one comes up at 1.0. Without this a /// muted session that lost its device came back at full volume while the /// control still said muted. Written by [`PlaybackSession::set_gain`] /// alone, so it cannot drift from the knob: whatever the caller last /// pushed is exactly what the next device is told. gain: Arc, /// The timeline is *meant* to be playing: what a play or a seek-while-playing /// asks for, and what the feeder turns into a running device the moment it /// has a real sample to play ([`Audio::set_playing`], [`feed`]). /// /// The device is not started by the intent, because an inactive stream has /// no callbacks and therefore no starved quanta: between the flush of a seek /// and the first sample of the new stream -- seconds, on a cold 25 GB film /// whose decoder is opened on the feeder -- a device started here would play /// its own silence and count every quantum of it as an underrun. /// /// Written and read under the device lock, beside the [`Audio::content_at`] /// stamp, and that is the whole race: whichever of the two sides takes the /// lock first, the other sees its half (a stamp already there, or an intent /// already set), so the device is started exactly once and a pause landing /// during an open can never be overtaken by a late activation. wants_active: Arc, /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest /// first: what a meter or an analyser draws. Written by the feeder, which /// is not the device's own callback -- the plugin's RT thread never sees /// this lock, and the feeder holds it for one memcpy per write. tap: Arc>>, /// The highest sample magnitude handed to the device since it was last read /// ([`PlaybackSession::levels`]), as f32 bits. Non-negative floats order the /// same as their bits, so the feeder raises it with a `fetch_max`. Taken /// after the mix and the limiter, before the device's own volume: the /// meter reads what the device is given, not what the speakers are told. peak: Arc, /// [`Self::peak`] per side, left then right (a mono stream fills both), read and cleared /// together with it for the stereo meter. peak_lr: Arc<[AtomicU32; 2]>, /// Feeder threads started and not yet returned. They are detached, so there /// is no handle to count instead, and a scrub leaves dozens of them exiting /// at once -- which is precisely what /// [`live_workers`](PlaybackSession::live_workers) is asked about. feeders: Arc, /// When this device was last opened *again* after dying /// ([`PlaybackSession::rearm_audio`]). A dead output is offered one open a /// second and no more, because the ask that makes the attempt runs once per /// rendered frame: a daemon restart takes a moment, and a device that is /// gone for good must not be opened sixty times a second for the rest of /// the session. rearm_at: Arc>>, } /// How much of the played signal the tap keeps. A power of two, because what /// reads it transforms it, and long enough that the lowest band the editor /// draws (20 Hz) has a whole cycle in the window at any rate we open. const TAP_SAMPLES: usize = 2048; /// `gains` (one per audio lane, in `audio`'s order) with every lane outside /// `solo` silenced. A solo naming no lane in `audio` is no solo at all, so a /// stale handle cannot silence everything. fn soloed_gains(mut gains: Vec, audio: &[Lane], solo: &[Lane]) -> Vec { if !audio.iter().any(|lane| solo.contains(lane)) { return gains; } for (gain, lane) in gains.iter_mut().zip(audio) { if !solo.contains(lane) { *gain = 0.0; } } gains } /// The level meters' reading: [`PlaybackSession::levels`]. Linear peaks in /// `0.0..=1.0` since the last read, one per audio lane in the lanes' own order, /// and the master. #[derive(Clone, Debug, Default, PartialEq)] pub struct Levels { pub lanes: Vec, pub master: f32, /// The master's peak on the left and on the right (a mono stream reads the same on both). pub master_lr: [f32; 2], } impl Audio { /// Whether the device has played everything there will ever be, i.e. the /// audio clock is about to stop meaning anything. fn played_out(&self, position: i64) -> bool { self.fed_all.load(Ordering::Acquire) && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed) } /// Says whether the timeline is playing, and starts or stops the device for /// it: `true` runs it *if there is already something to play*, and otherwise /// leaves it to the feeder's first sample ([`Audio::wants_active`]). `false` /// stops it at once -- a pause is never deferred, whatever an open in flight /// is about to find. fn set_playing(&self, playing: bool) { // The lock, not the atomics, is what orders this against the feeder's // stamp: the store below and the load after it are one critical section, // and so is the feeder's pair. let ao = self.ao.lock().unwrap(); self.wants_active.store(playing, Ordering::Release); if !playing || self.content_at.load(Ordering::Acquire) >= 0 { ao.set_active(playing); } } /// Keeps the newest [`TAP_SAMPLES`] of what was just queued, downmixed to /// mono. Called from the feeder only, once per accepted write. fn note_tap(&self, accepted: &[f32]) { // Every sample, not just the tail the tap keeps: a peak that falls // outside the window is still a peak the ear heard. let peak = accepted.iter().fold(0.0f32, |m, s| m.max(s.abs())); self.peak.fetch_max(peak.to_bits(), Ordering::Relaxed); let channels = self.channels.max(1) as usize; let side = |at: usize| { accepted.iter().skip(at.min(channels - 1)).step_by(channels).fold(0.0f32, |m, s| m.max(s.abs())) }; self.peak_lr[0].fetch_max(side(0).to_bits(), Ordering::Relaxed); self.peak_lr[1].fetch_max(side(1).to_bits(), Ordering::Relaxed); let mut tap = self.tap.lock().unwrap(); // Only the tail can survive anyway: a big write replaces the window // outright rather than being summed into it and then thrown away. let from = accepted.len().saturating_sub(TAP_SAMPLES * channels); for frame in accepted[from..].chunks_exact(channels) { tap.push(frame.iter().sum::() / channels as f32); } let over = tap.len().saturating_sub(TAP_SAMPLES); tap.drain(..over); } /// Starts a feeder for the current epoch, draining `rx` into the device. /// `false` if the thread would not start, i.e. nothing will ever be fed. fn spawn_feeder(&self, rx: Receiver) -> bool { self.spawn_feeder_deferred(move || Some(rx)) } /// As [`spawn_feeder`](Self::spawn_feeder), but the *stream* is opened on /// the feeder too: `open` runs on that thread, so nothing here touches the /// disk and the caller pays a thread spawn instead of a demux -- seconds off /// a cold cache on a big film, which is what a seek used to cost the UI /// thread ([`crate::DecodeSession::open_worker_deferred`] is the picture's /// half of the same move). /// /// The price is the same one: there is no [`crate::audio::AudioMeta`] to /// hand back and no synchronous answer to "will anything play". `None` from /// `open` -- a silent timeline, a source that will not open -- is a feeder /// with nothing to feed, which ends exactly as a played-out stream does and /// hands the clock to wall time ([`tick`](PlaybackSession::tick)). /// /// The epoch is captured *here*, at the seek, not when the open returns: a /// scrub abandons opens by the dozen and every one of them must still be /// the stale stream it was started as, however late it lands. /// /// corner-cut: an abandoned open is not *cancelled*, though the machinery /// for it exists ([`crate::demux::with_cancel`], which the import's Cancel /// uses): it runs to the end and its answer is dropped. Tried, and left /// out for want of evidence -- 200 cold scrub steps over the 25 GB HEVC /// remux measured 101, 137 and 14 live workers on three runs of the *same* /// build, so the machine decides that number and not this. There is a /// reason to expect it to hurt, too: a Matroska walk writes its sidecar /// index only when it finishes (`demux::mkv_blocks`), so a drag that /// cancels every step's walk would never write one and every step would /// walk the segment again from the top. Ceiling: an abandoned open keeps /// reading, and the decoder threads it started live until it does. Upgrade /// path is an index the walk publishes as it goes -- then cancelling costs /// nothing and can be measured on an idle machine. fn spawn_feeder_deferred( &self, open: impl FnOnce() -> Option> + Send + 'static, ) -> bool { let me = self.clone(); let epoch = self.epoch.load(Ordering::Acquire); // Counted before the spawn, so the count is never behind the thread. self.feeders.fetch_add(1, Ordering::Release); let started = thread::Builder::new() .name("audio-feed".into()) .spawn(move || { // Superseded before this thread was even scheduled: do not open // anything at all. A scrub leaves all but the last one here. if me.epoch.load(Ordering::Acquire) == epoch { if let Some(rx) = open() { feed(rx, &me, epoch); } // Only the current feeder gets to declare the end of the // audio: a superseded one is finished, the stream is not. if me.epoch.load(Ordering::Acquire) == epoch { me.fed_all.store(true, Ordering::Release); } } me.feeders.fetch_sub(1, Ordering::Release); }) .is_ok(); if !started { self.feeders.fetch_sub(1, Ordering::Release); } started } /// Feeder threads still running; see [`Self::feeders`]. fn live_feeders(&self) -> usize { self.feeders.load(Ordering::Acquire) } } /// Where the picture of the current span is decoded from. `Cached` is a render /// cache segment ([`crate::render_cache`]) that already holds the span's frames /// composed, so the decoder reads that file and nothing else is applied. #[derive(Clone, Debug, PartialEq, Eq)] enum Feed { /// The live path: the project's clips, composed as they play. Live, /// A render-cache segment at `segment`, read from its own first frame. Cached { segment: PathBuf }, } /// How the pictures of a span played backward are numbered (see /// [`PlaybackSession::stamp`]). Backward the span is the stretch of its clip /// *up to* the playhead, and its pictures are wanted from the playhead down. #[derive(Clone, Copy, PartialEq, Debug)] enum Back { /// Forward play, or a span (a still, a stack, a visualizer) that is drawn /// forward whichever way the clock runs. Off, /// A forward clip decoded last frame first ([`DecodeSession::open_reversed`] /// over the file frames ending at `top`). Mirror { top: u32 }, /// A reversed clip, whose backward is the file's forward. Forward, /// A gap: black numbered from zero, counted down from the span's last frame. Gap, } /// The cross-dissolve a span's tail owes its successor, tracked from the /// moment [`PlaybackSession::start_span`] opens A's own decoder until a later /// `start_span` throws it away. What decides there *is* one mirrors /// [`crate::export::dissolve_window`] exactly, on the very same span, so a /// preview blends the window an export would render -- but B's own decoder /// opens only once the playhead actually reaches it /// ([`PlaybackSession::open_dissolve_b`]), rather than for the whole span: /// most of a dissolving clip is never in the window, and a viewer who pauses /// or seeks away before the tail never pays for a decoder nobody sees. struct Dissolve { /// The first *timeline* frame inside the window. tail_start: u32, /// How many output frames the blend ramps across. window: u32, b_source: usize, b_in_frame: u32, /// Where B sits on the timeline -- what its own grade and fit are keyed /// on ([`Project::composite_color_at`], `composite_fit_at`), the same /// `b_start` [`crate::export`] grades B's side of the same dissolve by. b_start: u32, /// How the picture is blended ([`crate::transitions`]). kind: crate::transitions::TransitionKind, /// B's live decode, once open; `None` before the playhead reaches the /// window. b: Option, } /// B's own worker, decoding beside A's for the length of the window. struct DissolveB { frames: Receiver, worker: Worker, /// The last frame B handed over: a tick that lands between two of B's /// pictures still has one to blend A against, the same "keep showing the /// last one" policy A's own channel gets from the app's own pump -- done /// here instead, because B never leaves the engine to be pumped. held: Option, } /// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`]. /// One track that has ended: where it was, and what it did to its mask. #[derive(Clone, Debug, PartialEq)] pub struct TrackDone { pub lane: Lane, pub idx: usize, pub slot: usize, /// The keys written and the first and last source frame of the path, or why it stopped. pub result: Result, } /// What a finished track wrote: how many keys, the frames it covered, and the frame it /// was lost at when it stopped early. #[derive(Clone, Debug, PartialEq)] pub struct TrackOutcome { pub keys: usize, pub from: u32, pub to: u32, pub lost_at: Option, } /// A mask track in progress: the job ([`crate::track::start`]) and the mask it writes to. #[derive(Clone, Debug, PartialEq)] pub struct TrackJob { pub lane: Lane, pub idx: usize, pub slot: usize, pub id: crate::track::JobId, /// The source frame the track starts from, where its path begins. pub from: u32, /// The mask's centre at `from`, in canvas fractions. pub anchor: (f32, f32), } pub struct PlaybackSession { /// The thread that plays scrub snippets, made by the first [`PlaybackSession::scrub_audio`]. scrub: Scrub, /// The *timeline's* parameters, not any one file's: its frame rate and codec /// come from source 0 and are what every other source is held to, while /// `width`/`height` are the **project resolution** -- source 0's picture to /// begin with, and whatever [`PlaybackSession::set_resolution`] or a saved /// `resolution` line makes it after that. Every clip is composed onto it, so /// a file of another size is a placed picture rather than a refusal. meta: VideoMeta, /// What source 0's own file declared about how bright it gets /// ([`crate::colorspace::ContentLight`]) -- MaxCLL/MaxFALL and the /// mastering display's peak/black, read once at open exactly as `native` /// is, since the value is a property of the file and never changes under /// a running session. [`ContentLight::default()`] (every field `None`) /// for an SDR file and for a song or a still, neither of which is graded. content_light: ContentLight, /// Source 0's own picture, kept from the open: the project resolution /// starts here, and a caller offering sizes to pick from needs the media's /// own among them or a project moved off it could never come back. native: (u32, u32), /// ...and the scaffolding source's own frame rate, kept for exactly that /// reason: the project rate starts here, and the list a caller offers rates /// from needs the media's own on it or a project moved off it has no way /// back ([`PlaybackSession::set_frame_rate`] is not an undo step either). native_fps: f64, frames: Receiver, /// The current decode worker. worker: Worker, /// What that worker opened -- hardware, software, a still, a gap -- written /// by the worker itself and read by [`decode_backend`](Self::decode_backend). /// Replaced with the stream at every seek, so it always describes the /// pictures currently arriving and never the clip before them. backend: BackendCell, /// Why the current span stopped before the end of its range, if it did. /// Replaced with the stream at every seek for the same reason `backend` is, /// and read by [`video_failure_reason`](Self::video_failure_reason). video_failure: crate::decode::DecodeFailure, /// Workers cancelled by a seek or a clip change, waiting to be reaped. /// Joining one inline costs whatever VA-API init it is still inside (98 ms /// measured worst case), which is a visible hitch on the caller's thread; /// parking it here instead makes that free, and [`retire`] drops the ones /// that have already returned every time it adds another. /// /// Never a leak, and that is the invariant: everything in here is joined /// when the session drops (`Vec`'s own drop does it, one /// [`Worker::drop`] each), so no decode worker can outlive the session and /// meet Mesa's `atexit` handlers from inside libva. /// /// [`retire`]: PlaybackSession::retire retired: Vec, /// Picture workers that replaced another one, i.e. every restart the /// session's first worker did not cost: a seek, a resync, a clip boundary. /// Each carries a demuxer reopen and a VA-API init, so this is what a /// playback measurement counts to say how often the picture was thrown away /// ([`restarts`](Self::restarts)). restarts: u64, clock: PlaybackClock, audio: Option