forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBef5832fTahinli3 months ago597 commits

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