forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB6dae2b4Tahinli3 months ago555 commits

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