forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7cb30bfTahinli2 months ago908 commits

playback.rs5164 lines, 252.1 KiBHistoryRawDownload
1//! One timeline over one or more files: the decode workers, the audio output
2//! and the master clock wired together so a front-end only has to render and
3//! call [`tick`].
4//!
5//! [`tick`]: PlaybackSession::tick
6//!
7//! Everything degrades to silent-but-correct: no audio track, no plugin, no
8//! PipeWire daemon and an unusable format all end up in [`ClockSource::Wall`],
9//! where the video is paced by real time instead of by the device.
10//!
11//! Drift policy stays with the caller -- this type answers "what time is it",
12//! the renderer decides which frame that means.
13
14use std::path::{Path, PathBuf};
15use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, AtomicUsize, Ordering};
16use std::sync::mpsc::{Receiver, TryRecvError};
17use std::sync::{Arc, Mutex};
18use std::thread;
19use std::time::{Duration, Instant};
20
21use crate::ao::AoSession;
22use crate::audio::{AudioChunk, AudioSession};
23use crate::clock::{ClockSource, PlaybackClock};
24use crate::color::ColorParams;
25use crate::colorspace::{ColorDescription, ContentLight};
26use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};
27use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta};
28use crate::eq::EqParams;
29use crate::project::{
30 Clip, Edge, GapSweep, Lane, LaneKind, Project, Rate, Source, Span, Speed, SubClip,
31};
32use crate::scale::{Composer, FitPolicy};
33use crate::transform::TransformParams;
34
35/// How long the feeder waits out a full ring. The ring holds a second, so this
36/// only has to be short next to that; it costs one wakeup per 10 ms of audio.
37const RING_FULL_WAIT: Duration = Duration::from_millis(10);
38
39/// How long the feeder waits out a ring that took *nothing*: the flush of a
40/// restart, which only the device's own callback can clear (`engine-audio`
41/// refuses a write queued behind one). Short, because this is the gap at the
42/// head of every restart and the ear is in it -- one wakeup per millisecond,
43/// for the millisecond or two it lasts.
44const FLUSH_WAIT: Duration = Duration::from_millis(1);
45
46/// How long [`try_frame`](PlaybackSession::try_frame) blocks the caller
47/// waiting for B's first picture when the playhead lands in a dissolve
48/// window before B's eager-opened decoder ([`start_span`](PlaybackSession::start_span))
49/// has one ready -- a seek straight into the window, mostly. Above the 98 ms
50/// worst-case VA-API init measured for a picture open, so an eager-opened B
51/// almost never actually waits the full budget; a source B cannot decode at
52/// all pays this once per span rather than freezing the preview outright.
53const DISSOLVE_B_TIMEOUT: Duration = Duration::from_millis(200);
54
55/// How long a dead output is left alone before another open is attempted. A
56/// PipeWire daemon restart takes a moment, and the ask that makes the attempt
57/// runs once per rendered frame: a second is long enough that a restart lands
58/// inside it, and short enough that a play pressed after one does not wait.
59const AUDIO_REARM_AFTER: Duration = Duration::from_secs(1);
60
61/// What a session says when its output dies ([`PlaybackSession::tick`]): the
62/// one line a front-end shows for a session that has gone quiet, through the
63/// same door a file's own refusal reaches it by
64/// ([`PlaybackSession::audio_disabled_reason`]).
65const AUDIO_LOST: &str = "output device went away -- reconnecting the timeline's sound";
66
67/// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --
68/// nothing was shot on it, so it is the canvas a *later* import meets rather
69/// than a description of the song. H.264 because it is the one codec that
70/// decodes without the plugin, 30 fps because a rounded-up audio length is what
71/// the frame count means and a whole number of frames per second keeps it
72/// honest; both are what a video imported onto such a timeline is held to
73/// ([`matches_timeline`]).
74///
75/// corner-cut: a 25 fps video imported onto an audio-only timeline it could have
76/// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read
77/// through [`Rate`] like any other file shot at another rate rather than
78/// defining one. Upgrade path is adopting the first *picture's* rate and codec
79/// on import, which means retiming every audio clip already placed in frames.
80const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0);
81
82/// The frame rate a timeline scaffolded from a still image runs at, for
83/// [`AUDIO_ONLY_CANVAS`]'s reason: nothing was shot on it. The *size* is not
84/// invented the same way -- an image has a picture of its own, and that picture
85/// is the canvas a later import meets.
86const IMAGE_ONLY_RATE: f64 = 30.0;
87
88/// How long a still image *is*, in seconds: the wall a trim may drag its edge
89/// out to, since an image has no length of its own to be walled by. Ten
90/// minutes, which is a title card nobody will run out of and still a finite
91/// number -- a `u32::MAX` sentinel here would make [`Self::trim_room`] hand a
92/// drag a wall past what the timeline can hold.
93///
94/// corner-cut: a still cannot be held longer than this. Upgrade path is a
95/// per-source length the project file carries, which every `counts` reader
96/// would then have to take from the document rather than from the file.
97const IMAGE_MAX_SECS: f64 = 600.0;
98
99/// How long a still image is *placed* for: five seconds, the length a picture
100/// gets when nobody has said one -- trimmable either way up to
101/// [`IMAGE_MAX_SECS`].
102const IMAGE_PLACE_SECS: f64 = 5.0;
103
104/// The output half of a session: the device, plus what the feeder has handed it.
105/// Cloned into the feeder thread; every field that matters is shared.
106#[derive(Clone)]
107struct Audio {
108 /// Shared because `write` runs on the feeder thread while `position` and
109 /// `set_active` are called from the caller's. The plugin serialises those
110 /// itself (atomics and a channel), but the lock is what makes it sayable in
111 /// Rust and it is never held for more than a memcpy.
112 ao: Arc<Mutex<AoSession>>,
113 sample_rate: u32,
114 channels: u64,
115 /// Interleaved samples accepted by the device so far.
116 fed: Arc<AtomicU64>,
117 /// The decoder ran out and `fed` is final.
118 fed_all: Arc<AtomicBool>,
119 /// The output plugin failed mid-stream. Its position is frozen from here on,
120 /// so it can never satisfy [`Audio::played_out`] -- the flag is what lets
121 /// [`PlaybackSession::tick`] hand the timeline to wall time instead.
122 died: Arc<AtomicBool>,
123 /// Bumped by every seek. A feeder only owns the device while this still
124 /// matches the value it started with; see [`feed`].
125 epoch: Arc<AtomicU64>,
126 /// The device position the *current* stream's first real sample was queued
127 /// at, `-1` until the feeder has queued one. Written by the feeder under the
128 /// device lock, read by [`tick`](PlaybackSession::tick).
129 ///
130 /// This is what keeps a restart out of the timeline. Between a flush and the
131 /// first sample of the new stream the device plays silence -- a decoder open
132 /// is tens of milliseconds -- and that silence is elapsed *device* time
133 /// ([`crate::ao`] counts it, as it must: it really was played). It is not
134 /// elapsed *timeline* time, and a clock anchored on the first poll after a
135 /// seek counts it as such, which is a permanent offset between the picture
136 /// and the sound, re-rolled by every edit made while playing.
137 content_at: Arc<AtomicI64>,
138 /// The timeline is *meant* to be playing: what a play or a seek-while-playing
139 /// asks for, and what the feeder turns into a running device the moment it
140 /// has a real sample to play ([`Audio::set_playing`], [`feed`]).
141 ///
142 /// The device is not started by the intent, because an inactive stream has
143 /// no callbacks and therefore no starved quanta: between the flush of a seek
144 /// and the first sample of the new stream -- seconds, on a cold 25 GB film
145 /// whose decoder is opened on the feeder -- a device started here would play
146 /// its own silence and count every quantum of it as an underrun.
147 ///
148 /// Written and read under the device lock, beside the [`Audio::content_at`]
149 /// stamp, and that is the whole race: whichever of the two sides takes the
150 /// lock first, the other sees its half (a stamp already there, or an intent
151 /// already set), so the device is started exactly once and a pause landing
152 /// during an open can never be overtaken by a late activation.
153 wants_active: Arc<AtomicBool>,
154 /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest
155 /// first: what a meter or an analyser draws. Written by the feeder, which
156 /// is not the device's own callback -- the plugin's RT thread never sees
157 /// this lock, and the feeder holds it for one memcpy per write.
158 tap: Arc<Mutex<Vec<f32>>>,
159 /// Feeder threads started and not yet returned. They are detached, so there
160 /// is no handle to count instead, and a scrub leaves dozens of them exiting
161 /// at once -- which is precisely what
162 /// [`live_workers`](PlaybackSession::live_workers) is asked about.
163 feeders: Arc<AtomicUsize>,
164 /// When this device was last opened *again* after dying
165 /// ([`PlaybackSession::rearm_audio`]). A dead output is offered one open a
166 /// second and no more, because the ask that makes the attempt runs once per
167 /// rendered frame: a daemon restart takes a moment, and a device that is
168 /// gone for good must not be opened sixty times a second for the rest of
169 /// the session.
170 rearm_at: Arc<Mutex<Option<Instant>>>,
171}
172
173/// How much of the played signal the tap keeps. A power of two, because what
174/// reads it transforms it, and long enough that the lowest band the editor
175/// draws (20 Hz) has a whole cycle in the window at any rate we open.
176const TAP_SAMPLES: usize = 2048;
177
178impl Audio {
179 /// Whether the device has played everything there will ever be, i.e. the
180 /// audio clock is about to stop meaning anything.
181 fn played_out(&self, position: i64) -> bool {
182 self.fed_all.load(Ordering::Acquire)
183 && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed)
184 }
185
186 /// Says whether the timeline is playing, and starts or stops the device for
187 /// it: `true` runs it *if there is already something to play*, and otherwise
188 /// leaves it to the feeder's first sample ([`Audio::wants_active`]). `false`
189 /// stops it at once -- a pause is never deferred, whatever an open in flight
190 /// is about to find.
191 fn set_playing(&self, playing: bool) {
192 // The lock, not the atomics, is what orders this against the feeder's
193 // stamp: the store below and the load after it are one critical section,
194 // and so is the feeder's pair.
195 let ao = self.ao.lock().unwrap();
196 self.wants_active.store(playing, Ordering::Release);
197 if !playing || self.content_at.load(Ordering::Acquire) >= 0 {
198 ao.set_active(playing);
199 }
200 }
201
202 /// Keeps the newest [`TAP_SAMPLES`] of what was just queued, downmixed to
203 /// mono. Called from the feeder only, once per accepted write.
204 fn note_tap(&self, accepted: &[f32]) {
205 let channels = self.channels.max(1) as usize;
206 let mut tap = self.tap.lock().unwrap();
207 // Only the tail can survive anyway: a big write replaces the window
208 // outright rather than being summed into it and then thrown away.
209 let from = accepted.len().saturating_sub(TAP_SAMPLES * channels);
210 for frame in accepted[from..].chunks_exact(channels) {
211 tap.push(frame.iter().sum::<f32>() / channels as f32);
212 }
213 let over = tap.len().saturating_sub(TAP_SAMPLES);
214 tap.drain(..over);
215 }
216
217 /// Starts a feeder for the current epoch, draining `rx` into the device.
218 /// `false` if the thread would not start, i.e. nothing will ever be fed.
219 fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool {
220 self.spawn_feeder_deferred(move || Some(rx))
221 }
222
223 /// As [`spawn_feeder`](Self::spawn_feeder), but the *stream* is opened on
224 /// the feeder too: `open` runs on that thread, so nothing here touches the
225 /// disk and the caller pays a thread spawn instead of a demux -- seconds off
226 /// a cold cache on a big film, which is what a seek used to cost the UI
227 /// thread ([`crate::DecodeSession::open_worker_deferred`] is the picture's
228 /// half of the same move).
229 ///
230 /// The price is the same one: there is no [`crate::audio::AudioMeta`] to
231 /// hand back and no synchronous answer to "will anything play". `None` from
232 /// `open` -- a silent timeline, a source that will not open -- is a feeder
233 /// with nothing to feed, which ends exactly as a played-out stream does and
234 /// hands the clock to wall time ([`tick`](PlaybackSession::tick)).
235 ///
236 /// The epoch is captured *here*, at the seek, not when the open returns: a
237 /// scrub abandons opens by the dozen and every one of them must still be
238 /// the stale stream it was started as, however late it lands.
239 ///
240 /// corner-cut: an abandoned open is not *cancelled*, though the machinery
241 /// for it exists ([`crate::demux::with_cancel`], which the import's Cancel
242 /// uses): it runs to the end and its answer is dropped. Tried, and left
243 /// out for want of evidence -- 200 cold scrub steps over the 25 GB HEVC
244 /// remux measured 101, 137 and 14 live workers on three runs of the *same*
245 /// build, so the machine decides that number and not this. There is a
246 /// reason to expect it to hurt, too: a Matroska walk writes its sidecar
247 /// index only when it finishes (`demux::mkv_blocks`), so a drag that
248 /// cancels every step's walk would never write one and every step would
249 /// walk the segment again from the top. Ceiling: an abandoned open keeps
250 /// reading, and the decoder threads it started live until it does. Upgrade
251 /// path is an index the walk publishes as it goes -- then cancelling costs
252 /// nothing and can be measured on an idle machine.
253 fn spawn_feeder_deferred(
254 &self,
255 open: impl FnOnce() -> Option<Receiver<AudioChunk>> + Send + 'static,
256 ) -> bool {
257 let me = self.clone();
258 let epoch = self.epoch.load(Ordering::Acquire);
259 // Counted before the spawn, so the count is never behind the thread.
260 self.feeders.fetch_add(1, Ordering::Release);
261 let started = thread::Builder::new()
262 .name("audio-feed".into())
263 .spawn(move || {
264 // Superseded before this thread was even scheduled: do not open
265 // anything at all. A scrub leaves all but the last one here.
266 if me.epoch.load(Ordering::Acquire) == epoch {
267 if let Some(rx) = open() {
268 feed(rx, &me, epoch);
269 }
270 // Only the current feeder gets to declare the end of the
271 // audio: a superseded one is finished, the stream is not.
272 if me.epoch.load(Ordering::Acquire) == epoch {
273 me.fed_all.store(true, Ordering::Release);
274 }
275 }
276 me.feeders.fetch_sub(1, Ordering::Release);
277 })
278 .is_ok();
279 if !started {
280 self.feeders.fetch_sub(1, Ordering::Release);
281 }
282 started
283 }
284
285 /// Feeder threads still running; see [`Self::feeders`].
286 fn live_feeders(&self) -> usize {
287 self.feeders.load(Ordering::Acquire)
288 }
289}
290
291/// The cross-dissolve a span's tail owes its successor, tracked from the
292/// moment [`PlaybackSession::start_span`] opens A's own decoder until a later
293/// `start_span` throws it away. What decides there *is* one mirrors
294/// [`crate::export::dissolve_window`] exactly, on the very same span, so a
295/// preview blends the window an export would render -- but B's own decoder
296/// opens only once the playhead actually reaches it
297/// ([`PlaybackSession::open_dissolve_b`]), rather than for the whole span:
298/// most of a dissolving clip is never in the window, and a viewer who pauses
299/// or seeks away before the tail never pays for a decoder nobody sees.
300struct Dissolve {
301 /// The first *timeline* frame inside the window.
302 tail_start: u32,
303 /// How many output frames the blend ramps across.
304 window: u32,
305 b_source: usize,
306 b_in_frame: u32,
307 /// Where B sits on the timeline -- what its own grade and fit are keyed
308 /// on ([`Project::composite_color_at`], `composite_fit_at`), the same
309 /// `b_start` [`crate::export`] grades B's side of the same dissolve by.
310 b_start: u32,
311 /// B's live decode, once open; `None` before the playhead reaches the
312 /// window.
313 b: Option<DissolveB>,
314}
315
316/// B's own worker, decoding beside A's for the length of the window.
317struct DissolveB {
318 frames: Receiver<Frame>,
319 worker: Worker,
320 /// The last frame B handed over: a tick that lands between two of B's
321 /// pictures still has one to blend A against, the same "keep showing the
322 /// last one" policy A's own channel gets from the app's own pump -- done
323 /// here instead, because B never leaves the engine to be pumped.
324 held: Option<Frame>,
325}
326
327/// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`].
328pub struct PlaybackSession {
329 /// The *timeline's* parameters, not any one file's: its frame rate and codec
330 /// come from source 0 and are what every other source is held to, while
331 /// `width`/`height` are the **project resolution** -- source 0's picture to
332 /// begin with, and whatever [`PlaybackSession::set_resolution`] or a saved
333 /// `resolution` line makes it after that. Every clip is composed onto it, so
334 /// a file of another size is a placed picture rather than a refusal.
335 meta: VideoMeta,
336 /// What source 0's own file declared about how bright it gets
337 /// ([`crate::colorspace::ContentLight`]) -- MaxCLL/MaxFALL and the
338 /// mastering display's peak/black, read once at open exactly as `native`
339 /// is, since the value is a property of the file and never changes under
340 /// a running session. [`ContentLight::default()`] (every field `None`)
341 /// for an SDR file and for a song or a still, neither of which is graded.
342 content_light: ContentLight,
343 /// Source 0's own picture, kept from the open: the project resolution
344 /// starts here, and a caller offering sizes to pick from needs the media's
345 /// own among them or a project moved off it could never come back.
346 native: (u32, u32),
347 /// ...and the scaffolding source's own frame rate, kept for exactly that
348 /// reason: the project rate starts here, and the list a caller offers rates
349 /// from needs the media's own on it or a project moved off it has no way
350 /// back ([`PlaybackSession::set_frame_rate`] is not an undo step either).
351 native_fps: f64,
352 frames: Receiver<Frame>,
353 /// The current decode worker.
354 worker: Worker,
355 /// What that worker opened -- hardware, software, a still, a gap -- written
356 /// by the worker itself and read by [`decode_backend`](Self::decode_backend).
357 /// Replaced with the stream at every seek, so it always describes the
358 /// pictures currently arriving and never the clip before them.
359 backend: BackendCell,
360 /// Workers cancelled by a seek or a clip change, waiting to be reaped.
361 /// Joining one inline costs whatever VA-API init it is still inside (98 ms
362 /// measured worst case), which is a visible hitch on the caller's thread;
363 /// parking it here instead makes that free, and [`retire`] drops the ones
364 /// that have already returned every time it adds another.
365 ///
366 /// Never a leak, and that is the invariant: everything in here is joined
367 /// when the session drops (`Vec<Worker>`'s own drop does it, one
368 /// [`Worker::drop`] each), so no decode worker can outlive the session and
369 /// meet Mesa's `atexit` handlers from inside libva.
370 ///
371 /// [`retire`]: PlaybackSession::retire
372 retired: Vec<Worker>,
373 /// Picture workers that replaced another one, i.e. every restart the
374 /// session's first worker did not cost: a seek, a resync, a clip boundary.
375 /// Each carries a demuxer reopen and a VA-API init, so this is what a
376 /// playback measurement counts to say how often the picture was thrown away
377 /// ([`restarts`](Self::restarts)).
378 restarts: u64,
379 clock: PlaybackClock,
380 audio: Option<Audio>,
381 /// Why this timeline is silent, when the file itself is not: an audio track
382 /// we cannot decode is a session that plays perfectly and says nothing about
383 /// it otherwise. `None` for a file that has usable audio *and* for one that
384 /// has none at all, which is not a surprise worth a notice.
385 audio_disabled: Option<String>,
386 /// The edit list. Everything a caller says in seconds is a *timeline*
387 /// position; only this maps it onto the file.
388 project: Project,
389 /// How many frames each source actually holds, indexed exactly as
390 /// [`Project::sources`] is and grown with it. The project itself does not
391 /// know -- a clip names a source by index and carries its own range -- and
392 /// [`Self::trim_clip`] is the one edit that could ask for frames past the
393 /// end of a file, which is a save that would not open again
394 /// ([`Self::open_project`] refuses one by name). Append-only for
395 /// `sources`'s reason: an index handed out stays valid, undone import or
396 /// not -- with the single exception `sources` itself has,
397 /// [`Self::remove_source`], which takes the same entry out of both.
398 counts: Vec<u32>,
399 /// Audio headers already read, by the `(path, stream)` they were read for.
400 /// Every door that checks a file against the timeline asks the same two
401 /// questions -- what this file's sound is, and what the timeline's first
402 /// source's is ([`audio_matches`], [`first_audio_of`]) -- and each answer is
403 /// a container open. Warm that is 5-10 ms; on a film whose pages have been
404 /// evicted it is **1.7 s** (measured, 3.1 GB HEVC mkv), and both of those
405 /// are spent on the thread that draws, because placing and importing are
406 /// what a drag lands on. A header does not change while a session holds the
407 /// file, so it is read once and remembered. Errors are not kept: a file that
408 /// failed to open is asked again next time.
409 probes: std::collections::HashMap<(std::path::PathBuf, usize), Option<crate::AudioProbe>>,
410 /// What each source's own frame rate is against this timeline's, indexed
411 /// and grown exactly as [`Self::counts`] is (and shortened with it by
412 /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the
413 /// timeline's rate -- and for a still and a song, which have no rate of
414 /// their own -- so a single-rate project converts nothing anywhere.
415 ///
416 /// A clip counts *timeline* frames ([`Rate`]); this is the one thing that
417 /// knows which frames of the file those are, and only
418 /// [`start_span`](Self::start_span) and [`try_frame`](Self::try_frame) ask.
419 rates: Vec<Rate>,
420 /// The rate of the source the current worker is decoding, kept beside
421 /// [`Self::span`] because the frames coming back are numbered in *its*
422 /// file's frames and nothing else can put them back on the timeline.
423 span_rate: Rate,
424 /// What the current video worker was opened for: where it sits on the
425 /// timeline, how long it runs, and which source frame it started at --
426 /// together they rewrite a source frame index into a timeline one. Not a
427 /// clip index: a `split` cuts the clip under a running worker, and only the
428 /// mapping survives that. A span with no source is a *gap*, and the worker
429 /// feeding it emits black frames indexed from zero.
430 ///
431 /// `None` is the *emptied* timeline -- no clip on any lane, so there is no
432 /// stretch to be inside of. It is a state, not a failure: the picture is
433 /// black ([`start_span`](Self::start_span) feeds one black frame for it),
434 /// the sound is silence, the duration is zero, and placing anything reseeks
435 /// straight back out of it.
436 span: Option<Span>,
437 /// Whether the span now decoding still owes its first picture: set by
438 /// every span start ([`start_span`](Self::start_span)), cleared by the
439 /// first frame that span hands over ([`try_frame`](Self::try_frame)).
440 /// This is the window a clip boundary -- or any picture restart -- spends
441 /// reopening the decoder, and a front-end must not answer a picture that
442 /// is late by exactly this window's length with another restart of it
443 /// ([`picture_priming`](Self::picture_priming)).
444 span_priming: bool,
445 /// The cross-dissolve the current span's tail owes its successor, if any
446 /// ([`crate::export::dissolve_window`], the same test an export makes of
447 /// the same span) -- and, once the playhead has reached the window, B's
448 /// own decoder, opened beside A's exactly as [`crate::export`] opens one
449 /// for the render. `None` for a span with no dissolve out, which is every
450 /// span most of the time.
451 dissolve: Option<Dissolve>,
452 /// The last clip has been played out; see [`PlaybackSession::is_eos`].
453 /// The size a front-end showing this session *on screen* wants its
454 /// pictures at, in device pixels ([`Self::set_view_size`]). `None` is the
455 /// project's own -- every file-level caller, every test, and an export,
456 /// which has a seat of its own ([`crate::export`]) and never comes here.
457 view: Option<(u32, u32)>,
458 eos: bool,
459 /// The mix the running mixer is reading, when there is one: what lets a
460 /// fader and the master ceiling move without rebuilding the audio pipeline
461 /// at all ([`crate::audio::MixControls`]). `None` for a timeline that is
462 /// not mixed -- one audio lane at unity with the limiter off, which is the
463 /// bit-exact single-stream path -- and the first move off that reopens the
464 /// stream once, mixed, and lives from there.
465 mix: Option<Arc<crate::audio::MixControls>>,
466 /// An audio stream has been started and has not yet played a sample: the
467 /// window [`tick`](Self::tick) holds the clock still through, so the silence
468 /// of a restart is never counted as timeline time. See
469 /// [`Audio::content_at`].
470 priming: bool,
471 /// Whether the decode worker may drop a picture whose moment has already
472 /// passed ([`Self::drop_late_pictures`]). Off unless a caller says it is
473 /// watching this in real time.
474 drop_late: bool,
475 /// Whether the picture is decoded from the stand-ins rather than from the
476 /// films ([`crate::proxy`]). One switch for the whole project, saved with
477 /// it, and *only* the picture: the sound is always the film's own, and so
478 /// is everything an export reads.
479 ///
480 /// Which sources have a stand-in is not kept here -- it is asked of the
481 /// cache when a span opens ([`Self::picture_path`]), one `stat` against a
482 /// file open that already costs milliseconds, so a proxy made (or deleted)
483 /// mid-session is picked up at the next seek and nothing can go stale.
484 proxies: bool,
485 /// Whether a source that wants a stand-in gets one made for it as it
486 /// arrives ([`crate::proxy::wanted`]). On unless a project says otherwise,
487 /// which is what every project did before the switch existed. Saved with
488 /// the project like the one above it, and read by the front end: the engine
489 /// starts no encode of its own.
490 auto_proxies: bool,
491 /// Which encoder an export of this project writes its picture with
492 /// ([`crate::export::EncoderSeat`]). The project's, saved with it like the
493 /// two switches above, and read by the front end: the engine starts no
494 /// export of its own.
495 encoder_seat: crate::export::EncoderSeat,
496 /// The rate this project's mix was picked to run at
497 /// ([`crate::edith::Document::sample_rate`]), overriding the one the first
498 /// audio source would otherwise hand the mixer. `None` -- every project
499 /// before the field existed, and any project nobody has picked one for --
500 /// leaves the derived rate alone. Saved with the project like the switches
501 /// above it, and read by the front end: the engine picks no rate of its own.
502 ///
503 /// Setting it takes effect at the next audio rebuild (a seek, an edit, a
504 /// reopen); there is no live resample of an audio device already playing.
505 sample_rate: Option<u32>,
506}
507
508/// What an edit dirtied -- which half of the pipeline has to be rebuilt for the
509/// change to be seen or heard, and, far more to the point, which half must not
510/// be.
511///
512/// Rebuilding a half is expensive and *audible*: the video worker costs a
513/// decoder open (98 ms of VA-API init, worst case, measured) and the audio one
514/// costs a flush, a re-open and a hole in the sound. A grade changes no sample
515/// and a fader changes no picture, so neither may pay the other's price -- that
516/// is the whole of this type.
517#[derive(Clone, Copy, PartialEq, Eq, Debug)]
518enum Dirty {
519 /// The picture only: a grade, a fit policy, the project resolution. The
520 /// sound keeps playing, untouched, and the clock never moves.
521 Picture,
522 /// The sound only: a clip's equalizer. The picture keeps playing.
523 Sound,
524 /// The timeline itself -- what is where, how long, how fast. Both halves
525 /// are rebuilt, because both are decoding the wrong thing.
526 Both,
527}
528
529/// What an import is held to, off a timeline that is already up: the sources
530/// its sound has to agree with and the meta its rate is read against. Owned and
531/// `Send`, so the check itself can run on a worker with no session in reach --
532/// which is the whole point ([`PlaybackSession::probe_import`]).
533#[derive(Clone, Debug, PartialEq)]
534pub struct ImportGate {
535 sources: Vec<Source>,
536 timeline: VideoMeta,
537}
538
539/// A file read and accepted, waiting to be registered: what
540/// [`PlaybackSession::probe_import`] found and
541/// [`PlaybackSession::import_probed`] pushes. Carries the gate it was decided
542/// against, so a timeline that moved under it can be noticed rather than
543/// trusted.
544#[derive(Clone, Debug)]
545pub struct ImportProbe {
546 gate: ImportGate,
547 meta: VideoMeta,
548 rate: Rate,
549}
550
551impl PlaybackSession {
552 /// Opens `path` and starts both decode workers. Only video failure is fatal:
553 /// a file we cannot hear is still a file we can watch.
554 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {
555 Self::open_stream(path, 0)
556 }
557
558 /// Opens `path` exactly as [`open`](Self::open) does, but binds `stream` --
559 /// the index a library row names ([`crate::probe`]'s own numbering of a
560 /// file's audio tracks) -- as the one that keeps the clock and plays,
561 /// rather than always the first. What a library preview asks for when the
562 /// row *is* a particular stream, so a remux with several audio tracks
563 /// previews the one that was clicked.
564 pub fn open_with_audio_stream(
565 path: impl AsRef<Path>,
566 audio_stream: usize,
567 ) -> crate::Result<Self> {
568 Self::open_stream(path, audio_stream)
569 }
570
571 fn open_stream(path: impl AsRef<Path>, audio_stream: usize) -> crate::Result<Self> {
572 // Canonical from the first byte: the project canonicalizes every
573 // source ([`Source::new`]), and [`Worker::reseek`] reuses a decoder
574 // only when the paths match textually -- a raw path here would make
575 // every later picture edit pay a full reopen instead of a seek.
576 let path = crate::project::canonical(path.as_ref());
577 // A timeline is normally scaffolded from source 0's picture -- its size,
578 // its frame rate, its clock. A song has none of that, so it scaffolds
579 // the *canvas* instead and its own sound keeps the clock: an audio-only
580 // project is a project like any other, it simply plays black.
581 if crate::is_audio(&path) {
582 return Self::open_audio_only(&path, audio_stream);
583 }
584 // A still is the other source with no timeline in it: it has a picture
585 // (which becomes the canvas) but no rate and no length, so it too
586 // scaffolds rather than describes.
587 if crate::is_image(&path) {
588 return Self::open_image_only(&path);
589 }
590 // `open_worker` rather than `open` purely for the worker handle: the
591 // field has to exist from the start for the first seek to use it.
592 // Ungraded: a file just opened has one clip per lane and nothing has
593 // graded it yet. Every later span is opened by `start_span`, which asks
594 // the project.
595 // Passthrough: a freshly opened file *is* the project resolution, so
596 // there is nothing to place it on. Every later span goes through
597 // `start_span`, which builds the canvas from the project.
598 let opened = DecodeSession::open_worker(
599 &path,
600 0,
601 u32::MAX,
602 ColorParams::default(),
603 TransformParams::default(),
604 Composer::passthrough(),
605 // The default rendition: a file just opened is a project nobody has
606 // picked one for, exactly as it is a project nobody has graded.
607 crate::tonemap::Preset::default(),
608 );
609 // `is_audio` above is the extension's word, and an extension can lie: a
610 // song muxed into an `.mp4` reads as a film until the header is actually
611 // walked. The demuxer's own `NoVideoTrack` is that walk saying there was
612 // never a picture in it, and the fallback is the same audio-only door the
613 // extension check would have taken up front -- not a fault, a type.
614 let (meta, stream) = match opened {
615 Ok(opened) => opened,
616 Err(e) if NoVideoTrack::is_it(&e) => return Self::open_audio_only(&path, audio_stream),
617 Err(e) => return Err(e),
618 };
619 // A file is opened on its first audio stream by default, like
620 // `Project::single` names it -- unless a caller through
621 // `open_with_audio_stream` picked another.
622 let (audio, audio_disabled) = open_audio(&path, audio_stream);
623 let source = match audio {
624 Some(_) => ClockSource::Audio,
625 None => ClockSource::Wall,
626 };
627 // One clip per lane covering the file, so timeline == source until the
628 // first edit -- and the range opened above is exactly that clip's.
629 let project = Project::single(&path, meta.frame_count);
630 let span = project.composite_span_at(0);
631 // A second, header-only open purely for the light level: `open_worker`
632 // above already read one to hand the decode thread its own, but never
633 // hands it back out. The same trade the audio header cache above this
634 // makes -- a second container open, paid once at open rather than never
635 // -- since nothing here decodes a single picture.
636 let content_light = Demuxer::open(&path).map(|(_, d)| d.light()).unwrap_or_default();
637 Ok(Self {
638 meta,
639 content_light,
640 native: (meta.width, meta.height),
641 native_fps: meta.frame_rate,
642 frames: stream.frames,
643 worker: stream.worker,
644 backend: stream.backend,
645 retired: Vec::new(),
646 restarts: 0,
647 clock: PlaybackClock::new(source),
648 audio,
649 audio_disabled,
650 project,
651 counts: vec![meta.frame_count],
652 probes: std::collections::HashMap::new(),
653 // Source 0 *is* the timeline's rate: it defined it.
654 rates: vec![Rate::REAL_TIME],
655 span_rate: Rate::REAL_TIME,
656 span,
657 span_priming: true,
658 dissolve: None,
659 view: None,
660 eos: false,
661 mix: None,
662 priming: false,
663 drop_late: false,
664 // A file just opened is a project nobody has picked stand-ins for.
665 proxies: false,
666 auto_proxies: true,
667 encoder_seat: crate::export::EncoderSeat::default(),
668 sample_rate: None,
669 })
670 }
671
672 /// Opens `path` into the **library alone**: everything
673 /// [`open`](Self::open) scaffolds from it -- the resolution, the frame
674 /// rate, the clock, the source entry and its length -- over an *empty*
675 /// timeline. What an import into a window that has no session yet makes,
676 /// since an import registers a source and never places a clip
677 /// ([`import`](Self::import)); the file reaches a lane when it is dragged
678 /// there.
679 ///
680 /// Nothing to undo, like the import it stands in for: the lanes start
681 /// empty rather than being emptied, so no snapshot is pushed.
682 pub fn open_library(path: impl AsRef<Path>) -> crate::Result<Self> {
683 let mut session = Self::open(path)?;
684 // The pair of lanes an opened file comes up with (`Project::single`,
685 // `open_audio_only`), emptied -- the source list and so the noted
686 // counts are carried over untouched, which is what keeps a library row
687 // placeable at its full length.
688 session.project = Project::from_parts(
689 session.project.sources().to_vec(),
690 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())],
691 Vec::new(),
692 Vec::new(),
693 Vec::new(),
694 )?;
695 // Onto the emptied mapping: black picture, silence, zero duration.
696 session.seek(0.);
697 Ok(session)
698 }
699
700 /// Opens a standalone audio file ([`crate::is_audio`]) as a timeline of its
701 /// own: one clip on `A1`, nothing on the video lane, and a picture that is
702 /// the black of an uncovered canvas ([`AUDIO_ONLY_CANVAS`]) for as long as
703 /// the song runs. Its own sound keeps the clock, exactly as a video's does.
704 ///
705 /// Refused when the file has no sound to time it by: a source with neither a
706 /// picture nor a playable length is not a timeline, and that is what
707 /// [`audio_frames`] answers -- the *device* is a different question, and a
708 /// machine without one opens this like any other session, silently.
709 fn open_audio_only(path: &Path, stream: usize) -> crate::Result<Self> {
710 let (width, height, frame_rate) = AUDIO_ONLY_CANVAS;
711 let meta = VideoMeta {
712 width,
713 height,
714 frame_rate,
715 // Rounded up to whole frames, which is the only frame count a
716 // source with no picture has -- the same length `import_audio`
717 // gives a song joining a timeline of video. The demuxer's words are
718 // named with the file, since this is the door a file that is not
719 // really audio at all comes to.
720 frame_count: audio_frames(path, frame_rate)
721 .map_err(|e| format!("{}: {e}", path.display()))?,
722 codec: Codec::H264,
723 // A canvas this engine drew itself, not a stream that was read:
724 // the default description is what it is drawn in.
725 color: ColorDescription::default(),
726 rotation: Rotation::None,
727 };
728 let (audio, audio_disabled) = open_audio(path, stream);
729 // Through `from_parts` rather than `Project::single`, which is the
730 // *video* open's pair of grouped clips: here there is no picture to
731 // group the sound with, so the video lane starts empty.
732 let clip = Clip {
733 fade_in: 0,
734 fade_out: 0,
735 transition_out: 0,
736 visualizer: 0,
737 viz_paint: 0,
738 start: 0,
739 in_frame: 0,
740 out_frame: meta.frame_count,
741 source: 0,
742 link: None,
743 eq: None,
744 color: None,
745 transform: None,
746 fit: FitPolicy::default(),
747 speed: Speed::NORMAL,
748 };
749 let project = Project::from_parts(
750 vec![Source::new(path, 0)],
751 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, vec![clip])],
752 Vec::new(),
753 Vec::new(),
754 Vec::new(),
755 )?;
756 // Every frame of this timeline is a gap, since no video lane covers
757 // anything: `composite_span_at` says so and the black worker
758 // `start_span` would open is opened here instead, for the reason `open`
759 // opens its decoder inline -- the field has to exist for the first seek.
760 let span = project.composite_span_at(0);
761 let stream = DecodeSession::open_black(width, height, span.map_or(1, |s| s.len));
762 Ok(Self {
763 meta,
764 content_light: ContentLight::default(),
765 native: (width, height),
766 native_fps: frame_rate,
767 frames: stream.frames,
768 worker: stream.worker,
769 backend: stream.backend,
770 retired: Vec::new(),
771 restarts: 0,
772 // The song keeps the clock, as a video's own sound does -- and wall
773 // time keeps it on a machine with no device, where the picture
774 // (black) still has to move at some rate.
775 clock: PlaybackClock::new(match audio {
776 Some(_) => ClockSource::Audio,
777 None => ClockSource::Wall,
778 }),
779 audio,
780 audio_disabled,
781 project,
782 counts: vec![meta.frame_count],
783 probes: std::collections::HashMap::new(),
784 // Source 0 *is* the timeline's rate: it defined it.
785 rates: vec![Rate::REAL_TIME],
786 span_rate: Rate::REAL_TIME,
787 span,
788 span_priming: true,
789 dissolve: None,
790 view: None,
791 eos: false,
792 mix: None,
793 priming: false,
794 drop_late: false,
795 // A file just opened is a project nobody has picked stand-ins for.
796 proxies: false,
797 auto_proxies: true,
798 encoder_seat: crate::export::EncoderSeat::default(),
799 sample_rate: None,
800 })
801 }
802
803 /// Opens a still image ([`crate::is_image`]) as a timeline of its own: one
804 /// clip on `V1`, [`IMAGE_PLACE_SECS`] long, over silence. The *canvas* is
805 /// the image's own picture -- unlike a song, a still has one, and inventing
806 /// a 1080p canvas around a 640x360 PNG would letterbox it against nothing.
807 /// The frame rate is [`IMAGE_ONLY_RATE`], for the reason an audio-only
808 /// timeline has one at all: nothing was shot on it.
809 ///
810 /// Wall time keeps the clock, as it does for any silent source.
811 fn open_image_only(path: &Path) -> crate::Result<Self> {
812 // Decoded here rather than probed: this is the door a `.png` that is
813 // not one comes to, and the picture is wanted a line later anyway.
814 let still = crate::decode::Still::open(path)?;
815 let meta = VideoMeta {
816 width: still.width,
817 height: still.height,
818 frame_rate: IMAGE_ONLY_RATE,
819 // Its length is the wall a trim is held to, exactly as a song's
820 // playing time is -- see [`image_frames`].
821 frame_count: image_frames(IMAGE_ONLY_RATE),
822 codec: Codec::H264,
823 color: ColorDescription::default(),
824 rotation: Rotation::None,
825 };
826 let clip = Clip {
827 fade_in: 0,
828 fade_out: 0,
829 transition_out: 0,
830 visualizer: 0,
831 viz_paint: 0,
832 start: 0,
833 in_frame: 0,
834 out_frame: place_frames(meta.frame_count, IMAGE_ONLY_RATE),
835 source: 0,
836 link: None,
837 eq: None,
838 color: None,
839 transform: None,
840 fit: FitPolicy::default(),
841 speed: Speed::NORMAL,
842 };
843 // No group and no audio clip: a still is silent, and a clip on `A1`
844 // playing from a PNG is a source the audio worker cannot open.
845 let project = Project::from_parts(
846 vec![Source::new(path, 0)],
847 vec![(LaneKind::Video, vec![clip]), (LaneKind::Audio, Vec::new())],
848 Vec::new(),
849 Vec::new(),
850 Vec::new(),
851 )?;
852 let span = project.composite_span_at(0);
853 // The placeholder the first seek supersedes, opened here for `open`'s
854 // reason: the field has to exist before anything can seek.
855 let stream = DecodeSession::open_still(
856 path,
857 0,
858 span.map_or(1, |s| s.len),
859 ColorParams::default(),
860 TransformParams::default(),
861 Composer::passthrough(),
862 )?;
863 Ok(Self {
864 meta,
865 content_light: ContentLight::default(),
866 native: (meta.width, meta.height),
867 native_fps: IMAGE_ONLY_RATE,
868 frames: stream.frames,
869 worker: stream.worker,
870 backend: stream.backend,
871 retired: Vec::new(),
872 restarts: 0,
873 clock: PlaybackClock::new(ClockSource::Wall),
874 audio: None,
875 audio_disabled: None,
876 project,
877 counts: vec![meta.frame_count],
878 probes: std::collections::HashMap::new(),
879 // Source 0 *is* the timeline's rate: it defined it.
880 rates: vec![Rate::REAL_TIME],
881 span_rate: Rate::REAL_TIME,
882 span,
883 span_priming: true,
884 dissolve: None,
885 view: None,
886 eos: false,
887 mix: None,
888 priming: false,
889 drop_late: false,
890 // A file just opened is a project nobody has picked stand-ins for.
891 proxies: false,
892 auto_proxies: true,
893 encoder_seat: crate::export::EncoderSeat::default(),
894 sample_rate: None,
895 })
896 }
897
898 /// Opens a project file written by [`save_project`](Self::save_project):
899 /// the whole timeline, restored to where its playhead stood, paused like
900 /// [`open`](Self::open).
901 ///
902 /// A *new* session rather than a reload of this one, so a load that fails
903 /// leaves the caller's current session untouched -- atomic by
904 /// construction. Every named file is opened and checked here: the
905 /// *scaffolding* source -- the first that is not a still, since a picture
906 /// carries no rate -- defines the timeline exactly as `open` does, every
907 /// other source has to match it the way [`import`](Self::import) demands
908 /// (a save renumbers, so which index that is says nothing), and every clip
909 /// has to still be inside the file it plays from. A source that vanished or
910 /// shrank since the save is a refusal naming it, not a silently shorter
911 /// timeline -- the disappearing-file tolerance elsewhere in this type
912 /// applies only *after* a project has loaded.
913 ///
914 /// The undo history is not saved: `undo` is `false` on a fresh load.
915 pub fn open_project(path: &Path) -> crate::Result<Self> {
916 let doc = crate::edith::load(path)?;
917 // *Which* source scaffolds it: the first that is not a still, and index
918 // 0 only when there is no other. A still defines no frame rate -- it is
919 // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps
920 // footage off a PNG that a save happened to renumber to index 0
921 // (`Project::without_orphan_sources` numbers by first use, and a
922 // library removal moves indexes too) reads the timeline as 30 fps and
923 // then refuses every file on it for not matching. The rule this and
924 // [`audio_source_of`] share: nothing may assume what source 0 *is*.
925 //
926 // A v9 file says what rate it was cut at, and that answer beats the
927 // scaffold's *where the scaffold has none to give*: a still and a song
928 // are both given a made-up rate (`IMAGE_ONLY_RATE`,
929 // `AUDIO_ONLY_CANVAS`), so a timeline of nothing but those used to come
930 // back at 30 fps however it was cut. A scaffold with a picture keeps
931 // defining the timeline as it always did -- it is the file every clip
932 // on the lane was conformed to, and the two agree by construction.
933 let saved_fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0);
934 let scaffold = doc
935 .sources
936 .iter()
937 .position(|s| !crate::is_image(&s.path))
938 .unwrap_or(0);
939 // Owned: the sources move into the `Project` below, and the device is
940 // opened after that (see the comment there).
941 let first = doc
942 .sources
943 .get(scaffold)
944 .cloned()
945 .ok_or("the project names no sources")?;
946 // The scaffolding source both defines the timeline and is what the
947 // playhead's first picture comes from, so it is opened for playback
948 // rather than merely probed.
949 // One value, not two locals: everything below this line can refuse, and
950 // locals drop in reverse declaration order -- a bare worker would join
951 // its decode thread while the receiver next to it was still holding
952 // that thread parked in `send`, which is a hang (see [`FrameStream`]).
953 // Ungraded, and superseded before a frame of it is shown: the `seek` at
954 // the end of this function reopens the playhead's span through
955 // `start_span`, which is where a saved grade reaches the picture.
956 // ...unless it has no picture to open: a project whose source 0 is a
957 // song scaffolds the canvas the same way a fresh audio-only open does
958 // ([`open_audio_only`](Self::open_audio_only)), and the placeholder
959 // black stream is superseded by the `seek` at the end of this function
960 // like every other worker opened here.
961 // What source 0's own file declares about its light level, read the
962 // same way [`open_stream`](Self::open_stream) reads it for a fresh
963 // open: [`ContentLight::default()`] for a song or a still, neither of
964 // which is graded.
965 let content_light = if crate::is_audio(&first.path) || crate::is_image(&first.path) {
966 ContentLight::default()
967 } else {
968 Demuxer::open(&first.path).map(|(_, d)| d.light()).unwrap_or_default()
969 };
970 // The extension's word, corrected below the moment the header disagrees
971 // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every
972 // later question in this function about source 0 asks *this*, not
973 // `crate::is_audio` again, so a discovered song stays one for the rest
974 // of the scaffold.
975 let mut audio_only = crate::is_audio(&first.path);
976 let (mut meta, stream) = match audio_only {
977 true => {
978 let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS;
979 let frame_rate = saved_fps.unwrap_or(canvas_fps);
980 let meta = VideoMeta {
981 width,
982 height,
983 frame_rate,
984 frame_count: audio_frames(&first.path, frame_rate)
985 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
986 codec: Codec::H264,
987 color: ColorDescription::default(),
988 rotation: Rotation::None,
989 };
990 (meta, DecodeSession::open_black(width, height, 1))
991 }
992 // ...and a still scaffolds its own picture as the canvas, exactly
993 // as a fresh `open_image_only` does, with the same placeholder
994 // stream the `seek` at the end supersedes.
995 false if crate::is_image(&first.path) => {
996 let still = crate::decode::Still::open(&first.path)
997 .map_err(|e| format!("source {}: {e}", first.path.display()))?;
998 let frame_rate = saved_fps.unwrap_or(IMAGE_ONLY_RATE);
999 let meta = VideoMeta {
1000 width: still.width,
1001 height: still.height,
1002 frame_rate,
1003 frame_count: image_frames(frame_rate),
1004 codec: Codec::H264,
1005 color: ColorDescription::default(),
1006 rotation: Rotation::None,
1007 };
1008 let stream = DecodeSession::open_still(
1009 &first.path,
1010 0,
1011 1,
1012 ColorParams::default(),
1013 TransformParams::default(),
1014 Composer::passthrough(),
1015 )?;
1016 (meta, stream)
1017 }
1018 false => match DecodeSession::open_worker(
1019 &first.path,
1020 0,
1021 u32::MAX,
1022 ColorParams::default(),
1023 TransformParams::default(),
1024 Composer::passthrough(),
1025 // The saved rendition, from the document rather than from the
1026 // project (which is built below): this placeholder is what the
1027 // window shows until the `seek` at the end reopens the span.
1028 doc.tone,
1029 ) {
1030 Ok(opened) => opened,
1031 // A saved source whose extension named a film but whose header
1032 // names no picture: the same door a fresh open falls to
1033 // (`open_stream`), so a project first cut around a song muxed
1034 // into an `.mp4` reloads instead of refusing on a track that was
1035 // never there to begin with.
1036 Err(e) if NoVideoTrack::is_it(&e) => {
1037 audio_only = true;
1038 let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS;
1039 let frame_rate = saved_fps.unwrap_or(canvas_fps);
1040 let meta = VideoMeta {
1041 width,
1042 height,
1043 frame_rate,
1044 frame_count: audio_frames(&first.path, frame_rate)
1045 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
1046 codec: Codec::H264,
1047 color: ColorDescription::default(),
1048 rotation: Rotation::None,
1049 };
1050 (meta, DecodeSession::open_black(width, height, 1))
1051 }
1052 Err(e) => return Err(format!("source {}: {e}", first.path.display()).into()),
1053 },
1054 };
1055 // The project's own resolution, which is source 0's picture unless the
1056 // file says otherwise -- every dialect before v7 had no way to say it,
1057 // and that default is exactly what those projects meant.
1058 let native = (meta.width, meta.height);
1059 if let Some((width, height)) = doc.resolution {
1060 meta.width = width;
1061 meta.height = height;
1062 }
1063 // ...and the project's own *rate*, which is the scaffold's unless the
1064 // file says otherwise. The two made-up rates above already took the
1065 // saved one (their counts are computed from it); a scaffold with a
1066 // picture keeps its own here, so a project cut at a rate nobody picked
1067 // is the file it always was -- and one where a rate *was* picked
1068 // ([`set_frame_rate`](Self::set_frame_rate)) comes back at it rather
1069 // than at the media's, which would leave every clip number counted in
1070 // frames the timeline no longer has.
1071 let native_fps = match audio_only {
1072 true => AUDIO_ONLY_CANVAS.2,
1073 false if crate::is_image(&first.path) => IMAGE_ONLY_RATE,
1074 false => meta.frame_rate,
1075 };
1076 if let Some(fps) = saved_fps {
1077 meta.frame_rate = fps;
1078 }
1079 // A song and a still have no rate of their own to be conformed from:
1080 // their length above was counted in the timeline's frames already,
1081 // whatever those are. A file with pictures is read through [`Rate`] like
1082 // any other source when the project is cut at another rate.
1083 let made_up = audio_only || crate::is_image(&first.path);
1084 let scaffold_rate = match made_up || native_fps == meta.frame_rate {
1085 true => Rate::REAL_TIME,
1086 false => Rate::from_fps(native_fps, meta.frame_rate)
1087 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
1088 };
1089 let first_audio = first_audio_of(&doc.sources)?;
1090
1091 // In source order, with the scaffold's own count in its own slot: the
1092 // clip check below indexes this list by source, so it must line up with
1093 // `doc.sources` whichever entry the scaffolding came from.
1094 let mut counts = Vec::with_capacity(doc.sources.len());
1095 // Beside it, one entry per source, grown at every `push` below: the
1096 // scaffold defines the rate, so it is read frame for frame; every other
1097 // one is however long it is *in this timeline's frames*, which is the
1098 // length `import` noted for it and the wall the clip check below holds
1099 // it to.
1100 let mut rates = Vec::with_capacity(doc.sources.len());
1101 for (i, source) in doc.sources.iter().enumerate() {
1102 if i == scaffold {
1103 counts.push(scaffold_rate.timeline_at(meta.frame_count));
1104 rates.push(scaffold_rate);
1105 continue;
1106 }
1107 // A still has neither a rate to match nor a track to match with:
1108 // its length is the one it is held to, recomputed exactly as the
1109 // import that first noted it did ([`image_frames`]), which is what
1110 // makes the clip check below meaningful on a reload.
1111 if crate::is_image(&source.path) {
1112 crate::decode::image_size(&source.path)
1113 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1114 counts.push(image_frames(meta.frame_rate));
1115 rates.push(Rate::REAL_TIME);
1116 continue;
1117 }
1118 // A source with no picture is checked on what it does have, and
1119 // its length is its playing time -- the same two answers `import`
1120 // gave it when it first joined the timeline.
1121 if crate::is_audio(&source.path) {
1122 audio_matches(source, &first_audio)
1123 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1124 counts.push(audio_frames(&source.path, meta.frame_rate)?);
1125 rates.push(Rate::REAL_TIME);
1126 continue;
1127 }
1128 let (other, _) = Demuxer::open(&source.path)
1129 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1130 let rate = matches_timeline(source, &other, &meta, &first_audio)
1131 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1132 counts.push(rate.timeline_at(other.frame_count));
1133 rates.push(rate);
1134 }
1135 // A still is silent, so a clip playing one on an audio lane is a
1136 // segment the audio worker would open a PNG for. Refused by name
1137 // here, which is the one door it can arrive through
1138 // (`place_stream_at` never puts one there). An audio file on a
1139 // *video* lane used to be refused the same way; it plays as a
1140 // waveform visualizer now ([`DecodeSession::open_visualizer`]).
1141 for (kind, clip) in doc
1142 .lanes
1143 .iter()
1144 .flat_map(|(kind, clips)| clips.iter().map(move |clip| (*kind, clip)))
1145 {
1146 let path = &doc.sources[clip.source].path;
1147 if kind == LaneKind::Audio && crate::is_image(path) {
1148 return Err(format!(
1149 "{} is a still image: it can only play on a video lane",
1150 path.display()
1151 )
1152 .into());
1153 }
1154 }
1155 for (i, clip) in doc.lanes.iter().flat_map(|(_, clips)| clips).enumerate() {
1156 if clip.out_frame > counts[clip.source] {
1157 return Err(format!(
1158 "clip {i} ends at frame {} but {} has {} frames",
1159 clip.out_frame,
1160 doc.sources[clip.source].path.display(),
1161 counts[clip.source]
1162 )
1163 .into());
1164 }
1165 }
1166
1167 let playhead = doc.playhead;
1168 // The subtitle files are read here rather than in the parser: a
1169 // `.edith` names them and holds no cues. One that has gone missing, or
1170 // whose track is a codec of pictures, comes back listed and refused by
1171 // name ([`crate::subtitle::open_all`]) -- a project does not stop
1172 // opening over a subtitle, and a re-save does not lose the row.
1173 //
1174 // All of them in one call, in saved order, because a file is walked
1175 // whole to reach one track: a film whose project names many of its
1176 // tracks is one walk here rather than one per row.
1177 let subtitles = crate::subtitle::open_all(&doc.subtitles);
1178 let project =
1179 Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)?
1180 .with_mix(&doc.gains, doc.limiter)
1181 .with_tone(doc.tone)
1182 // The palette before what is placed on it: a caption names a row of
1183 // it, and [`Project::with_subs`] refuses one naming a row that is
1184 // not there.
1185 .with_subtitles(subtitles)
1186 .with_subs(doc.subs)?;
1187 let span = project.composite_span_at(0);
1188 // Last, because it is the one thing here that cannot be taken back: the
1189 // feeder thread outlives the `Audio` value (it holds its own clones) and
1190 // only a session's `drop` retires it, so a refusal above this line would
1191 // leave a PipeWire stream and a thread behind for a project that never
1192 // opened. Nothing before it needs the device.
1193 //
1194 // On the source the timeline's *sound* is defined by, which is the
1195 // scaffold unless that one is a still ([`audio_source_of`]): opening a
1196 // PNG as the device is a session with no audio at all, however many
1197 // clips with sound are on its lanes.
1198 //
1199 // `audio_source_of` alone only rules out a still; it says nothing
1200 // about whether the file it lands on actually *has* a track. A device
1201 // pinned to the first candidate that opens silent (no track, or one
1202 // the decoder refuses) would leave every later clip's sound unheard
1203 // for the rest of the session, however many other sources on the
1204 // timeline have real audio -- so this walks forward past a silent
1205 // candidate to the first source that really opens a device, and keeps
1206 // only the last attempt's reason when none of them do (a later
1207 // source's silence is not worth reporting over an earlier one's).
1208 let (audio, audio_disabled) = {
1209 let mut opened = (None, None);
1210 for source in project.sources().iter().filter(|s| !crate::is_image(&s.path)) {
1211 opened = open_audio(&source.path, source.audio_stream);
1212 if opened.0.is_some() {
1213 break;
1214 }
1215 }
1216 opened
1217 };
1218 let mut session = Self {
1219 meta,
1220 content_light,
1221 native,
1222 native_fps,
1223 frames: stream.frames,
1224 worker: stream.worker,
1225 backend: stream.backend,
1226 retired: Vec::new(),
1227 restarts: 0,
1228 clock: PlaybackClock::new(match audio {
1229 Some(_) => ClockSource::Audio,
1230 None => ClockSource::Wall,
1231 }),
1232 audio,
1233 audio_disabled,
1234 project,
1235 counts,
1236 probes: std::collections::HashMap::new(),
1237 rates,
1238 span_rate: Rate::REAL_TIME,
1239 span,
1240 span_priming: true,
1241 dissolve: None,
1242 view: None,
1243 eos: false,
1244 mix: None,
1245 priming: false,
1246 drop_late: false,
1247 // What the file says, and `false` for every dialect before v12:
1248 // a project cut on the films themselves opens on them.
1249 proxies: doc.proxy,
1250 // ...and what it says about making them, which is "yes" for every
1251 // dialect before v13 and for one that leaves the line out.
1252 auto_proxies: doc.auto_proxy,
1253 // ...and which encoder it exports with, which is the seat this
1254 // machine has for every dialect before v14.
1255 encoder_seat: doc.encoder,
1256 sample_rate: doc.sample_rate,
1257 };
1258 // The scaffolding above opened source 0 from its first frame and the
1259 // whole of its audio; this puts both onto the clip the playhead is
1260 // actually in -- a seek replaces the decoder and supersedes the audio
1261 // worker by epoch, exactly as it does after an edit. It also clamps,
1262 // so a playhead past a hand-shortened timeline lands on the last frame.
1263 session.seek(f64::from(playhead) / meta.frame_rate);
1264 Ok(session)
1265 }
1266
1267 pub fn meta(&self) -> &VideoMeta {
1268 &self.meta
1269 }
1270
1271 /// What the pictures now arriving are being decoded by: the clip under the
1272 /// playhead, since one video worker feeds the composite at a time. An
1273 /// atomic load -- a front-end may ask it every repaint -- and it is what
1274 /// *opened*, so a clip whose hardware session fell back to software reads
1275 /// [`Backend::Software`] from the frame that fallback happened.
1276 pub fn decode_backend(&self) -> Backend {
1277 self.backend.get()
1278 }
1279
1280 /// What an export of this timeline would encode the *sound* with, before
1281 /// one is started: the copy an mp4 normally makes, or the software encoder
1282 /// the format (or an equalized lane) forces. Pure -- no probe, no file
1283 /// opened -- so a card may ask it per repaint; the picture's half costs a
1284 /// plugin open and lives in [`crate::export::planned_video`].
1285 pub fn planned_audio(&self, format: crate::export::Format, ranged: bool) -> &'static str {
1286 crate::export::planned_audio(&self.project, format, ranged)
1287 }
1288
1289 /// The timeline an export started right now would be run against, owned:
1290 /// what lets a front-end ask [`crate::export::planned_seats`] what that
1291 /// export would open *off* its render thread, which is the only way to ask
1292 /// a question that opens files. The very snapshot
1293 /// [`export_to_with`](Self::export_to_with) hands the worker, so the answer
1294 /// is about the export that would really start.
1295 pub fn export_snapshot(&self) -> (crate::project::Project, VideoMeta) {
1296 (self.project.export_snapshot(), self.meta)
1297 }
1298
1299 /// What an export would do about the tracks at `picks` --
1300 /// [`crate::export::planned_subtitles`], asked of the project a front-end is
1301 /// holding, and pure for the same reason. `picks` is any run of rows of
1302 /// [`subtitles`](Self::subtitles): the whole
1303 /// [`ExportSettings::subtitles`](crate::export::ExportSettings::subtitles)
1304 /// list a card is about to send (`picks.iter().copied()`) as much as a
1305 /// single `Some(row)`.
1306 pub fn planned_subtitles(
1307 &self,
1308 format: crate::export::Format,
1309 picks: impl IntoIterator<Item = usize>,
1310 ) -> String {
1311 crate::export::planned_subtitles(&self.project, format, picks)
1312 }
1313
1314 /// Where the cues of the track at `pick` land on *this* timeline --
1315 /// [`crate::export::timeline_cues`], the very map an export writes the file
1316 /// with, so a front-end that draws these draws what the file will say. On a
1317 /// rippled or cut timeline that is the whole point: an embedded track rides
1318 /// the spans that still play it, and a standalone `.srt` keeps the
1319 /// timeline's own clock, clipped to its length.
1320 ///
1321 /// Empty for a row that is not there and for a track that could not be read.
1322 /// Pure and file-free, so it may be asked per repaint; the cost is a walk of
1323 /// the spans and of the cues.
1324 pub fn timeline_cues(&self, pick: usize) -> Vec<crate::subtitle::Cue> {
1325 self.project
1326 .subtitles()
1327 .get(pick)
1328 .map_or_else(Vec::new, |t| {
1329 crate::export::timeline_cues(&self.project, t, self.meta.frame_rate)
1330 })
1331 }
1332
1333 /// Why the sound's rate is not a choice for this timeline in this format --
1334 /// [`crate::export::audio_rate_refusal`], asked of the project a front-end
1335 /// is holding, and pure for the same reason.
1336 pub fn audio_rate_refusal(
1337 &self,
1338 format: crate::export::Format,
1339 ranged: bool,
1340 ) -> Option<&'static str> {
1341 crate::export::audio_rate_refusal(&self.project, format, ranged)
1342 }
1343
1344 /// Why this session plays silent although the file has sound -- an audio
1345 /// track in a codec we cannot decode, or one the decoder refused. `None`
1346 /// when there is audio, and for a file that never had any. A front-end
1347 /// shows it once, at open: without it the whole thing is a stderr line.
1348 pub fn audio_disabled_reason(&self) -> Option<&str> {
1349 self.audio_disabled.as_deref()
1350 }
1351
1352 /// The files this timeline plays from, index 0 first -- a caller needs it
1353 /// to name an export or a window after the media rather than the project.
1354 pub fn sources(&self) -> &[Source] {
1355 self.project.sources()
1356 }
1357
1358 /// The subtitle tracks on this timeline, in the order they were added: what
1359 /// a front-end lists and what [`save_project`](Self::save_project) writes.
1360 /// A track that could not be read is *in* this list, saying why
1361 /// ([`crate::subtitle::SubtitleTrack::refused`]) -- listed and skipped, not
1362 /// dropped.
1363 pub fn subtitles(&self) -> &[crate::subtitle::SubtitleTrack] {
1364 self.project.subtitles()
1365 }
1366
1367 /// Adds subtitles from `path`: every subtitle track of a Matroska file, or
1368 /// the one track a standalone `.srt`/`.vtt`/`.ass` is. Hands back how many
1369 /// were added -- 0 for a file whose tracks are all on the timeline already,
1370 /// since importing the same file twice is the same subtitles.
1371 ///
1372 /// An error only when the file cannot be read *at all*; a track this cannot
1373 /// parse is added refused by name, for the reason
1374 /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves:
1375 /// subtitles are not clips and land on no lane.
1376 pub fn import_subtitles(&mut self, path: &Path) -> crate::Result<usize> {
1377 let tracks = Self::parse_subtitles(path)?;
1378 // A file that was walked and carries none is refused as *that*, because
1379 // the alternative -- 0 added -- is the very sentence a file whose tracks
1380 // are already on this timeline gets, and the two are opposite answers a
1381 // person acts differently on. Said only after the walk actually looked
1382 // ([`crate::subtitle::of_media`]); a *file* that is not a container at
1383 // all never reaches here, [`parse_subtitles`](Self::parse_subtitles)
1384 // refuses it in its own words.
1385 if tracks.is_empty() {
1386 return Err(Self::no_subtitles_in(path));
1387 }
1388 Ok(self.add_subtitle_tracks(tracks))
1389 }
1390
1391 /// The reading half of [`import_subtitles`](Self::import_subtitles), with no
1392 /// session in it: every subtitle track of a Matroska file, or the one track
1393 /// a standalone `.srt`/`.vtt`/`.ass` is, cues and all. Same refusal rule.
1394 ///
1395 /// This is the half that costs -- a walk of the whole container, measured at
1396 /// 210 ms on a 25 GB 35-track file and 1.3 s on a 3 GB one whose pages were
1397 /// cold -- so a front-end runs *this* on its background executor and hands
1398 /// what comes back to [`add_subtitle_tracks`](Self::add_subtitle_tracks),
1399 /// which costs a push. Both doors are this one function, so the import
1400 /// button and the background one cannot drift apart.
1401 pub fn parse_subtitles(path: &Path) -> crate::Result<Vec<crate::subtitle::SubtitleTrack>> {
1402 // The containers that carry subtitle tracks *inside* them: every
1403 // Matroska one ([`crate::demux::is_matroska`], which is where `.mks` --
1404 // the subtitles alone -- comes in) and the mp4 family, whose `tx3g`
1405 // timed text is what an mp4 export of this project's own writes, so a
1406 // file edith wrote is a file edith imports back.
1407 let tracks = match crate::demux::is_matroska(path)
1408 || path.extension().is_some_and(|e| {
1409 matches!(
1410 e.to_string_lossy().to_ascii_lowercase().as_str(),
1411 "mp4" | "m4v" | "mov"
1412 )
1413 }) {
1414 true => crate::subtitle::of_media(path)?,
1415 false => vec![crate::subtitle::open(path, None)],
1416 };
1417 // A standalone file that could not be parsed is a refusal here rather
1418 // than a row nobody asked for: the import is the moment to say so, and
1419 // the load is the moment to keep it.
1420 if let [one] = &tracks[..]
1421 && one.track.is_none()
1422 && let Some(why) = &one.refused
1423 {
1424 return Err(why.clone().into());
1425 }
1426 Ok(tracks)
1427 }
1428
1429 /// What a file the walk found no subtitle track in is refused with,
1430 /// wherever the refusal is worded: the engine's own door
1431 /// ([`import_subtitles`](Self::import_subtitles)) and a front-end that
1432 /// splits the walk from the push ([`parse_subtitles`](Self::parse_subtitles)
1433 /// then [`add_subtitle_tracks`](Self::add_subtitle_tracks)) must not tell a
1434 /// person two different stories about the same file.
1435 pub fn no_subtitles_in(path: &Path) -> crate::Error {
1436 format!("no subtitle tracks in {}", path.display()).into()
1437 }
1438
1439 /// Puts tracks already read by [`parse_subtitles`](Self::parse_subtitles)
1440 /// on this timeline, in the order given. Hands back how many actually went
1441 /// on: [`Project::add_subtitles`] drops the ones already here -- same file,
1442 /// same track number -- so 0 is "this file's subtitles are on the timeline
1443 /// already", which is the sentence a front-end says.
1444 ///
1445 /// The whole of what an import costs the thread that calls it, which is why
1446 /// the parse is a separate door: nothing here opens, seeks or decodes.
1447 /// Subtitles are not clips and land on no lane, so nothing playable changes
1448 /// and no undo step is pushed ([`Project::remove_subtitles`] says why).
1449 pub fn add_subtitle_tracks(&mut self, tracks: Vec<crate::subtitle::SubtitleTrack>) -> usize {
1450 tracks
1451 .into_iter()
1452 .filter(|t| self.project.add_subtitles(t))
1453 .count()
1454 }
1455
1456 /// Takes the track at `idx` off this timeline -- the door a subtitle row's
1457 /// own remove goes through, the way [`import_subtitles`](
1458 /// Self::import_subtitles) is the door that puts one on. Refused in
1459 /// [`Project::remove_subtitles`]'s words for a row this timeline does not
1460 /// have, and for one a caption on a subtitle lane still plays -- delete
1461 /// those placements first, or the words under them would change.
1462 ///
1463 /// Nothing playable changes and no worker was opened against a cue, so
1464 /// unlike [`remove_source`](Self::remove_source) this does not reseek. Rows
1465 /// past `idx` move down by one: a caller holding a picked row (the export's
1466 /// subtitle pick) has to fix it up or drop it; the placements on the lanes
1467 /// are walked down with it and need no fixing. Not an undo step, for the
1468 /// reason [`Project::remove_subtitles`] gives -- the way back is
1469 /// [`import_subtitles`](Self::import_subtitles), which reads a file's
1470 /// subtitles and touches nothing else on the timeline -- and it *empties*
1471 /// the undo history, because the steps in it name the tracks by the indexes
1472 /// this call just changed.
1473 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1474 self.project.remove_subtitles(idx)
1475 }
1476
1477 /// Writes the timeline to `path` as a `.edith`, atomically (see
1478 /// [`crate::edith`]). Sources no clip plays from are left out, and the
1479 /// playhead is saved with it so a reopened project resumes where it stood.
1480 ///
1481 /// Refused, writing nothing, for a session whose library is empty (every
1482 /// row removed, [`Project::remove_source`]): a file naming no source has no
1483 /// timeline in it and [`open_project`](Self::open_project) could only
1484 /// refuse it, so the refusal belongs here, where nothing has been
1485 /// overwritten yet.
1486 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
1487 if self.project.sources().is_empty() {
1488 return Err("this project names no file: there is nothing to save".into());
1489 }
1490 let (sources, lanes, eq, color, transform) = self.project.without_orphan_sources();
1491 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
1492 .min(self.project.timeline_frames().saturating_sub(1));
1493 crate::edith::save(
1494 path,
1495 &sources,
1496 &lanes,
1497 // The lane volumes and the limiter with them: a mix that vanished
1498 // on a reload would be a mix nobody could keep, and both are the
1499 // project's, not this machine's (the monitoring volume is not
1500 // written and never will be).
1501 &self.project.lane_gains(),
1502 // ...and what is placed on each lane, in the same order again: the
1503 // captions, which are the only thing a subtitle lane holds.
1504 &self.project.lane_subs(),
1505 // The subtitle tracks with them, by reference: which file the cues
1506 // are in, never the cues (see [`crate::edith`]).
1507 self.project.subtitles(),
1508 &eq,
1509 &color,
1510 &transform,
1511 (self.meta.width, self.meta.height),
1512 // ...and the rate it was cut at, which nothing else in the file
1513 // says: a timeline of stills and songs used to come back at
1514 // whatever its scaffold implied (`open_project`).
1515 Some(self.meta.frame_rate),
1516 // ...and which rendition its HDR media is watched in, for the same
1517 // reason: a picked look that vanished on a reload is a look nobody
1518 // could keep.
1519 self.project.tone(),
1520 // ...and whether it is cut on the stand-ins, for the same reason.
1521 // *Which* files have one is not saved: [`crate::proxy`] finds that
1522 // out from the film itself, so nothing here can go stale.
1523 self.proxies,
1524 // ...and whether it makes them by itself, which is a different
1525 // question from whether it cuts on them and the only one an import
1526 // asks ([`Self::auto_proxies`]).
1527 self.auto_proxies,
1528 // ...and which encoder an export of it opens, for the same reason:
1529 // a project delivered on the software encoder is delivered on it
1530 // again after a reload.
1531 self.encoder_seat,
1532 self.project.limiter(),
1533 // ...and the rate the mix was picked to run at, for the same
1534 // reason: a project delivered at a chosen rate is delivered at it
1535 // again after a reload.
1536 self.sample_rate,
1537 playhead,
1538 )
1539 }
1540
1541 /// The next decoded frame, its `index` rewritten from a source frame to a
1542 /// *timeline* frame -- the only frame space that leaves the engine, and the
1543 /// one [`PlaybackSession::now`] is in.
1544 ///
1545 /// `None` means "nothing right now": the decoder is behind, or a clip
1546 /// boundary is being reopened -- and *that* now happens entirely on the new
1547 /// worker ([`DecodeSession::open_worker_deferred`]), so it costs this
1548 /// thread a thread spawn and the caller simply keeps showing its last frame
1549 /// for however long the source takes to open (hundreds of milliseconds on a
1550 /// big film, seconds off a cold cache). End of stream is
1551 /// [`PlaybackSession::is_eos`].
1552 pub fn try_frame(&mut self) -> Option<Frame> {
1553 self.publish_playhead();
1554 loop {
1555 match self.frames.try_recv() {
1556 Ok(mut frame) => {
1557 // A gap's worker indexes from zero, a decoder's from its in
1558 // point, and the span itself knows which: [`Span::timeline_at`]
1559 // is the *stamp*, and it is the ceil half of the pair whose
1560 // floor half an export encodes with -- so the frame the pump
1561 // is holding at any timeline frame is the very frame the
1562 // export writes there, at every rate
1563 // (`speed_maps_both_ways`). An empty timeline has no span,
1564 // and its one black frame is frame 0. Real time is the
1565 // arithmetic this always did, frame for frame.
1566 // ...through the file's own rate first, which is the ceil
1567 // half of *that* pair: the picture at source frame `i` is
1568 // due at the first timeline-rate frame that shows it, and a
1569 // slower file's picture is therefore held for the frames in
1570 // between. Real time for a gap and for a single-rate
1571 // project, where this is the identity.
1572 frame.index = self.span.map_or(frame.index, |s| {
1573 s.timeline_at(self.span_rate.timeline_at(frame.index))
1574 });
1575 // The first picture out of the span now decoding ends its
1576 // prime ([`Self::span_priming`]).
1577 self.span_priming = false;
1578 // Inside the dissolve window this span's tail owes its
1579 // successor, if any: B's own decoder, graded and placed
1580 // exactly as an export would place it, blended over A's
1581 // already-converted picture -- the one blend point every
1582 // path to the screen goes through, playing or scrubbed,
1583 // since both drain this same channel one frame at a time.
1584 if self
1585 .dissolve
1586 .as_ref()
1587 .is_some_and(|d| frame.index >= d.tail_start)
1588 {
1589 self.open_dissolve_b();
1590 }
1591 if let Some(d) = self.dissolve.as_mut()
1592 && frame.index >= d.tail_start
1593 && let Some(b) = d.b.as_mut()
1594 {
1595 while let Ok(bf) = b.frames.try_recv() {
1596 b.held = Some(bf);
1597 }
1598 // The window's first tick, with B's decoder not yet
1599 // caught up: a paused or scrubbed preview gets no
1600 // later tick to correct itself on (nothing is due
1601 // while the clock is frozen -- `Player::pump`), so
1602 // this is the one chance to blend rather than show A
1603 // alone. Bounded so a source B cannot decode never
1604 // freezes the preview -- eager-opened in
1605 // `start_span`, B is normally already warm here and
1606 // this waits on nothing at all.
1607 if b.held.is_none() {
1608 b.held = b.frames.recv_timeout(DISSOLVE_B_TIMEOUT).ok();
1609 }
1610 if let Some(bf) = &b.held {
1611 let idx_in_window = (frame.index - d.tail_start).min(d.window - 1);
1612 let t = crate::export::dissolve_weight(idx_in_window, d.window);
1613 frame.bgra = blend_bgra(&frame.bgra, &bf.bgra, t);
1614 }
1615 }
1616 return Some(frame);
1617 }
1618 Err(TryRecvError::Empty) => return None,
1619 // The worker stopped: at the end of its range, or on a decode
1620 // error -- which is why this skips the rest of a broken clip
1621 // rather than stalling on it.
1622 Err(TryRecvError::Disconnected) => {
1623 if !self.next_clip() {
1624 self.eos = true;
1625 return None;
1626 }
1627 }
1628 }
1629 }
1630 }
1631
1632 /// Whether the timeline has been played out: the picture worker ran to the
1633 /// end and there was no next clip. It is exactly that and nothing more,
1634 /// which is what decides who clears it -- **starting a picture does**
1635 /// (`start_picture`), so a seek clears it and so does every edit that
1636 /// rebuilds the picture (`Dirty::Picture`, `Dirty::Both` -- a paste or a
1637 /// placement past the end revives the session, and it has a new picture to
1638 /// show for it).
1639 ///
1640 /// A **sound-only** edit does not (`Dirty::Sound`: an equalizer, a fader):
1641 /// it rebuilds the sound where the playhead stands and starts no picture
1642 /// worker, so the last frame is still the last frame and this is still the
1643 /// end. A front-end's `Ended` therefore survives an EQ tweak made after the
1644 /// timeline ran out -- the parameters are on the project either way, and the
1645 /// next press restarts from the top with them, which is what `Ended` means.
1646 pub fn is_eos(&self) -> bool {
1647 self.eos
1648 }
1649
1650 /// Tells the decode worker which frame of its *file* the clock has reached,
1651 /// so the pictures it is holding that are already behind the playhead are
1652 /// dropped where they are cheap to drop -- before the conversion and before
1653 /// the queue -- instead of being converted, queued and thrown away by the
1654 /// caller one repaint later. The whole of the late-frame policy: a decoder
1655 /// that has fallen behind catches up by not painting what nobody can see,
1656 /// rather than by being restarted every two seconds (`Player::pump`).
1657 ///
1658 /// The stamp is the exact inverse of the one [`try_frame`](Self::try_frame)
1659 /// puts on a decoded frame: timeline frame -> the clip's own frames
1660 /// ([`Span::speed`]) -> the file's ([`Rate`]). A gap and the emptied
1661 /// timeline have no file to be inside of, and publish nothing.
1662 fn publish_playhead(&self) {
1663 if !self.drop_late {
1664 return;
1665 }
1666 let Some(span) = self.span else { return };
1667 let Some((_, in_frame)) = span.from else {
1668 return;
1669 };
1670 let now = secs_to_frame(self.clock.now(), self.meta.frame_rate);
1671 let offset = now.saturating_sub(span.start).min(span.len);
1672 self.worker
1673 .playhead(self.span_rate.source_at(in_frame + span.speed.source_at(offset)));
1674 }
1675
1676 /// Installs `replacement` as the decode worker, parking the outgoing one in
1677 /// [`retired`](Self::retired) rather than joining it here, and reaping the
1678 /// parked ones that have already returned.
1679 ///
1680 /// The sweep is what bounds the list: every worker in it was cancelled
1681 /// before this ran, and a cancelled worker is out within an access unit
1682 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's
1683 /// worker on this seek and the list stays a handful long. Nothing waits.
1684 fn retire(&mut self, replacement: Worker) {
1685 // A *replacement*, which is now the narrow case: a seek onto the file
1686 // the worker already has open steers it instead ([`Worker::reseek`])
1687 // and never comes here, so this count is the picture restarts that
1688 // really cost a thread and a decoder open -- which is what makes it
1689 // worth counting.
1690 self.restarts += 1;
1691 let mut outgoing = std::mem::replace(&mut self.worker, replacement);
1692 // Terminal, unlike the [`Worker::abandon`] a seek does: this worker is
1693 // being replaced rather than steered, so its thread has to end -- and
1694 // the cancel is what drops its command channel, without which a worker
1695 // parked between spans would sit in `recv` forever, never reaped here
1696 // and never joined in any bounded time at exit.
1697 outgoing.cancel();
1698 self.retired.push(outgoing);
1699 self.retired.retain(|w| !w.is_finished());
1700 }
1701
1702 /// Picture restarts so far; see [`restarts`](Self::restarts). The one place
1703 /// a worker is ever replaced counts them, so a seek, a resync and a clip
1704 /// boundary all land here and a measurement need not guess which it saw.
1705 #[doc(hidden)]
1706 pub fn restarts(&self) -> u64 {
1707 self.restarts
1708 }
1709
1710 /// Whether the picture span now decoding has yet to hand over a frame:
1711 /// true from the moment a span is started -- a seek, a clip boundary, a
1712 /// picture restart -- until that span's first frame arrives. Whatever
1713 /// lateness that first frame carries is the span's own reopen, not a
1714 /// decoder falling behind, so a front-end gating its late-picture restart
1715 /// on this answers a prime with the decode already on its way rather than
1716 /// with another restart of it.
1717 pub fn picture_priming(&self) -> bool {
1718 self.span_priming
1719 }
1720
1721 /// Starved audio callbacks since the device opened, and how far into the
1722 /// device's own playback (seconds) the last of them was -- `None` for a
1723 /// session with no device at all. The counter the plugin prints on drop,
1724 /// readable while the session runs: read it either side of a seek and the
1725 /// difference is what that seek cost the ear.
1726 #[doc(hidden)]
1727 pub fn audio_underruns(&self) -> Option<(u64, Option<f64>)> {
1728 let audio = self.audio.as_ref()?;
1729 let (count, last) = audio.ao.lock().unwrap().underruns();
1730 Some((count, last.map(|p| p as f64 / f64::from(audio.sample_rate))))
1731 }
1732
1733 /// How many threads this session still has running of its own: the decode
1734 /// worker, every retired one that has not returned yet, and the audio
1735 /// feeders still in the air. One for a session playing along quietly.
1736 ///
1737 /// The oracle a seek storm is judged by. `/proc/self/status` counts the
1738 /// *process*, and a suite decoding twenty files at once moves that number
1739 /// under a test that never touched them -- this counts only what the
1740 /// session in hand owns, so it says the same thing alone and in a crowd.
1741 #[doc(hidden)]
1742 pub fn live_workers(&self) -> usize {
1743 usize::from(!self.worker.is_finished())
1744 + self.retired.iter().filter(|w| !w.is_finished()).count()
1745 + self.audio.as_ref().map_or(0, Audio::live_feeders)
1746 }
1747
1748 /// Starts feeding whatever follows the current span on the timeline --
1749 /// another clip, or a gap, which is black frames from a worker that opens no
1750 /// file. `false` past the end. The next timeline frame is derived rather
1751 /// than remembered as a clip index, because a `split` while playing cuts the
1752 /// clip under the running worker and only the mapping stays true.
1753 fn next_clip(&mut self) -> bool {
1754 // No span is the emptied timeline: it was played out the moment its one
1755 // black frame went by, and there is no "next" to walk to.
1756 let next = match self.span {
1757 Some(span) => span.end(),
1758 None => return false,
1759 };
1760 let Some(span) = self.project.composite_span_at(next) else {
1761 return false;
1762 };
1763 // We only get here on a disconnect, so the old span is already done;
1764 // abandon anyway, so `start_span` treats every path alike -- and the
1765 // *worker* is kept, because the next clip is very often the same file
1766 // (a split cuts one clip in two) and it already has it open.
1767 self.worker.abandon();
1768 self.start_span(Some(span));
1769 true
1770 }
1771
1772 /// Points the video worker at `span`: a decoder over its source range, or a
1773 /// black-frame generator for a gap -- and for `None`, the emptied timeline,
1774 /// which is one frame of black so the viewer shows the nothing that is
1775 /// there rather than the last picture of the clip that was deleted. The old
1776 /// worker must already have been cancelled -- this is the half both `seek`
1777 /// and `next_clip` share.
1778 ///
1779 /// A source that will not open leaves the *span* installed anyway: the
1780 /// timeline still moves, there are simply no more pictures, and the
1781 /// disconnected receiver carries the session on to the next span. For a
1782 /// video that is now the worker's own doing -- it opens the file, so it is
1783 /// the one that finds out -- and nothing on this thread waits to hear it.
1784 fn start_span(&mut self, span: Option<Span>) {
1785 // The viewer's own size, once one has said it ([`Self::set_view_size`]):
1786 // every picture below is painted at *this*, and the project's
1787 // resolution otherwise.
1788 let (canvas_w, canvas_h) = self.view_size();
1789 // The outgoing span's own dissolve, if it ever opened B's decoder:
1790 // that decoder's pictures were for a window this span is leaving
1791 // (played through, paused before, or seeked away from), and never
1792 // for the one about to start -- parked in `retired` exactly like the
1793 // picture worker below, so joining it costs this thread nothing.
1794 if let Some(Dissolve { b: Some(b), .. }) = self.dissolve.take() {
1795 let mut worker = b.worker;
1796 worker.cancel();
1797 self.retired.push(worker);
1798 self.retired.retain(|w| !w.is_finished());
1799 }
1800 // What the *new* span's own tail owes its successor -- checked here,
1801 // once, rather than every tick: adjacency can only change on an edit,
1802 // and every edit that could touches this span starts it over
1803 // ([`crate::export::dissolve_window`] makes the identical check for
1804 // the same reason, on export).
1805 self.dissolve = span.and_then(|s| {
1806 crate::export::dissolve_window(&self.project, &s).map(
1807 |(b_source, b_in_frame, window, b_start)| Dissolve {
1808 tail_start: s.start + s.len - window,
1809 window,
1810 b_source,
1811 b_in_frame,
1812 b_start,
1813 b: None,
1814 },
1815 )
1816 });
1817 // B's decoder opens now, at the start of the *span*, rather than
1818 // waiting for the playhead to reach the window: the window is about a
1819 // second, which is exactly the head start a decoder open (VA-API
1820 // init measured 98ms worst case) needs to have a first picture ready
1821 // by the time playback -- or a seek straight into the window -- asks
1822 // for one. Without this a paused seek into the window met a `held`
1823 // that was still `None` and nothing ever asked again
1824 // (`try_frame`'s bounded wait below is the last-resort backstop for a
1825 // seek that lands inside the window before this head start pays off).
1826 if self.dissolve.is_some() {
1827 self.open_dissolve_b();
1828 }
1829 // Which file's frames the worker about to be opened will number its
1830 // pictures in: the span's own source, and real time for a gap, whose
1831 // black worker counts timeline frames already. Set before the open,
1832 // because the open is the first thing that converts with it.
1833 self.span_rate = match span.and_then(|s| s.from) {
1834 Some((source, _)) => self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME),
1835 None => Rate::REAL_TIME,
1836 };
1837 // The new span owes its first picture from the moment it is asked for:
1838 // every path below, the reused worker as much as a fresh one
1839 // ([`Self::span_priming`]).
1840 self.span_priming = true;
1841 let opened = match span {
1842 // The grade is the composite's at this frame -- the same clip the
1843 // span itself came from -- and it is constant across the span, so
1844 // the worker carries it and every frame it converts wears it.
1845 Some(Span {
1846 start,
1847 from: Some((source, in_frame)),
1848 ..
1849 }) if crate::is_image(&self.project.sources()[source].path) => {
1850 // A still: the same grade and the same canvas as any other
1851 // clip, over a picture decoded once and repeated for the span.
1852 // As many pictures as the span reads *source* frames, so a still
1853 // is numbered like a decoder's output and a speed reaches it
1854 // through the same rewrite (`try_frame`) as any other clip.
1855 DecodeSession::open_still(
1856 &self.project.sources()[source].path,
1857 in_frame,
1858 span.expect("matched above").source_len(),
1859 self.project
1860 .composite_color_at(start)
1861 .copied()
1862 .unwrap_or_default(),
1863 self.project
1864 .composite_transform_at(start)
1865 .copied()
1866 .unwrap_or_default(),
1867 Composer::new(
1868 canvas_w,
1869 canvas_h,
1870 self.project.composite_fit_at(start),
1871 ),
1872 )
1873 .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}"))
1874 }
1875 Some(Span {
1876 start,
1877 from: Some((source, in_frame)),
1878 ..
1879 }) if crate::is_audio(&self.project.sources()[source].path)
1880 || self.project.composite_visualizer_at(start) & 1 != 0 =>
1881 {
1882 let (path, stream) = {
1883 let src = &self.project.sources()[source];
1884 (src.path.clone(), src.audio_stream)
1885 };
1886 DecodeSession::open_visualizer(
1887 &path,
1888 stream,
1889 in_frame,
1890 span.expect("matched above").source_len(),
1891 self.meta.frame_rate,
1892 self.project
1893 .composite_color_at(start)
1894 .copied()
1895 .unwrap_or_default(),
1896 self.project
1897 .composite_transform_at(start)
1898 .copied()
1899 .unwrap_or_default(),
1900 Composer::new(
1901 canvas_w,
1902 canvas_h,
1903 self.project.composite_fit_at(start),
1904 ),
1905 self.project.composite_visualizer_at(start),
1906 self.project.composite_viz_paint_at(start),
1907 )
1908 .inspect_err(|e| {
1909 eprintln!("timeline frame {start}: visualizer open failed: {e}")
1910 })
1911 }
1912 Some(Span {
1913 start,
1914 from: Some((source, in_frame)),
1915 speed,
1916 ..
1917 }) => {
1918 // The stand-in where there is one and the switch is on, the
1919 // film itself otherwise -- the one place the picture's file is
1920 // decided ([`Self::picture_path`]). The sound is opened
1921 // elsewhere and is always the film's.
1922 //
1923 // It decides for the reuse door below as well, and that is what
1924 // makes the switch flippable while watching: a worker holding
1925 // the film is asked for a span of the stand-in, declines on the
1926 // path it already has ([`Worker::reseek`]), and the seek
1927 // [`Self::set_proxies`] does becomes a respawn on the other
1928 // file. Asking the *project* here instead would have left every
1929 // proxied span opening a worker from scratch.
1930 let path = self.picture_path(source);
1931 // The file's own frames, which is the only place they exist: a
1932 // clip counts the timeline's ([`Rate`]).
1933 let start_frame = self.span_rate.source_at(in_frame);
1934 // Source frames, which a speed makes more (or fewer) than the
1935 // timeline frames the span covers -- and which a file shot at
1936 // another rate makes fewer (or more) again. One past the last
1937 // frame this span shows, not one past its length: at another
1938 // rate those are two different frames.
1939 let end_frame = self.span_rate.source_at(
1940 in_frame + span.expect("matched above").source_len().saturating_sub(1),
1941 ) + 1;
1942 let color = self
1943 .project
1944 .composite_color_at(start)
1945 .copied()
1946 .unwrap_or_default();
1947 let transform = self
1948 .project
1949 .composite_transform_at(start)
1950 .copied()
1951 .unwrap_or_default();
1952 // ...and the canvas it is placed on: the project's resolution
1953 // and this clip's own fit policy, constant across the span for
1954 // the reason the grade is. Built where it is handed over rather
1955 // than kept in a local, because a `Composer` owns the scratch
1956 // buffers it places through -- the value is not copied about.
1957 let fit = self.project.composite_fit_at(start);
1958 let canvas = || Composer::new(canvas_w, canvas_h, fit);
1959 // ...and the rendition an HDR source among them is mapped to,
1960 // the project's own and constant across the span for that
1961 // reason too.
1962 let tone = self.project.tone();
1963 // At faster than real time several source frames decode to the
1964 // same timeline frame ([`Speed::timeline_at`]) and only the last
1965 // of a run is ever shown; the worker skips converting the rest
1966 // ([`crate::decode::skip_for_speed`]) rather than paying a full
1967 // colour convert and scale for a picture nothing displays.
1968 //
1969 // corner-cut: correct only when this file plays at the
1970 // timeline's own rate -- `skip_for_speed`'s own math is in the
1971 // file's frame numbers, which a `Rate` conversion would make a
1972 // different sequence than the timeline's. `Speed::NORMAL` (never
1973 // skip) covers that rarer case exactly as every frame was
1974 // delivered before this.
1975 let decode_speed = if self.span_rate.is_real_time() {
1976 speed
1977 } else {
1978 Speed::NORMAL
1979 };
1980 // The worker already decoding this very file takes the new span
1981 // itself: no thread, no container parse, no VA-API init -- the
1982 // whole of what a seek used to cost. It answers `None` for any
1983 // other file (and for a worker whose thread has ended), and the
1984 // deferred opener below is then exactly the path it always was.
1985 if let Some((frames, backend)) = self.worker.reseek(
1986 &path,
1987 start_frame,
1988 end_frame,
1989 color,
1990 transform,
1991 canvas(),
1992 tone,
1993 decode_speed,
1994 ) {
1995 self.frames = frames;
1996 self.backend = backend;
1997 self.span = span;
1998 return;
1999 }
2000 Ok(DecodeSession::open_worker_deferred(
2001 &path,
2002 start_frame,
2003 end_frame,
2004 color,
2005 transform,
2006 canvas(),
2007 tone,
2008 decode_speed,
2009 ))
2010 }
2011 // A gap: black for as long as it runs. An emptied timeline has no
2012 // span at all and gets one frame of it -- enough to put black on
2013 // screen, and it ends where the timeline does, at once.
2014 gap => Ok(DecodeSession::open_black(
2015 canvas_w,
2016 canvas_h,
2017 gap.map_or(1, |s| s.len),
2018 )),
2019 };
2020 let Ok(stream) = opened else {
2021 // The file would not open. The span still goes in -- the timeline
2022 // moves on, there are simply no more pictures -- but the *frames*
2023 // must not: the old channel's pictures are numbered in the old
2024 // source's frames, and presenting them under the new mapping would
2025 // put the wrong picture at the wrong time (and leave
2026 // [`decode_backend`](Self::decode_backend) describing a worker that
2027 // is no longer feeding anything). A dead receiver instead, which is
2028 // what carries the session on to the next span. The old worker stays
2029 // parked in `self.worker`, where the caller has already abandoned
2030 // the span it was decoding ([`Worker::abandon`]) without ending the
2031 // thread; the next span reseeks it or retires it.
2032 self.frames = std::sync::mpsc::channel().1;
2033 self.backend = BackendCell::new(Backend::Gap);
2034 self.span = span;
2035 return;
2036 };
2037 // Receiver first, worker second: the drop of the *old* receiver is
2038 // what wakes the outgoing worker if it is parked in `send`, and only
2039 // then can it return and be reaped by a later sweep. Nothing here
2040 // joins, so this ordering costs the seek nothing.
2041 self.frames = stream.frames;
2042 self.backend = stream.backend;
2043 self.retire(stream.worker);
2044 self.span = span;
2045 }
2046
2047 /// Opens B's own decoder for the current span's dissolve, the first time
2048 /// [`try_frame`](Self::try_frame) sees the playhead inside the window --
2049 /// a no-op once it is already open, or if this span has no dissolve at
2050 /// all. Everything [`start_span`](Self::start_span) works out for A's own
2051 /// decoder, worked out again for B: the stand-in switch
2052 /// ([`Self::picture_path`]), the file's own frame numbering
2053 /// ([`Self::rates`]), and B's *own* grade and fit, asked at B's own start
2054 /// on the timeline rather than at the position the blend writes to
2055 /// (still inside A's span) -- the same asymmetry
2056 /// [`crate::export`]'s own `Dissolve` is built with.
2057 fn open_dissolve_b(&mut self) {
2058 let (canvas_w, canvas_h) = self.view_size();
2059 let Some(d) = &self.dissolve else { return };
2060 if d.b.is_some() {
2061 return;
2062 }
2063 let (source, in_frame, window, b_start) = (d.b_source, d.b_in_frame, d.window, d.b_start);
2064 let path = self.picture_path(source);
2065 let rate = self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME);
2066 let start_frame = rate.source_at(in_frame);
2067 let end_frame = rate.source_at(in_frame + window);
2068 let color = self
2069 .project
2070 .composite_color_at(b_start)
2071 .copied()
2072 .unwrap_or_default();
2073 let transform = self
2074 .project
2075 .composite_transform_at(b_start)
2076 .copied()
2077 .unwrap_or_default();
2078 let canvas = Composer::new(
2079 canvas_w,
2080 canvas_h,
2081 self.project.composite_fit_at(b_start),
2082 );
2083 let tone = self.project.tone();
2084 let stream = DecodeSession::open_worker_deferred(
2085 &path,
2086 start_frame,
2087 end_frame,
2088 color,
2089 transform,
2090 canvas,
2091 tone,
2092 Speed::NORMAL,
2093 );
2094 if let Some(d) = self.dissolve.as_mut() {
2095 d.b = Some(DissolveB {
2096 frames: stream.frames,
2097 worker: stream.worker,
2098 held: None,
2099 });
2100 }
2101 }
2102
2103 /// Length of the edited timeline in seconds -- what a ruler shows, and it
2104 /// shrinks with every delete.
2105 pub fn timeline_duration(&self) -> f64 {
2106 f64::from(self.project.timeline_frames()) / self.meta.frame_rate
2107 }
2108
2109 /// Whether no lane holds anything: the emptied timeline, which plays black
2110 /// and silent and is zero seconds long. A state, not a failure -- but the
2111 /// one a caller with nothing to render (an export) has to refuse by name
2112 /// rather than write a file of no frames.
2113 pub fn is_empty(&self) -> bool {
2114 self.project.timeline_frames() == 0
2115 }
2116
2117 /// `(start, len)` per clip in timeline seconds, in order: what a clips lane
2118 /// needs to lay itself out. Selection is the caller's business.
2119 pub fn clip_spans(&self) -> Vec<(f64, f64)> {
2120 let fps = self.meta.frame_rate;
2121 self.project
2122 .clip_spans()
2123 .iter()
2124 .map(|&(start, len)| (f64::from(start) / fps, f64::from(len) / fps))
2125 .collect()
2126 }
2127
2128 /// [`clip_spans`](Self::clip_spans) plus the index into
2129 /// [`Project::sources`] each clip plays from -- what a lane needs to colour
2130 /// an imported clip differently from the file the session was opened with.
2131 pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> {
2132 self.lane_spans_by_source(Lane::V1)
2133 }
2134
2135 /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane,
2136 /// with each clip's group id -- what a two-lane front-end draws. The holes
2137 /// between consecutive entries are the gaps.
2138 pub fn lane_spans_by_source(&self, lane: Lane) -> Vec<(f64, f64, usize)> {
2139 let fps = self.meta.frame_rate;
2140 self.project
2141 .lane(lane)
2142 .iter()
2143 .map(|c| (f64::from(c.start) / fps, f64::from(c.len()) / fps, c.source))
2144 .collect()
2145 }
2146
2147 /// Every placement of one lane, in timeline order. What a two-lane
2148 /// front-end draws and nothing
2149 /// [`lane_spans_by_source`](Self::lane_spans_by_source) can answer: a clip
2150 /// carries its group id (which halves a click marks together) and its
2151 /// source range (where a waveform reads its peaks from) as well as its
2152 /// span. The holes between consecutive clips are the gaps.
2153 pub fn lane_clips(&self, lane: Lane) -> &[Clip] {
2154 self.project.lane(lane)
2155 }
2156
2157 /// The empty stretch of `lane` covering `frame`, or `None` when `frame`
2158 /// is inside a clip/caption placement or past the last one
2159 /// ([`Project::gap_at`]). What a right-click on empty bench space asks
2160 /// before offering to close it.
2161 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
2162 self.project.gap_at(lane, frame)
2163 }
2164
2165 /// How many bounded gaps that same right-click lane holds. The tail after
2166 /// the last placement is not counted, because nothing would ripple there.
2167 pub fn gap_count(&self, lane: Lane) -> usize {
2168 self.project.gap_count(lane)
2169 }
2170
2171 /// Every lane's handle, in display order -- what a front-end lays out top to
2172 /// bottom, and the list [`add_lane`](Self::add_lane) grows.
2173 pub fn lanes(&self) -> Vec<Lane> {
2174 self.project.lanes()
2175 }
2176
2177 /// Appends an empty lane and hands back its handle. One undo step
2178 /// ([`Project::add_lane`]), and no reseek: an empty lane changes nothing
2179 /// that plays until something is placed on it.
2180 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
2181 self.project.add_lane(kind)
2182 }
2183
2184 /// Drops that empty lane again, in [`Project::remove_lane`]'s words when it
2185 /// refuses. One undo step, and no reseek for the same reason the add needs
2186 /// none: an empty lane was playing nothing.
2187 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
2188 self.project.remove_lane(lane)
2189 }
2190
2191 /// Moves a whole track to display position `to`, clips and all
2192 /// ([`Project::move_lane`]), and hands back the handle it answers to
2193 /// afterwards -- `None` when nothing moved. One undo step.
2194 ///
2195 /// A *video* track that moves rebuilds the picture where the playhead
2196 /// stands, because display order is the stack and the frame on screen may
2197 /// be another lane's from here on; the sound plays on through it, untouched
2198 /// -- a mix is a sum, and a lane's gain travelled with it.
2199 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
2200 let moved = self.project.move_lane(lane, to)?;
2201 if lane.kind == LaneKind::Video {
2202 self.invalidate(Dirty::Picture);
2203 }
2204 Some(moved)
2205 }
2206
2207 /// The subtitle lanes in display order -- `S1..Sn`, the rows a front-end
2208 /// lays out beside the picture and sound ones
2209 /// ([`Project::subtitle_lanes`]). Empty until something adds one, which is
2210 /// [`add_lane`](Self::add_lane) with [`LaneKind::Subtitle`], and they come
2211 /// off, move and reorder through the very same doors every other lane does.
2212 pub fn subtitle_lanes(&self) -> Vec<Lane> {
2213 self.project.subtitle_lanes()
2214 }
2215
2216 /// What is placed on one subtitle lane, in timeline order: what a front-end
2217 /// draws as clips, each naming the palette row it plays
2218 /// ([`Self::subtitles`]) and the window of it it keeps
2219 /// ([`Project::sub_lane`]).
2220 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
2221 self.project.sub_lane(lane)
2222 }
2223
2224 /// Places a stretch of a subtitle track on `lane` at timeline frame `at`
2225 /// ([`Project::place_sub`], whose words a refusal is shown in). One undo
2226 /// step.
2227 ///
2228 /// No reseek and no invalidation, which is what the whole wrapper layer is
2229 /// here for: cues are drawn from [`sub_lane_cues`](Self::sub_lane_cues)
2230 /// over whatever picture is on screen, so nothing already decoded stops
2231 /// being right.
2232 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
2233 self.project.place_sub(lane, at, sub)
2234 }
2235
2236 /// Drags a placement to another subtitle lane or another frame
2237 /// ([`Project::move_sub`]). One undo step, and `Ok` with none for a drop
2238 /// that changed nothing. A caption in a group drags the group's clips with
2239 /// it -- a mapping change -- so this reseeks like a clip's drag does; a
2240 /// caption in no group moves nothing that plays and disturbs nothing.
2241 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
2242 let grouped = self.caption_grouped_with_clips(from, idx);
2243 let moved = self.project.move_sub(from, idx, to, start);
2244 if moved.is_ok() && grouped {
2245 self.invalidate(Dirty::Both);
2246 }
2247 moved
2248 }
2249
2250 /// Drags one edge of a placement to timeline frame `to`
2251 /// ([`Project::trim_sub`]), **at this timeline's own frame rate** -- a
2252 /// placement's position is in frames while its words are in microseconds,
2253 /// and the rate that joins them is the one thing a [`Project`] does not
2254 /// know. That is why a front-end trims through this door and never converts
2255 /// a cue's microseconds itself. One undo step. A caption in a group trims
2256 /// the group's clips with it, and that half reseeked; a lone caption's trim
2257 /// changes only the words, which are drawn over whatever is decoded.
2258 pub fn trim_sub(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> crate::Result<()> {
2259 let grouped = self.caption_grouped_with_clips(lane, idx);
2260 let trimmed = self.project.trim_sub(lane, idx, edge, to, self.meta.frame_rate);
2261 if trimmed.is_ok() && grouped {
2262 self.invalidate(Dirty::Both);
2263 }
2264 trimmed
2265 }
2266
2267 /// How far that edge may travel, `(first, last)` timeline frame inclusive
2268 /// ([`Project::trim_sub_room`]) -- what a front-end drawing the box during
2269 /// a drag asks, at this timeline's rate.
2270 pub fn trim_sub_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
2271 self.project.trim_sub_room(lane, idx, edge, self.meta.frame_rate)
2272 }
2273
2274 /// Takes one placement off a subtitle lane, leaving a gap
2275 /// ([`Project::lift_sub`]). One undo step; the palette row it played stays
2276 /// on this timeline's list.
2277 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
2278 self.project.lift_sub(lane, idx)
2279 }
2280
2281 /// What that subtitle lane shows on *this* timeline, in start order
2282 /// ([`Project::sub_lane_cues`] at this timeline's rate) -- the placed-clip
2283 /// counterpart of [`timeline_cues`](Self::timeline_cues), which carries a
2284 /// whole palette track through the spans that play its media. Pure, so a
2285 /// front-end may ask it per repaint.
2286 pub fn sub_lane_cues(&self, lane: Lane) -> Vec<crate::subtitle::Cue> {
2287 self.project.sub_lane_cues(lane, self.meta.frame_rate)
2288 }
2289
2290 /// Splits every lane at `timeline_secs`, so the two sides become two
2291 /// groups. Metadata only: a split never changes the timeline->source
2292 /// mapping, so the running decoder stays correct and playback does not
2293 /// blink. `false` at a clip start, in a gap and past the end, where there
2294 /// would be nothing to split off.
2295 pub fn cut_at(&mut self, timeline_secs: f64) -> bool {
2296 self.project
2297 .split(secs_to_frame(timeline_secs, self.meta.frame_rate))
2298 }
2299
2300 /// The inverse of [`cut_at`](Self::cut_at): rejoins the clips that meet at
2301 /// `timeline_secs` in every lane and puts them back in one group. `false`
2302 /// unless a split could have produced what is there. Metadata only, like the
2303 /// split -- no reseek.
2304 pub fn regroup_at(&mut self, timeline_secs: f64) -> bool {
2305 self.project
2306 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))
2307 }
2308
2309 /// Takes that clip out of its group, so its picture and its sound are edited
2310 /// apart from here on. Metadata only like a cut -- no reseek -- and one undo
2311 /// step. `false` for a bad index and for a clip that is not grouped with
2312 /// anything, which is already detached.
2313 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
2314 self.project.ungroup(lane, idx)
2315 }
2316
2317 /// Puts two clips covering the same frames back into one group: the regroup
2318 /// of what [`ungroup`](Self::ungroup) took apart. Metadata only, one undo
2319 /// step, and the error says why when it refuses.
2320 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
2321 self.project.group(a, a_idx, b, b_idx)
2322 }
2323
2324 /// Puts every placement the picks name into one group
2325 /// ([`Project::group_all`]) -- the ctrl-click selection's own door, which
2326 /// may name clips and captions alike. Metadata only like the pair above:
2327 /// no reseek, one undo step, and the error says why when it refuses.
2328 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
2329 self.project.group_all(picks)
2330 }
2331
2332 /// [`delete_clip`](Self::delete_clip) for the caption the pick named: a
2333 /// caption in no group lifts exactly as [`lift_sub`](Self::lift_sub) lifts
2334 /// it -- no reseek, because nothing that plays has changed -- and a caption
2335 /// in a group takes the group with it, which ripples every member's own
2336 /// lane and reseeks like a delete. `false` for a bad index.
2337 pub fn delete_sub(&mut self, lane: Lane, idx: usize) -> bool {
2338 // Which of the two, asked before anything moves: the reseek a grouped
2339 // delete owes is the whole difference between the paths. A group of
2340 // captions alone (no clip on another lane) still ripples every
2341 // member's *own* sub lane closed (`Project::delete_sub_in`, since
2342 // cdc53a6), and a sub lane counts toward `timeline_frames` exactly
2343 // like a clip lane does -- so the timeline can shrink out from under
2344 // the playhead from a caption-only group too, not only a media one.
2345 // `caption_grouped_with_clips` answers a narrower question than the
2346 // one this dispatch needs; a caption carries a link at all only once
2347 // grouped (`place_sub` always starts one at `None`), so that alone is
2348 // "this delete ripples more than its own lane".
2349 match self.sub_lane(lane).get(idx).is_some_and(|s| s.link.is_some()) {
2350 true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)),
2351 // A caption in no group is the plain lift that touches nothing
2352 // else: no reseek owed.
2353 false => self.project.delete_sub_in(lane, idx),
2354 }
2355 }
2356
2357 /// Whether the caption at `idx` of `lane` is grouped with clips on other
2358 /// lanes: the one question every caption edit that can move media has to
2359 /// ask first, because the answer is whether the edit owes a reseek -- and
2360 /// the front-end owes the same answer, asked before the edit moves the
2361 /// indices, so its flag reset matches the engine's reseek exactly.
2362 pub fn caption_grouped_with_clips(&self, lane: Lane, idx: usize) -> bool {
2363 self.project
2364 .sub_lane(lane)
2365 .get(idx)
2366 .and_then(|s| s.link)
2367 .is_some_and(|id| {
2368 self.project
2369 .lanes()
2370 .into_iter()
2371 .any(|l| l != lane && self.project.lane(l).iter().any(|c| c.link == Some(id)))
2372 })
2373 }
2374
2375 /// What the clip at `idx` of `lane` is equalized with, or `None` for one
2376 /// that plays flat -- what a card shows before it lets anyone drag a band.
2377 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
2378 self.project.eq_of(lane, idx)
2379 }
2380
2381 /// Gives that clip an equalizer, or takes it off with `None`. One undo step,
2382 /// like every other edit -- and it rebuilds the **sound** where the playhead
2383 /// is, so a band changed during playback is heard from the next chunk on
2384 /// rather than at the next play. The picture is not touched: the video
2385 /// worker keeps decoding through it ([`Dirty`]). `false` for a bad index or
2386 /// a non-finite band, and nothing changes.
2387 ///
2388 /// corner-cut: the audio rebuild is what makes it live, so the cost of a
2389 /// change is a decoder restart -- inaudible at a drag's end, but too much to
2390 /// call once per pointer sample (a caller commits one change per gesture).
2391 /// Upgrade path is the per-segment twin of [`crate::audio::MixControls`],
2392 /// which the lane worker would poll per chunk the way the mixer polls the
2393 /// gains.
2394 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
2395 self.edit(Dirty::Sound, |p| p.set_eq(lane, idx, params))
2396 }
2397
2398 /// How loud that lane plays, in dB -- everything on it, every frequency of
2399 /// it. See [`Project::lane_gain_db`] for what it is *not*.
2400 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
2401 self.project.lane_gain_db(lane)
2402 }
2403
2404 /// Sets it. One undo step -- and **nothing is rebuilt**: a lane's volume
2405 /// lives at the sum, so the running mixer is handed the new number and
2406 /// picks it up at its next block ([`crate::audio::MixControls`]). A fader
2407 /// held down under an arrow key therefore moves the level and nothing else:
2408 /// no flush, no decoder restart, no hole in the sound and no blink in the
2409 /// picture.
2410 ///
2411 /// The one exception is the timeline that is not mixed at all -- a single
2412 /// audio lane at unity with the limiter off, which plays through the
2413 /// bit-exact single-stream path and has no mixer to talk to. Moving *that*
2414 /// off unity opens one, once; every move after it is live.
2415 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
2416 if !self.project.set_lane_gain_db(lane, db) {
2417 return false;
2418 }
2419 self.push_mix();
2420 true
2421 }
2422
2423 /// Hands the mix the running mixer is reading its new settings -- the whole
2424 /// of what a fader and a ceiling cost. With no mixer listening (the
2425 /// single-lane flat path, and a session with no sound at all) the sound is
2426 /// rebuilt instead, which is what opens one.
2427 fn push_mix(&mut self) {
2428 let gains = self.project.audio_gains();
2429 let limiter = self.project.limiter();
2430 // A mixer reading these, or an open on its way to being one: either way
2431 // the number is heard without a rebuild, and *that* is what a handle
2432 // left over from an open that found nothing cannot do
2433 // ([`crate::audio::MixControls::is_reachable`]).
2434 if let Some(mix) = self.mix.as_ref().filter(|mix| mix.is_reachable()) {
2435 mix.set(gains, limiter);
2436 return;
2437 }
2438 // Nothing to hand it to. Only a setting that *needs* a mixer is worth
2439 // the flush and the re-open: a ceiling dragged with the limiter off, or
2440 // a fader put back to unity, changes not one sample of the flat
2441 // single-stream path the timeline is already playing
2442 // ([`AudioSession::is_mixed`]), and reseeking per nudge was a hole in
2443 // the sound for a change nobody could hear.
2444 if crate::audio::AudioSession::is_mixed(gains.len(), &gains, limiter) {
2445 self.reseek_audio();
2446 }
2447 }
2448
2449 /// The master limiter the whole mix is summed through.
2450 pub fn limiter(&self) -> crate::limiter::Limiter {
2451 self.project.limiter()
2452 }
2453
2454 /// Sets it, live like a lane volume and for the same reason -- the ceiling
2455 /// a person is dragging has to be the ceiling they are hearing. Nothing is
2456 /// rebuilt: the running limiter is *retuned* between two blocks
2457 /// ([`crate::limiter::LimiterState::retune`]), so its delay line keeps
2458 /// running and the sample count the master clock is made of does not move.
2459 ///
2460 /// corner-cut: not an undo step, and deliberately -- [`Project::undo`]
2461 /// restores the lane list, and the limiter is not in it, so snapshotting
2462 /// here would push a step whose undo changes nothing a person can see or
2463 /// hear (the twin [`set_lane_gain_db`](Self::set_lane_gain_db) *is*
2464 /// undoable only because a lane volume lives in that list). The project
2465 /// resolution is outside undo for the same reason and says so. Upgrade path
2466 /// is a history that carries the mix beside the lanes, which every existing
2467 /// snapshot site would then have to fill in.
2468 pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool {
2469 if !self.project.set_limiter(limiter) {
2470 return false;
2471 }
2472 self.push_mix();
2473 true
2474 }
2475
2476 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
2477 /// silence on the audio one, and nothing else moves. Reseeks, because what
2478 /// the playhead sits on has changed. `false` for a bad index -- the lift of
2479 /// the last placement there is empties the timeline, which is a state
2480 /// ([`is_empty`](Self::is_empty)) and one undo away.
2481 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {
2482 self.edit(Dirty::Both, |p| p.lift(lane, idx))
2483 }
2484
2485 /// Moves that clip onto lane `to` with its head at timeline frame `start` --
2486 /// the drag that carries a take along its track or onto another one, and its
2487 /// whole group with it. See [`Project::move_clip`] for the walls `start` is
2488 /// clamped to and the ways a drop is refused. One undo step, and it reseeks
2489 /// like every other edit: which lane a clip sits on is what the compositor's
2490 /// topmost-lane-wins rule reads, and where it starts is what the playhead
2491 /// reads, so the frame on screen is recomposed at once.
2492 ///
2493 /// A *frame*, where the rest of this type takes seconds, for
2494 /// [`trim_clip`](Self::trim_clip)'s reason: the drag has already put the
2495 /// pointer on a frame, and converting it back through seconds would be a
2496 /// rounding step between the box let go of and the box committed.
2497 pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
2498 self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start))
2499 }
2500
2501 /// [`move_clip_to`](Self::move_clip_to)'s general form: every one of
2502 /// `picks` travels the same frame delta as the dragged clip at `idx` of
2503 /// `from`, all-or-nothing, one undo step for the lot -- what a hand drags
2504 /// on a selection rather than a lone clip. See
2505 /// [`Project::move_selection`] for the clamp that makes it all-or-nothing.
2506 pub fn move_selection_to(
2507 &mut self,
2508 picks: &[(Lane, usize)],
2509 from: Lane,
2510 idx: usize,
2511 to: Lane,
2512 start: u32,
2513 ) -> bool {
2514 self.edit(Dirty::Both, |p| p.move_selection(picks, from, idx, to, start))
2515 }
2516
2517 /// Drags one end of that clip to timeline frame `to`, changing how much of
2518 /// its source it plays and nothing else on the lane -- see [`Project::trim`]
2519 /// for the walls it is clamped by, which this fills the source lengths in
2520 /// for. One undo step per call, so a front-end calls it once, at the release
2521 /// of the drag. Reseeks like every other edit, which is what makes the
2522 /// picture (and the sound) follow a new in-point straight away. `false` for
2523 /// a bad index and for an edge already where it was asked to go.
2524 ///
2525 /// A *frame*, where the rest of this type takes seconds: a drag has already
2526 /// asked [`trim_room`](Self::trim_room) where the edge may land, and that
2527 /// answer is in frames -- converting it back through seconds would be a
2528 /// rounding step between the width drawn and the width committed.
2529 pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
2530 // Spelled out rather than through `edit`, whose closure cannot hold a
2531 // second borrow of the session while it has the project.
2532 if !self.project.trim(lane, idx, edge, to, &self.counts) {
2533 return false;
2534 }
2535 let now = self.now();
2536 self.seek(now);
2537 true
2538 }
2539
2540 /// How fast the clip at `idx` of `lane` plays -- what a card shows before
2541 /// anyone drags it.
2542 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
2543 self.project.speed_of(lane, idx)
2544 }
2545
2546 /// Sets it, for that clip and its whole group ([`Project::set_speed`]): one
2547 /// undo step for the lot. Reseeks like every other edit, so the picture runs
2548 /// -- and the sound is resampled -- from the next frame on rather than at the
2549 /// next play. The `Err` names the clip in the way when slowing one down
2550 /// would run it into its neighbour, and nothing changes.
2551 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2552 // Spelled out rather than through `edit`, whose closure hands back a
2553 // bool and would drop the refusal's own words. The playhead moves
2554 let at = self.project.speeded_playhead(
2555 lane,
2556 idx,
2557 speed,
2558 secs_to_frame(self.now(), self.meta.frame_rate),
2559 );
2560 self.project.set_speed(lane, idx, speed)?;
2561 let now = at.map_or_else(
2562 || self.now(),
2563 |frame| f64::from(frame) / self.meta.frame_rate,
2564 );
2565 self.seek(now);
2566 Ok(())
2567 }
2568
2569 /// [`set_speed`](Self::set_speed) without the undo step -- the samples inside
2570 /// one drag ([`Project::set_speed_live`]). Reseeks like the committing one,
2571 /// which is what makes the bar move the picture under the hand.
2572 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
2573 // The mapping on every sample, not just at the commit: the bar moves
2574 // the rate live, and the scene has to stay put across the whole
2575 // gesture or the last picture before the release is not the one the
2576 // commit lands on.
2577 let at = self.project.speeded_playhead(
2578 lane,
2579 idx,
2580 speed,
2581 secs_to_frame(self.now(), self.meta.frame_rate),
2582 );
2583 self.project.set_speed_live(lane, idx, speed)?;
2584 let now = at.map_or_else(
2585 || self.now(),
2586 |frame| f64::from(frame) / self.meta.frame_rate,
2587 );
2588 self.seek(now);
2589 Ok(())
2590 }
2591
2592 /// The picture's source frame at `timeline_secs`: which source, and which
2593 /// frame of it -- the composite a viewer is looking at, through the same
2594 /// span math the decoder walks. What a test asks to prove a reseek kept
2595 /// the scene, and nothing in the editor itself reads.
2596 pub fn video_source_frame_at(&self, timeline_secs: f64) -> Option<(usize, u32)> {
2597 self.project
2598 .composite_span_at(secs_to_frame(timeline_secs, self.meta.frame_rate))
2599 .and_then(|s| s.from)
2600 }
2601
2602 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
2603 /// together to keep every media take crossing it in sync
2604 /// ([`Project::gap_take_scope`]) -- what a right-click on empty bench
2605 /// space asks before offering to close it. Subtitle gaps stay on their own
2606 /// lane because captions are not A/V take halves.
2607 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
2608 self.project.gap_take_scope(lane, start, frames)
2609 }
2610
2611 /// Closes every bounded gap on one lane. Media lanes keep linked takes
2612 /// whole when the other half has the matching empty stretch and report the
2613 /// gaps that were not safe to close; subtitle lanes ripple captions only.
2614 pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> {
2615 let report = self.project.close_all_gaps_on_lane(lane)?;
2616 if report.closed > 0 {
2617 let now = self.now();
2618 self.seek(now);
2619 }
2620 Ok(report)
2621 }
2622
2623 /// Cuts every one of `regions` -- `(start, len)` in timeline frames -- out
2624 /// of the lanes in `scope` and closes each hole, as **one** edit
2625 /// ([`Project::cut_regions`]): the jumpcut a silence scan
2626 /// ([`crate::silence`]) asks for, one undo press however many silences it
2627 /// found. A lane outside `scope` does not move. Reseeks like every other
2628 /// edit, so what plays is the cut timeline from the playhead on. The `Err`
2629 /// names what is in the way and nothing changes.
2630 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
2631 // Spelled out rather than through `edit`, whose closure hands back a
2632 // bool and would drop the refusal's own words.
2633 self.project.cut_regions(regions, scope)?;
2634 let now = self.now();
2635 self.seek(now);
2636 Ok(())
2637 }
2638
2639 /// Plays every one of those regions at `speed` instead of cutting them,
2640 /// closing the room each one no longer needs ([`Project::speed_regions`]) --
2641 /// one edit, one undo press, and the same scope rule. The `Err` names the
2642 /// lane and frame in the way and nothing changes.
2643 pub fn speed_regions(
2644 &mut self,
2645 regions: &[(u32, u32)],
2646 speed: Speed,
2647 scope: &[Lane],
2648 ) -> crate::Result<()> {
2649 self.project.speed_regions(regions, speed, scope)?;
2650 let now = self.now();
2651 self.seek(now);
2652 Ok(())
2653 }
2654
2655 /// Where that edge may land, `(first, last)` timeline frame inclusive: what
2656 /// a drag clamps the pointer to so the box it draws is the box
2657 /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
2658 pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
2659 self.project.trim_room(lane, idx, edge, &self.counts)
2660 }
2661
2662 /// Records how long a source is and what rate it was shot at, for a source
2663 /// index that may be one `Project::import` just made or one it handed back.
2664 /// See [`Self::counts`] and [`Self::rates`], which are one table in two
2665 /// vectors and grow together.
2666 fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) {
2667 if source == self.counts.len() {
2668 self.counts.push(frames);
2669 self.rates.push(rate);
2670 }
2671 debug_assert_eq!(self.counts.len(), self.project.sources().len());
2672 debug_assert_eq!(self.rates.len(), self.counts.len());
2673 // A source just joined, which is the one moment the session's audio
2674 // device may need arming ([`Self::arm_audio`]).
2675 self.arm_audio();
2676 }
2677
2678 /// Opens the audio device for the first source in the library that has a
2679 /// track, when this session has none.
2680 ///
2681 /// A session opened silent -- its first file carried no sound, so
2682 /// [`Self::open_library`]/[`Self::open`] had no track to open a device on
2683 /// -- must not stay silent once a source *with* sound joins it: every later
2684 /// clip's audio would go unheard for the rest of the session. That is
2685 /// exactly what the walk [`Self::open_project`] makes at open prevents for
2686 /// a loaded project (c581d41); this is the same walk at the add door, and
2687 /// [`Self::note_frames`] is the one place a source joins.
2688 ///
2689 /// A no-op once a device is open, so it costs a scan of `is_some` on every
2690 /// later import. The clock stays on wall time until the next seek
2691 /// ([`Self::seek`]'s own `switch_to_audio`), which is the seek a front-end
2692 /// makes as it places the file it just imported.
2693 fn arm_audio(&mut self) {
2694 // A device that is there but *dead* is not a device: the walk below
2695 // opens another one, which is also what clears the notice a death put up
2696 // ([`Self::tick`]).
2697 if let Some(audio) = &self.audio
2698 && !audio.died.load(Ordering::Acquire)
2699 {
2700 return;
2701 }
2702 for source in self
2703 .project
2704 .sources()
2705 .iter()
2706 .filter(|s| !crate::is_image(&s.path))
2707 {
2708 let (audio, disabled) = open_audio(&source.path, source.audio_stream);
2709 if audio.is_some() {
2710 self.audio = audio;
2711 self.audio_disabled = disabled;
2712 return;
2713 }
2714 }
2715 }
2716
2717 /// Opens the output again for a stream that died, at the rate and channel
2718 /// count it carried, and clears the flag that stopped the session feeding.
2719 ///
2720 /// An output that goes away -- a PipeWire daemon restarting, a sink node
2721 /// removed and put back -- leaves every stream that was open on it dead for
2722 /// good: its position is frozen, so the clock can only fall to wall time, and
2723 /// a session that never opens another device is silent for the rest of its
2724 /// life, through every seek and every pause/play, with nothing said about it.
2725 ///
2726 /// The device *only*, never the file: the feeder is [`Self::start_audio`]'s,
2727 /// at the seek that follows. That is what lets [`Self::tick`] call this too,
2728 /// once a frame -- a tick is not a seek and must not reseek the timeline. The
2729 /// clock is on wall time by then and stays there until a seek comes, which is
2730 /// the seek whose feeder opens in step with the picture.
2731 ///
2732 /// `if_idle_for` is the cooldown: a tick passes [`AUDIO_REARM_AFTER`], because
2733 /// sixty opens a second against a device that is gone for good is a spin; a
2734 /// seek passes zero, because that one is a person asking.
2735 ///
2736 /// `false` when there is nothing to open, nothing came back, or the cooldown
2737 /// has not passed -- and the flag stays standing for the next attempt.
2738 fn rearm_audio(&mut self, if_idle_for: Duration) -> bool {
2739 let Some(audio) = &self.audio else {
2740 return false;
2741 };
2742 if !audio.died.load(Ordering::Acquire) {
2743 return true;
2744 }
2745 {
2746 let mut at = audio.rearm_at.lock().unwrap();
2747 if at.is_some_and(|at| at.elapsed() < if_idle_for) {
2748 return false;
2749 }
2750 *at = Some(Instant::now());
2751 }
2752 let Some(ao) = AoSession::open(audio.sample_rate, audio.channels as u32) else {
2753 return false;
2754 };
2755 // A stream comes up streaming and a session starts paused: the fresh one
2756 // is silenced until the seek that feeds it says otherwise, which is the
2757 // same two steps [`open_audio`] takes on the way in.
2758 ao.set_active(false);
2759 // Replacing the session is what closes the dead stream, so it is done
2760 // under the device lock the feeder writes through.
2761 *audio.ao.lock().unwrap() = ao;
2762 // The clock anchor and the played-out arithmetic both belong to the
2763 // stream that died: the new one stamps its own first sample
2764 // ([`Audio::content_at`]), and `start_audio` re-bases the count from the
2765 // device's own position.
2766 audio.content_at.store(-1, Ordering::Release);
2767 audio.died.store(false, Ordering::Release);
2768 if self.audio_disabled.as_deref() == Some(AUDIO_LOST) {
2769 self.audio_disabled = None;
2770 }
2771 true
2772 }
2773
2774 /// The rate noted for whichever source plays `path`, by
2775 /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however
2776 /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session
2777 /// has never taken in.
2778 fn file_rate(&self, path: &Path) -> Rate {
2779 self.source_of(path)
2780 .map_or(Rate::REAL_TIME, |i| self.rates[i])
2781 }
2782
2783 /// Which file this source's **picture** is decoded from: its stand-in when
2784 /// the project is cut on stand-ins and one has been made for it, and the
2785 /// film itself in every other case ([`crate::proxy`]).
2786 ///
2787 /// One `stat` per span open, against a decoder open that costs milliseconds
2788 /// -- so a proxy that appeared (or was deleted) since the last seek is
2789 /// picked up at this one, and no table of attachments exists to disagree
2790 /// with the cache.
2791 ///
2792 /// The sound never comes through here: [`open_audio`] is given the
2793 /// project's own source path, so a mix is the film's however this answers.
2794 pub fn picture_path(&self, source: usize) -> PathBuf {
2795 let path = &self.project.sources()[source].path;
2796 let Some(proxy) = self.proxies.then(|| crate::proxy::cached(path)).flatten() else {
2797 return path.clone();
2798 };
2799 // Said out loud, once per span opened, because "the picture came off
2800 // the stand-in and the delivery did not" is a claim somebody has to be
2801 // able to check: `export` prints the file *it* reads by the same rule.
2802 eprintln!("picture: proxy {}", proxy.display());
2803 proxy
2804 }
2805
2806 /// Whether the picture comes off the stand-ins ([`Self::set_proxies`]).
2807 pub fn proxies(&self) -> bool {
2808 self.proxies
2809 }
2810
2811 /// Cut on the stand-ins, or on the films themselves. Reseeks, so the very
2812 /// next picture comes from the other file -- which is what makes this a
2813 /// switch a person can flip while watching.
2814 ///
2815 /// Says nothing about *which* films have one: a source with no stand-in
2816 /// keeps playing its own pictures either way, and one made while this is on
2817 /// is picked up at the next seek.
2818 pub fn set_proxies(&mut self, on: bool) {
2819 if self.proxies == on {
2820 return;
2821 }
2822 self.proxies = on;
2823 let now = self.now();
2824 self.seek(now);
2825 }
2826
2827 /// Which encoder an export of this project would open its picture on
2828 /// ([`crate::export::EncoderSeat`]). What a front-end puts into the
2829 /// [`ExportSettings`](crate::export::ExportSettings) it starts an export
2830 /// with -- and what the export card shows -- so the pick, the prediction
2831 /// and the file are one answer.
2832 pub fn encoder_seat(&self) -> crate::export::EncoderSeat {
2833 self.encoder_seat
2834 }
2835
2836 /// Pick the seat. Nothing to reseek and nothing to re-probe here: this
2837 /// decides what an *export* opens, never what plays.
2838 pub fn set_encoder_seat(&mut self, seat: crate::export::EncoderSeat) {
2839 self.encoder_seat = seat;
2840 }
2841
2842 /// The rate this project's mix was picked to run at
2843 /// ([`Self::set_sample_rate`]), or `None` for the rate the first audio
2844 /// source derives it to.
2845 pub fn sample_rate(&self) -> Option<u32> {
2846 self.sample_rate
2847 }
2848
2849 /// Pick the mix's own rate, overriding the derived one. Nothing to reseek
2850 /// here: it takes effect at the next audio rebuild (a seek, an edit, a
2851 /// reopen), not on the device already playing.
2852 pub fn set_sample_rate(&mut self, rate: Option<u32>) {
2853 self.sample_rate = rate;
2854 }
2855
2856 /// Whether an imported film that wants a stand-in gets one made for it
2857 /// there and then ([`Self::set_auto_proxies`]).
2858 pub fn auto_proxies(&self) -> bool {
2859 self.auto_proxies
2860 }
2861
2862 /// Make the stand-ins on import, or make none until asked. Nothing to
2863 /// reseek: this decides what is *started*, never what is decoded -- a proxy
2864 /// already in the cache is still cut on while [`Self::proxies`] is on.
2865 pub fn set_auto_proxies(&mut self, on: bool) {
2866 self.auto_proxies = on;
2867 }
2868
2869 /// Which source `path` is, canonicalising only if it has to: a source's own
2870 /// path is canonical ([`Source::new`]), so a caller handing one back from
2871 /// [`sources`](Self::sources) -- which is every library row -- hits on the
2872 /// first walk and never pays for the `canonicalize` syscall the second one
2873 /// makes. One rule, so a path that names a length names a rate too.
2874 fn source_of(&self, path: &Path) -> Option<usize> {
2875 let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted);
2876 at(path).or_else(|| at(&Source::new(path, 0).path))
2877 }
2878
2879 /// How long the whole of `path` is, in timeline frames: the length noted
2880 /// when it became a source, so a file sitting in the library with no clip
2881 /// anywhere still knows how much of itself there is to place. `0` for a
2882 /// file this session has never taken in.
2883 ///
2884 /// By path and not by stream, because a file is one length however many
2885 /// audio tracks it carries -- the picture's frame count for an mp4, the
2886 /// playing time for a song.
2887 pub fn file_frames(&self, path: &Path) -> u32 {
2888 self.source_of(path).map_or(0, |i| self.counts[i])
2889 }
2890
2891 /// What rate the file at `path` was *shot* at, in frames per second -- which
2892 /// is the timeline's own rate for every source that shares it, and is not
2893 /// for one placed at another ([`Rate`]). By path like
2894 /// [`file_frames`](Self::file_frames), and the timeline's rate for a file
2895 /// this session has never taken in (and for a still and a song, which were
2896 /// shot at no rate at all).
2897 ///
2898 /// What a library row names the file with: the timeline's rate there would
2899 /// be a lie about a 23.976 fps file the moment one can join.
2900 pub fn file_fps(&self, path: &Path) -> f64 {
2901 self.file_rate(path).as_f64() * self.meta.frame_rate
2902 }
2903
2904 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
2905 /// on and its index there, by the same topmost-lane-wins rule the decoder
2906 /// follows. `None` over a gap and past the end. What a card that grades
2907 /// "this clip" opens on when nothing has been clicked.
2908 pub fn video_clip_at(&self, timeline_secs: f64) -> Option<(Lane, usize)> {
2909 self.project
2910 .composite_clip_at(secs_to_frame(timeline_secs, self.meta.frame_rate))
2911 }
2912
2913 /// Which clip of `lane` sits at `timeline_secs`, by the same rule
2914 /// [`video_clip_at`](Self::video_clip_at) picks the picture's with -- per
2915 /// lane, so a keyboard walking the lanes for something to select asks the
2916 /// engine rather than re-deriving where a clip ends.
2917 pub fn lane_clip_at(&self, lane: Lane, timeline_secs: f64) -> Option<usize> {
2918 self.project
2919 .lane_clip_at(lane, secs_to_frame(timeline_secs, self.meta.frame_rate))
2920 }
2921
2922 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
2923 /// as it was shot -- what a colour card reads when it opens.
2924 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
2925 self.project.color_of(lane, idx)
2926 }
2927
2928 /// Grades that clip, or takes the grade off with `None`. One undo step like
2929 /// every other edit, and it reseeks like one too -- which is what puts the
2930 /// new grade on the frame that is already on screen, paused or playing,
2931 /// without the caller having to nudge the playhead itself. `false` for an
2932 /// index that is not there and for a value that is not finite.
2933 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2934 self.edit(Dirty::Picture, |p| p.set_color(lane, idx, params))
2935 }
2936
2937 /// The same grade and the same reseek without the undo step
2938 /// ([`Project::set_color_live`]): what the samples inside one slider drag go
2939 /// through, so the frame regrades under the hand and the whole gesture is
2940 /// still a single `z`.
2941 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
2942 self.edit(Dirty::Picture, |p| p.set_color_live(lane, idx, params))
2943 }
2944
2945 /// Where the clip at `idx` of `lane` is placed -- [`color_of`](Self::color_of)'s
2946 /// twin for geometry instead of grade.
2947 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
2948 self.project.transform_of(lane, idx)
2949 }
2950
2951 /// Moves/scales/rotates/crops that clip, or takes the placement off with
2952 /// `None` -- [`set_color`](Self::set_color)'s twin, one undo step and one
2953 /// reseek.
2954 pub fn set_transform(
2955 &mut self,
2956 lane: Lane,
2957 idx: usize,
2958 params: Option<TransformParams>,
2959 ) -> bool {
2960 self.edit(Dirty::Picture, |p| p.set_transform(lane, idx, params))
2961 }
2962
2963 /// The same placement and the same reseek without the undo step
2964 /// ([`Project::set_transform_live`]) -- [`set_color_live`](Self::set_color_live)'s
2965 /// twin for a slider drag.
2966 pub fn set_transform_live(
2967 &mut self,
2968 lane: Lane,
2969 idx: usize,
2970 params: Option<TransformParams>,
2971 ) -> bool {
2972 self.edit(Dirty::Picture, |p| p.set_transform_live(lane, idx, params))
2973 }
2974
2975 /// The project's resolution: what every clip is composed onto, what the
2976 /// window is sized to and what an export writes -- *not* any one file's.
2977 /// It starts as source 0's picture, which is what a project meant before it
2978 /// could have a resolution of its own.
2979 pub fn resolution(&self) -> (u32, u32) {
2980 (self.meta.width, self.meta.height)
2981 }
2982
2983 /// Source 0's own picture size -- what the project resolution started as,
2984 /// and the one size a caller offering a list of them must not leave out.
2985 pub fn native_resolution(&self) -> (u32, u32) {
2986 self.native
2987 }
2988
2989 /// Sets it. Rebuilds the **picture** where the playhead is, so the frame on
2990 /// screen is recomposed at the new size at once, paused or playing -- and
2991 /// the sound is not touched at all: the size of the canvas is not something
2992 /// a sample can carry, so resizing a 4K film mid-play costs neither a hole
2993 /// in the audio nor an offset against it ([`Dirty`]). `false` for a size
2994 /// that is not a picture -- zero either way, or past 8K, which is where the
2995 /// per-frame buffers stop being a sane thing to allocate from a keystroke.
2996 ///
2997 /// corner-cut: not an undo step. The project resolution is not in the lane
2998 /// snapshots [`Project::undo`] restores, so cycling it back is one more
2999 /// keypress rather than a `z`. Upgrade path is snapshotting it beside the
3000 /// lanes, which every existing snapshot site would then have to carry.
3001 pub fn set_resolution(&mut self, width: u32, height: u32) -> bool {
3002 if !crate::is_resolution(width, height) {
3003 return false;
3004 }
3005 if (width, height) == (self.meta.width, self.meta.height) {
3006 return false;
3007 }
3008 self.meta.width = width;
3009 self.meta.height = height;
3010 self.invalidate(Dirty::Picture);
3011 true
3012 }
3013
3014 /// Which HDR-to-SDR rendition this project is watched and exported in
3015 /// ([`crate::tonemap::Preset`]) -- the reference one until somebody picks
3016 /// another, and a setting on the project rather than on any clip.
3017 pub fn tone(&self) -> crate::tonemap::Preset {
3018 self.project.tone()
3019 }
3020
3021 /// What source 0's own file declared about how bright it gets
3022 /// ([`ContentLight`]): a property of the film, read once at open, and
3023 /// entirely absent (every field `None`) for an SDR file, a song or a
3024 /// still. Read-only -- the number a file carries, never a project setting
3025 /// a user can override, since nothing in [`Project`] holds one to persist.
3026 pub fn content_light(&self) -> ContentLight {
3027 self.content_light
3028 }
3029
3030 /// Picks one. Rebuilds the **picture** where the playhead is, exactly as
3031 /// [`set_resolution`](Self::set_resolution) does -- the frame on screen is
3032 /// remapped at once, paused or playing, and the sound is not touched: a
3033 /// rendition is not something a sample can carry. `false` for the rendition
3034 /// already in force.
3035 ///
3036 /// An SDR project is unmoved by this by construction: no clip of it builds a
3037 /// tone map at all ([`crate::tonemap`]), so the reseek recomposes the very
3038 /// same bytes.
3039 ///
3040 /// corner-cut: not an undo step, for the reason the resolution is not
3041 /// ([`Project::set_tone`]).
3042 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
3043 if !self.project.set_tone(preset) {
3044 return false;
3045 }
3046 self.invalidate(Dirty::Picture);
3047 true
3048 }
3049
3050 /// The scaffolding source's own frame rate -- what the project rate started
3051 /// as, and the one rate a caller offering a list of them must not leave out
3052 /// ([`native_resolution`](Self::native_resolution)'s reason).
3053 pub fn native_frame_rate(&self) -> f64 {
3054 self.native_fps
3055 }
3056
3057 /// Cuts this timeline at `fps` from here on: every clip is *conformed* to
3058 /// the new rate ([`Project::retime`]), every source is read through a
3059 /// [`Rate`] against it, and an export written from this session comes out at
3060 /// it. The edit survives as the same seconds of the same footage on a finer
3061 /// or coarser grid -- a 30 fps take on a timeline moved to 24 keeps its
3062 /// length and its sync, it is simply counted in 24ths now.
3063 ///
3064 /// Reseeks like [`set_resolution`](Self::set_resolution), so the picture and
3065 /// the sound under the playhead are already the new rate's when this
3066 /// returns. `false` -- changing nothing -- for a rate that is not a rate, for
3067 /// the one already in force, and for one no timescale can name
3068 /// ([`crate::mux::frame_timing`], the same wall a file of an unnameable rate
3069 /// is refused at).
3070 ///
3071 /// corner-cut: not an undo step, exactly as the project resolution is not --
3072 /// and this one *moves the frame numbers*, so the way back is picking the
3073 /// old rate (or the media's, [`native_frame_rate`](Self::native_frame_rate))
3074 /// rather than a `z`, and it lands within a frame of where it started rather
3075 /// than on it (see [`Project::retime`]). Upgrade path is the same one: the
3076 /// project's settings snapshotted beside the lanes.
3077 pub fn set_frame_rate(&mut self, fps: f64) -> bool {
3078 if !fps.is_finite() || fps <= 0.0 || fps == self.meta.frame_rate {
3079 return false;
3080 }
3081 // Old timeline frames per new one, exactly -- the one map every frame
3082 // number on every lane goes through. Built before anything is touched,
3083 // since a rate no timescale can name is a refusal and not a half-retimed
3084 // project.
3085 let Ok(k) = Rate::from_fps(self.meta.frame_rate, fps) else {
3086 return false;
3087 };
3088 // Lengths first: the retime holds every clip inside its source's *new*
3089 // length, so a clip that played to the last frame of its file still
3090 // does rather than naming one past the end.
3091 for count in &mut self.counts {
3092 *count = k.timeline_at(*count).max(1);
3093 }
3094 self.project.retime(k, &self.counts);
3095 // A file's own rate has not changed; what it is *against* has.
3096 for rate in &mut self.rates {
3097 *rate = rate.then(k);
3098 }
3099 self.meta.frame_rate = fps;
3100 self.meta.frame_count = k.timeline_at(self.meta.frame_count).max(1);
3101 let now = self.now();
3102 self.seek(now);
3103 true
3104 }
3105
3106 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
3107 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
3108 self.project.fit_of(lane, idx)
3109 }
3110
3111 /// Sets that clip's fit policy. One undo step and a reseek, exactly like a
3112 /// grade: the picture on screen is recomposed through the new policy without
3113 /// the caller nudging the playhead. `false` for an index that is not there.
3114 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
3115 self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit))
3116 }
3117
3118 /// Waveform flags on a visualizer clip. Reseeks like a grade: the
3119 /// painter reads them on the next picture.
3120 pub fn set_visualizer(&mut self, lane: Lane, idx: usize, flags: u8) -> bool {
3121 self.edit(Dirty::Picture, |p| p.set_visualizer(lane, idx, flags))
3122 }
3123
3124 pub fn set_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
3125 self.edit(Dirty::Picture, |p| p.set_viz_paint(lane, idx, paint))
3126 }
3127
3128 /// The same look and the same repaint without the undo step
3129 /// ([`Project::set_viz_paint_live`]): what the samples inside one drag
3130 /// across the colour wheel go through, so the picture follows the hand and
3131 /// the whole gesture is still a single `z`.
3132 pub fn set_viz_paint_live(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
3133 self.edit(Dirty::Picture, |p| p.set_viz_paint_live(lane, idx, paint))
3134 }
3135
3136 /// Timeline frames of ramp-up from silence at the start of the clip at
3137 /// `idx` of `lane`. `0` for an index that is not there.
3138 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
3139 self.project.fade_in_of(lane, idx)
3140 }
3141
3142 /// Sets that clip's fade-in, clamped to its own length. A sound-only
3143 /// edit, same as an equalizer or a fader: no reseek needed.
3144 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
3145 self.edit(Dirty::Sound, |p| p.set_fade_in(lane, idx, frames))
3146 }
3147
3148 /// Timeline frames of ramp-down to silence at the end of the clip at
3149 /// `idx` of `lane`. `0` for an index that is not there.
3150 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
3151 self.project.fade_out_of(lane, idx)
3152 }
3153
3154 /// Sets that clip's fade-out. Same promises as [`Self::set_fade_in`].
3155 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
3156 self.edit(Dirty::Sound, |p| p.set_fade_out(lane, idx, frames))
3157 }
3158
3159 /// Crossfades the audio clip at `idx` of `lane` into its neighbour, over
3160 /// `frames`. Same promises as [`Project::crossfade`].
3161 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
3162 self.edit(Dirty::Sound, |p| p.crossfade(lane, idx, frames))
3163 }
3164
3165 /// Timeline frames of dissolve at the end of the clip at `idx` of `lane`,
3166 /// into its neighbour. `0` for an index that is not there.
3167 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
3168 self.project.transition_out_of(lane, idx)
3169 }
3170
3171 /// Sets that clip's dissolve into its neighbour, clamped to its own
3172 /// length. A picture edit -- same as a grade or fit policy.
3173 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
3174 self.edit(Dirty::Picture, |p| p.set_transition_out(lane, idx, frames))
3175 }
3176
3177 /// The clip at `idx` -- what a caller copies. It is a pair of source frame
3178 /// numbers and nothing else, so a copy stays valid after the clip it came
3179 /// from is deleted. `None` past the end.
3180 pub fn clip_at(&self, idx: usize) -> Option<Clip> {
3181 self.project.clips().get(idx).copied()
3182 }
3183
3184 /// Inserts `clip` at the playhead, splitting the clip under it. Like a
3185 /// delete this moves every following frame, so the session reseeks; past
3186 /// the end of the timeline the clip is appended. One undo step.
3187 pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool {
3188 // The clipboard's own rule, and only the clipboard's: a paste past the
3189 // end is an append, never a clip with black in front of it. The frame
3190 // itself is honoured in [`Project::paste`], because a *drop* names a
3191 // place on the bed and means it.
3192 let at = secs_to_frame(timeline_secs, self.meta.frame_rate)
3193 .min(self.project.timeline_frames());
3194 self.edit(Dirty::Both, |p| p.paste(at, clip))
3195 }
3196
3197 /// [`paste_at`](Self::paste_at)'s general form: [`Project::paste_set`]'s
3198 /// door, clamped to the timeline's own end the same way -- a set let go
3199 /// past the last frame lands there rather than carrying black in front of
3200 /// it, exactly as a lone clip's paste does.
3201 pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool {
3202 let at = secs_to_frame(timeline_secs, self.meta.frame_rate)
3203 .min(self.project.timeline_frames());
3204 self.edit(Dirty::Both, |p| p.paste_set(at, items))
3205 }
3206
3207 /// Places the whole of `path` played on its audio `stream` at
3208 /// `timeline_secs`, the way [`paste_at`](Self::paste_at) places a copy --
3209 /// the door a library row goes through, and the only way a stream other
3210 /// than the one an import brought in reaches the timeline. The `(file,
3211 /// stream)` pair becomes a source if it is not one already.
3212 ///
3213 /// Refused, changing nothing, unless that stream can join *this* timeline:
3214 /// same audio parameters as the first source, in the same words
3215 /// [`import`](Self::import) refuses a file with. One output device and one
3216 /// copied AAC track mean one *layout* for the whole timeline, so a mono
3217 /// track cannot join a stereo one. Its sample rate may be its own: the
3218 /// segment's resampler conforms it at the decoder's door.
3219 /// A front-end greys such a row out; this is the backstop that keeps a
3220 /// stale one from making the whole timeline silent.
3221 ///
3222 /// Which lane it lands on is decided here, from the file and from `onto` --
3223 /// the lane it was let go over, if it was let go over one at all: a file
3224 /// with a picture asked for by no lane, or for one of the first pair, is
3225 /// pasted across `V1` and `A1` as a grouped take; asked for by a further
3226 /// *video* lane it is *placed* there with its sound on that lane's own audio
3227 /// row (`V2` -> `A2`, added if it is not there yet), overwriting what the two
3228 /// halves land on and rippling nothing; asked for by a further audio lane it
3229 /// is that file's sound alone. A file with no picture ([`crate::is_audio`]) is placed
3230 /// on the audio lane it was asked for, or on `A1`, and never on a video
3231 /// lane. A still image ([`crate::is_image`]) is its mirror: the video lane
3232 /// it was asked for or `V1`, never an audio one, and it goes down
3233 /// [`IMAGE_PLACE_SECS`] long rather than at the length it is *allowed* to
3234 /// be trimmed out to. A caller never has to ask.
3235 pub fn place_stream_at(
3236 &mut self,
3237 timeline_secs: f64,
3238 path: &Path,
3239 stream: usize,
3240 onto: Option<Lane>,
3241 ) -> crate::Result<bool> {
3242 let wanted = Source::new(path, stream);
3243 // Another stream of a file this session has taken in: that is what a
3244 // library row is, and it is why nothing here has to check dimensions or
3245 // frame rate -- the file passed that at import. Its length is the one
3246 // the import noted, so a source that has never been placed is as
3247 // placeable as one that is already on a lane.
3248 let frames = self.file_frames(&wanted.path);
3249 if frames == 0 {
3250 return Err(format!("{} is not on this timeline", path.display()).into());
3251 }
3252 // A still has no sound to hold to the timeline's -- and no length
3253 // either, so it goes down at [`IMAGE_PLACE_SECS`] rather than at the
3254 // ten minutes it is *allowed* to be dragged out to.
3255 let image = crate::is_image(path);
3256 if !image {
3257 let first = self.first_audio()?;
3258 self.audio_matches_cached(&wanted, &first)?;
3259 }
3260 let rate = self.file_rate(&wanted.path);
3261 let source = self.project.import(path, stream);
3262 self.note_frames(source, frames, rate);
3263 let clip = Clip {
3264 fade_in: 0,
3265 fade_out: 0,
3266 transition_out: 0,
3267 visualizer: 0,
3268 viz_paint: 0,
3269 start: 0,
3270 in_frame: 0,
3271 out_frame: match image {
3272 true => place_frames(frames, self.meta.frame_rate),
3273 false => frames.max(1),
3274 },
3275 source,
3276 link: None,
3277 eq: None,
3278 color: None,
3279 transform: None,
3280 fit: FitPolicy::default(),
3281 speed: Speed::NORMAL,
3282 };
3283 // Which lane a source may land on is decided here and only here, so a
3284 // front-end never has to make the same call twice: a file with no
3285 // picture goes on an audio lane alone, overwriting and rippling
3286 // nothing, because there is nothing on the video lane to move along
3287 // with it. A lane of the source's own kind takes it as it is dropped;
3288 // only `V1` means the grouped take, since that is the pair the paste
3289 // spans and a second video lane is a layer of its own.
3290 // ...and a still is the mirror of a song: a picture and no sound, so a
3291 // video lane and nothing else -- never the grouped take, which would
3292 // put a clip on `A1` for a source the audio worker cannot open.
3293 if image {
3294 let lane = match onto {
3295 Some(lane) if lane.kind == LaneKind::Video => lane,
3296 _ => Lane::V1,
3297 };
3298 return Ok(self.place_at(lane, timeline_secs, clip));
3299 }
3300 let onto = match (crate::is_audio(path), onto) {
3301 // No picture: an audio lane and nothing else, whichever one was
3302 // asked for -- `A1` when none was.
3303 (true, Some(lane)) if lane.kind == LaneKind::Audio => Some(lane),
3304 (true, _) => Some(Lane::A1),
3305 // A picture: the lane it was let go over, unless that is one of the
3306 // first pair. Those two are the grouped take a paste spans, and a
3307 // further lane is a layer of its own -- its picture on `V2`, its
3308 // sound on `A2` (below).
3309 (false, Some(lane)) if lane.ord > 0 => Some(lane),
3310 (false, _) => None,
3311 };
3312 Ok(match onto {
3313 // A picture let go over a further *video* track lands there with the
3314 // sound it came with -- `V2`'s picture, `A2`'s sound, one take and
3315 // one undo step ([`Project::place_take`]). Dropped on a further
3316 // audio lane it is the sound alone, which is what asking an audio
3317 // row for an mp4 means.
3318 Some(lane) if lane.kind == LaneKind::Video => {
3319 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
3320 self.edit(Dirty::Both, |p| p.place_take(lane, at, clip))
3321 }
3322 Some(lane) => self.place_at(lane, timeline_secs, clip),
3323 // The grouped take, at the frame it was let go on -- past the last
3324 // clip included, where the bed is black and the ghost was drawn.
3325 // Not [`Self::paste_at`]: that door clamps to the end for the
3326 // clipboard, and a drop that named a place is not a paste.
3327 None => {
3328 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
3329 self.edit(Dirty::Both, |p| p.paste(at, clip))
3330 }
3331 })
3332 }
3333
3334 /// Takes `path` played on `stream` out of the library -- the door a library
3335 /// row's own remove goes through, naming the row exactly as
3336 /// [`place_stream_at`](Self::place_stream_at) does. Refused in
3337 /// [`Project::remove_source`]'s words while a clip still plays from it, and
3338 /// for a row this timeline does not have.
3339 ///
3340 /// Reseeks like an edit even though nothing playable changed: the clip
3341 /// indexes into the source list have just moved, and the running workers
3342 /// were opened against the old numbering.
3343 ///
3344 /// The index that went, because everything past it moved down: a caller
3345 /// holding a source index of its own (a clipboard) has to fix it up or drop
3346 /// it, or it names a different file afterwards. The **last** row goes like
3347 /// any other and leaves a session with an empty library -- silent, empty of
3348 /// clips, and unsaveable ([`save_project`](Self::save_project)); a
3349 /// front-end showing one is showing an empty window.
3350 pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> {
3351 let wanted = Source::new(path, stream);
3352 let idx = self
3353 .project
3354 .sources()
3355 .iter()
3356 .position(|s| *s == wanted)
3357 .ok_or_else(|| format!("{} is not on this timeline", path.display()))?;
3358 self.project.remove_source(idx)?;
3359 // The one thing that shortens the source list, so the one place
3360 // [`Self::counts`] shortens with it: left behind, the gone file's length
3361 // would become the wall a *surviving* source is trimmed against
3362 // ([`trim_room`](Self::trim_room)) and the next import would land its
3363 // count one index late.
3364 if idx < self.counts.len() {
3365 self.counts.remove(idx);
3366 self.rates.remove(idx);
3367 }
3368 let now = self.now();
3369 self.seek(now);
3370 Ok(idx)
3371 }
3372
3373 /// What the timeline's audio *is*: the chosen stream of the first source
3374 /// that could have any ([`audio_source_of`]), probed. Every other source is
3375 /// held to it.
3376 ///
3377 /// Through the session's own memo ([`probes`](Self::probes)), because this
3378 /// is asked on the render thread: the free [`first_audio_of`] is the one a
3379 /// worker with no session to reach for calls.
3380 fn first_audio(&mut self) -> crate::Result<Option<crate::AudioProbe>> {
3381 match audio_source_of(self.project.sources()) {
3382 Some(first) => {
3383 let (path, stream) = (first.path.clone(), first.audio_stream);
3384 self.probe_cached(&path, stream)
3385 }
3386 None => Ok(None),
3387 }
3388 }
3389
3390 /// One audio header, read at most once per session per `(path, stream)`.
3391 fn probe_cached(
3392 &mut self,
3393 path: &Path,
3394 stream: usize,
3395 ) -> crate::Result<Option<crate::AudioProbe>> {
3396 let key = (path.to_path_buf(), stream);
3397 if let Some(probe) = self.probes.get(&key) {
3398 return Ok(*probe);
3399 }
3400 let probe = AudioSession::probe(path, stream)?;
3401 self.probes.insert(key, probe);
3402 Ok(probe)
3403 }
3404
3405 /// [`audio_matches`] with this session's memo behind the new file's own
3406 /// header too -- the second of the two opens a place or an import pays.
3407 fn audio_matches_cached(
3408 &mut self,
3409 source: &Source,
3410 first: &Option<crate::AudioProbe>,
3411 ) -> crate::Result<()> {
3412 let probe = self.probe_cached(&source.path, source.audio_stream)?;
3413 audio_matches_probed(probe, first)
3414 }
3415
3416 /// Places `clip` on `lane` alone at the playhead, overwriting what it lands
3417 /// on and rippling nothing -- the one-lane insert a source with no picture
3418 /// makes, and the only way an audio-only file reaches the timeline. The
3419 /// placement belongs to no group (see [`Project::place`]). One undo step,
3420 /// and it reseeks like every other edit.
3421 pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool {
3422 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
3423 self.edit(Dirty::Both, |p| p.place(lane, at, clip))
3424 }
3425
3426 /// Places a waveform-visualizer clip of `path`'s audio on a video lane.
3427 /// The picture is painted from the sound ([`DecodeSession::open_visualizer`]);
3428 /// this does not also put a copy on an audio lane.
3429 pub fn place_visualizer(
3430 &mut self,
3431 start: u32,
3432 path: &Path,
3433 stream: usize,
3434 in_frame: u32,
3435 out_frame: u32,
3436 onto: Option<Lane>,
3437 ) -> crate::Result<bool> {
3438 if out_frame <= in_frame {
3439 return Err("visualizer clip is empty".into());
3440 }
3441 let wanted = Source::new(path, stream);
3442 let first = self.first_audio()?;
3443 self.audio_matches_cached(&wanted, &first)?;
3444 let frames = match self.file_frames(&wanted.path) {
3445 0 => {
3446 let n = audio_frames(path, self.meta.frame_rate)?;
3447 let source = self.project.import(path, stream);
3448 self.note_frames(source, n, Rate::REAL_TIME);
3449 n
3450 }
3451 n => n,
3452 };
3453 let out_frame = out_frame.min(frames);
3454 if out_frame <= in_frame {
3455 return Err("visualizer clip is empty".into());
3456 }
3457 let source = self.project.import(path, stream);
3458 let clip = Clip {
3459 fade_in: 0,
3460 fade_out: 0,
3461 transition_out: 0,
3462 visualizer: 1,
3463 viz_paint: 0,
3464 start: 0,
3465 in_frame,
3466 out_frame,
3467 source,
3468 link: None,
3469 eq: None,
3470 color: None,
3471 transform: None,
3472 fit: FitPolicy::default(),
3473 speed: Speed::NORMAL,
3474 };
3475 let end = start + clip.frames();
3476 let overlaps = |lane: Lane| {
3477 self.project
3478 .lane(lane)
3479 .iter()
3480 .any(|c| c.start < end && start < c.end())
3481 };
3482 let lane = match onto {
3483 Some(lane) if lane.kind == LaneKind::Video && !overlaps(lane) => lane,
3484 _ => self
3485 .project
3486 .lanes()
3487 .into_iter()
3488 .filter(|l| l.kind == LaneKind::Video)
3489 .find(|&l| !overlaps(l))
3490 .unwrap_or_else(|| self.add_lane(LaneKind::Video)),
3491 };
3492 Ok(self.edit(Dirty::Both, |p| p.place(lane, start, clip)))
3493 }
3494
3495 /// Removes `lane`'s clip at `idx` and everything under it, closing the gap
3496 /// on every lane. Unlike a split this *does* move every following frame, so
3497 /// the session reseeks to wherever the playhead now points.
3498 /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead.
3499 /// `false` for a bad index; the last remaining clip goes like any other and
3500 /// leaves the timeline empty ([`is_empty`](Self::is_empty)).
3501 ///
3502 /// The lane travels because the index is a lane's own: `V2`'s third clip is
3503 /// not `V1`'s, and a front-end that could only say "the third clip" would
3504 /// delete the wrong one the moment a second lane exists.
3505 pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool {
3506 self.edit(Dirty::Both, |p| p.delete_in(lane, idx))
3507 }
3508
3509 /// Undoes the last successful edit, and reseeks like a delete.
3510 pub fn undo(&mut self) -> bool {
3511 self.edit(Dirty::Both, Project::undo)
3512 }
3513
3514 /// Redoes the last edit [`undo`](Self::undo) took back, and reseeks like
3515 /// a delete.
3516 pub fn redo(&mut self) -> bool {
3517 self.edit(Dirty::Both, Project::redo)
3518 }
3519
3520 /// Takes `path` into the **library**: it becomes a source of this session,
3521 /// with its length noted ([`file_frames`](Self::file_frames)), and nothing
3522 /// is placed on any lane. What reaches the timeline is decided afterwards,
3523 /// by dragging the row onto a lane
3524 /// ([`place_stream_at`](Self::place_stream_at)) -- importing a file is not
3525 /// a decision about where it plays.
3526 ///
3527 /// The source index, new or the one this file already had: importing twice
3528 /// registers once. *Not* an undo step -- a source entry alone changes
3529 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take
3530 /// back, and nothing reseeks.
3531 ///
3532 /// Refused unless it can join the timeline -- a decoder this machine can
3533 /// open, and audio parameters that agree or none at all; the `Err` names
3534 /// the property that disagrees,
3535 /// for a caller to show. Nothing is changed by a refusal. A *resolution* of
3536 /// its own is not a refusal: the clip is placed on the project canvas by its
3537 /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame
3538 /// rate* of its own: the file is placed for the seconds it lasts and read at
3539 /// [`Rate`] against the timeline's rate, so it plays at the speed it was
3540 /// shot at.
3541 pub fn import(&mut self, path: &Path) -> crate::Result<usize> {
3542 if crate::is_audio(path) {
3543 return self.import_audio(path);
3544 }
3545 if crate::is_image(path) {
3546 return self.import_image(path);
3547 }
3548 // Both halves on this thread, which is what a caller with nothing else
3549 // to do wants; a front-end splits them across a worker instead
3550 // ([`probe_import`](Self::probe_import)).
3551 // A container with sound but no picture is a song wearing a video
3552 // extension -- the same fallback `open_stream` and the project
3553 // scaffold make, so every door in agrees on what the file is.
3554 match Self::probe_import(self.import_gate(), path) {
3555 Ok(probe) => Ok(self.take_probe(path, probe)),
3556 Err(e) if crate::demux::NoVideoTrack::is_it(&e) => self.import_audio(path),
3557 Err(e) => Err(e),
3558 }
3559 }
3560
3561 /// Everything an import is *checked against*, taken off this timeline in
3562 /// one owned piece: the sources its audio must agree with and the meta its
3563 /// rate is read against. Costs two clones and touches no disk, so the
3564 /// thread holding the session can hand it to a worker and go on painting.
3565 pub fn import_gate(&self) -> ImportGate {
3566 ImportGate {
3567 sources: self.project.sources().to_vec(),
3568 timeline: self.meta,
3569 }
3570 }
3571
3572 /// The reading half of [`import`](Self::import), with no session in it: the
3573 /// container's header, the decoder this machine would open it with, and the
3574 /// audio check against the gate -- every read an import pays.
3575 ///
3576 /// This is the half that costs. Measured on a 24 GB 4K HEVC remux: 21.4 s of
3577 /// header with the pages cold, 429 ms warm, plus 1-4 s of probing the
3578 /// timeline's own first source. So a front-end runs *this* on its background
3579 /// executor and hands what comes back to
3580 /// [`import_probed`](Self::import_probed), which costs a push -- the same
3581 /// split [`parse_subtitles`](Self::parse_subtitles) makes, for the same
3582 /// reason.
3583 ///
3584 /// The container fork only: a song and a still fork before the demuxer
3585 /// ([`import`](Self::import)) and pay a header read of their own.
3586 ///
3587 /// The `Err` is the refusal [`import`](Self::import) would have given, in
3588 /// the same words -- nothing is refused twice and nothing is worded twice.
3589 pub fn probe_import(gate: ImportGate, path: &Path) -> crate::Result<ImportProbe> {
3590 let (meta, _) = Demuxer::open(path)?;
3591 let first = first_audio_of(&gate.sources)?;
3592 // Stream 0: an import brings a file in on its first audio track, and
3593 // [`place_stream_at`](Self::place_stream_at) is how any other one of
3594 // its streams reaches the timeline afterwards.
3595 // ...and the rate it will be read at comes back from the check that
3596 // accepted it, so the number the refusal was decided on is the number
3597 // the file is played by.
3598 let rate = matches_timeline(&Source::new(path, 0), &meta, &gate.timeline, &first)?;
3599 Ok(ImportProbe { gate, meta, rate })
3600 }
3601
3602 /// Registers a file already read by [`probe_import`](Self::probe_import).
3603 /// The whole of what an import costs the thread that calls it: a source
3604 /// entry and its length, no open, no seek, no decode -- which is why the
3605 /// probe is a separate door.
3606 ///
3607 /// The timeline may have moved while the worker read: a source removed or a
3608 /// file opened is a different set of things the probe was checked against,
3609 /// so the probe is re-read here ([`ImportGate`]) and a stale one is simply
3610 /// imported the slow way rather than trusted. Same answer either way, so no
3611 /// caller has to know which arm it took.
3612 pub fn import_probed(&mut self, path: &Path, probe: ImportProbe) -> crate::Result<usize> {
3613 match probe.gate.sources == self.project.sources() && probe.gate.timeline == self.meta {
3614 true => Ok(self.take_probe(path, probe)),
3615 false => self.import(path),
3616 }
3617 }
3618
3619 /// The push both import doors end at.
3620 fn take_probe(&mut self, path: &Path, probe: ImportProbe) -> usize {
3621 let source = self.project.import(path, 0);
3622 // Its length *on this timeline*: a file shot slower than the timeline
3623 // runs covers more frames than it holds, which is the whole of what
3624 // placing it at another rate means ([`Rate`]).
3625 self.note_frames(
3626 source,
3627 probe.rate.timeline_at(probe.meta.frame_count),
3628 probe.rate,
3629 );
3630 source
3631 }
3632
3633 /// The same registration for a standalone audio file: a song has no
3634 /// picture, so the length noted for it is its playing time rounded up to
3635 /// whole frames, which is the only frame count such a source has.
3636 ///
3637 /// Refused in the same words as any other import when its layout disagrees
3638 /// with the timeline's track -- one output device, one layout. A silent
3639 /// timeline has no track to disagree with, so a song joins it and *is* its
3640 /// sound ([`Self::arm_audio`]). Nothing is changed by a refusal.
3641 fn import_audio(&mut self, path: &Path) -> crate::Result<usize> {
3642 let first = self.first_audio()?;
3643 // Stream 0, and there is no other: a standalone audio file carries one
3644 // track (`AudioSession::probe_streams`), so nothing here has a stream
3645 // to pick the way `place_stream_at` does for an mp4.
3646 self.audio_matches_cached(&Source::new(path, 0), &first)?;
3647 let frames = audio_frames(path, self.meta.frame_rate)?;
3648 let source = self.project.import(path, 0);
3649 self.note_frames(source, frames, Rate::REAL_TIME);
3650 Ok(source)
3651 }
3652
3653 /// The same registration for a still image, and the shortest of the three:
3654 /// a picture has nothing to agree with. No frame rate (it is one picture),
3655 /// no audio (it is silent), and a resolution of its own is what every
3656 /// import is allowed -- the clip is placed on the project canvas by its fit
3657 /// policy. The one refusal left is a file that is not a picture at all, or
3658 /// one too big to compose ([`crate::is_resolution`]), and the header alone
3659 /// answers both.
3660 ///
3661 /// The length noted is the wall a trim is held to, not a duration the file
3662 /// has: see [`image_frames`].
3663 fn import_image(&mut self, path: &Path) -> crate::Result<usize> {
3664 let (width, height) = crate::decode::image_size(path)?;
3665 if !crate::is_resolution(width, height) {
3666 return Err(format!(
3667 "{} is {width}x{height}, which is not a picture this engine composes",
3668 path.display()
3669 )
3670 .into());
3671 }
3672 let source = self.project.import(path, 0);
3673 self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME);
3674 Ok(source)
3675 }
3676
3677 /// Applies an edit and, if it took, rebuilds **what it dirtied** and nothing
3678 /// else ([`Dirty`]). A structural edit reseeks: `seek` clamps to the new
3679 /// duration and keeps playing playing, so a delete that shortens the
3680 /// timeline past the playhead lands on the last frame. A grade or a fit
3681 /// policy rebuilds the picture where it stands, with the sound running
3682 /// through it untouched -- no flush, no re-open, no hole -- and an
3683 /// equalizer the other way round.
3684 fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool {
3685 if !f(&mut self.project) {
3686 return false;
3687 }
3688 self.invalidate(dirty);
3689 true
3690 }
3691
3692 /// Rebuilds the dirtied half (or both) at the playhead.
3693 fn invalidate(&mut self, dirty: Dirty) {
3694 match dirty {
3695 Dirty::Picture => {
3696 let (_, target) = self.landing(self.now());
3697 self.start_picture(target);
3698 }
3699 Dirty::Sound => self.reseek_audio(),
3700 Dirty::Both => {
3701 let now = self.now();
3702 self.seek(now);
3703 }
3704 }
3705 }
3706
3707 /// Says how big the picture is on screen, in device pixels -- what a
3708 /// front-end showing this session pushes once it knows where the picture
3709 /// actually lands. Rendering a 1080p project's visualizer for a 600 px
3710 /// preview costs nine times the pixels for nothing the eye can see; a
3711 /// window that is fullscreen gets the project's own size back by pushing
3712 /// it. `true` when the size moved enough to be worth a new picture: under
3713 /// 8 px on both axes is a resize nobody can see, and a window being
3714 /// dragged would otherwise restart the picture every tick.
3715 pub fn set_view_size(&mut self, width: u32, height: u32) -> bool {
3716 let want = self.view_want(width, height);
3717 match self.view {
3718 Some(now) if now.0.abs_diff(want.0) < 8 && now.1.abs_diff(want.1) < 8 => false,
3719 _ => {
3720 self.view = Some(want);
3721 true
3722 }
3723 }
3724 }
3725
3726 /// [`Self::set_view_size`] with no deadband: what asks for the *exact*
3727 /// size rather than one within 8 px of it. A still saved at the project's
3728 /// own pixels is a file whose dimensions are read back, so "close enough
3729 /// to be invisible" is not close enough to be right. `true` when the view
3730 /// moved, `false` when it was already there -- which is also the answer
3731 /// that lets a caller skip waiting for a frame it already has.
3732 pub fn set_view_size_exact(&mut self, width: u32, height: u32) -> bool {
3733 let want = self.view_want(width, height);
3734 match self.view {
3735 Some(now) if now == want => false,
3736 _ => {
3737 self.view = Some(want);
3738 true
3739 }
3740 }
3741 }
3742
3743 /// The size a push of `(width, height)` settles on: even on both axes
3744 /// (YUV 4:2:0 has no odd chroma) and never past the project's own.
3745 fn view_want(&self, width: u32, height: u32) -> (u32, u32) {
3746 let fit = |n: u32, cap: u32| (n & !1).clamp(2, cap.max(2));
3747 (fit(width, self.meta.width), fit(height, self.meta.height))
3748 }
3749
3750 /// The canvas a span's pictures are painted at: [`Self::set_view_size`]'s
3751 /// size once one has been pushed, the project's own otherwise.
3752 pub fn view_size(&self) -> (u32, u32) {
3753 self.view.unwrap_or((self.meta.width, self.meta.height))
3754 }
3755
3756 /// Current timeline position in seconds.
3757 pub fn now(&self) -> f64 {
3758 self.clock.now()
3759 }
3760
3761 pub fn is_playing(&self) -> bool {
3762 self.clock.is_playing()
3763 }
3764
3765 pub fn play(&mut self) {
3766 if self.clock.is_playing() {
3767 return;
3768 }
3769 // Invariant: the clock is positioned *before* audio restarts. Audio
3770 // reports are relative to the first one after that, so a seek would go
3771 // here too -- `clock.seek_to(t)` and then `set_active(true)`.
3772 self.clock.play();
3773 if let Some(audio) = &self.audio {
3774 audio.set_playing(true);
3775 }
3776 }
3777
3778 pub fn pause(&mut self) {
3779 if !self.clock.is_playing() {
3780 return;
3781 }
3782 if let Some(audio) = &self.audio {
3783 audio.set_playing(false);
3784 }
3785 self.clock.pause();
3786 }
3787
3788 pub fn toggle(&mut self) {
3789 if self.clock.is_playing() {
3790 self.pause()
3791 } else {
3792 self.play()
3793 }
3794 }
3795
3796 /// Stops the transport where the timeline stops: the clock is paused and put
3797 /// on the out point.
3798 ///
3799 /// Playing past the last frame is wall time counting on past the end of the
3800 /// media -- there is no picture left to pace it -- so a session left at EOF
3801 /// reports a `now()` that walks off the end of the timeline in real time,
3802 /// and a caller that reads the playhead (a cut, a paste, an insert) then
3803 /// acts at a position no clip is at. How far off depends only on how long
3804 /// the window was left open, so no clamp in a caller is worth writing.
3805 ///
3806 /// End of stream is deliberately left set: the picture is still the last
3807 /// frame and this is still the end. That is what makes it safe to call on
3808 /// the crossing into it -- the state the transport shows does not change,
3809 /// only the running clock stops.
3810 pub fn halt_at_end(&mut self) {
3811 self.pause();
3812 self.clock.seek_to(self.timeline_duration());
3813 }
3814
3815 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
3816 /// one knob, because muting and turning it down are the same thing to the
3817 /// device, and *which* the user meant is a question only the UI can answer
3818 /// -- it keeps the level to come back to.
3819 ///
3820 /// Deliberately not session state: nothing here remembers it, so a caller
3821 /// pushes it once per session and an export -- which renders the file
3822 /// rather than what the speakers are doing -- can never pick it up. Silent
3823 /// with no audio device, which is also the only honest answer there.
3824 ///
3825 /// Mute is not pause: the samples are still consumed and the device clock
3826 /// still runs, so the picture keeps playing against it.
3827 pub fn set_gain(&self, gain: f32) -> bool {
3828 match &self.audio {
3829 Some(audio) => audio.ao.lock().unwrap().set_volume(gain),
3830 None => false,
3831 }
3832 }
3833
3834 /// A copy of the most recent mono samples the device was handed, and the
3835 /// rate they play at: the signal *after* every clip's equalizer, speed and
3836 /// the mix, which is what an analyser drawn behind an EQ curve has to show.
3837 /// `None` with no audio output at all, and empty until the feeder has
3838 /// written once (right after a seek, for instance).
3839 ///
3840 /// Never blocks anything that matters: the feeder holds this lock for one
3841 /// memcpy and the device's own callback lives in the plugin, on the far
3842 /// side of a ring buffer, where it cannot see this at all.
3843 pub fn audio_tap(&self) -> Option<(Vec<f32>, u32)> {
3844 let audio = self.audio.as_ref()?;
3845 let tap = audio.tap.lock().unwrap().clone();
3846 Some((tap, audio.sample_rate))
3847 }
3848
3849 /// Says that this session is being **watched in real time**, so a picture
3850 /// whose moment has passed is worth nothing and the decode worker may drop
3851 /// it where it is cheap to drop -- before the conversion (a full BGRA pass
3852 /// over 8 MB at 1080p) and before the queue.
3853 ///
3854 /// Off by default, and that is the contract every *pull* consumer relies on:
3855 /// an export, the file-level [`DecodeSession`] API and a test draining as
3856 /// fast as it can all ask for a range of frames and must be given every one
3857 /// of them, in order. Only a viewer has a moment for a picture to be past.
3858 ///
3859 /// A front-end that turns this on was dropping those very frames itself, one
3860 /// repaint later (`Player::pump` takes everything due and shows the last):
3861 /// what changes is where the work stops, and therefore how quickly a decoder
3862 /// that fell behind catches up.
3863 ///
3864 /// It does not replace [`resync_picture`](Self::resync_picture): both
3865 /// mechanisms are live and this one is the first line. It catches up without
3866 /// restarting anything, which is why the front-end's resync -- a picture
3867 /// restart, once per `RESYNC_GAP` -- now fires only where dropping was not
3868 /// enough (a decoder so far behind that even one picture in nine
3869 /// ([`crate::decode`]'s `LATE_RUN`) cannot close the gap).
3870 pub fn drop_late_pictures(&mut self, on: bool) {
3871 self.drop_late = on;
3872 }
3873
3874 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
3875 /// workers are replaced rather than steered: a fresh channel cannot hold a
3876 /// stale frame, and it works just as well after EOF, where the old workers
3877 /// have already exited.
3878 ///
3879 /// Playing stays playing and paused stays paused -- but a paused seek still
3880 /// decodes, so the caller can show the frame it landed on.
3881 pub fn seek(&mut self, secs: f64) {
3882 let (t, target) = self.landing(secs);
3883 let was_playing = self.clock.is_playing();
3884 self.stop_audio();
3885 self.start_picture(target);
3886 let audio_running = self.start_audio(target);
3887 // Same invariant as `play`: position the clock before audio restarts.
3888 if audio_running && self.clock.source() != ClockSource::Audio {
3889 self.clock.switch_to_audio();
3890 }
3891 self.clock.seek_to(t);
3892 self.resume(was_playing);
3893 }
3894
3895 /// Abandons whatever the picture worker still owes and restarts it at the
3896 /// clock. The sound and the clock are untouched -- this is the *video*
3897 /// catching up to its master, not a seek -- so nothing the ear is following
3898 /// moves, and a caller that is behind by more than it can watch calls this
3899 /// instead of waiting for a decoder that only falls further back
3900 /// (`Player::pump`).
3901 pub fn resync_picture(&mut self) {
3902 self.invalidate(Dirty::Picture);
3903 }
3904
3905 /// Where a seek to `secs` lands: the clamped timeline position and the
3906 /// timeline frame it means. The one place the clamp lives, so every
3907 /// invalidation below lands on the same frame a seek would.
3908 fn landing(&self, secs: f64) -> (f64, u32) {
3909 let fps = self.meta.frame_rate;
3910 let total = self.project.timeline_frames();
3911 let t = secs.clamp(0.0, f64::from(total) / fps);
3912 (t, secs_to_frame(t, fps).min(total.saturating_sub(1)))
3913 }
3914
3915 /// Rebuilds the **picture** at `target` and touches nothing else: the sound
3916 /// keeps playing out of the same stream, the clock keeps running, and a
3917 /// grade dragged during playback is therefore silent.
3918 fn start_picture(&mut self, target: u32) {
3919 // Abandon first, drop second: the old worker may be parked in `send` on
3920 // the bounded channel, where only the disconnect wakes it -- and it
3921 // then finds the span already superseded. The *thread* is kept, and
3922 // with it the open file and the open decoder, so a seek onto the same
3923 // source costs a demuxer seek and a decoder flush rather than the
3924 // VA-API init (98 ms) a new worker would pay; a worker that cannot take
3925 // the new span is retired by [`retire`](Self::retire) instead, and
3926 // nothing on this thread joins either way.
3927 self.worker.abandon();
3928 // The span runs from `target` to the end of whatever it landed in -- a
3929 // clip, or a gap, which starts a black-frame worker instead. `None` is
3930 // the emptied timeline, black too, and `start_span` says so.
3931 self.start_span(self.project.composite_span_at(target));
3932 self.eos = false;
3933 }
3934
3935 /// Silences the device and supersedes whatever is feeding it: the first half
3936 /// of every audio restart, and the only thing that ever discards queued
3937 /// sound.
3938 fn stop_audio(&mut self) {
3939 self.mix = None;
3940 if let Some(audio) = &self.audio {
3941 let ao = audio.ao.lock().unwrap();
3942 ao.set_active(false);
3943 // Bumped and flushed while holding the device lock, because the
3944 // feeder re-checks the epoch inside that same lock: whatever it is
3945 // carrying can no longer reach the ring after this point.
3946 audio.epoch.fetch_add(1, Ordering::Release);
3947 // Nothing of the new stream has been played yet, by definition.
3948 audio.content_at.store(-1, Ordering::Release);
3949 ao.flush();
3950 // The flushed samples are not being played any more, so nothing may
3951 // still be drawn from them.
3952 audio.tap.lock().unwrap().clear();
3953 }
3954 }
3955
3956 /// Puts the device back where it was: playing if it was playing, and with
3957 /// the clock held until the new stream is really audible (see
3958 /// [`Audio::content_at`]).
3959 ///
3960 /// Only the *intent* is set here: the open runs on the feeder
3961 /// ([`start_audio`](Self::start_audio)), so the device is started by that
3962 /// stream's first real sample instead ([`Audio::wants_active`]). A device
3963 /// made active over an empty ring plays its own silence and counts one
3964 /// underrun per starved quantum -- a scripted cold play-seek-scrub session
3965 /// used to go from 5 to 1721 of them -- while the ear hears the same silence
3966 /// either way, so nothing is gained for the count that is lost.
3967 fn resume(&mut self, was_playing: bool) {
3968 self.priming = true;
3969 if let Some(audio) = &self.audio {
3970 audio.set_playing(was_playing);
3971 }
3972 }
3973
3974 /// Rebuilds the **sound** from `target` -- the second half of a restart --
3975 /// and says whether a feeder took the job. Not whether it will find
3976 /// anything to play: the stream is opened on that feeder
3977 /// ([`Audio::spawn_feeder_deferred`]), so a silent timeline is heard of
3978 /// there, not here. Nothing on this thread reads the file.
3979 ///
3980 /// The clock is unaffected by the wait, which is the reason it may be a
3981 /// long one: it holds where the seek put it until the *first real sample*
3982 /// is queued ([`Audio::content_at`], [`tick`](Self::tick)), whether that is
3983 /// ten milliseconds later or ten seconds.
3984 ///
3985 /// `true` is therefore *optimistic*, and the callers' `switch_to_audio` with
3986 /// it: a timeline that turns out to have nothing to play ends its feeder at
3987 /// once, which sets `fed_all` and hands the clock back to wall time at the
3988 /// next tick, from where it stood ([`PlaybackClock::switch_to_wall`] is
3989 /// continuous, so nothing jumps).
3990 fn start_audio(&mut self, target: u32) -> bool {
3991 let fps = self.meta.frame_rate;
3992 let mut audio_running = false;
3993 let mut live = None;
3994 // A dead output gets an attempt here without waiting out the cooldown: a
3995 // seek is a person asking, and this is the one moment the sound can come
3996 // back into step with the picture, because the feeder opened below starts
3997 // at the target. If it does not come back the flag stands and the guard
3998 // under it leaves the clock on wall time.
3999 self.rearm_audio(Duration::ZERO);
4000 if let Some(audio) = &self.audio
4001 && !audio.died.load(Ordering::Acquire)
4002 {
4003 // The device position keeps counting across a flush, so re-basing
4004 // `fed` on it is what keeps `played_out` exact for the new stream.
4005 let played = audio.ao.lock().unwrap().position().unwrap_or(0).max(0) as u64;
4006 audio.fed.store(played * audio.channels, Ordering::Relaxed);
4007 audio.fed_all.store(false, Ordering::Release);
4008 // One worker for the whole rest of the timeline, so the joins
4009 // between clips are gapless: the video reopens at a boundary, the
4010 // ear never hears it -- and a join between two *files* is just
4011 // another segment, because every segment names its own source.
4012 // One play list per audio lane, summed by the mixer: what the ear
4013 // hears is every lane at once, and a lane's own gaps are silence in
4014 // it rather than a hole in the count the master clock keeps.
4015 let segs = self.project.audio_segments_from(target, fps);
4016 // The equalizers beside them, one per segment: the worker filters a
4017 // segment's own samples before the mix, so a clip's curve reaches
4018 // that clip and stops. Rebuilt on every seek, which is what makes an
4019 // EQ edit audible at once -- `edit` reseeks, so the drag that
4020 // changed a band restarts the workers with the new curve already in
4021 // them, and no live channel has to reach into a running one.
4022 let eqs = self.project.audio_eqs_from(target, fps);
4023 // ...and the rates, the same way again: a speeded segment is
4024 // resampled inside its own worker, before the mix, so what the ear
4025 // hears is what the timeline shows. Empty for a project nobody has
4026 // speeded, which is the path that decodes the same samples it always
4027 // did.
4028 let speeds = self.project.audio_speeds_from(target, fps);
4029 // ...and the fades, the same way again: a clip's own envelope runs
4030 // inside its worker, after the rate and the equalizer, so a fade
4031 // edit is audible at once exactly as an EQ edit is.
4032 let fades = self.project.audio_fades_from(target, fps);
4033 // Each source on the stream it was placed with: what plays is what
4034 // the library row said, and what an export copies (`export::run`).
4035 let sources = self.project.audio_sources();
4036 // ...and the mix settings over the lot: each lane's own volume on
4037 // its way into the sum and the master limiter over the sum. These
4038 // two are handed over *live* as well as at the open: they sit at
4039 // the sum, where nothing is decoded, so a fader moved later is a
4040 // number the running mixer picks up rather than a stream rebuilt
4041 // under the ear ([`crate::audio::MixControls`]).
4042 let gains = self.project.audio_gains();
4043 let limiter = self.project.limiter();
4044 let controls = crate::audio::MixControls::new(gains.clone(), limiter);
4045 // Only a mixed timeline has a mixer to talk to; the single-lane
4046 // flat path is the bit-exact one and has none. Decided here from
4047 // the very lists the open is about to be handed
4048 // ([`AudioSession::is_mixed`]) rather than read off the handle
4049 // afterwards, because there *is* no afterwards on this thread any
4050 // more -- the open runs on the feeder.
4051 let mixed = crate::audio::AudioSession::is_mixed(segs.len(), &gains, limiter);
4052 let worker_controls = Arc::clone(&controls);
4053 // ...and the rate the mix runs at, if the project picked one: the
4054 // same override [`crate::edith::save`] writes and [`Self::open_project`]
4055 // reads back.
4056 let sample_rate = self.sample_rate;
4057 // ...and the open itself -- every track a segment names, its packet
4058 // table, its priming -- happens there too. That is the whole point:
4059 // one `pread` on a cold 25 GB film is seconds, and this is called
4060 // from a ruler drag ([`Audio::spawn_feeder_deferred`]).
4061 audio_running = audio.spawn_feeder_deferred(move || {
4062 match AudioSession::open_mixed_streams_live_fade(
4063 &sources,
4064 &segs,
4065 &eqs,
4066 &speeds,
4067 &fades,
4068 fps,
4069 &gains,
4070 limiter,
4071 Some(&worker_controls),
4072 sample_rate,
4073 ) {
4074 Ok(Some((_, rx))) => Some(rx),
4075 // A silent timeline, and a source that will not open: both
4076 // feed nothing, which the feeder itself reports by ending.
4077 // The mix goes with them -- no mixer was started, so a fader
4078 // moved later must rebuild the sound rather than hand its
4079 // number to a thread that does not exist
4080 // ([`crate::audio::MixControls::detach`]).
4081 Ok(None) => {
4082 worker_controls.detach();
4083 None
4084 }
4085 Err(e) => {
4086 worker_controls.detach();
4087 // A read this session abandoned on purpose -- the seek
4088 // after it, or the session going away -- is not a file
4089 // that would not open, and says nothing.
4090 if !crate::demux::is_cancelled(&e) {
4091 eprintln!("timeline audio open failed: {e}");
4092 }
4093 None
4094 }
4095 }
4096 });
4097 live = (audio_running && mixed).then_some(controls);
4098 if !audio_running {
4099 // Nothing will ever be fed again; let `tick` fall to wall time
4100 // instead of waiting on a device that has no more work coming.
4101 audio.fed_all.store(true, Ordering::Release);
4102 }
4103 }
4104 self.mix = live;
4105 audio_running
4106 }
4107
4108 /// Rebuilds the sound alone, from where the playhead is: what a change that
4109 /// no picture can show goes through. The video worker is left decoding, so
4110 /// the picture does not blink -- and the clock, held still by
4111 /// [`resume`](Self::resume) until the new stream is audible, puts the sound
4112 /// back exactly where the picture already is.
4113 ///
4114 /// End of stream is deliberately left alone -- no picture worker is started
4115 /// here, so a timeline that was played out still is; see
4116 /// [`is_eos`](Self::is_eos).
4117 fn reseek_audio(&mut self) {
4118 let (t, target) = self.landing(self.now());
4119 let was_playing = self.clock.is_playing();
4120 self.stop_audio();
4121 let audio_running = self.start_audio(target);
4122 if audio_running && self.clock.source() != ClockSource::Audio {
4123 self.clock.switch_to_audio();
4124 }
4125 self.clock.seek_to(t);
4126 self.resume(was_playing);
4127 }
4128
4129 /// Renders the edited timeline to `out` on a worker thread. The session is
4130 /// untouched -- the export decodes the source file for itself -- but a
4131 /// caller should still [`pause`](PlaybackSession::pause) first, because
4132 /// playback and export otherwise fight over the same decoder hardware.
4133 ///
4134 /// Later edits do not reach a running export: it works from a snapshot of
4135 /// the edit list taken here.
4136 ///
4137 /// corner-cut: this defaults the settings; the app still calls it that way,
4138 /// and the export options card replaces the call with
4139 /// [`export_to_with`](PlaybackSession::export_to_with).
4140 pub fn export_to(&self, out: &Path) -> crate::ExportHandle {
4141 self.export_to_with(out, &crate::export::ExportSettings::default())
4142 }
4143
4144 /// [`export_to`](PlaybackSession::export_to) with the output settings spelled
4145 /// out rather than defaulted.
4146 pub fn export_to_with(
4147 &self,
4148 out: &Path,
4149 settings: &crate::export::ExportSettings,
4150 ) -> crate::ExportHandle {
4151 crate::export::start(
4152 self.project.export_snapshot(),
4153 self.meta,
4154 out,
4155 settings,
4156 self.sample_rate,
4157 )
4158 }
4159
4160 /// Moves the clock forward; the caller runs this once per rendered frame.
4161 /// Costs an atomic load, and once per session a mode switch.
4162 pub fn tick(&mut self) {
4163 // Before every early return below: where the playhead stands is what the
4164 // decode worker drops its stale pictures against, and a front-end that
4165 // repaints without draining (a slow frame, a busy render thread) must
4166 // still be moving it -- otherwise the queue fills with pictures whose
4167 // moment passed while nobody was taking them.
4168 self.publish_playhead();
4169 // Before the clock-source guard below, and not after it: a dead output is
4170 // what *puts* the clock on wall time, so this branch has to keep running
4171 // while it is there -- the one attempt that can bring the sound back is
4172 // in it.
4173 if self
4174 .audio
4175 .as_ref()
4176 .is_some_and(|audio| audio.died.load(Ordering::Acquire))
4177 {
4178 // Output died mid-stream: its position will never reach `fed`, so the
4179 // EOF comparison below is unreachable. Wall time takes over from
4180 // wherever the clock last stood, and the session says so rather than
4181 // going silent for good without a word: a front-end already has a
4182 // line for a silent session ([`Self::audio_disabled_reason`]).
4183 if self.audio_disabled.is_none() {
4184 self.audio_disabled = Some(AUDIO_LOST.to_string());
4185 }
4186 self.clock.switch_to_wall();
4187 // ...and the output is offered another open, once a second: a
4188 // restarting daemon takes a moment, and this runs once a frame. A
4189 // re-arm that takes is what clears the notice, and the next seek
4190 // feeds it.
4191 self.rearm_audio(AUDIO_REARM_AFTER);
4192 return;
4193 }
4194 let Some(audio) = &self.audio else {
4195 return; // wall time from the start, nothing to poll
4196 };
4197 if self.clock.source() != ClockSource::Audio {
4198 return;
4199 }
4200 // `None` until the device's first callback: the clock holds at its
4201 // anchor rather than guessing, which is why playback starts on time
4202 // instead of a quantum early.
4203 let Some(position) = audio.ao.lock().unwrap().position() else {
4204 return;
4205 };
4206 if audio.played_out(position) {
4207 // Audio EOF. Wall time carries the same timeline on from here, with
4208 // no jump, and this branch cannot be reached again.
4209 //
4210 // The device is stopped with it: nothing will ever be queued for
4211 // this stream again, so every quantum it would go on playing is
4212 // silence counted as a decoder that fell behind -- the tail of a
4213 // stream, where [`crate::ao`]'s own `primed` covers the head of
4214 // one. A seek from here starts it again like any other
4215 // ([`resume`](Self::resume)), which is why the stamp goes with it:
4216 // there is no sample of *this* stream left to start on.
4217 audio.set_playing(false);
4218 audio.content_at.store(-1, Ordering::Release);
4219 self.clock.switch_to_wall();
4220 return;
4221 }
4222 if self.priming {
4223 // A stream that has been started and has not been heard yet: the
4224 // device is playing the silence of its own restart, and none of it
4225 // is timeline time ([`Audio::content_at`]). The clock holds where
4226 // the seek left it -- so the picture holds too, on the frame it
4227 // landed on, rather than sliding ahead of a sound that has not
4228 // started.
4229 let started = audio.content_at.load(Ordering::Acquire);
4230 if started < 0 {
4231 return;
4232 }
4233 // ...and then the *first sample of the stream* becomes the
4234 // reference, not whatever position this poll happened to catch: the
4235 // clock's own anchor is its first report ([`PlaybackClock`]), and
4236 // anchoring it here is what makes a mid-play edit cost no offset.
4237 //
4238 // corner-cut: `started` is the position when the sample was queued,
4239 // and it is heard at the next callback -- up to one quantum (5-21
4240 // ms) later, so that much of the restart is still counted. Upgrade
4241 // path is the position at the first *pop* of real audio, which only
4242 // the plugin's RT thread can see.
4243 self.clock
4244 .set_audio_position(started as u64, audio.sample_rate);
4245 self.priming = false;
4246 }
4247 self.clock
4248 .set_audio_position(position as u64, audio.sample_rate);
4249 }
4250}
4251
4252impl Drop for PlaybackSession {
4253 /// The video workers -- the running one and every cancelled one still in
4254 /// [`retired`](PlaybackSession::retired) -- cancel and join themselves when
4255 /// those fields drop right after this, the running one behind its receiver
4256 /// so a `send` cannot hold the join. *That* is what a session must not exit
4257 /// without: no decode worker outlives it, so none can be inside libva when
4258 /// Mesa's `atexit` handlers free the state under it.
4259 ///
4260 /// This is the audio half: bumping the epoch retires the feeder at its next write,
4261 /// which drops the decode receiver with it. Neither is waited for -- no
4262 /// driver state is torn down on the audio side.
4263 fn drop(&mut self) {
4264 if let Some(audio) = &self.audio {
4265 audio.epoch.fetch_add(1, Ordering::Release);
4266 }
4267 }
4268}
4269
4270/// Whether `path`, already demuxed to `meta`, may join a timeline whose
4271/// parameters are `timeline` and whose audio probes as `first`: a decoder this
4272/// machine can open, audio parameters that agree (or no audio at all), and a
4273/// frame rate that can be named
4274/// against the timeline's. The [`Rate`] it will be read at comes back with the
4275/// answer, so the number the check was decided on is the number it plays by.
4276///
4277/// *Not* the same size any more. A project has its own resolution
4278/// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its
4279/// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
4280/// letterboxed clip rather than a refusal, and so is a frame rate of its own:
4281/// the timeline keeps its own rate and the file is read at [`Rate`] against it
4282/// ([`PlaybackSession::import`] notes how long it is *here*). Nor the same
4283/// codec: every clip opens its own decoder, so a mixed-codec timeline is a
4284/// decoder each rather than a refusal.
4285///
4286/// The `Err` names the property that disagrees, and those strings are what a
4287/// front-end shows verbatim; [`PlaybackSession::import`] and
4288/// [`PlaybackSession::open_project`] share them so a file refused at import is
4289/// refused in the same words at load.
4290fn matches_timeline(
4291 source: &Source,
4292 meta: &VideoMeta,
4293 timeline: &VideoMeta,
4294 first: &Option<crate::AudioProbe>,
4295) -> crate::Result<Rate> {
4296 // The codec is *not* held to the timeline's -- every clip opens its own
4297 // decoder, so an H.264 take and an HEVC one play on one timeline. What the
4298 // codec gate was really protecting against stays, in the one place that
4299 // can actually answer it: on a machine without the VA-API plugin an HEVC,
4300 // VP9 or VP8 clip would be black frames with the refusal on stderr alone,
4301 // so the file is asked for a decoder *here*, at the door, where the `Err`
4302 // is still something a front-end can show. A zero-length range probes and
4303 // starts no
4304 // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`]
4305 // only enters VA-API off that path.
4306 DecodeSession::open_worker(
4307 &source.path,
4308 0,
4309 0,
4310 ColorParams::default(),
4311 TransformParams::default(),
4312 Composer::passthrough(),
4313 // A zero-length range decodes nothing, so no table is built and the
4314 // rendition cannot matter here.
4315 crate::tonemap::Preset::default(),
4316 )?;
4317 // The frame rate is *not* a refusal any more: a file shot at another rate is
4318 // placed for the seconds it lasts and read through [`Rate`] at the
4319 // decoder's door, so it plays at the speed it was shot at on a timeline
4320 // that counts frames faster or slower.
4321 //
4322 // A rate that cannot be *named* still is, and this is the one place it is
4323 // caught: `Rate::from_fps` builds itself out of the muxer's own timescales,
4324 // and a file whose rate has none of those (a container that says nothing and
4325 // holds one block, so the demuxer measures 0 fps) would otherwise be read
4326 // 1:1 in silence -- the old rate gate refused those too, by arithmetic
4327 // accident. The `Err` is `mux::frame_timing`'s own words.
4328 let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?;
4329 audio_matches(source, first)?;
4330 Ok(rate)
4331}
4332
4333/// Whether a candidate's audio may join a timeline whose first source probes as
4334/// `first`: same layout -- or no audio of its own at all, which is silence over
4335/// the clip's span and agrees with everything. One output device and one
4336/// exported track is all there is, so one width; the *rate* is conformed rather
4337/// than matched ([`crate::audio::Resample`]), which is why it is not asked
4338/// about here.
4339///
4340/// The audio half of [`matches_timeline`], which a stream placed on its own
4341/// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
4342/// comes with is already on the timeline.
4343///
4344/// The format itself is deliberately *not* part of this: an mp3 that agrees on
4345/// layout plays alongside a timeline of mp4s perfectly well. What it
4346/// cannot do is be copied into an export, which is a refusal of its own, at
4347/// export time (`AudioSession::copy_multi_streams`).
4348/// What a timeline's audio is held to: the probe of the first source that could
4349/// have any track.
4350///
4351/// The probe of the first source that really **has a track**, walking forward
4352/// past a still (no track by definition) and past a source whose file carries
4353/// none (a screen recording with no sound). A silent leading source must not
4354/// pin the timeline's layout: pinned to it, a later file with sound could never
4355/// be admitted, and the layout a *following* file is held to would be the
4356/// silent source's `None`. This is the same walk
4357/// [`PlaybackSession::open_project`] makes when it opens the device -- the two
4358/// have to agree, so probing and opening can never name different sources.
4359///
4360/// `Ok(None)` for a timeline with no track anywhere: nothing but stills, with
4361/// no file at all, or every non-still source silent. That is a silent timeline,
4362/// and a file with sound is admitted onto it -- it *becomes* the timeline's
4363/// sound ([`PlaybackSession::arm_audio`] opens the device for it), exactly the
4364/// c581d41 rule ("a later source with real audio must be heard") at the add
4365/// door.
4366fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
4367 for source in sources.iter().filter(|s| !crate::is_image(&s.path)) {
4368 if let Some(probe) = AudioSession::probe(&source.path, source.audio_stream)? {
4369 return Ok(Some(probe));
4370 }
4371 }
4372 Ok(None)
4373}
4374
4375/// *Which* source that is: the first one that is not a still. The single answer
4376/// to "what does this timeline's sound come from", so that probing it
4377/// ([`first_audio_of`]) and opening the device on it
4378/// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only
4379/// the scaffolding file until a save renumbers it or a library removal takes it
4380/// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the
4381/// device is a timeline that plays silent although every clip on it has sound.
4382///
4383/// `None` for a library of nothing but stills, and for one with no file at all:
4384/// both are silent timelines.
4385fn audio_source_of(sources: &[Source]) -> Option<&Source> {
4386 sources.iter().find(|s| !crate::is_image(&s.path))
4387}
4388
4389fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
4390 let probe = AudioSession::probe(&source.path, source.audio_stream)?;
4391 audio_matches_probed(probe, first)
4392}
4393
4394/// The verdict alone, once the file's own header is in hand: the half a session
4395/// with a memo behind it ([`PlaybackSession::audio_matches_cached`]) does not
4396/// have to open the file for.
4397fn audio_matches_probed(
4398 probe: Option<crate::AudioProbe>,
4399 first: &Option<crate::AudioProbe>,
4400) -> crate::Result<()> {
4401 // The layout, which the audio worker holds every source to anyway -- and not
4402 // the rate any more: a file written at another one is resampled to the
4403 // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as
4404 // a file shot at another frame rate is read through [`Rate`]. Both silent is
4405 // a match.
4406 if probe.map(|p| p.channels) == first.map(|p| p.channels) {
4407 return Ok(());
4408 }
4409 // A mono file joins a wider timeline: [`crate::audio::widen`] duplicates
4410 // its one channel into every channel the timeline carries, the inverse of
4411 // the [`crate::audio::downmix`] a wider file already folds through. The
4412 // reverse -- a wider file onto a mono timeline -- stays refused below;
4413 // nothing here narrows a source, only the decoder's own downmix does.
4414 if let (Some(p), Some(b)) = (probe, first) {
4415 if p.channels == 1 && b.channels > 1 {
4416 return Ok(());
4417 }
4418 }
4419 // ...and a *silent* file joins whatever the timeline is: it contributes
4420 // silence over its span, which is the very thing both audio paths already
4421 // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays
4422 // it, `AudioSession::copy_multi_streams` writes it). There is no rate and
4423 // no layout to disagree about, so there is nothing left to refuse.
4424 let Some(probe) = probe else {
4425 return Ok(());
4426 };
4427 // The timeline has no track anywhere (nothing but stills, or every
4428 // non-image source silent): there is no layout to disagree with, and the
4429 // arriving file with sound *becomes* the timeline's sound --
4430 // [`PlaybackSession::arm_audio`] opens the device for it, exactly the walk
4431 // [`PlaybackSession::open_project`] makes. Refusing here ("the file has
4432 // audio, the timeline is silent") pinned the timeline to its silent first
4433 // source for good: remove that file and add another, and the second file's
4434 // sound could never be heard.
4435 let Some(b) = first else {
4436 return Ok(());
4437 };
4438 Err(format!(
4439 "audio {} ch does not match the timeline's {} ch",
4440 probe.channels, b.channels
4441 )
4442 .into())
4443}
4444
4445/// How many timeline frames a still image is *held to*: [`IMAGE_MAX_SECS`] of
4446/// them, since an image has no length of its own. The number a source's own
4447/// entry in [`PlaybackSession::counts`] gets, so a trim may drag an image out
4448/// to ten minutes and no further -- and so a saved project reloads, because
4449/// [`PlaybackSession::open_project`] recomputes exactly this and refuses a clip
4450/// that ends past it.
4451fn image_frames(fps: f64) -> u32 {
4452 ((IMAGE_MAX_SECS * fps)
4453 .ceil()
4454 .clamp(1.0, f64::from(u32::MAX))) as u32
4455}
4456
4457/// How long a still is placed for: [`IMAGE_PLACE_SECS`], never past the length
4458/// it is held to and never zero (a clip is never empty).
4459fn place_frames(count: u32, fps: f64) -> u32 {
4460 ((IMAGE_PLACE_SECS * fps)
4461 .ceil()
4462 .clamp(1.0, f64::from(count.max(1)))) as u32
4463}
4464
4465/// How many timeline frames a standalone audio file occupies: its playing time
4466/// rounded *up*, so the last partial frame is still covered rather than cut off,
4467/// and never zero (a clip is never empty).
4468fn audio_frames(path: &Path, fps: f64) -> crate::Result<u32> {
4469 let secs = AudioSession::duration_secs(path)?
4470 .ok_or_else(|| format!("{} has no audio track", path.display()))?;
4471 let frames = (secs * fps).ceil();
4472 if !frames.is_finite() || frames < 0.0 || frames > f64::from(u32::MAX) {
4473 return Err(format!(
4474 "{} is {secs} s long, which is not a timeline",
4475 path.display()
4476 )
4477 .into());
4478 }
4479 Ok((frames as u32).max(1))
4480}
4481
4482/// `None` for a silent session -- no audio track, no plugin, no daemon, or a
4483/// track the decoder refuses. Dropping the receiver on the way out stops the
4484/// audio decode worker, so a failure here leaves nothing running.
4485///
4486/// The second half is why, for the cases the *file* is to blame for: those are
4487/// a surprise worth showing (see
4488/// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a
4489/// file with no audio at all and a machine with no output device are not.
4490fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
4491 let sources = [(path.to_path_buf(), stream)];
4492 let (meta, rx) =
4493 match AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) {
4494 Ok(Some(opened)) => opened,
4495 // No AAC track: silent by nature, or sound in a codec we do not
4496 // have -- and only the second of those is worth a word.
4497 Ok(None) => {
4498 let reason = AudioSession::unsupported(path).ok().flatten();
4499 if let Some(reason) = &reason {
4500 eprintln!("audio disabled: {reason}");
4501 }
4502 return (None, reason);
4503 }
4504 Err(e) => {
4505 eprintln!("audio disabled: {e}");
4506 return (None, Some(e.to_string()));
4507 }
4508 };
4509 let Some(ao) = AoSession::open(meta.sample_rate, u32::from(meta.channels)) else {
4510 return (None, None); // no device: the machine's business, not the file's
4511 };
4512 // The stream comes up streaming; a session starts paused, so silence the
4513 // device until `play`. The feeder still fills the ring in the meantime.
4514 ao.set_active(false);
4515
4516 let audio = Audio {
4517 ao: Arc::new(Mutex::new(ao)),
4518 sample_rate: meta.sample_rate,
4519 channels: u64::from(meta.channels),
4520 fed: Arc::new(AtomicU64::new(0)),
4521 fed_all: Arc::new(AtomicBool::new(false)),
4522 died: Arc::new(AtomicBool::new(false)),
4523 epoch: Arc::new(AtomicU64::new(0)),
4524 content_at: Arc::new(AtomicI64::new(-1)),
4525 wants_active: Arc::new(AtomicBool::new(false)),
4526 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),
4527 feeders: Arc::new(AtomicUsize::new(0)),
4528 rearm_at: Arc::new(Mutex::new(None)),
4529 };
4530 (audio.spawn_feeder(rx).then_some(audio), None)
4531}
4532
4533/// Pours decoded chunks into the device, keeping whatever the ring would not
4534/// take. Ends when the decoder is done, the output dies, or a seek supersedes
4535/// this feeder.
4536fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
4537 let mut pending: Vec<f32> = Vec::new();
4538 loop {
4539 if pending.is_empty() {
4540 match rx.recv() {
4541 Ok(chunk) => pending = chunk.samples,
4542 Err(_) => {
4543 // Decoder finished or went away. What is in the ring still
4544 // plays out; what comes after it is the end of the timeline
4545 // and not a decoder that fell behind, so the device is told
4546 // to stop counting it. Under the lock and past the epoch,
4547 // like every other word this thread has with the device: a
4548 // superseded feeder must not say this about the stream that
4549 // replaced it.
4550 let ao = audio.ao.lock().unwrap();
4551 if audio.epoch.load(Ordering::Acquire) == epoch {
4552 ao.stream_ended();
4553 }
4554 return;
4555 }
4556 }
4557 }
4558 let accepted = {
4559 let mut ao = audio.ao.lock().unwrap();
4560 // Under the lock, immediately before the write: `seek` bumps the
4561 // epoch and flushes the ring holding this very lock, so past this
4562 // check no stale sample can be queued behind the flush.
4563 if audio.epoch.load(Ordering::Acquire) != epoch {
4564 return;
4565 }
4566 let accepted = match ao.write(&pending) {
4567 Some(n) => n,
4568 None => {
4569 // Output died; flag it so `tick` moves the clock to wall time.
4570 audio.died.store(true, Ordering::Release);
4571 return;
4572 }
4573 };
4574 // The first sample of this stream to reach the ring, stamped with
4575 // what the device had played by then: everything before it was the
4576 // silence of the restart, and [`PlaybackSession::tick`] anchors the
4577 // clock here so that silence is never timeline time. Under the
4578 // device lock, with the epoch already checked, so the stamp and the
4579 // sample belong to the same stream.
4580 if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 {
4581 let at = ao.position().unwrap_or(0).max(0);
4582 audio.content_at.store(at, Ordering::Release);
4583 // ...and the device position this stream's samples are counted
4584 // from ([`Audio::played_out`]). Rebased *here* rather than at
4585 // the seek, because the open runs on this thread now: every
4586 // millisecond it took is device time nobody fed, and counting
4587 // it would make the stream read as played out that long before
4588 // it really is -- an early hand-off to wall time at the end of
4589 // the timeline. The seek's own rebase still stands for the
4590 // stream that never queues a sample at all.
4591 audio
4592 .fed
4593 .store(at as u64 * audio.channels, Ordering::Relaxed);
4594 // ...and *this* is where a playing timeline's device starts: on
4595 // the first sample there is to play, under the same lock and
4596 // past the same epoch check as the stamp, so the silence of the
4597 // open was never played and never counted
4598 // ([`Audio::wants_active`]).
4599 if audio.wants_active.load(Ordering::Acquire) {
4600 ao.set_active(true);
4601 }
4602 } else if accepted == 0 && audio.content_at.load(Ordering::Acquire) < 0 {
4603 // Nothing taken with nothing yet queued is the *flush* of the
4604 // restart still standing: the ring refuses a write until a
4605 // callback has consumed the flag (`engine_audio::accept`), and
4606 // only a running device has callbacks. So the device is started
4607 // here too -- there is a sample in hand, which is what the wait
4608 // was for -- and the quantum or two of that handshake is the
4609 // silence `Shared::primed` does not count.
4610 if audio.wants_active.load(Ordering::Acquire) {
4611 ao.set_active(true);
4612 }
4613 }
4614 accepted
4615 };
4616 audio.fed.fetch_add(accepted as u64, Ordering::Relaxed);
4617 audio.note_tap(&pending[..accepted]);
4618 pending.drain(..accepted);
4619 if !pending.is_empty() {
4620 // Ring full: nothing to do but let the device drain it. Except when
4621 // *nothing* was taken, which after a flush means the ring is still
4622 // waiting for the device to consume the flush flag rather than
4623 // being full: that is the head of a restart, and every millisecond
4624 // spent parked there is a millisecond of silence.
4625 match accepted {
4626 0 => thread::sleep(FLUSH_WAIT),
4627 _ => thread::sleep(RING_FULL_WAIT),
4628 }
4629 }
4630 }
4631}
4632
4633/// Timeline seconds to a 0-based frame index, floor semantics: position `t`
4634/// shows the frame whose interval contains it. The epsilon absorbs float error
4635/// at exact frame boundaries -- `123.0/30.0 * 30.0` is `122.999...`, and a
4636/// bare truncation would land one frame early (S6 finding: 4 of every 300
4637/// frames round-trip wrong through `clip_spans()` seconds without this).
4638fn secs_to_frame(secs: f64, fps: f64) -> u32 {
4639 (secs * fps + 1e-6).floor().max(0.0) as u32
4640}
4641
4642/// Per-byte lerp of two same-sized BGRA8 frames -- [`crate::scale::blend_i420`]'s
4643/// interleaved-buffer twin. By the time a picture reaches [`try_frame`]
4644/// (`PlaybackSession::try_frame`) it is already colour-converted for the
4645/// screen, so there are no separate Y/U/V planes left to blend, only the one
4646/// buffer; straight alpha survives the lerp untouched (255 against 255 is
4647/// still 255). `t` is B's weight, [`crate::export::dissolve_weight`]'s own
4648/// convention.
4649fn blend_bgra(a: &[u8], b: &[u8], t: f32) -> Vec<u8> {
4650 let t = t.clamp(0.0, 1.0);
4651 assert_eq!(a.len(), b.len(), "blend_bgra: mismatched frame sizes");
4652 a.iter()
4653 .zip(b)
4654 .map(|(&av, &bv)| (av as f32 + (bv as f32 - av as f32) * t).round() as u8)
4655 .collect()
4656}
4657
4658#[cfg(test)]
4659mod tests {
4660 use super::{
4661 Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of, blend_bgra, secs_to_frame,
4662 AUDIO_LOST,
4663 };
4664 use std::path::PathBuf;
4665 use std::sync::atomic::Ordering;
4666
4667 fn asset(name: &str) -> PathBuf {
4668 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
4669 .join("../../assets")
4670 .join(name)
4671 }
4672
4673 /// A dead output is not the end of a session's sound.
4674 ///
4675 /// The stream is stopped the way a seek stops one and then flagged the way a
4676 /// failed write flags it ([`feed`]): nothing is feeding and nothing will. The
4677 /// session must say so -- a dead output used to hand the clock to wall time
4678 /// in silence, for the rest of the session's life, through every seek -- and
4679 /// the play (and the seek after it) must put the output back, which is read
4680 /// off the tap: the samples that actually reached the device. A session that
4681 /// only switched the clock leaves the tap empty.
4682 ///
4683 /// The tick below runs with the cooldown already spent (an attempt stamped
4684 /// just now), which is what makes the notice observable at all *and* what
4685 /// proves the one thing a frame-rate poll must not do: open a device that is
4686 /// gone for good sixty times a second.
4687 #[test]
4688 fn a_dead_output_is_rearmed_and_the_sound_comes_back() {
4689 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4690 assert!(
4691 session.audio_tap().is_some(),
4692 "test_av.mp4 carries an audio track, which is what this drives"
4693 );
4694
4695 session.stop_audio();
4696 let audio = session.audio.as_ref().expect("audio");
4697 audio.died.store(true, Ordering::Release);
4698 *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now());
4699
4700 session.tick();
4701 assert_eq!(
4702 session.audio_disabled_reason(),
4703 Some(AUDIO_LOST),
4704 "a dead output went to wall time without a word"
4705 );
4706 assert!(
4707 session.audio.as_ref().expect("audio").died.load(Ordering::Acquire),
4708 "a tick opened the output again inside the cooldown"
4709 );
4710 assert!(
4711 session.audio_tap().expect("audio").0.is_empty(),
4712 "something was still feeding the device"
4713 );
4714
4715 // Playing is the ask that is not throttled: the output is opened again,
4716 // the flag clears and a feeder fills the device -- asynchronously, so the
4717 // tap is waited on.
4718 session.play();
4719 session.seek(1.0);
4720 let mut fed = Vec::new();
4721 for _ in 0..200 {
4722 fed = session.audio_tap().expect("audio").0;
4723 if !fed.is_empty() {
4724 break;
4725 }
4726 std::thread::sleep(std::time::Duration::from_millis(5));
4727 }
4728 assert!(
4729 !fed.is_empty(),
4730 "playing after a dead output fed nothing: the session cannot come back"
4731 );
4732 assert!(
4733 !session.audio.as_ref().expect("audio").died.load(Ordering::Acquire),
4734 "the death flag stood after the output was replaced"
4735 );
4736 assert_eq!(
4737 session.audio_disabled_reason(),
4738 None,
4739 "the notice was left standing over a session that is playing again"
4740 );
4741 }
4742
4743 /// `blend_bgra` at the two ends and the midpoint of its weight -- `t=0` is
4744 /// pure A, `t=1` is pure B, `t=0.5` rounds each byte to its own midpoint.
4745 /// Straight alpha (255 in both) survives every weight, which is the one
4746 /// channel a wrong blend would otherwise fog.
4747 #[test]
4748 fn blend_bgra_interpolates_every_byte_including_alpha() {
4749 let a = [10u8, 20, 30, 255];
4750 let b = [110u8, 120, 130, 255];
4751 assert_eq!(blend_bgra(&a, &b, 0.0), a);
4752 assert_eq!(blend_bgra(&a, &b, 1.0), b);
4753 assert_eq!(blend_bgra(&a, &b, 0.5), [60, 70, 80, 255]);
4754 }
4755
4756 /// A still wants the project's own pixels, not a view near them.
4757 /// [`PlaybackSession::set_view_size`] calls under 8 px no change at all (a
4758 /// window being dragged must not restart the picture every tick), so a
4759 /// caller that means "paint at the project's size" has to say it through
4760 /// [`PlaybackSession::set_view_size_exact`] -- and read its `false` as "the
4761 /// view is already there, the frame in hand is the one wanted", which is
4762 /// what stops it waiting for a picture nothing will reseek into existence.
4763 #[test]
4764 fn a_still_gets_the_exact_view_size_where_a_push_settles_for_near() {
4765 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4766 assert!(session.set_resolution(1920, 1080));
4767 let (w, h) = session.resolution();
4768 assert_eq!((w, h), (1920, 1080));
4769 // A preview-sized push, then the ask a still makes: two pixels short on
4770 // each axis, which the deadbanded push calls no change at all.
4771 assert!(session.set_view_size(1918, 1078));
4772 assert!(
4773 std::ops::Not::not(session.set_view_size(w, h)),
4774 "the push's deadband is exactly what a still cannot use"
4775 );
4776 assert_eq!(
4777 session.view_size(),
4778 (1918, 1078),
4779 "the push left the view near, not at, full -- so a still written now would be short"
4780 );
4781 assert!(
4782 session.set_view_size_exact(w, h),
4783 "the exact setter must move a view the push called close enough"
4784 );
4785 assert_eq!(session.view_size(), (w, h));
4786 // ...and at the size already it says so rather than repainting: that
4787 // `false` is the caller's "write the frame you have".
4788 assert!(std::ops::Not::not(session.set_view_size_exact(w, h)));
4789 }
4790
4791 /// The dissolve window's own edges, in the units [`PlaybackSession::start_span`]
4792 /// computes them in: a `tail_start` of `span.start + span.len - window`
4793 /// puts the very first output frame of the window at `idx_in_window == 0`
4794 /// and the very last at `window - 1`, clamped rather than overrun by a
4795 /// frame that lands exactly on the span's own end -- the same off-by-one
4796 /// a stray `%` or unclamped subtraction would have shown on screen as a
4797 /// blend that never quite reached full B.
4798 #[test]
4799 fn dissolve_window_edges_index_zero_to_window_minus_one() {
4800 let (span_start, span_len, window) = (100u32, 30u32, 10u32);
4801 let tail_start = span_start + span_len - window;
4802 assert_eq!(tail_start, 120);
4803 let idx_in_window = |frame: u32| (frame - tail_start).min(window - 1);
4804 assert_eq!(idx_in_window(120), 0, "first frame of the window");
4805 assert_eq!(idx_in_window(129), 9, "last frame of the window");
4806 assert_eq!(
4807 idx_in_window(130),
4808 9,
4809 "one past the span's own end clamps rather than panics"
4810 );
4811 }
4812
4813 /// A picked project rate overrides the derived one, and its absence leaves
4814 /// the source's own -- the seam every explicit-sample-rate caller
4815 /// (playback rebuild, both export encoders) goes through
4816 /// ([`crate::AudioSession::open_multi_streams_speed_at`]). The per-segment
4817 /// conform chain resamples to whatever `meta` names, so the meta *is* the
4818 /// behaviour.
4819 #[test]
4820 fn a_picked_sample_rate_overrides_the_derived_one() {
4821 let file = asset("test_av.mp4");
4822 let sources = [(file, 0)];
4823 let segs = [(Some(0), 0., 1.)];
4824 let derived = crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], None)
4825 .expect("open the fixture")
4826 .expect("the fixture has sound")
4827 .0
4828 .sample_rate;
4829 let picked =
4830 crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], Some(32000))
4831 .expect("open the fixture")
4832 .expect("the fixture has sound")
4833 .0
4834 .sample_rate;
4835 assert_ne!(derived, 32000, "a fixture at the picked rate proves nothing");
4836 assert_eq!(picked, 32000);
4837 }
4838
4839 /// Which source the timeline's sound is opened on -- the one rule
4840 /// [`open_project`](PlaybackSession::open_project), the probe every import
4841 /// is held to and the audio worker all read through. A still at index 0 is
4842 /// a picture, not a silent timeline: opening the device on it is a project
4843 /// that plays silent although every clip on it has sound.
4844 #[test]
4845 fn the_audio_reference_is_never_a_still() {
4846 let (video, still) = (asset("test_av.mp4"), asset("test_still.png"));
4847 let sources = [Source::new(&still, 0), Source::new(&video, 3)];
4848 assert_eq!(
4849 audio_source_of(&sources).map(|s| (&s.path, s.audio_stream)),
4850 Some((&sources[1].path, 3)),
4851 "the first source that could have a track, with its own stream"
4852 );
4853 assert!(
4854 audio_source_of(&sources[..1]).is_none(),
4855 "nothing but stills"
4856 );
4857 assert!(audio_source_of(&[]).is_none(), "and no file at all");
4858 }
4859
4860 /// What a front end's "resolution/rate picked before any file is open"
4861 /// setting costs the engine: nothing new. `open` then `set_resolution`/
4862 /// `set_frame_rate` right after construction -- the app's technique for
4863 /// applying a pre-import pick to the session it just made, mirroring
4864 /// [`PlaybackSession::open_project`]'s own `doc.resolution`/`doc.fps`
4865 /// override -- lands exactly where either setter lands it whenever it is
4866 /// called, and a later `import` of another file leaves both untouched: an
4867 /// import registers a source and its length, and never writes `meta.width`,
4868 /// `meta.height` or `meta.frame_rate`.
4869 #[test]
4870 fn a_pre_import_setting_survives_construction_and_a_later_import() {
4871 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4872 let native = session.native_resolution();
4873 let native_fps = session.native_frame_rate();
4874 // The explicit picks a pre-import setting would apply, distinct from
4875 // the fixture's own so a no-op would be caught.
4876 let (picked_w, picked_h) = (1920, 1080);
4877 assert_ne!((picked_w, picked_h), native, "the test needs a real change");
4878 let picked_fps = 24.0;
4879 assert_ne!(picked_fps, native_fps, "the test needs a real change");
4880 assert!(session.set_resolution(picked_w, picked_h));
4881 assert!(session.set_frame_rate(picked_fps));
4882 assert_eq!(session.resolution(), (picked_w, picked_h));
4883 assert_eq!(session.meta().frame_rate, picked_fps);
4884
4885 // A second file joining the timeline is exactly the case the front end
4886 // worried a later import could silently override the explicit pick --
4887 // it cannot, because `import` never touches the canvas.
4888 session
4889 .import(&asset("test_av2.mp4"))
4890 .expect("av2 matches the timeline it was set to");
4891 assert_eq!(
4892 session.resolution(),
4893 (picked_w, picked_h),
4894 "an import must not move the project's own canvas size"
4895 );
4896 assert_eq!(
4897 session.meta().frame_rate, picked_fps,
4898 "an import must not move the project's own rate"
4899 );
4900 }
4901
4902 /// The seam between the two lists a source index reaches: dropping a file
4903 /// from the library shortens `sources`, and `counts` -- the frame length
4904 /// per source, which is what a trim is walled by -- has to lose the same
4905 /// entry. Left behind, the dead file's length would wall the survivor.
4906 #[test]
4907 fn removing_a_source_takes_its_frame_count_with_it() {
4908 // Source 0 is 5 s, source 1 is 4 s: two different walls, so a stale
4909 // count cannot pass for the right one.
4910 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4911 session.set_gain(0.0);
4912 // Imported, then dragged onto the end -- an import alone places nothing
4913 // ([`PlaybackSession::import`]), and this test needs both takes there.
4914 session.import(&asset("test_av2.mp4")).expect("av2 matches");
4915 let end = session.timeline_duration();
4916 assert!(
4917 session
4918 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
4919 .expect("a file just imported is on this timeline")
4920 );
4921 let (long, short) = (session.counts[0], session.counts[1]);
4922 assert!(long > short, "{long} vs {short}");
4923
4924 // Clear source 0's take, then take the file itself out: av2's clip is
4925 // the only one left and it is source 0 now.
4926 assert!(session.delete_clip(Lane::V1, 0));
4927 session
4928 .remove_source(&asset("test_av.mp4"), 0)
4929 .expect("nothing plays it any more");
4930 assert_eq!(session.counts, vec![short], "the dead length went with it");
4931 assert_eq!(session.sources().len(), session.counts.len());
4932
4933 // The wall is the surviving file's own length, not the gone one's: a
4934 // whole-file clip cannot be dragged out any further at all.
4935 let clip = session.lane_clips(Lane::V1)[0];
4936 assert_eq!(clip.len(), short, "av2's take, whole");
4937 assert_eq!(
4938 session.trim_room(Lane::V1, 0, Edge::End),
4939 Some((clip.start + 1, clip.end()))
4940 );
4941 assert!(
4942 !session.trim_clip(Lane::V1, 0, Edge::End, clip.end() + 30),
4943 "past the file's last frame is refused, by ITS length"
4944 );
4945
4946 // ...and the next import still lines the two lists up, which is the
4947 // alignment `note_frames` asserts on.
4948 session
4949 .import(&asset("test_av.mp4"))
4950 .expect("it may come back");
4951 assert_eq!(session.counts, vec![short, long]);
4952 assert_eq!(session.sources().len(), session.counts.len());
4953 }
4954
4955 /// The two headers a place reads are read *once*: an mp4 dropped on a lane
4956 /// used to open its own container and the timeline's first source every
4957 /// time, both on the thread that draws, and a film whose pages have gone
4958 /// cold is 1.7 s of that.
4959 ///
4960 /// Proved by answering, not by timing: the memo is filled with a layout the
4961 /// file does not have, and the place is refused. Only a door that read the
4962 /// remembered header rather than the disk can refuse it.
4963 #[test]
4964 fn a_place_reads_each_audio_header_once() {
4965 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4966 session.set_gain(0.0);
4967 session.import(&asset("test_av2.mp4")).expect("av2 matches");
4968 let end = session.timeline_duration();
4969 assert!(
4970 session
4971 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
4972 .expect("a file just imported is on this timeline")
4973 );
4974 assert_eq!(
4975 session.probes.len(),
4976 2,
4977 "the timeline's first source and the file placed, once each"
4978 );
4979
4980 // Now say av2 is 5.1. Nothing on disk changed, so a door that opens the
4981 // file still matches; one that trusts the memo refuses by layout.
4982 // Keyed exactly as a [`Source`] names a file -- canonical, symlinks
4983 // resolved -- which is the key the doors look up.
4984 let av2 = Source::new(asset("test_av2.mp4"), 0).path;
4985 session.probes.insert(
4986 (av2, 0),
4987 Some(crate::AudioProbe {
4988 sample_rate: 48_000,
4989 channels: 6,
4990 }),
4991 );
4992 let refused = session
4993 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
4994 .expect_err("the remembered layout disagrees with the timeline's");
4995 assert!(
4996 refused.to_string().contains("6 ch"),
4997 "refused in the layout's own words: {refused}"
4998 );
4999 assert_eq!(session.probes.len(), 2, "and nothing was opened to say so");
5000 }
5001
5002 /// The door a library preview opens a chosen stream through: `test_multiaudio.mp4`
5003 /// has stream 0 stereo and stream 1 mono
5004 /// ([`crate::waveform::tests::each_stream_of_a_file_has_its_own_envelope`]
5005 /// names the same fixture), so a session that actually bound the stream it
5006 /// was asked for plays a different layout than one that did not -- and
5007 /// plain [`PlaybackSession::open`] still lands on stream 0, unchanged.
5008 #[test]
5009 fn open_with_audio_stream_binds_the_named_track() {
5010 let multi = asset("test_multiaudio.mp4");
5011 let zero = PlaybackSession::open_with_audio_stream(&multi, 0).expect("stream 0 opens");
5012 let one = PlaybackSession::open_with_audio_stream(&multi, 1).expect("stream 1 opens");
5013 let default = PlaybackSession::open(&multi).expect("default open");
5014 let (Some(a0), Some(a1), Some(ad)) =
5015 (zero.audio.as_ref(), one.audio.as_ref(), default.audio.as_ref())
5016 else {
5017 // No audio device on this machine: nothing further to check --
5018 // the device is the machine's business, not this door's.
5019 return;
5020 };
5021 assert_eq!(a0.channels, 2, "stream 0 is the stereo pair");
5022 assert_eq!(a1.channels, 1, "stream 1 is the mono track");
5023 assert_ne!(a0.channels, a1.channels, "the two streams must differ");
5024 assert_eq!(ad.channels, a0.channels, "open() still defaults to stream 0");
5025 }
5026
5027 /// The bug this regression pins: a preview paused (or scrubbed) to a
5028 /// frame inside a dissolve window used to show plain A forever, because
5029 /// B's decoder only opened on the tick that landed in the window and
5030 /// nothing polled `try_frame` again while the clock stood still
5031 /// (`Player::pump` only drains while playing or a seek is owed, and one
5032 /// delivered frame clears "owed"). Two clips of real fixtures, touching,
5033 /// with a dissolve set on the join -- seeking into the window and taking
5034 /// exactly one frame (no play, no second tick) must already show a blend:
5035 /// the same position with the dissolve turned off must differ from it.
5036 #[test]
5037 fn a_single_paused_tick_inside_the_dissolve_window_is_already_blended() {
5038 let window = 6u32;
5039 let build = |transition: u32| {
5040 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open a");
5041 s.set_gain(0.0);
5042 s.import(&asset("test_av2.mp4")).expect("av2 matches");
5043 let end = s.timeline_duration();
5044 assert!(
5045 s.place_stream_at(end, &asset("test_av2.mp4"), 0, None)
5046 .expect("av2, placed right after a")
5047 );
5048 if transition > 0 {
5049 assert!(s.set_transition_out(Lane::V1, 0, transition));
5050 }
5051 s
5052 };
5053 let mut on = build(window);
5054 let mut off = build(0);
5055
5056 let fps = on.meta().frame_rate;
5057 let clip0_len = on.lane_clips(Lane::V1)[0].len();
5058 assert!(clip0_len > window, "the fixture needs to outlast the window");
5059 let mid_of_window = clip0_len - window / 2;
5060 let t = f64::from(mid_of_window) / fps;
5061
5062 // One seek, then one frame -- exactly what a paused preview's single
5063 // repaint asks the engine for. Polled rather than taken on the first
5064 // call because the seek itself just restarted the decoder
5065 // (`start_span`) and its first picture is not synchronous; once
5066 // *a* frame lands this is the one tick under test.
5067 let frame_at = |s: &mut PlaybackSession| -> crate::decode::Frame {
5068 s.seek(t);
5069 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
5070 loop {
5071 if let Some(f) = s.try_frame() {
5072 return f;
5073 }
5074 assert!(std::time::Instant::now() < deadline, "no frame within 20s of the seek");
5075 std::thread::sleep(std::time::Duration::from_millis(10));
5076 }
5077 };
5078
5079 let off_frame = frame_at(&mut off);
5080 let on_frame = frame_at(&mut on);
5081 assert_eq!(on_frame.index, off_frame.index, "same timeline position");
5082 assert_ne!(
5083 on_frame.bgra, off_frame.bgra,
5084 "paused inside the window, the dissolve must already show B blended in"
5085 );
5086 }
5087
5088 #[test]
5089 fn boundary_seconds_round_trip_to_their_own_frame() {
5090 for f in 0u32..300 {
5091 let secs = f64::from(f) / 30.0;
5092 assert_eq!(secs_to_frame(secs, 30.0), f, "frame {f}");
5093 }
5094 // Mid-frame positions still floor, and negatives clamp.
5095 assert_eq!(secs_to_frame(10.5 / 30.0, 30.0), 10);
5096 assert_eq!(secs_to_frame(-0.2, 30.0), 0);
5097 }
5098
5099 /// A paused transform nudge -- `set_transform_live` at the position the
5100 /// picture already stands on -- never pays a full decoder restart: the
5101 /// worker is reused (`Worker::reseek`), never replaced
5102 /// (`PlaybackSession::retire`), so `restarts()` does not move. Guards the
5103 /// path a card's live edits go through against a future change routing
5104 /// them back through `seek`/a fresh worker, and a gap left between two
5105 /// edits (a person's think-time between nudges) longer than the *old*
5106 /// hardware-idle window still counts zero restarts -- a decoder worker
5107 /// outliving its span is not a "restart" this counter (or a caller) sees,
5108 /// whatever the hardware session inside it did.
5109 #[test]
5110 fn a_paused_transform_nudge_reuses_the_worker_not_a_restart() {
5111 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
5112 s.set_gain(0.0);
5113 let poll = |s: &mut PlaybackSession| -> crate::decode::Frame {
5114 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(20);
5115 loop {
5116 if let Some(f) = s.try_frame() {
5117 return f;
5118 }
5119 assert!(std::time::Instant::now() < deadline, "no frame within 20s");
5120 std::thread::sleep(std::time::Duration::from_millis(10));
5121 }
5122 };
5123 let first = poll(&mut s);
5124 let before = s.restarts();
5125
5126 // A gap past the pre-fix 2s hardware-idle window: the whole point of
5127 // widening it is that a nudge landing here still reuses the worker.
5128 std::thread::sleep(std::time::Duration::from_millis(2500));
5129
5130 let clip = s.video_clip_at(s.now()).expect("a clip under the playhead");
5131 let params = TransformParams {
5132 scale: 1.2,
5133 ..Default::default()
5134 };
5135 assert!(s.set_transform_live(clip.0, clip.1, Some(params)), "the edit took");
5136 let next = poll(&mut s);
5137
5138 assert_eq!(before, s.restarts(), "a live transform edit must reuse the worker");
5139 assert_eq!(next.index, first.index, "paused: same timeline position before and after");
5140 }
5141
5142 /// The session's live look samples leave its history exactly where the
5143 /// press left it -- the colour-wheel drag's twin for the packed look, and
5144 /// what lets the app drive one from a pointer: `z` after a drag lands
5145 /// before the press, not one sample back down the drag.
5146 #[test]
5147 fn a_live_look_drag_is_one_step_of_the_sessions_history() {
5148 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
5149 let (lane, idx) = s.video_clip_at(s.now()).expect("a clip under the playhead");
5150 let look = |hue: u8| crate::decode::with_viz_paint_hue(crate::decode::VIZ_PAINT_AZURE, hue);
5151 assert!(s.set_viz_paint(lane, idx, look(1)), "the press");
5152 for hue in 2..=6u8 {
5153 assert!(s.set_viz_paint_live(lane, idx, look(hue)), "a sample");
5154 }
5155 assert_eq!(s.project.lane(lane)[idx].viz_paint, look(6));
5156 assert!(s.undo(), "the drag's own step");
5157 assert_eq!(
5158 s.project.lane(lane)[idx].viz_paint,
5159 0,
5160 "one undo is the whole drag"
5161 );
5162 }
5163}
5164