forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB0563cbfTahinli2 months ago824 commits

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