//! 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::path::Path; use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering}; use std::sync::mpsc::{Receiver, TryRecvError}; use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; use crate::ao::AoSession; use crate::audio::{AudioChunk, AudioSession}; use crate::clock::{ClockSource, PlaybackClock}; use crate::color::ColorParams; use crate::colorspace::ColorDescription; use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker}; use crate::demux::{Codec, Demuxer, VideoMeta}; use crate::eq::EqParams; use crate::project::{Clip, Edge, Lane, LaneKind, Project, Rate, Source, Span, Speed}; use crate::scale::{Composer, FitPolicy}; /// 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); /// 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`]). /// /// ponytail: 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. /// /// ponytail: 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; /// How long a still image is *placed* for: five seconds, the length a picture /// gets when nobody has said one -- trimmable either way up to /// [`IMAGE_MAX_SECS`]. const IMAGE_PLACE_SECS: f64 = 5.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 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>>, } /// 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; 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) } /// 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]) { let channels = self.channels.max(1) as usize; 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. fn spawn_feeder_deferred( &self, open: impl FnOnce() -> Option> + Send + 'static, ) -> bool { let me = self.clone(); let epoch = self.epoch.load(Ordering::Acquire); 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 { return; } 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); } }) .is_ok() } } /// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`]. pub struct PlaybackSession { /// 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, /// 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, /// 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, clock: PlaybackClock, audio: Option