forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

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