forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBc327308Tahinli26 days ago1014 commits

playback.rs9258 lines, 436.0 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::borrow::Cow;
15use std::path::{Path, PathBuf};
16use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32, AtomicU64, AtomicUsize, Ordering};
17use std::sync::mpsc::{Receiver, TryRecvError};
18use std::sync::{Arc, Mutex};
19use std::thread;
20use std::time::{Duration, Instant};
21
22use crate::ao::AoSession;
23use crate::audio::{AudioChunk, AudioSession};
24use crate::clock::{ClockSource, PlaybackClock};
25use crate::color::ColorParams;
26use crate::colorspace::{ColorDescription, ContentLight};
27use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};
28use crate::demux::{Codec, Demuxer, NoVideoTrack, Rotation, VideoMeta};
29use crate::eq::EqParams;
30use crate::project::{
31 Clip, Edge, GainKey, GapSweep, Lane, LaneKind, Project, ProjectSettings, Rate, RedoCheckpoint, Source,
32 SourceWalls, Span, Speed, SubClip, TrimWalls, WallBound, STILL_DEFAULT_SECS,
33};
34use crate::scale::{Composer, FitPolicy};
35use crate::transform::TransformParams;
36
37/// How long the feeder waits out a full ring. The ring holds a second, so this
38/// only has to be short next to that; it costs one wakeup per 10 ms of audio.
39const RING_FULL_WAIT: Duration = Duration::from_millis(10);
40
41/// How long the feeder waits out a ring that took *nothing*: the flush of a
42/// restart, which only the device's own callback can clear (`engine-audio`
43/// refuses a write queued behind one). Short, because this is the gap at the
44/// head of every restart and the ear is in it -- one wakeup per millisecond,
45/// for the millisecond or two it lasts.
46const FLUSH_WAIT: Duration = Duration::from_millis(1);
47
48/// How long [`try_frame`](PlaybackSession::try_frame) blocks the caller
49/// waiting for B's first picture when the playhead lands in a dissolve
50/// window before B's eager-opened decoder ([`start_span`](PlaybackSession::start_span))
51/// has one ready -- a seek straight into the window, mostly. Above the 98 ms
52/// worst-case VA-API init measured for a picture open, so an eager-opened B
53/// almost never actually waits the full budget; a source B cannot decode at
54/// all pays this once per span rather than freezing the preview outright.
55const DISSOLVE_B_TIMEOUT: Duration = Duration::from_millis(200);
56
57/// How long a dead output is left alone before another open is attempted. A
58/// PipeWire daemon restart takes a moment, and the ask that makes the attempt
59/// runs once per rendered frame: a second is long enough that a restart lands
60/// inside it, and short enough that a play pressed after one does not wait.
61const AUDIO_REARM_AFTER: Duration = Duration::from_secs(1);
62
63/// The reason a session gives for having gone quiet when its output dies
64/// ([`PlaybackSession::tick`]), through the same door a file's own refusal
65/// reaches a front-end by ([`PlaybackSession::audio_disabled_reason`]).
66///
67/// That door is read where a notice is *built* -- at open and at load -- so this
68/// is fetchable rather than announced: the engine sets the reason and clears it
69/// again when the output comes back, and a front-end that reads the door after
70/// the session is open (a per-frame check, or one at the next load) is what
71/// shows it. Nothing here pushes a notice.
72const AUDIO_LOST: &str = "output device went away -- reconnecting the timeline's sound";
73
74/// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --
75/// nothing was shot on it, so it is the canvas a *later* import meets rather
76/// than a description of the song. H.264 because it is the one codec that
77/// decodes without the plugin, 30 fps because a rounded-up audio length is what
78/// the frame count means and a whole number of frames per second keeps it
79/// honest; both are what a video imported onto such a timeline is held to
80/// ([`matches_timeline`]).
81///
82/// corner-cut: a 25 fps video imported onto an audio-only timeline it could have
83/// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read
84/// through [`Rate`] like any other file shot at another rate rather than
85/// defining one. Upgrade path is adopting the first *picture's* rate and codec
86/// on import, which means retiming every audio clip already placed in frames.
87const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0);
88
89/// The frame rate a timeline scaffolded from a still image runs at, for
90/// [`AUDIO_ONLY_CANVAS`]'s reason: nothing was shot on it. The *size* is not
91/// invented the same way -- an image has a picture of its own, and that picture
92/// is the canvas a later import meets.
93const IMAGE_ONLY_RATE: f64 = 30.0;
94
95/// How long a still image *is*, in seconds: the wall a trim may drag its edge
96/// out to, since an image has no length of its own to be walled by. Ten
97/// minutes, which is a title card nobody will run out of and still a finite
98/// number -- a `u32::MAX` sentinel here would make [`Self::trim_room`] hand a
99/// drag a wall past what the timeline can hold.
100///
101/// corner-cut: a still cannot be held longer than this. Upgrade path is a
102/// per-source length the project file carries, which every `counts` reader
103/// would then have to take from the document rather than from the file.
104const IMAGE_MAX_SECS: f64 = 600.0;
105
106/// The output half of a session: the device, plus what the feeder has handed it.
107/// Cloned into the feeder thread; every field that matters is shared.
108#[derive(Clone)]
109struct Audio {
110 /// Shared because `write` runs on the feeder thread while `position` and
111 /// `set_active` are called from the caller's. The plugin serialises those
112 /// itself (atomics and a channel), but the lock is what makes it sayable in
113 /// Rust and it is never held for more than a memcpy.
114 ao: Arc<Mutex<AoSession>>,
115 sample_rate: u32,
116 channels: u64,
117 /// Interleaved samples accepted by the device so far.
118 fed: Arc<AtomicU64>,
119 /// The decoder ran out and `fed` is final.
120 fed_all: Arc<AtomicBool>,
121 /// The output plugin failed mid-stream. Its position is frozen from here on,
122 /// so it can never satisfy [`Audio::played_out`] -- the flag is what lets
123 /// [`PlaybackSession::tick`] hand the timeline to wall time instead.
124 died: Arc<AtomicBool>,
125 /// Bumped by every seek. A feeder only owns the device while this still
126 /// matches the value it started with; see [`feed`].
127 epoch: Arc<AtomicU64>,
128 /// The device position the *current* stream's first real sample was queued
129 /// at, `-1` until the feeder has queued one. Written by the feeder under the
130 /// device lock, read by [`tick`](PlaybackSession::tick).
131 ///
132 /// This is what keeps a restart out of the timeline. Between a flush and the
133 /// first sample of the new stream the device plays silence -- a decoder open
134 /// is tens of milliseconds -- and that silence is elapsed *device* time
135 /// ([`crate::ao`] counts it, as it must: it really was played). It is not
136 /// elapsed *timeline* time, and a clock anchored on the first poll after a
137 /// seek counts it as such, which is a permanent offset between the picture
138 /// and the sound, re-rolled by every edit made while playing.
139 content_at: Arc<AtomicI64>,
140 /// The monitoring gain this session's device is running at, as f32 bits.
141 ///
142 /// The device is the owner -- [`PlaybackSession::gain`] reads the level
143 /// back out of it -- and this is the *only* reason a session knows what to
144 /// restore: the device object is replaced from under the session whenever
145 /// the output dies ([`Self::rearm_audio`]) or is armed late
146 /// ([`Self::arm_audio`]), and a fresh one comes up at 1.0. Without this a
147 /// muted session that lost its device came back at full volume while the
148 /// control still said muted. Written by [`PlaybackSession::set_gain`]
149 /// alone, so it cannot drift from the knob: whatever the caller last
150 /// pushed is exactly what the next device is told.
151 gain: Arc<AtomicU32>,
152 /// The timeline is *meant* to be playing: what a play or a seek-while-playing
153 /// asks for, and what the feeder turns into a running device the moment it
154 /// has a real sample to play ([`Audio::set_playing`], [`feed`]).
155 ///
156 /// The device is not started by the intent, because an inactive stream has
157 /// no callbacks and therefore no starved quanta: between the flush of a seek
158 /// and the first sample of the new stream -- seconds, on a cold 25 GB film
159 /// whose decoder is opened on the feeder -- a device started here would play
160 /// its own silence and count every quantum of it as an underrun.
161 ///
162 /// Written and read under the device lock, beside the [`Audio::content_at`]
163 /// stamp, and that is the whole race: whichever of the two sides takes the
164 /// lock first, the other sees its half (a stamp already there, or an intent
165 /// already set), so the device is started exactly once and a pause landing
166 /// during an open can never be overtaken by a late activation.
167 wants_active: Arc<AtomicBool>,
168 /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest
169 /// first: what a meter or an analyser draws. Written by the feeder, which
170 /// is not the device's own callback -- the plugin's RT thread never sees
171 /// this lock, and the feeder holds it for one memcpy per write.
172 tap: Arc<Mutex<Vec<f32>>>,
173 /// The highest sample magnitude handed to the device since it was last read
174 /// ([`PlaybackSession::levels`]), as f32 bits. Non-negative floats order the
175 /// same as their bits, so the feeder raises it with a `fetch_max`. Taken
176 /// after the mix and the limiter, before the device's own volume: the
177 /// meter reads what the device is given, not what the speakers are told.
178 peak: Arc<AtomicU32>,
179 /// [`Self::peak`] per side, left then right (a mono stream fills both), read and cleared
180 /// together with it for the stereo meter.
181 peak_lr: Arc<[AtomicU32; 2]>,
182 /// Feeder threads started and not yet returned. They are detached, so there
183 /// is no handle to count instead, and a scrub leaves dozens of them exiting
184 /// at once -- which is precisely what
185 /// [`live_workers`](PlaybackSession::live_workers) is asked about.
186 feeders: Arc<AtomicUsize>,
187 /// When this device was last opened *again* after dying
188 /// ([`PlaybackSession::rearm_audio`]). A dead output is offered one open a
189 /// second and no more, because the ask that makes the attempt runs once per
190 /// rendered frame: a daemon restart takes a moment, and a device that is
191 /// gone for good must not be opened sixty times a second for the rest of
192 /// the session.
193 rearm_at: Arc<Mutex<Option<Instant>>>,
194}
195
196/// How much of the played signal the tap keeps. A power of two, because what
197/// reads it transforms it, and long enough that the lowest band the editor
198/// draws (20 Hz) has a whole cycle in the window at any rate we open.
199const TAP_SAMPLES: usize = 2048;
200
201/// `gains` (one per audio lane, in `audio`'s order) with every lane outside
202/// `solo` silenced. A solo naming no lane in `audio` is no solo at all, so a
203/// stale handle cannot silence everything.
204fn soloed_gains(mut gains: Vec<f32>, audio: &[Lane], solo: &[Lane]) -> Vec<f32> {
205 if !audio.iter().any(|lane| solo.contains(lane)) {
206 return gains;
207 }
208 for (gain, lane) in gains.iter_mut().zip(audio) {
209 if !solo.contains(lane) {
210 *gain = 0.0;
211 }
212 }
213 gains
214}
215
216/// The level meters' reading: [`PlaybackSession::levels`]. Linear peaks in
217/// `0.0..=1.0` since the last read, one per audio lane in the lanes' own order,
218/// and the master.
219#[derive(Clone, Debug, Default, PartialEq)]
220pub struct Levels {
221 pub lanes: Vec<f32>,
222 pub master: f32,
223 /// The master's peak on the left and on the right (a mono stream reads the same on both).
224 pub master_lr: [f32; 2],
225}
226
227impl Audio {
228 /// Whether the device has played everything there will ever be, i.e. the
229 /// audio clock is about to stop meaning anything.
230 fn played_out(&self, position: i64) -> bool {
231 self.fed_all.load(Ordering::Acquire)
232 && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed)
233 }
234
235 /// Says whether the timeline is playing, and starts or stops the device for
236 /// it: `true` runs it *if there is already something to play*, and otherwise
237 /// leaves it to the feeder's first sample ([`Audio::wants_active`]). `false`
238 /// stops it at once -- a pause is never deferred, whatever an open in flight
239 /// is about to find.
240 fn set_playing(&self, playing: bool) {
241 // The lock, not the atomics, is what orders this against the feeder's
242 // stamp: the store below and the load after it are one critical section,
243 // and so is the feeder's pair.
244 let ao = self.ao.lock().unwrap();
245 self.wants_active.store(playing, Ordering::Release);
246 if !playing || self.content_at.load(Ordering::Acquire) >= 0 {
247 ao.set_active(playing);
248 }
249 }
250
251 /// Keeps the newest [`TAP_SAMPLES`] of what was just queued, downmixed to
252 /// mono. Called from the feeder only, once per accepted write.
253 fn note_tap(&self, accepted: &[f32]) {
254 // Every sample, not just the tail the tap keeps: a peak that falls
255 // outside the window is still a peak the ear heard.
256 let peak = accepted.iter().fold(0.0f32, |m, s| m.max(s.abs()));
257 self.peak.fetch_max(peak.to_bits(), Ordering::Relaxed);
258 let channels = self.channels.max(1) as usize;
259 let side = |at: usize| {
260 accepted.iter().skip(at.min(channels - 1)).step_by(channels).fold(0.0f32, |m, s| m.max(s.abs()))
261 };
262 self.peak_lr[0].fetch_max(side(0).to_bits(), Ordering::Relaxed);
263 self.peak_lr[1].fetch_max(side(1).to_bits(), Ordering::Relaxed);
264 let mut tap = self.tap.lock().unwrap();
265 // Only the tail can survive anyway: a big write replaces the window
266 // outright rather than being summed into it and then thrown away.
267 let from = accepted.len().saturating_sub(TAP_SAMPLES * channels);
268 for frame in accepted[from..].chunks_exact(channels) {
269 tap.push(frame.iter().sum::<f32>() / channels as f32);
270 }
271 let over = tap.len().saturating_sub(TAP_SAMPLES);
272 tap.drain(..over);
273 }
274
275 /// Starts a feeder for the current epoch, draining `rx` into the device.
276 /// `false` if the thread would not start, i.e. nothing will ever be fed.
277 fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool {
278 self.spawn_feeder_deferred(move || Some(rx))
279 }
280
281 /// As [`spawn_feeder`](Self::spawn_feeder), but the *stream* is opened on
282 /// the feeder too: `open` runs on that thread, so nothing here touches the
283 /// disk and the caller pays a thread spawn instead of a demux -- seconds off
284 /// a cold cache on a big film, which is what a seek used to cost the UI
285 /// thread ([`crate::DecodeSession::open_worker_deferred`] is the picture's
286 /// half of the same move).
287 ///
288 /// The price is the same one: there is no [`crate::audio::AudioMeta`] to
289 /// hand back and no synchronous answer to "will anything play". `None` from
290 /// `open` -- a silent timeline, a source that will not open -- is a feeder
291 /// with nothing to feed, which ends exactly as a played-out stream does and
292 /// hands the clock to wall time ([`tick`](PlaybackSession::tick)).
293 ///
294 /// The epoch is captured *here*, at the seek, not when the open returns: a
295 /// scrub abandons opens by the dozen and every one of them must still be
296 /// the stale stream it was started as, however late it lands.
297 ///
298 /// corner-cut: an abandoned open is not *cancelled*, though the machinery
299 /// for it exists ([`crate::demux::with_cancel`], which the import's Cancel
300 /// uses): it runs to the end and its answer is dropped. Tried, and left
301 /// out for want of evidence -- 200 cold scrub steps over the 25 GB HEVC
302 /// remux measured 101, 137 and 14 live workers on three runs of the *same*
303 /// build, so the machine decides that number and not this. There is a
304 /// reason to expect it to hurt, too: a Matroska walk writes its sidecar
305 /// index only when it finishes (`demux::mkv_blocks`), so a drag that
306 /// cancels every step's walk would never write one and every step would
307 /// walk the segment again from the top. Ceiling: an abandoned open keeps
308 /// reading, and the decoder threads it started live until it does. Upgrade
309 /// path is an index the walk publishes as it goes -- then cancelling costs
310 /// nothing and can be measured on an idle machine.
311 fn spawn_feeder_deferred(
312 &self,
313 open: impl FnOnce() -> Option<Receiver<AudioChunk>> + Send + 'static,
314 ) -> bool {
315 let me = self.clone();
316 let epoch = self.epoch.load(Ordering::Acquire);
317 // Counted before the spawn, so the count is never behind the thread.
318 self.feeders.fetch_add(1, Ordering::Release);
319 let started = thread::Builder::new()
320 .name("audio-feed".into())
321 .spawn(move || {
322 // Superseded before this thread was even scheduled: do not open
323 // anything at all. A scrub leaves all but the last one here.
324 if me.epoch.load(Ordering::Acquire) == epoch {
325 if let Some(rx) = open() {
326 feed(rx, &me, epoch);
327 }
328 // Only the current feeder gets to declare the end of the
329 // audio: a superseded one is finished, the stream is not.
330 if me.epoch.load(Ordering::Acquire) == epoch {
331 me.fed_all.store(true, Ordering::Release);
332 }
333 }
334 me.feeders.fetch_sub(1, Ordering::Release);
335 })
336 .is_ok();
337 if !started {
338 self.feeders.fetch_sub(1, Ordering::Release);
339 }
340 started
341 }
342
343 /// Feeder threads still running; see [`Self::feeders`].
344 fn live_feeders(&self) -> usize {
345 self.feeders.load(Ordering::Acquire)
346 }
347}
348
349/// Where the picture of the current span is decoded from. `Cached` is a render
350/// cache segment ([`crate::render_cache`]) that already holds the span's frames
351/// composed, so the decoder reads that file and nothing else is applied.
352#[derive(Clone, Debug, PartialEq, Eq)]
353enum Feed {
354 /// The live path: the project's clips, composed as they play.
355 Live,
356 /// A render-cache segment at `segment`, read from its own first frame.
357 Cached { segment: PathBuf },
358}
359
360/// How the pictures of a span played backward are numbered (see
361/// [`PlaybackSession::stamp`]). Backward the span is the stretch of its clip
362/// *up to* the playhead, and its pictures are wanted from the playhead down.
363#[derive(Clone, Copy, PartialEq, Debug)]
364enum Back {
365 /// Forward play, or a span (a still, a stack, a visualizer) that is drawn
366 /// forward whichever way the clock runs.
367 Off,
368 /// A forward clip decoded last frame first ([`DecodeSession::open_reversed`]
369 /// over the file frames ending at `top`).
370 Mirror { top: u32 },
371 /// A reversed clip, whose backward is the file's forward.
372 Forward,
373 /// A gap: black numbered from zero, counted down from the span's last frame.
374 Gap,
375}
376
377/// The cross-dissolve a span's tail owes its successor, tracked from the
378/// moment [`PlaybackSession::start_span`] opens A's own decoder until a later
379/// `start_span` throws it away. What decides there *is* one mirrors
380/// [`crate::export::dissolve_window`] exactly, on the very same span, so a
381/// preview blends the window an export would render -- but B's own decoder
382/// opens only once the playhead actually reaches it
383/// ([`PlaybackSession::open_dissolve_b`]), rather than for the whole span:
384/// most of a dissolving clip is never in the window, and a viewer who pauses
385/// or seeks away before the tail never pays for a decoder nobody sees.
386struct Dissolve {
387 /// The first *timeline* frame inside the window.
388 tail_start: u32,
389 /// How many output frames the blend ramps across.
390 window: u32,
391 b_source: usize,
392 b_in_frame: u32,
393 /// Where B sits on the timeline -- what its own grade and fit are keyed
394 /// on ([`Project::composite_color_at`], `composite_fit_at`), the same
395 /// `b_start` [`crate::export`] grades B's side of the same dissolve by.
396 b_start: u32,
397 /// How the picture is blended ([`crate::transitions`]).
398 kind: crate::transitions::TransitionKind,
399 /// B's live decode, once open; `None` before the playhead reaches the
400 /// window.
401 b: Option<DissolveB>,
402}
403
404/// B's own worker, decoding beside A's for the length of the window.
405struct DissolveB {
406 frames: Receiver<Frame>,
407 worker: Worker,
408 /// The last frame B handed over: a tick that lands between two of B's
409 /// pictures still has one to blend A against, the same "keep showing the
410 /// last one" policy A's own channel gets from the app's own pump -- done
411 /// here instead, because B never leaves the engine to be pumped.
412 held: Option<Frame>,
413}
414
415/// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`].
416/// One track that has ended: where it was, and what it did to its mask.
417#[derive(Clone, Debug, PartialEq)]
418pub struct TrackDone {
419 pub lane: Lane,
420 pub idx: usize,
421 pub slot: usize,
422 /// The keys written and the first and last source frame of the path, or why it stopped.
423 pub result: Result<TrackOutcome, String>,
424}
425
426/// What a finished track wrote: how many keys, the frames it covered, and the frame it
427/// was lost at when it stopped early.
428#[derive(Clone, Debug, PartialEq)]
429pub struct TrackOutcome {
430 pub keys: usize,
431 pub from: u32,
432 pub to: u32,
433 pub lost_at: Option<u32>,
434}
435
436/// A mask track in progress: the job ([`crate::track::start`]) and the mask it writes to.
437#[derive(Clone, Debug, PartialEq)]
438pub struct TrackJob {
439 pub lane: Lane,
440 pub idx: usize,
441 pub slot: usize,
442 pub id: crate::track::JobId,
443 /// The source frame the track starts from, where its path begins.
444 pub from: u32,
445 /// The mask's centre at `from`, in canvas fractions.
446 pub anchor: (f32, f32),
447}
448
449pub struct PlaybackSession {
450 /// The thread that plays scrub snippets, made by the first [`PlaybackSession::scrub_audio`].
451 scrub: Scrub,
452 /// The *timeline's* parameters, not any one file's: its frame rate and codec
453 /// come from source 0 and are what every other source is held to, while
454 /// `width`/`height` are the **project resolution** -- source 0's picture to
455 /// begin with, and whatever [`PlaybackSession::set_resolution`] or a saved
456 /// `resolution` line makes it after that. Every clip is composed onto it, so
457 /// a file of another size is a placed picture rather than a refusal.
458 meta: VideoMeta,
459 /// What source 0's own file declared about how bright it gets
460 /// ([`crate::colorspace::ContentLight`]) -- MaxCLL/MaxFALL and the
461 /// mastering display's peak/black, read once at open exactly as `native`
462 /// is, since the value is a property of the file and never changes under
463 /// a running session. [`ContentLight::default()`] (every field `None`)
464 /// for an SDR file and for a song or a still, neither of which is graded.
465 content_light: ContentLight,
466 /// Source 0's own picture, kept from the open: the project resolution
467 /// starts here, and a caller offering sizes to pick from needs the media's
468 /// own among them or a project moved off it could never come back.
469 native: (u32, u32),
470 /// ...and the scaffolding source's own frame rate, kept for exactly that
471 /// reason: the project rate starts here, and the list a caller offers rates
472 /// from needs the media's own on it or a project moved off it has no way
473 /// back ([`PlaybackSession::set_frame_rate`] is not an undo step either).
474 native_fps: f64,
475 frames: Receiver<Frame>,
476 /// The current decode worker.
477 worker: Worker,
478 /// What that worker opened -- hardware, software, a still, a gap -- written
479 /// by the worker itself and read by [`decode_backend`](Self::decode_backend).
480 /// Replaced with the stream at every seek, so it always describes the
481 /// pictures currently arriving and never the clip before them.
482 backend: BackendCell,
483 /// Why the current span stopped before the end of its range, if it did.
484 /// Replaced with the stream at every seek for the same reason `backend` is,
485 /// and read by [`video_failure_reason`](Self::video_failure_reason).
486 video_failure: crate::decode::DecodeFailure,
487 /// Workers cancelled by a seek or a clip change, waiting to be reaped.
488 /// Joining one inline costs whatever VA-API init it is still inside (98 ms
489 /// measured worst case), which is a visible hitch on the caller's thread;
490 /// parking it here instead makes that free, and [`retire`] drops the ones
491 /// that have already returned every time it adds another.
492 ///
493 /// Never a leak, and that is the invariant: everything in here is joined
494 /// when the session drops (`Vec<Worker>`'s own drop does it, one
495 /// [`Worker::drop`] each), so no decode worker can outlive the session and
496 /// meet Mesa's `atexit` handlers from inside libva.
497 ///
498 /// [`retire`]: PlaybackSession::retire
499 retired: Vec<Worker>,
500 /// Picture workers that replaced another one, i.e. every restart the
501 /// session's first worker did not cost: a seek, a resync, a clip boundary.
502 /// Each carries a demuxer reopen and a VA-API init, so this is what a
503 /// playback measurement counts to say how often the picture was thrown away
504 /// ([`restarts`](Self::restarts)).
505 restarts: u64,
506 clock: PlaybackClock,
507 audio: Option<Audio>,
508 /// Why this timeline is silent, when the file itself is not: an audio track
509 /// we cannot decode is a session that plays perfectly and says nothing about
510 /// it otherwise. `None` for a file that has usable audio *and* for one that
511 /// has none at all, which is not a surprise worth a notice.
512 audio_disabled: Option<String>,
513 /// The edit list. Everything a caller says in seconds is a *timeline*
514 /// position; only this maps it onto the file.
515 project: Project,
516 /// How many frames each source actually holds, indexed exactly as
517 /// [`Project::sources`] is and grown with it. The project itself does not
518 /// know -- a clip names a source by index and carries its own range -- and
519 /// [`Self::trim_clip`] is the one edit that could ask for frames past the
520 /// end of a file, which is a save that would not open again
521 /// ([`Self::open_project`] refuses one by name). Append-only for
522 /// `sources`'s reason: an index handed out stays valid, undone import or
523 /// not -- with the single exception `sources` itself has,
524 /// [`Self::remove_source`], which takes the same entry out of both.
525 counts: Vec<u32>,
526 /// What a load had to change to open the file, one line per change: a clip that
527 /// ran past its source is clamped to the source's end rather than refused (see
528 /// [`PlaybackSession::load_warnings`]). Empty for a project that opened as saved.
529 load_warnings: Vec<String>,
530 /// Audio headers already read, by the `(path, stream)` they were read for.
531 /// Every door that checks a file against the timeline asks the same two
532 /// questions -- what this file's sound is, and what the timeline's first
533 /// source's is ([`audio_matches`], [`first_audio_of`]) -- and each answer is
534 /// a container open. Warm that is 5-10 ms; on a film whose pages have been
535 /// evicted it is **1.7 s** (measured, 3.1 GB HEVC mkv), and both of those
536 /// are spent on the thread that draws, because placing and importing are
537 /// what a drag lands on. A header does not change while a session holds the
538 /// file, so it is read once and remembered. Errors are not kept: a file that
539 /// failed to open is asked again next time.
540 probes: std::collections::HashMap<(std::path::PathBuf, usize), Option<crate::AudioProbe>>,
541 /// What each source's own frame rate is against this timeline's, indexed
542 /// and grown exactly as [`Self::counts`] is (and shortened with it by
543 /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the
544 /// timeline's rate -- and for a still and a song, which have no rate of
545 /// their own -- so a single-rate project converts nothing anywhere.
546 ///
547 /// A clip counts *timeline* frames ([`Rate`]); this is the one thing that
548 /// knows which frames of the file those are, and only
549 /// [`start_span`](Self::start_span) and [`try_frame`](Self::try_frame) ask.
550 rates: Vec<Rate>,
551 /// The rate of the source the current worker is decoding, kept beside
552 /// [`Self::span`] because the frames coming back are numbered in *its*
553 /// file's frames and nothing else can put them back on the timeline.
554 span_rate: Rate,
555 /// What the current video worker was opened for: where it sits on the
556 /// timeline, how long it runs, and which source frame it started at --
557 /// together they rewrite a source frame index into a timeline one. Not a
558 /// clip index: a `split` cuts the clip under a running worker, and only the
559 /// mapping survives that. A span with no source is a *gap*, and the worker
560 /// feeding it emits black frames indexed from zero.
561 ///
562 /// `None` is the *emptied* timeline -- no clip on any lane, so there is no
563 /// stretch to be inside of. It is a state, not a failure: the picture is
564 /// black ([`start_span`](Self::start_span) feeds one black frame for it),
565 /// the sound is silence, the duration is zero, and placing anything reseeks
566 /// straight back out of it.
567 span: Option<Span>,
568 /// Whether the span now decoding still owes its first picture: set by
569 /// every span start ([`start_span`](Self::start_span)), cleared by the
570 /// first frame that span hands over ([`try_frame`](Self::try_frame)).
571 /// This is the window a clip boundary -- or any picture restart -- spends
572 /// reopening the decoder, and a front-end must not answer a picture that
573 /// is late by exactly this window's length with another restart of it
574 /// ([`picture_priming`](Self::picture_priming)).
575 span_priming: bool,
576 /// Where the picture of the current span is decoded from ([`Feed`]).
577 feed: Feed,
578 /// How the stream feeding the current span is numbered when the clock runs
579 /// backward ([`Back`]); `Off` at every forward rate.
580 back: Back,
581 /// The cross-dissolve the current span's tail owes its successor, if any
582 /// ([`crate::export::dissolve_window`], the same test an export makes of
583 /// the same span) -- and, once the playhead has reached the window, B's
584 /// own decoder, opened beside A's exactly as [`crate::export`] opens one
585 /// for the render. `None` for a span with no dissolve out, which is every
586 /// span most of the time.
587 dissolve: Option<Dissolve>,
588 /// The last clip has been played out; see [`PlaybackSession::is_eos`].
589 /// The size a front-end showing this session *on screen* wants its
590 /// pictures at, in device pixels ([`Self::set_view_size`]). `None` is the
591 /// project's own -- every file-level caller, every test, and an export,
592 /// which has a seat of its own ([`crate::export`]) and never comes here.
593 view: Option<(u32, u32)>,
594 eos: bool,
595 /// Where the timeline ended (seconds) when `eos` was set. The clock runs on
596 /// past it on wall time, so an edit at the end reseeks here, not to
597 /// wherever the wall clock has drifted -- which, after a slow drain, can be
598 /// past the very clip a paste just appended.
599 eos_end: f64,
600 /// The mix the running mixer is reading, when there is one: what lets a
601 /// fader and the master ceiling move without rebuilding the audio pipeline
602 /// at all ([`crate::audio::MixControls`]). `None` for a timeline that is
603 /// not mixed -- one audio lane at unity with the limiter off, which is the
604 /// bit-exact single-stream path -- and the first move off that reopens the
605 /// stream once, mixed, and lives from there.
606 mix: Option<Arc<crate::audio::MixControls>>,
607 /// The audio lanes soloed for listening: while any is set, the other audio
608 /// lanes are silent in the sound this session plays. Monitoring only -- it
609 /// is not in the [`Project`], is not saved, and an export never reads it
610 /// ([`Self::mix_gains`]). Empty is no solo at all.
611 solo: Vec<Lane>,
612 /// An audio stream has been started and has not yet played a sample: the
613 /// window [`tick`](Self::tick) holds the clock still through, so the silence
614 /// of a restart is never counted as timeline time. See
615 /// [`Audio::content_at`].
616 priming: bool,
617 /// Whether the decode worker may drop a picture whose moment has already
618 /// passed ([`Self::drop_late_pictures`]). Off unless a caller says it is
619 /// watching this in real time.
620 drop_late: bool,
621 /// Whether the picture is decoded from the stand-ins rather than from the
622 /// films ([`crate::proxy`]). One switch for the whole project, saved with
623 /// it, and *only* the picture: the sound is always the film's own, and so
624 /// is everything an export reads.
625 ///
626 /// Which sources have a stand-in is not kept here -- it is asked of the
627 /// cache when a span opens ([`Self::picture_path`]), one `stat` against a
628 /// file open that already costs milliseconds, so a proxy made (or deleted)
629 /// mid-session is picked up at the next seek and nothing can go stale.
630 proxies: bool,
631 /// Whether a source that wants a stand-in gets one made for it as it
632 /// arrives ([`crate::proxy::wanted`]). On unless a project says otherwise,
633 /// which is what every project did before the switch existed. Saved with
634 /// the project like the one above it, and read by the front end: the engine
635 /// starts no encode of its own.
636 auto_proxies: bool,
637 /// Which encoder an export of this project writes its picture with
638 /// ([`crate::export::EncoderSeat`]). The project's, saved with it like the
639 /// two switches above, and read by the front end: the engine starts no
640 /// export of its own.
641 encoder_seat: crate::export::EncoderSeat,
642 /// The rate this project's mix was picked to run at
643 /// ([`crate::edith::Document::sample_rate`]), overriding the one the first
644 /// audio source would otherwise hand the mixer. `None` -- every project
645 /// before the field existed, and any project nobody has picked one for --
646 /// leaves the derived rate alone. Saved with the project like the switches
647 /// above it, and read by the front end: the engine picks no rate of its own.
648 ///
649 /// Setting it takes effect at the next audio rebuild (a seek, an edit, a
650 /// reopen); there is no live resample of an audio device already playing.
651 sample_rate: Option<u32>,
652}
653
654/// What an edit dirtied -- which half of the pipeline has to be rebuilt for the
655/// change to be seen or heard, and, far more to the point, which half must not
656/// be.
657///
658/// Rebuilding a half is expensive and *audible*: the video worker costs a
659/// decoder open (98 ms of VA-API init, worst case, measured) and the audio one
660/// costs a flush, a re-open and a hole in the sound. A grade changes no sample
661/// and a fader changes no picture, so neither may pay the other's price -- that
662/// is the whole of this type.
663#[derive(Clone, Copy, PartialEq, Eq, Debug)]
664enum Dirty {
665 /// The picture only: a grade, a fit policy, the project resolution. The
666 /// sound keeps playing, untouched, and the clock never moves.
667 Picture,
668 /// The sound only: a clip's equalizer. The picture keeps playing.
669 Sound,
670 /// The timeline itself -- what is where, how long, how fast. Both halves
671 /// are rebuilt, because both are decoding the wrong thing.
672 Both,
673}
674
675/// How [`PlaybackSession::make_multicam_at`] lines the cameras up.
676#[derive(Clone, Copy, Debug, PartialEq, Eq)]
677pub enum MulticamSync {
678 /// By the loudness curve of each camera's sound.
679 Audio,
680 /// Every camera starts at the same moment.
681 Start,
682}
683
684/// How one angle was placed.
685#[derive(Clone, Copy, Debug, PartialEq)]
686pub enum AngleSync {
687 /// The camera the others were lined up with.
688 Reference,
689 /// Matched by sound with this normalised correlation (0 to 1).
690 Audio { score: f32 },
691 /// Placed at the start: that was asked for.
692 Start,
693 /// Placed at the start: its sound did not match the reference well enough.
694 Weak { score: f32 },
695 /// Placed at the start: the file has no sound.
696 NoSound,
697}
698
699/// What [`PlaybackSession::make_multicam_at`] did.
700#[derive(Clone, Debug)]
701pub struct MulticamReport {
702 pub made: crate::project::MulticamMade,
703 /// Per angle, how it was placed.
704 pub how: Vec<AngleSync>,
705 /// Per angle, seconds later than the reference that its sound happens (0 for unmatched ones).
706 pub offsets_secs: Vec<f64>,
707 /// Per angle, where its first frame sits in the multicam clip, in timeline frames.
708 pub starts: Vec<u32>,
709}
710
711/// One camera of a [`MulticamJob`].
712#[derive(Clone, Debug)]
713pub struct MulticamJobSource {
714 pub index: usize,
715 pub path: std::path::PathBuf,
716 pub audio_stream: usize,
717 pub frames: u32,
718}
719
720/// The reading half of making a multicam clip ([`PlaybackSession::multicam_job`]): the cameras'
721/// loudness curves are measured and matched, which takes a while and touches no project state.
722#[derive(Clone, Debug)]
723pub struct MulticamJob {
724 sources: Vec<MulticamJobSource>,
725 sync: MulticamSync,
726 fps: f64,
727}
728
729/// What [`MulticamJob::run`] found, ready for [`PlaybackSession::apply_multicam`].
730#[derive(Clone, Debug)]
731pub struct MulticamPlan {
732 sources: Vec<MulticamJobSource>,
733 angles: Vec<crate::project::AngleSpec>,
734 how: Vec<AngleSync>,
735 offsets: Vec<f64>,
736}
737
738impl MulticamJob {
739 /// Measures and matches the cameras. `progress` runs 0..=1000; setting `cancel` stops it at the
740 /// next camera with an error.
741 pub fn run(&self, progress: &std::sync::atomic::AtomicU32, cancel: &std::sync::atomic::AtomicBool) -> crate::Result<MulticamPlan> {
742 use std::sync::atomic::Ordering;
743 let n = self.sources.len().max(1) as u32;
744 let range = match self.sync {
745 MulticamSync::Audio => (0.0, crate::multisync::SYNC_SECS),
746 MulticamSync::Start => (0.0, 0.5),
747 };
748 let mut curves: Vec<Option<Vec<f32>>> = Vec::new();
749 for (i, src) in self.sources.iter().enumerate() {
750 if cancel.load(Ordering::Relaxed) {
751 return Err("stopped".into());
752 }
753 let levels = if crate::is_image(&src.path) { None } else { crate::silence::levels(&src.path, src.audio_stream, range).ok().flatten() };
754 curves.push(levels);
755 progress.store((i as u32 + 1) * 900 / n, Ordering::Relaxed);
756 }
757 let mut how = vec![AngleSync::Start; self.sources.len()];
758 let mut offsets = vec![0.0f64; self.sources.len()];
759 if self.sync == MulticamSync::Audio {
760 let reference = curves.iter().position(Option::is_some);
761 for (i, c) in curves.iter().enumerate() {
762 match (reference, c) {
763 (_, None) => how[i] = AngleSync::NoSound,
764 (Some(r), Some(_)) if r == i => how[i] = AngleSync::Reference,
765 (Some(r), Some(c)) => {
766 let lag = curves[r].as_deref().and_then(|a| crate::multisync::best_lag(a, c, crate::multisync::MAX_LAG_SECS));
767 match lag {
768 Some(l) if l.score >= crate::multisync::MIN_SCORE => {
769 offsets[i] = l.secs;
770 how[i] = AngleSync::Audio { score: l.score };
771 }
772 Some(l) => how[i] = AngleSync::Weak { score: l.score },
773 None => how[i] = AngleSync::Weak { score: 0.0 },
774 }
775 }
776 (None, Some(_)) => {}
777 }
778 }
779 }
780 // `offsets[i]`: the same sound happens that much later in camera i, so camera i started
781 // that much earlier on the common clock, so it starts at `top - offset`; the earliest at 0.
782 let top = offsets.iter().copied().fold(0.0, f64::max);
783 let angles = self
784 .sources
785 .iter()
786 .enumerate()
787 .map(|(i, s)| crate::project::AngleSpec {
788 source: s.index,
789 name: s.path.file_stem().map(|x| x.to_string_lossy().into_owned()).unwrap_or_default(),
790 frames: s.frames,
791 start: secs_to_frame(top - offsets[i], self.fps),
792 audio: curves[i].is_some(),
793 })
794 .collect();
795 progress.store(1000, Ordering::Relaxed);
796 Ok(MulticamPlan { sources: self.sources.clone(), angles, how, offsets })
797 }
798}
799
800/// What an import is held to, off a timeline that is already up: the sources
801/// its sound has to agree with and the meta its rate is read against. Owned and
802/// `Send`, so the check itself can run on a worker with no session in reach --
803/// which is the whole point ([`PlaybackSession::probe_import`]).
804#[derive(Clone, Debug, PartialEq)]
805pub struct ImportGate {
806 sources: Vec<Source>,
807 timeline: VideoMeta,
808}
809
810/// A file read and accepted, waiting to be registered: what
811/// [`PlaybackSession::probe_import`] found and
812/// [`PlaybackSession::import_probed`] pushes. Carries the gate it was decided
813/// against, so a timeline that moved under it can be noticed rather than
814/// trusted.
815#[derive(Clone, Debug)]
816pub struct ImportProbe {
817 gate: ImportGate,
818 meta: VideoMeta,
819 rate: Rate,
820}
821
822/// The project sound rates a person can pick, slowest first: the export sheet and the MCP
823/// `project_settings sample_rate` both offer these. "Source" (no pick) is `None`, not a row here.
824pub const SAMPLE_RATES: [u32; 3] = [44_100, 48_000, 96_000];
825
826/// How long one scrub snippet plays ([`PlaybackSession::scrub_audio`]): long enough to hear
827/// what a word or a beat is, short enough that a drag across a second of sound is a run of
828/// clicks rather than a smear.
829pub const SCRUB_SECS: f64 = 0.07;
830/// The fade at each end of a scrub snippet, in seconds ([`scrub_snippet`]).
831const SCRUB_FADE_SECS: f64 = 0.01;
832
833/// One scrub snippet's samples: the window `src` holds (interleaved, `channels` wide) with a
834/// raised-cosine fade of `fade` frames at each end, so the snippet starts and stops at silence
835/// and no edge of it can click. The fade is held to half the window, and the result is the
836/// window's length.
837pub fn scrub_snippet(src: &[f32], channels: usize, fade: usize) -> Vec<f32> {
838 let channels = channels.max(1);
839 let frames = src.len() / channels;
840 let mut out = src[..frames * channels].to_vec();
841 let fade = fade.min(frames / 2);
842 for f in 0..fade {
843 // Rising from just above silence to just below unity over `fade` frames.
844 let g = 0.5 - 0.5 * (std::f32::consts::PI * (f as f32 + 0.5) / fade as f32).cos();
845 for c in 0..channels {
846 out[f * channels + c] *= g;
847 out[(frames - 1 - f) * channels + c] *= g;
848 }
849 }
850 out
851}
852
853/// A piece of scrub work: opening and reading a snippet's audio, which happens off the caller's
854/// thread. It hands back the device's rate and width and the faded samples.
855type ScrubWork = Box<dyn FnOnce() -> Option<(u32, u32, Vec<f32>)> + Send>;
856
857/// The scrub thread's handle: `None` until the first snippet is asked for.
858#[derive(Default)]
859struct Scrub {
860 tx: Option<std::sync::mpsc::Sender<ScrubWork>>,
861 /// How many snippets have been asked for ([`PlaybackSession::scrub_requests`]).
862 requests: u64,
863}
864
865/// The scrub thread. It owns one output stream for as long as the rate and width hold, and
866/// plays only the newest request: a drag that outruns the decoder skips the ones it left behind.
867fn scrub_thread(rx: Receiver<ScrubWork>) {
868 let mut out: Option<(u32, u32, AoSession)> = None;
869 while let Ok(mut work) = rx.recv() {
870 while let Ok(newer) = rx.try_recv() {
871 work = newer;
872 }
873 let Some((rate, channels, samples)) = work() else {
874 continue;
875 };
876 if out.as_ref().is_none_or(|(r, c, _)| *r != rate || *c != channels) {
877 out = AoSession::open(rate, channels).map(|ao| (rate, channels, ao));
878 }
879 if let Some((_, _, ao)) = out.as_mut() {
880 // A snippet replaces the one still sounding, so the newest is heard at once.
881 ao.flush();
882 ao.set_active(true);
883 ao.write(&samples);
884 }
885 }
886}
887
888impl PlaybackSession {
889 /// Opens `path` and starts both decode workers. Only video failure is fatal:
890 /// a file we cannot hear is still a file we can watch.
891 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {
892 Self::open_stream(path, 0)
893 }
894
895 /// Opens `path` exactly as [`open`](Self::open) does, but binds `stream` --
896 /// the index a library row names ([`crate::probe`]'s own numbering of a
897 /// file's audio tracks) -- as the one that keeps the clock and plays,
898 /// rather than always the first. What a library preview asks for when the
899 /// row *is* a particular stream, so a remux with several audio tracks
900 /// previews the one that was clicked.
901 pub fn open_with_audio_stream(
902 path: impl AsRef<Path>,
903 audio_stream: usize,
904 ) -> crate::Result<Self> {
905 Self::open_stream(path, audio_stream)
906 }
907
908 fn open_stream(path: impl AsRef<Path>, audio_stream: usize) -> crate::Result<Self> {
909 // Canonical from the first byte: the project canonicalizes every
910 // source ([`Source::new`]), and [`Worker::reseek`] reuses a decoder
911 // only when the paths match textually -- a raw path here would make
912 // every later picture edit pay a full reopen instead of a seek.
913 let path = crate::project::canonical(path.as_ref());
914 // A timeline is normally scaffolded from source 0's picture -- its size,
915 // its frame rate, its clock. A song has none of that, so it scaffolds
916 // the *canvas* instead and its own sound keeps the clock: an audio-only
917 // project is a project like any other, it simply plays black.
918 if crate::is_audio(&path) {
919 return Self::open_audio_only(&path, audio_stream);
920 }
921 // A still is the other source with no timeline in it: it has a picture
922 // (which becomes the canvas) but no rate and no length, so it too
923 // scaffolds rather than describes.
924 // A numbered run opens as one clip of its frames, the same as an import of it.
925 if let Some(run) = crate::sequence::Run::parse(&path).or_else(|| crate::sequence::Run::detect(&path)) {
926 return Self::open_image_only(&run.spelled(), Some(run.count));
927 }
928 if crate::is_image(&path) {
929 return Self::open_image_only(&path, None);
930 }
931 // `open_worker` rather than `open` purely for the worker handle: the
932 // field has to exist from the start for the first seek to use it.
933 // Ungraded: a file just opened has one clip per lane and nothing has
934 // graded it yet. Every later span is opened by `start_span`, which asks
935 // the project.
936 // Passthrough: a freshly opened file *is* the project resolution, so
937 // there is nothing to place it on. Every later span goes through
938 // `start_span`, which builds the canvas from the project.
939 let opened = DecodeSession::open_worker(
940 &path,
941 0,
942 u32::MAX,
943 ColorParams::default(),
944 TransformParams::default(),
945 Composer::passthrough(),
946 // The default rendition: a file just opened is a project nobody has
947 // picked one for, exactly as it is a project nobody has graded.
948 crate::tonemap::Preset::default(),
949 );
950 // `is_audio` above is the extension's word, and an extension can lie: a
951 // song muxed into an `.mp4` reads as a film until the header is actually
952 // walked. The demuxer's own `NoVideoTrack` is that walk saying there was
953 // never a picture in it, and the fallback is the same audio-only door the
954 // extension check would have taken up front -- not a fault, a type.
955 let (meta, stream) = match opened {
956 Ok(opened) => opened,
957 Err(e) if NoVideoTrack::is_it(&e) => return Self::open_audio_only(&path, audio_stream),
958 Err(e) => return Err(e),
959 };
960 // A file is opened on its first audio stream by default, like
961 // `Project::single` names it -- unless a caller through
962 // `open_with_audio_stream` picked another.
963 let (audio, audio_disabled) = open_audio(&path, audio_stream);
964 let source = match audio {
965 Some(_) => ClockSource::Audio,
966 None => ClockSource::Wall,
967 };
968 // One clip per lane covering the file, so timeline == source until the
969 // first edit -- and the range opened above is exactly that clip's.
970 // The grouped pair runs one length: the sound's when the file's sound is shorter
971 // than its picture (the walls the save and the load check the audio lane to), so
972 // the take is sound_held_frames long from the start, not the picture's count.
973 let held = sound_held_frames(&path, 0, meta.frame_count, meta.frame_rate);
974 let project = Project::single(&path, held);
975 let span = crate::export::stack_span_at(&project, 0);
976 // A second, header-only open purely for the light level: `open_worker`
977 // above already read one to hand the decode thread its own, but never
978 // hands it back out. The same trade the audio header cache above this
979 // makes -- a second container open, paid once at open rather than never
980 // -- since nothing here decodes a single picture.
981 let content_light = Demuxer::open(&path)
982 .map(|(_, d)| d.light())
983 .unwrap_or_default();
984 Ok(Self {
985 scrub: Scrub::default(),
986 load_warnings: Vec::new(),
987 meta,
988 content_light,
989 native: (meta.width, meta.height),
990 native_fps: meta.frame_rate,
991 frames: stream.frames,
992 worker: stream.worker,
993 backend: stream.backend,
994 video_failure: stream.failure,
995 retired: Vec::new(),
996 restarts: 0,
997 clock: PlaybackClock::new(source),
998 audio,
999 audio_disabled,
1000 project,
1001 counts: vec![meta.frame_count],
1002 probes: std::collections::HashMap::new(),
1003 // Source 0 *is* the timeline's rate: it defined it.
1004 rates: vec![Rate::REAL_TIME],
1005 span_rate: Rate::REAL_TIME,
1006 span,
1007 span_priming: true,
1008 feed: Feed::Live,
1009 back: Back::Off,
1010 dissolve: None,
1011 view: None,
1012 eos: false,
1013 eos_end: 0.0,
1014 mix: None,
1015 solo: Vec::new(),
1016 priming: false,
1017 drop_late: false,
1018 // A file just opened is a project nobody has picked stand-ins for.
1019 proxies: false,
1020 auto_proxies: false,
1021 encoder_seat: crate::export::EncoderSeat::default(),
1022 sample_rate: None,
1023 })
1024 }
1025
1026 /// Opens `path` into the **library alone**: everything
1027 /// [`open`](Self::open) scaffolds from it -- the resolution, the frame
1028 /// rate, the clock, the source entry and its length -- over an *empty*
1029 /// timeline. What an import into a window that has no session yet makes,
1030 /// since an import registers a source and never places a clip
1031 /// ([`import`](Self::import)); the file reaches a lane when it is dragged
1032 /// there.
1033 ///
1034 /// Nothing to undo, like the import it stands in for: the lanes start
1035 /// empty rather than being emptied, so no snapshot is pushed.
1036 pub fn open_library(path: impl AsRef<Path>) -> crate::Result<Self> {
1037 let mut session = Self::open(path)?;
1038 // The pair of lanes an opened file comes up with (`Project::single`,
1039 // `open_audio_only`), emptied -- the source list and so the noted
1040 // counts are carried over untouched, which is what keeps a library row
1041 // placeable at its full length.
1042 session.project = Project::from_parts(
1043 session.project.sources().to_vec(),
1044 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())],
1045 Vec::new(),
1046 Vec::new(),
1047 Vec::new(),
1048 )?;
1049 // Onto the emptied mapping: black picture, silence, zero duration.
1050 session.seek(0.);
1051 Ok(session)
1052 }
1053
1054 /// A timeline with no file behind it: a `width` x `height` canvas at `fps`,
1055 /// no sources and no clips, for a project started from nothing. Its picture
1056 /// is the black of an uncovered canvas, its length is zero, and the first
1057 /// import sets the sources the way it does on any session.
1058 pub fn empty(width: u32, height: u32, fps: f64) -> crate::Result<Self> {
1059 if width == 0 || height == 0 || fps <= 0.0 {
1060 return Err(format!("empty timeline: {width}x{height} at {fps} fps").into());
1061 }
1062 let meta = VideoMeta {
1063 width,
1064 height,
1065 frame_rate: fps,
1066 frame_count: 0,
1067 codec: Codec::H264,
1068 color: ColorDescription::default(),
1069 matrix_assumed: false,
1070 rotation: Rotation::None,
1071 coded_width: width,
1072 coded_height: height,
1073 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1074 };
1075 let stream = DecodeSession::open_black(width, height, 0);
1076 Ok(Self {
1077 scrub: Scrub::default(),
1078 load_warnings: Vec::new(),
1079 meta,
1080 content_light: ContentLight::default(),
1081 native: (width, height),
1082 native_fps: fps,
1083 frames: stream.frames,
1084 worker: stream.worker,
1085 backend: stream.backend,
1086 video_failure: stream.failure,
1087 retired: Vec::new(),
1088 restarts: 0,
1089 clock: PlaybackClock::new(ClockSource::Wall),
1090 audio: None,
1091 audio_disabled: None,
1092 project: Project::from_parts(
1093 Vec::new(),
1094 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())],
1095 Vec::new(),
1096 Vec::new(),
1097 Vec::new(),
1098 )?,
1099 counts: Vec::new(),
1100 probes: std::collections::HashMap::new(),
1101 rates: Vec::new(),
1102 span_rate: Rate::REAL_TIME,
1103 span: None,
1104 span_priming: true,
1105 feed: Feed::Live,
1106 back: Back::Off,
1107 dissolve: None,
1108 view: None,
1109 eos: false,
1110 eos_end: 0.0,
1111 mix: None,
1112 solo: Vec::new(),
1113 priming: false,
1114 drop_late: false,
1115 proxies: false,
1116 auto_proxies: false,
1117 encoder_seat: crate::export::EncoderSeat::default(),
1118 sample_rate: None,
1119 })
1120 }
1121
1122 /// Opens a standalone audio file ([`crate::is_audio`]) as a timeline of its
1123 /// own: one clip on `A1`, nothing on the video lane, and a picture that is
1124 /// the black of an uncovered canvas ([`AUDIO_ONLY_CANVAS`]) for as long as
1125 /// the song runs. Its own sound keeps the clock, exactly as a video's does.
1126 ///
1127 /// Refused when the file has no sound to time it by: a source with neither a
1128 /// picture nor a playable length is not a timeline, and that is what
1129 /// [`audio_frames`] answers -- the *device* is a different question, and a
1130 /// machine without one opens this like any other session, silently.
1131 fn open_audio_only(path: &Path, stream: usize) -> crate::Result<Self> {
1132 let (width, height, frame_rate) = AUDIO_ONLY_CANVAS;
1133 let meta = VideoMeta {
1134 width,
1135 height,
1136 frame_rate,
1137 // Rounded up to whole frames, which is the only frame count a
1138 // source with no picture has -- the same length `import_audio`
1139 // gives a song joining a timeline of video. The demuxer's words are
1140 // named with the file, since this is the door a file that is not
1141 // really audio at all comes to.
1142 frame_count: audio_frames(path, frame_rate)
1143 .map_err(|e| format!("{}: {e}", path.display()))?,
1144 codec: Codec::H264,
1145 // A canvas this engine drew itself, not a stream that was read:
1146 // the default description is what it is drawn in.
1147 color: ColorDescription::default(),
1148 matrix_assumed: false,
1149 rotation: Rotation::None,
1150 // No container said anything about these: the canvas this engine drew
1151 // itself is square pixels at the size it was drawn at.
1152 coded_width: width,
1153 coded_height: height,
1154 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1155 };
1156 let (audio, audio_disabled) = open_audio(path, stream);
1157 // Through `from_parts` rather than `Project::single`, which is the
1158 // *video* open's pair of grouped clips: here there is no picture to
1159 // group the sound with, so the video lane starts empty.
1160 let clip = Clip {
1161 speed_keys: Vec::new(),
1162 reversed: false,
1163 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1164 angle: Default::default(),
1165 fade_in: 0,
1166 fade_out: 0,
1167 transition_out: 0,
1168 transition_kind: Default::default(),
1169 visualizer: 0,
1170 viz_paint: 0,
1171 gain_db: 0.0,
1172 gain_keys: Vec::new(),
1173 pan: 0,
1174 transform_keys: Vec::new(),
1175 opacity_keys: Vec::new(),
1176 color_keys: Vec::new(),
1177 effects: Vec::new(),
1178 start: 0,
1179 in_frame: 0,
1180 out_frame: meta.frame_count,
1181 source: 0,
1182 link: None,
1183 eq: None,
1184 color: None,
1185 transform: None,
1186 fit: FitPolicy::default(),
1187 speed: Speed::NORMAL,
1188 pitch: 0,
1189 };
1190 let project = Project::from_parts(
1191 vec![Source::new(path, 0)],
1192 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, vec![clip])],
1193 Vec::new(),
1194 Vec::new(),
1195 Vec::new(),
1196 )?;
1197 // Every frame of this timeline is a gap, since no video lane covers
1198 // anything: `composite_span_at` says so and the black worker
1199 // `start_span` would open is opened here instead, for the reason `open`
1200 // opens its decoder inline -- the field has to exist for the first seek.
1201 let span = crate::export::stack_span_at(&project, 0);
1202 let stream = DecodeSession::open_black(width, height, span.map_or(1, |s| s.len));
1203 Ok(Self {
1204 scrub: Scrub::default(),
1205 load_warnings: Vec::new(),
1206 meta,
1207 content_light: ContentLight::default(),
1208 native: (width, height),
1209 native_fps: frame_rate,
1210 frames: stream.frames,
1211 worker: stream.worker,
1212 backend: stream.backend,
1213 video_failure: stream.failure,
1214 retired: Vec::new(),
1215 restarts: 0,
1216 // The song keeps the clock, as a video's own sound does -- and wall
1217 // time keeps it on a machine with no device, where the picture
1218 // (black) still has to move at some rate.
1219 clock: PlaybackClock::new(match audio {
1220 Some(_) => ClockSource::Audio,
1221 None => ClockSource::Wall,
1222 }),
1223 audio,
1224 audio_disabled,
1225 project,
1226 counts: vec![meta.frame_count],
1227 probes: std::collections::HashMap::new(),
1228 // Source 0 *is* the timeline's rate: it defined it.
1229 rates: vec![Rate::REAL_TIME],
1230 span_rate: Rate::REAL_TIME,
1231 span,
1232 span_priming: true,
1233 feed: Feed::Live,
1234 back: Back::Off,
1235 dissolve: None,
1236 view: None,
1237 eos: false,
1238 eos_end: 0.0,
1239 mix: None,
1240 solo: Vec::new(),
1241 priming: false,
1242 drop_late: false,
1243 // A file just opened is a project nobody has picked stand-ins for.
1244 proxies: false,
1245 auto_proxies: false,
1246 encoder_seat: crate::export::EncoderSeat::default(),
1247 sample_rate: None,
1248 })
1249 }
1250
1251 /// Opens a still image ([`crate::is_image`]) as a timeline of its own: one
1252 /// clip on `V1`, [`STILL_DEFAULT_SECS`] long, over silence. The *canvas* is
1253 /// the image's own picture -- unlike a song, a still has one, and inventing
1254 /// a 1080p canvas around a 640x360 PNG would letterbox it against nothing.
1255 /// The frame rate is [`IMAGE_ONLY_RATE`], for the reason an audio-only
1256 /// timeline has one at all: nothing was shot on it.
1257 ///
1258 /// Wall time keeps the clock, as it does for any silent source.
1259 /// `frames` is the length of a numbered run (its spelling is `path`), or `None` for one picture,
1260 /// which is held and placed for [`image_frames`] and [`IMAGE_PLACE_SECS`].
1261 fn open_image_only(path: &Path, frames: Option<u32>) -> crate::Result<Self> {
1262 // Decoded here rather than probed: this is the door a `.png` that is
1263 // not one comes to, and the picture is wanted a line later anyway.
1264 let still = crate::decode::Still::open(path)?;
1265 let meta = VideoMeta {
1266 width: still.width,
1267 height: still.height,
1268 frame_rate: IMAGE_ONLY_RATE,
1269 // Its length is the wall a trim is held to, exactly as a song's
1270 // playing time is -- see [`image_frames`].
1271 frame_count: frames.unwrap_or_else(|| image_frames(IMAGE_ONLY_RATE)),
1272 codec: Codec::H264,
1273 color: ColorDescription::default(),
1274 matrix_assumed: false,
1275 // `Rotation::None` is honest, not a shrug: a still's own turn was
1276 // made in `Still::open`, before these planes were written, so the
1277 // pair below is already the displayed one and there is nothing left
1278 // for a consumer to make.
1279 rotation: Rotation::None,
1280 // No container said anything about these: the picture this engine
1281 // decoded itself is square pixels at the size it was decoded at.
1282 coded_width: still.width,
1283 coded_height: still.height,
1284 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1285 };
1286 let clip = Clip {
1287 speed_keys: Vec::new(),
1288 reversed: false,
1289 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1290 angle: Default::default(),
1291 fade_in: 0,
1292 fade_out: 0,
1293 transition_out: 0,
1294 transition_kind: Default::default(),
1295 visualizer: 0,
1296 viz_paint: 0,
1297 gain_db: 0.0,
1298 gain_keys: Vec::new(),
1299 pan: 0,
1300 transform_keys: Vec::new(),
1301 opacity_keys: Vec::new(),
1302 color_keys: Vec::new(),
1303 effects: Vec::new(),
1304 start: 0,
1305 in_frame: 0,
1306 out_frame: place_frames(meta.frame_count, IMAGE_ONLY_RATE, STILL_DEFAULT_SECS),
1307 source: 0,
1308 link: None,
1309 eq: None,
1310 color: None,
1311 transform: None,
1312 fit: FitPolicy::default(),
1313 speed: Speed::NORMAL,
1314 pitch: 0,
1315 };
1316 // No group and no audio clip: a still is silent, and a clip on `A1`
1317 // playing from a PNG is a source the audio worker cannot open.
1318 let project = Project::from_parts(
1319 vec![Source::new(path, 0)],
1320 vec![(LaneKind::Video, vec![clip]), (LaneKind::Audio, Vec::new())],
1321 Vec::new(),
1322 Vec::new(),
1323 Vec::new(),
1324 )?;
1325 let span = crate::export::stack_span_at(&project, 0);
1326 // The placeholder the first seek supersedes, opened here for `open`'s
1327 // reason: the field has to exist before anything can seek.
1328 let stream = DecodeSession::open_still(
1329 path,
1330 0,
1331 span.map_or(1, |s| s.len),
1332 ColorParams::default(),
1333 TransformParams::default(),
1334 Composer::passthrough(),
1335 )?;
1336 Ok(Self {
1337 scrub: Scrub::default(),
1338 load_warnings: Vec::new(),
1339 meta,
1340 content_light: ContentLight::default(),
1341 native: (meta.width, meta.height),
1342 native_fps: IMAGE_ONLY_RATE,
1343 frames: stream.frames,
1344 worker: stream.worker,
1345 backend: stream.backend,
1346 video_failure: stream.failure,
1347 retired: Vec::new(),
1348 restarts: 0,
1349 clock: PlaybackClock::new(ClockSource::Wall),
1350 audio: None,
1351 audio_disabled: None,
1352 project,
1353 counts: vec![meta.frame_count],
1354 probes: std::collections::HashMap::new(),
1355 // Source 0 *is* the timeline's rate: it defined it.
1356 rates: vec![Rate::REAL_TIME],
1357 span_rate: Rate::REAL_TIME,
1358 span,
1359 span_priming: true,
1360 feed: Feed::Live,
1361 back: Back::Off,
1362 dissolve: None,
1363 view: None,
1364 eos: false,
1365 eos_end: 0.0,
1366 mix: None,
1367 solo: Vec::new(),
1368 priming: false,
1369 drop_late: false,
1370 // A file just opened is a project nobody has picked stand-ins for.
1371 proxies: false,
1372 auto_proxies: false,
1373 encoder_seat: crate::export::EncoderSeat::default(),
1374 sample_rate: None,
1375 })
1376 }
1377
1378 /// Opens a project file written by [`save_project`](Self::save_project):
1379 /// the whole timeline, restored to where its playhead stood, paused like
1380 /// [`open`](Self::open).
1381 ///
1382 /// A *new* session rather than a reload of this one, so a load that fails
1383 /// leaves the caller's current session untouched -- atomic by
1384 /// construction. Every named file is opened and checked here: the
1385 /// *scaffolding* source -- the first that is not a still, since a picture
1386 /// carries no rate -- defines the timeline exactly as `open` does, every
1387 /// other source has to match it the way [`import`](Self::import) demands
1388 /// (a save renumbers, so which index that is says nothing), and every clip
1389 /// has to still be inside the file it plays from. A source that vanished or
1390 /// shrank since the save is a refusal naming it, not a silently shorter
1391 /// timeline -- the disappearing-file tolerance elsewhere in this type
1392 /// applies only *after* a project has loaded.
1393 ///
1394 /// The undo history is not saved: `undo` is `false` on a fresh load.
1395 pub fn open_project(path: &Path) -> crate::Result<Self> {
1396 Self::open_project_relinked(path, &[])
1397 }
1398
1399 /// What the last load changed to open the file, one line per clip it clamped
1400 /// (a clip that ran past its source). Empty for a project that opened as saved.
1401 pub fn load_warnings(&self) -> &[String] {
1402 &self.load_warnings
1403 }
1404
1405 /// [`open_project`](Self::open_project) with some saved paths replaced:
1406 /// each `(saved, found)` pair points the source the project saved at `saved`
1407 /// at `found` before anything is checked. A source whose file is still
1408 /// missing is **offline**: its clips stay on the timeline, nothing is read
1409 /// from it, and [`offline_sources`](Self::offline_sources) names it. Only a
1410 /// project with no present source at all is refused.
1411 /// A project none of whose sources is on disk: the timeline is the canvas and rate it was saved
1412 /// with, every clip stays, and every source is offline. Each source's length is the furthest
1413 /// frame a clip reaches into it, which is what a relink is checked against.
1414 fn open_all_offline(doc: crate::edith::Document) -> crate::Result<Self> {
1415 let (width, height) = doc.resolution.unwrap_or((1920, 1080));
1416 let fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0).unwrap_or(30.0);
1417 let counts: Vec<u32> = (0..doc.sources.len())
1418 .map(|i| {
1419 doc.lanes
1420 .iter()
1421 .flat_map(|(_, clips)| clips)
1422 .filter(|clip| clip.source == i)
1423 .map(|clip| clip.out_frame)
1424 .max()
1425 .unwrap_or(0)
1426 })
1427 .collect();
1428 let rates = vec![Rate::REAL_TIME; doc.sources.len()];
1429 let mut session = Self::empty(width, height, fps)?;
1430 session.project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)?
1431 .with_mix(&doc.gains, doc.limiter)
1432 .with_ducks(&doc.ducks)
1433 .with_voices(&doc.voices)
1434 .with_lane_names(&doc.names)
1435 .with_bins(doc.bins)
1436 .with_lane_flags(&doc.flags)
1437 .with_tone(doc.tone)
1438 .with_notes(doc.notes)
1439 .with_still_secs(doc.still_secs);
1440 session.counts = counts;
1441 session.rates = rates;
1442 Ok(session)
1443 }
1444
1445 pub fn open_project_relinked(path: &Path, relinks: &[(PathBuf, PathBuf)]) -> crate::Result<Self> {
1446 let mut doc = crate::edith::load(path)?;
1447 for source in doc.sources.iter_mut() {
1448 if let Some((_, found)) = relinks
1449 .iter()
1450 .find(|(saved, _)| crate::project::canonical(saved) == source.path)
1451 {
1452 *source = Source { fav: source.fav, bin: source.bin, ..Source::new(found, source.audio_stream) };
1453 }
1454 }
1455 if doc.sources.iter().all(|s| !crate::source_present(&s.path)) && !doc.sources.is_empty() {
1456 return Self::open_all_offline(doc);
1457 }
1458 // *Which* source scaffolds it: the first that is not a still, and index
1459 // 0 only when there is no other. A still defines no frame rate -- it is
1460 // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps
1461 // footage off a PNG that was imported first and so sits at index 0
1462 // (`Project::without_orphan_sources` keeps every source in session
1463 // order, so whatever was imported first is saved first) reads the
1464 // timeline as 30 fps and then refuses every file on it for not
1465 // matching. The rule this and
1466 // [`audio_source_of`] share: nothing may assume what source 0 *is*.
1467 //
1468 // A v9 file says what rate it was cut at, and that answer beats the
1469 // scaffold's *where the scaffold has none to give*: a still and a song
1470 // are both given a made-up rate (`IMAGE_ONLY_RATE`,
1471 // `AUDIO_ONLY_CANVAS`), so a timeline of nothing but those used to come
1472 // back at 30 fps however it was cut. A scaffold with a picture keeps
1473 // defining the timeline as it always did -- it is the file every clip
1474 // on the lane was conformed to, and the two agree by construction.
1475 let saved_fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0);
1476 // An offline source cannot scaffold: the first present non-still does,
1477 // then the first present anything.
1478 let scaffold = doc
1479 .sources
1480 .iter()
1481 .position(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
1482 .or_else(|| doc.sources.iter().position(|s| crate::source_present(&s.path)))
1483 .unwrap_or(0);
1484 // Owned: the sources move into the `Project` below, and the device is
1485 // opened after that (see the comment there).
1486 let first = doc
1487 .sources
1488 .get(scaffold)
1489 .cloned()
1490 .ok_or("the project names no sources")?;
1491 // The scaffolding source both defines the timeline and is what the
1492 // playhead's first picture comes from, so it is opened for playback
1493 // rather than merely probed.
1494 // One value, not two locals: everything below this line can refuse, and
1495 // locals drop in reverse declaration order -- a bare worker would join
1496 // its decode thread while the receiver next to it was still holding
1497 // that thread parked in `send`, which is a hang (see [`FrameStream`]).
1498 // Ungraded, and superseded before a frame of it is shown: the `seek` at
1499 // the end of this function reopens the playhead's span through
1500 // `start_span`, which is where a saved grade reaches the picture.
1501 // ...unless it has no picture to open: a project whose source 0 is a
1502 // song scaffolds the canvas the same way a fresh audio-only open does
1503 // ([`open_audio_only`](Self::open_audio_only)), and the placeholder
1504 // black stream is superseded by the `seek` at the end of this function
1505 // like every other worker opened here.
1506 // What source 0's own file declares about its light level, read the
1507 // same way [`open_stream`](Self::open_stream) reads it for a fresh
1508 // open: [`ContentLight::default()`] for a song or a still, neither of
1509 // which is graded.
1510 let content_light = if crate::is_audio(&first.path) || crate::is_image(&first.path) {
1511 ContentLight::default()
1512 } else {
1513 Demuxer::open(&first.path)
1514 .map(|(_, d)| d.light())
1515 .unwrap_or_default()
1516 };
1517 // The extension's word, corrected below the moment the header disagrees
1518 // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every
1519 // later question in this function about source 0 asks *this*, not
1520 // `crate::is_audio` again, so a discovered song stays one for the rest
1521 // of the scaffold.
1522 let mut audio_only = crate::is_audio(&first.path);
1523 let (mut meta, stream) = match audio_only {
1524 true => {
1525 let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS;
1526 let frame_rate = saved_fps.unwrap_or(canvas_fps);
1527 let meta = VideoMeta {
1528 width,
1529 height,
1530 frame_rate,
1531 frame_count: audio_frames(&first.path, frame_rate)
1532 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
1533 codec: Codec::H264,
1534 color: ColorDescription::default(),
1535 matrix_assumed: false,
1536 rotation: Rotation::None,
1537 // No container said anything about these: the canvas this engine drew
1538 // itself is square pixels at the size it was drawn at.
1539 coded_width: width,
1540 coded_height: height,
1541 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1542 };
1543 (meta, DecodeSession::open_black(width, height, 1))
1544 }
1545 // ...and a still scaffolds its own picture as the canvas, exactly
1546 // as a fresh `open_image_only` does, with the same placeholder
1547 // stream the `seek` at the end supersedes.
1548 false if crate::is_image(&first.path) => {
1549 let still = crate::decode::Still::open(&first.path)
1550 .map_err(|e| format!("source {}: {e}", first.path.display()))?;
1551 let frame_rate = saved_fps.unwrap_or(IMAGE_ONLY_RATE);
1552 let meta = VideoMeta {
1553 width: still.width,
1554 height: still.height,
1555 frame_rate,
1556 frame_count: image_frames(frame_rate),
1557 codec: Codec::H264,
1558 color: ColorDescription::default(),
1559 matrix_assumed: false,
1560 // `Rotation::None` is honest, not a shrug: `Still::open`
1561 // made the file's own turn before these planes were
1562 // written, so the pair below is already the displayed one.
1563 rotation: Rotation::None,
1564 // No container said anything about these: the picture this
1565 // engine decoded itself is square pixels at its own size.
1566 coded_width: still.width,
1567 coded_height: still.height,
1568 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1569 };
1570 let stream = DecodeSession::open_still(
1571 &first.path,
1572 0,
1573 1,
1574 ColorParams::default(),
1575 TransformParams::default(),
1576 Composer::passthrough(),
1577 )?;
1578 (meta, stream)
1579 }
1580 false => match DecodeSession::open_worker(
1581 &first.path,
1582 0,
1583 u32::MAX,
1584 ColorParams::default(),
1585 TransformParams::default(),
1586 Composer::passthrough(),
1587 // The saved rendition, from the document rather than from the
1588 // project (which is built below): this placeholder is what the
1589 // window shows until the `seek` at the end reopens the span.
1590 doc.tone,
1591 ) {
1592 Ok(opened) => opened,
1593 // A saved source whose extension named a film but whose header
1594 // names no picture: the same door a fresh open falls to
1595 // (`open_stream`), so a project first cut around a song muxed
1596 // into an `.mp4` reloads instead of refusing on a track that was
1597 // never there to begin with.
1598 Err(e) if NoVideoTrack::is_it(&e) => {
1599 audio_only = true;
1600 let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS;
1601 let frame_rate = saved_fps.unwrap_or(canvas_fps);
1602 let meta = VideoMeta {
1603 width,
1604 height,
1605 frame_rate,
1606 frame_count: audio_frames(&first.path, frame_rate)
1607 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
1608 codec: Codec::H264,
1609 color: ColorDescription::default(),
1610 matrix_assumed: false,
1611 rotation: Rotation::None,
1612 // No container said anything about these: the canvas this engine drew
1613 // itself is square pixels at the size it was drawn at.
1614 coded_width: width,
1615 coded_height: height,
1616 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1617 };
1618 (meta, DecodeSession::open_black(width, height, 1))
1619 }
1620 Err(e) => return Err(format!("source {}: {e}", first.path.display()).into()),
1621 },
1622 };
1623 // The project's own resolution, which is source 0's picture unless the
1624 // file says otherwise -- every dialect before v7 had no way to say it,
1625 // and that default is exactly what those projects meant.
1626 let native = (meta.width, meta.height);
1627 if let Some((width, height)) = doc.resolution {
1628 meta.width = width;
1629 meta.height = height;
1630 }
1631 // ...and the project's own *rate*, which is the scaffold's unless the
1632 // file says otherwise. The two made-up rates above already took the
1633 // saved one (their counts are computed from it); a scaffold with a
1634 // picture keeps its own here, so a project cut at a rate nobody picked
1635 // is the file it always was -- and one where a rate *was* picked
1636 // ([`set_frame_rate`](Self::set_frame_rate)) comes back at it rather
1637 // than at the media's, which would leave every clip number counted in
1638 // frames the timeline no longer has.
1639 let native_fps = match audio_only {
1640 true => AUDIO_ONLY_CANVAS.2,
1641 false if crate::is_image(&first.path) => IMAGE_ONLY_RATE,
1642 false => meta.frame_rate,
1643 };
1644 if let Some(fps) = saved_fps {
1645 meta.frame_rate = fps;
1646 }
1647 // A song and a still have no rate of their own to be conformed from:
1648 // their length above was counted in the timeline's frames already,
1649 // whatever those are. A file with pictures is read through [`Rate`] like
1650 // any other source when the project is cut at another rate.
1651 let made_up = audio_only || crate::is_image(&first.path);
1652 let scaffold_rate = match made_up || native_fps == meta.frame_rate {
1653 true => Rate::REAL_TIME,
1654 false => Rate::from_fps(native_fps, meta.frame_rate)
1655 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
1656 };
1657 let first_audio = first_audio_of(&doc.sources)?;
1658
1659 // In source order, with the scaffold's own count in its own slot: the
1660 // clip check below indexes this list by source, so it must line up with
1661 // `doc.sources` whichever entry the scaffolding came from.
1662 let mut counts = Vec::with_capacity(doc.sources.len());
1663 // Beside it, one entry per source, grown at every `push` below: the
1664 // scaffold defines the rate, so it is read frame for frame; every other
1665 // one is however long it is *in this timeline's frames*, which is the
1666 // length `import` noted for it and the wall the clip check below holds
1667 // it to.
1668 let mut rates = Vec::with_capacity(doc.sources.len());
1669 for (i, source) in doc.sources.iter().enumerate() {
1670 if i == scaffold {
1671 counts.push(scaffold_rate.timeline_at(meta.frame_count));
1672 rates.push(scaffold_rate);
1673 continue;
1674 }
1675 // Offline: nothing to check it against. Its length is the furthest
1676 // frame a clip reaches into it, so the clip check below holds.
1677 if !crate::source_present(&source.path) {
1678 let reach = doc
1679 .lanes
1680 .iter()
1681 .flat_map(|(_, clips)| clips)
1682 .filter(|clip| clip.source == i)
1683 .map(|clip| clip.out_frame)
1684 .max()
1685 .unwrap_or(0);
1686 counts.push(reach);
1687 rates.push(Rate::REAL_TIME);
1688 continue;
1689 }
1690 // A still has neither a rate to match nor a track to match with:
1691 // its length is the one it is held to, recomputed exactly as the
1692 // import that first noted it did ([`image_frames`]), which is what
1693 // makes the clip check below meaningful on a reload.
1694 if crate::is_image(&source.path) {
1695 crate::decode::image_size(&source.path)
1696 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1697 counts.push(image_frames(meta.frame_rate));
1698 rates.push(Rate::REAL_TIME);
1699 continue;
1700 }
1701 // A source with no picture is checked on what it does have, and
1702 // its length is its playing time -- the same two answers `import`
1703 // gave it when it first joined the timeline.
1704 if crate::is_audio(&source.path) {
1705 audio_matches(source, &first_audio)
1706 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1707 counts.push(audio_frames(&source.path, meta.frame_rate)?);
1708 rates.push(Rate::REAL_TIME);
1709 continue;
1710 }
1711 // A container with sound but no picture (an audio-only mp4 behind a
1712 // video extension) is held and counted exactly as `import_audio` holds
1713 // and counts it when it first joins the timeline -- the same door
1714 // `import` takes, so a file that imports always reopens.
1715 let (other, _) = match Demuxer::open(&source.path) {
1716 Ok(opened) => opened,
1717 Err(e) if NoVideoTrack::is_it(&e) => {
1718 audio_matches(source, &first_audio)
1719 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1720 counts.push(audio_frames(&source.path, meta.frame_rate)?);
1721 rates.push(Rate::REAL_TIME);
1722 continue;
1723 }
1724 Err(e) => return Err(format!("source {}: {e}", source.path.display()).into()),
1725 };
1726 let rate = matches_timeline(source, &other, &meta, &first_audio)
1727 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1728 counts.push(rate.timeline_at(other.frame_count));
1729 rates.push(rate);
1730 }
1731 // A still is silent, so a clip playing one on an audio lane is a
1732 // segment the audio worker would open a PNG for. Refused by name
1733 // here, which is the one door it can arrive through
1734 // (`place_stream_at` never puts one there). An audio file on a
1735 // *video* lane used to be refused the same way; it plays as a
1736 // waveform visualizer now ([`DecodeSession::open_visualizer`]).
1737 for (kind, clip) in doc
1738 .lanes
1739 .iter()
1740 .chain(doc.sequences.iter().flat_map(|s| s.doc.lanes.iter()))
1741 .flat_map(|(kind, clips)| clips.iter().map(move |clip| (*kind, clip)))
1742 .filter(|(_, clip)| !crate::project::is_sequence_source(clip.source))
1743 {
1744 let path = &doc.sources[clip.source].path;
1745 if kind == LaneKind::Audio && crate::is_image(path) {
1746 return Err(format!(
1747 "{} is a still image: it can only play on a video lane",
1748 path.display()
1749 )
1750 .into());
1751 }
1752 }
1753 // Each lane is held to the length its own clips are walled by ([`wall_table`]).
1754 // A clip that runs past its source is clamped to the source's end and
1755 // reported in `warnings`, not refused: a project that was saved with one
1756 // (a placement or a trim that used the wrong length) must still open, and
1757 // the clamp is the one change that keeps every later edit's walls true.
1758 let audio_walls = wall_table(&doc.sources, &counts, meta.frame_rate, Lane::A1);
1759 let mut warnings = Vec::new();
1760 let mut i = 0;
1761 let sources = doc.sources.clone();
1762 for (kind, clips) in doc
1763 .lanes
1764 .iter_mut()
1765 .chain(doc.sequences.iter_mut().flat_map(|s| s.doc.lanes.iter_mut()))
1766 {
1767 let walls: &[u32] = if *kind == LaneKind::Audio { &audio_walls } else { &counts };
1768 for clip in clips.iter_mut() {
1769 let n = i;
1770 i += 1;
1771 if crate::project::is_sequence_source(clip.source) {
1772 continue;
1773 }
1774 let wall = walls[clip.source];
1775 if clip.out_frame > wall && wall > 0 {
1776 warnings.push(format!(
1777 "clip {n} ended at frame {} but {} has {wall} frames: clamped to {wall}",
1778 clip.out_frame,
1779 sources[clip.source].path.display(),
1780 ));
1781 clip.out_frame = wall;
1782 if clip.in_frame >= clip.out_frame {
1783 clip.in_frame = clip.out_frame - 1;
1784 }
1785 }
1786 }
1787 }
1788 // The subtitle files are read here rather than in the parser: a
1789 // `.edith` names them and holds no cues. One that has gone missing, or
1790 // whose track is a codec of pictures, comes back listed and refused by
1791 // name ([`crate::subtitle::open_all`]) -- a project does not stop
1792 // opening over a subtitle, and a re-save does not lose the row.
1793 //
1794 // All of them in one call, in saved order, because a file is walked
1795 // whole to reach one track: a film whose project names many of its
1796 // tracks is one walk here rather than one per row.
1797 let playhead = doc.playhead;
1798 let (proxy, auto_proxy, encoder, sample_rate) = (doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate);
1799 let seq_active = doc.seq_active.take();
1800 let seq_order = std::mem::take(&mut doc.seq_order);
1801 let seq_docs = std::mem::take(&mut doc.sequences);
1802 let mcams = std::mem::take(&mut doc.mcams);
1803 let mut project = project_of(doc, &meta)?;
1804 if let Some((active, name)) = seq_active {
1805 // The fresh project's placeholder sequence is not the file's: the file's
1806 // sequences (the active one by `set_sequence_meta`) are all there is.
1807 project.clear_sequences();
1808 for sd in seq_docs {
1809 let other = project_of(sd.doc, &meta)?;
1810 project.absorb_sequence(sd.id, &sd.name, other)?;
1811 }
1812 project.set_sequence_meta(active, &name, &seq_order);
1813 project.set_multicam(&mcams)?;
1814 project.check_sequences()?;
1815 }
1816 let span = crate::export::stack_span_at(&project.render_view(), 0);
1817 // Last, because it is the one thing here that cannot be taken back: the
1818 // feeder thread outlives the `Audio` value (it holds its own clones) and
1819 // only a session's `drop` retires it, so a refusal above this line would
1820 // leave a PipeWire stream and a thread behind for a project that never
1821 // opened. Nothing before it needs the device.
1822 //
1823 // On the source the timeline's *sound* is defined by, which is the
1824 // scaffold unless that one is a still ([`audio_source_of`]): opening a
1825 // PNG as the device is a session with no audio at all, however many
1826 // clips with sound are on its lanes.
1827 //
1828 // `audio_source_of` alone only rules out a still; it says nothing
1829 // about whether the file it lands on actually *has* a track. A device
1830 // pinned to the first candidate that opens silent (no track, or one
1831 // the decoder refuses) would leave every later clip's sound unheard
1832 // for the rest of the session, however many other sources on the
1833 // timeline have real audio -- so this walks forward past a silent
1834 // candidate to the first source that really opens a device, and keeps
1835 // only the last attempt's reason when none of them do (a later
1836 // source's silence is not worth reporting over an earlier one's).
1837 let (audio, audio_disabled) = {
1838 let mut opened = (None, None);
1839 for source in project
1840 .sources()
1841 .iter()
1842 .filter(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
1843 {
1844 opened = open_audio(&source.path, source.audio_stream);
1845 if opened.0.is_some() {
1846 break;
1847 }
1848 }
1849 opened
1850 };
1851 let mut session = Self {
1852 scrub: Scrub::default(),
1853 meta,
1854 load_warnings: warnings,
1855 content_light,
1856 native,
1857 native_fps,
1858 frames: stream.frames,
1859 worker: stream.worker,
1860 backend: stream.backend,
1861 video_failure: stream.failure,
1862 retired: Vec::new(),
1863 restarts: 0,
1864 clock: PlaybackClock::new(match audio {
1865 Some(_) => ClockSource::Audio,
1866 None => ClockSource::Wall,
1867 }),
1868 audio,
1869 audio_disabled,
1870 project,
1871 counts,
1872 probes: std::collections::HashMap::new(),
1873 rates,
1874 span_rate: Rate::REAL_TIME,
1875 span,
1876 span_priming: true,
1877 feed: Feed::Live,
1878 back: Back::Off,
1879 dissolve: None,
1880 view: None,
1881 eos: false,
1882 eos_end: 0.0,
1883 mix: None,
1884 solo: Vec::new(),
1885 priming: false,
1886 drop_late: false,
1887 // What the file says, and `false` for every dialect before v12:
1888 // a project cut on the films themselves opens on them.
1889 proxies: proxy,
1890 // ...and what it says about making them, which is "yes" for every
1891 // dialect before v13 and for one that leaves the line out.
1892 auto_proxies: auto_proxy,
1893 // ...and which encoder it exports with, which is the seat this
1894 // machine has for every dialect before v14.
1895 encoder_seat: encoder,
1896 sample_rate,
1897 };
1898 // The scaffolding above opened source 0 from its first frame and the
1899 // whole of its audio; this puts both onto the clip the playhead is
1900 // actually in -- a seek replaces the decoder and supersedes the audio
1901 // worker by epoch, exactly as it does after an edit. It also clamps,
1902 // so a playhead past a hand-shortened timeline lands on the last frame.
1903 session.seek(f64::from(playhead) / meta.frame_rate);
1904 Ok(session)
1905 }
1906
1907 pub fn meta(&self) -> &VideoMeta {
1908 &self.meta
1909 }
1910
1911 /// What the pictures now arriving are being decoded by: the clip under the
1912 /// playhead, since one video worker feeds the composite at a time. An
1913 /// atomic load -- a front-end may ask it every repaint -- and it is what
1914 /// *opened*, so a clip whose hardware session fell back to software reads
1915 /// [`Backend::Software`] from the frame that fallback happened.
1916 pub fn decode_backend(&self) -> Backend {
1917 self.backend.get()
1918 }
1919
1920 /// What an export of this timeline would encode the *sound* with, before
1921 /// one is started: the copy an mp4 normally makes, or the software encoder
1922 /// the format (or an equalized lane) forces. Pure -- no probe, no file
1923 /// opened -- so a card may ask it per repaint; the picture's half costs a
1924 /// plugin open and lives in [`crate::export::planned_video`].
1925 pub fn planned_audio(&self, format: crate::export::Format, ranged: bool) -> &'static str {
1926 crate::export::planned_audio(&self.project.render_view(), format, ranged)
1927 }
1928
1929 /// The timeline an export started right now would be run against, owned:
1930 /// what lets a front-end ask [`crate::export::planned_seats`] what that
1931 /// export would open *off* its render thread, which is the only way to ask
1932 /// a question that opens files. The very snapshot
1933 /// [`export_to_with`](Self::export_to_with) hands the worker, so the answer
1934 /// is about the export that would really start.
1935 pub fn export_snapshot(&self) -> (crate::project::Project, VideoMeta) {
1936 (self.project.export_snapshot(), self.meta)
1937 }
1938
1939 /// The timeline's frame rate: what an editor timeline is read at ([`crate::interchange::otio::read`]).
1940 pub fn timeline_frame_rate(&self) -> f64 {
1941 self.meta.frame_rate
1942 }
1943
1944 /// The active sequence as an editor timeline, for the interchange formats ([`crate::interchange`]).
1945 pub fn timeline_snapshot(&self) -> crate::interchange::Timeline {
1946 let (project, meta) = self.export_snapshot();
1947 crate::interchange::of_project(&project, meta.frame_rate, (meta.width, meta.height))
1948 }
1949
1950 /// The composed picture at timeline `frame`, headless and exact: what
1951 /// export writes for that frame, scaled to fit `width` x `height`. Does not
1952 /// touch the playback clock. See [`crate::export::compose_at`].
1953 pub fn compose_at(
1954 &self,
1955 frame: u32,
1956 width: u32,
1957 height: u32,
1958 ) -> crate::Result<crate::decode::Frame> {
1959 let (project, meta) = self.export_snapshot();
1960 crate::export::compose_at(&project, &meta, frame, width, height)
1961 }
1962
1963 /// What an export would do about the tracks at `picks` --
1964 /// [`crate::export::planned_subtitles`], asked of the project a front-end is
1965 /// holding, and pure for the same reason. `picks` is any run of rows of
1966 /// [`subtitles`](Self::subtitles): the whole
1967 /// [`ExportSettings::subtitles`](crate::export::ExportSettings::subtitles)
1968 /// list a card is about to send (`picks.iter().copied()`) as much as a
1969 /// single `Some(row)`.
1970 pub fn planned_subtitles(
1971 &self,
1972 format: crate::export::Format,
1973 picks: impl IntoIterator<Item = usize>,
1974 ) -> String {
1975 crate::export::planned_subtitles(&self.project.render_view(), format, picks)
1976 }
1977
1978 /// Where the cues of the track at `pick` land on *this* timeline --
1979 /// [`crate::export::timeline_cues`], the very map an export writes the file
1980 /// with, so a front-end that draws these draws what the file will say. On a
1981 /// rippled or cut timeline that is the whole point: an embedded track rides
1982 /// the spans that still play it, and a standalone `.srt` keeps the
1983 /// timeline's own clock, clipped to its length.
1984 ///
1985 /// Empty for a row that is not there and for a track that could not be read.
1986 /// Pure and file-free, so it may be asked per repaint; the cost is a walk of
1987 /// the spans and of the cues.
1988 pub fn timeline_cues(&self, pick: usize) -> Vec<crate::subtitle::Cue> {
1989 self.project
1990 .subtitles()
1991 .get(pick)
1992 .map_or_else(Vec::new, |t| {
1993 crate::export::timeline_cues(&self.project.render_view(), t, self.meta.frame_rate)
1994 })
1995 }
1996
1997 /// Why the sound's rate is not a choice for this timeline in this format --
1998 /// [`crate::export::audio_rate_refusal`], asked of the project a front-end
1999 /// is holding, and pure for the same reason.
2000 pub fn audio_rate_refusal(
2001 &self,
2002 format: crate::export::Format,
2003 ranged: bool,
2004 ) -> Option<&'static str> {
2005 crate::export::audio_rate_refusal(&self.project.render_view(), format, ranged)
2006 }
2007
2008 /// Why this session plays silent although the file has sound -- an audio
2009 /// track in a codec we cannot decode, or one the decoder refused. `None`
2010 /// when there is audio, and for a file that never had any. A front-end
2011 /// shows it once, at open: without it the whole thing is a stderr line.
2012 pub fn audio_disabled_reason(&self) -> Option<&str> {
2013 self.audio_disabled.as_deref()
2014 }
2015
2016 /// Why the picture stopped short of the end of its range, if it did -- the
2017 /// video twin of [`Self::audio_disabled_reason`], and the reason a corrupt
2018 /// file used to be indistinguishable from a finished one.
2019 ///
2020 /// A closed frame channel is not an answer: a span that ran to the end of
2021 /// the file and a span that gave up on a broken packet both drop the
2022 /// sender, and [`Self::try_frame`] returns `None` for either. The app read
2023 /// that as end-of-stream, so a file with a damaged middle froze on its last
2024 /// good picture and the transport said ENDED -- no notice, no banner, and
2025 /// nothing on the screen to say the film had stopped being the film.
2026 ///
2027 /// `None` for a span that played its whole range, which is the ordinary
2028 /// case and the one that must stay silent: a notice that fires on every
2029 /// film is a notice nobody reads. The reason is the engine's own words, for
2030 /// the same reason the sound one is.
2031 pub fn video_failure_reason(&self) -> Option<String> {
2032 self.video_failure.reason()
2033 }
2034
2035 /// The files this timeline plays from, index 0 first -- a caller needs it
2036 /// to name an export or a window after the media rather than the project.
2037 pub fn sources(&self) -> &[Source] {
2038 self.project.sources()
2039 }
2040
2041 /// The subtitle tracks on this timeline, in the order they were added: what
2042 /// a front-end lists and what [`save_project`](Self::save_project) writes.
2043 /// A track that could not be read is *in* this list, saying why
2044 /// ([`crate::subtitle::SubtitleTrack::refused`]) -- listed and skipped, not
2045 /// dropped.
2046 pub fn subtitles(&self) -> &[crate::subtitle::SubtitleTrack] {
2047 self.project.subtitles()
2048 }
2049
2050 /// Adds subtitles from `path`: every subtitle track of a Matroska file, or
2051 /// the one track a standalone `.srt`/`.vtt`/`.ass` is. Hands back how many
2052 /// were added -- 0 for a file whose tracks are all on the timeline already,
2053 /// since importing the same file twice is the same subtitles.
2054 ///
2055 /// An error only when the file cannot be read *at all*; a track this cannot
2056 /// parse is added refused by name, for the reason
2057 /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves:
2058 /// subtitles are not clips and land on no lane.
2059 pub fn import_subtitles(&mut self, path: &Path) -> crate::Result<usize> {
2060 let tracks = Self::parse_subtitles(path)?;
2061 // A file that was walked and carries none is refused as *that*, because
2062 // the alternative -- 0 added -- is the very sentence a file whose tracks
2063 // are already on this timeline gets, and the two are opposite answers a
2064 // person acts differently on. Said only after the walk actually looked
2065 // ([`crate::subtitle::of_media`]); a *file* that is not a container at
2066 // all never reaches here, [`parse_subtitles`](Self::parse_subtitles)
2067 // refuses it in its own words.
2068 if tracks.is_empty() {
2069 return Err(Self::no_subtitles_in(path));
2070 }
2071 Ok(self.add_subtitle_tracks(tracks))
2072 }
2073
2074 /// The reading half of [`import_subtitles`](Self::import_subtitles), with no
2075 /// session in it: every subtitle track of a Matroska file, or the one track
2076 /// a standalone `.srt`/`.vtt`/`.ass` is, cues and all. Same refusal rule.
2077 ///
2078 /// This is the half that costs -- a walk of the whole container, measured at
2079 /// 210 ms on a 25 GB 35-track file and 1.3 s on a 3 GB one whose pages were
2080 /// cold -- so a front-end runs *this* on its background executor and hands
2081 /// what comes back to [`add_subtitle_tracks`](Self::add_subtitle_tracks),
2082 /// which costs a push. Both doors are this one function, so the import
2083 /// button and the background one cannot drift apart.
2084 pub fn parse_subtitles(path: &Path) -> crate::Result<Vec<crate::subtitle::SubtitleTrack>> {
2085 // The containers that carry subtitle tracks *inside* them: every
2086 // Matroska one ([`crate::demux::is_matroska`], which is where `.mks` --
2087 // the subtitles alone -- comes in) and the mp4 family, whose `tx3g`
2088 // timed text is what an mp4 export of this project's own writes, so a
2089 // file edith wrote is a file edith imports back. A transport stream
2090 // carries Blu-ray/AVCHD PGS bitmaps the same way.
2091 let tracks = match crate::demux::is_matroska(path)
2092 || crate::demux::is_mpegts(path)
2093 || path.extension().is_some_and(|e| {
2094 matches!(
2095 e.to_string_lossy().to_ascii_lowercase().as_str(),
2096 "mp4" | "m4v" | "mov" | "3gp" | "3g2"
2097 )
2098 }) {
2099 true => crate::subtitle::of_media(path)?,
2100 false => vec![crate::subtitle::open(path, None)],
2101 };
2102 // A standalone file that could not be parsed is a refusal here rather
2103 // than a row nobody asked for: the import is the moment to say so, and
2104 // the load is the moment to keep it.
2105 if let [one] = &tracks[..]
2106 && one.track.is_none()
2107 && let Some(why) = &one.refused
2108 {
2109 return Err(why.clone().into());
2110 }
2111 Ok(tracks)
2112 }
2113
2114 /// What a file the walk found no subtitle track in is refused with,
2115 /// wherever the refusal is worded: the engine's own door
2116 /// ([`import_subtitles`](Self::import_subtitles)) and a front-end that
2117 /// splits the walk from the push ([`parse_subtitles`](Self::parse_subtitles)
2118 /// then [`add_subtitle_tracks`](Self::add_subtitle_tracks)) must not tell a
2119 /// person two different stories about the same file.
2120 pub fn no_subtitles_in(path: &Path) -> crate::Error {
2121 format!("no subtitle tracks in {}", path.display()).into()
2122 }
2123
2124 /// Puts tracks already read by [`parse_subtitles`](Self::parse_subtitles)
2125 /// on this timeline, in the order given. Hands back how many actually went
2126 /// on: [`Project::add_subtitles`] drops the ones already here -- same file,
2127 /// same track number -- so 0 is "this file's subtitles are on the timeline
2128 /// already", which is the sentence a front-end says.
2129 ///
2130 /// The whole of what an import costs the thread that calls it, which is why
2131 /// the parse is a separate door: nothing here opens, seeks or decodes.
2132 /// Subtitles are not clips and land on no lane, so nothing playable changes
2133 /// and no undo step is pushed ([`Project::remove_subtitles`] says why).
2134 /// [`import_subtitles`](Self::import_subtitles) with a language on its tracks: `lang` as a
2135 /// person typed it, on every track, or else a standalone file's own name
2136 /// ([`crate::subtitle::import_language`]). Returns the count added and the language with where
2137 /// it came from, `None` when none was set. One undo step, as the import is.
2138 pub fn import_subtitles_as(
2139 &mut self,
2140 path: &Path,
2141 lang: Option<&str>,
2142 ) -> crate::Result<(usize, Option<(String, &'static str)>)> {
2143 let mut tracks = Self::parse_subtitles(path)?;
2144 if tracks.is_empty() {
2145 return Err(Self::no_subtitles_in(path));
2146 }
2147 let standalone = tracks.iter().all(|t| t.track.is_none());
2148 let named = if lang.is_some() || standalone {
2149 crate::subtitle::import_language(path, lang)?
2150 } else {
2151 None
2152 };
2153 if let Some((code, _)) = &named {
2154 for t in &mut tracks {
2155 if lang.is_some() || t.track.is_none() {
2156 crate::subtitle::set_language(t, code);
2157 }
2158 }
2159 }
2160 let n = self.add_subtitle_tracks(tracks);
2161 Ok((n, named))
2162 }
2163
2164 /// Names the language of subtitle track `track` ([`Project::set_subtitle_language`]). One undo step.
2165 pub fn set_subtitle_language(&mut self, track: usize, code: &str) -> bool {
2166 self.project.set_subtitle_language(track, code)
2167 }
2168
2169 pub fn add_subtitle_tracks(&mut self, tracks: Vec<crate::subtitle::SubtitleTrack>) -> usize {
2170 // One undo step for the whole import (see [`Project::add_subtitles_all`]).
2171 self.project.add_subtitles_all(&tracks)
2172 }
2173
2174 /// Takes the track at `idx` off this timeline -- the door a subtitle row's
2175 /// own remove goes through, the way [`import_subtitles`](
2176 /// Self::import_subtitles) is the door that puts one on. Refused in
2177 /// [`Project::remove_subtitles`]'s words for a row this timeline does not
2178 /// have, and for one a caption on a subtitle lane still plays -- delete
2179 /// those placements first, or the words under them would change.
2180 ///
2181 /// Nothing playable changes and no worker was opened against a cue, so
2182 /// unlike [`remove_source`](Self::remove_source) this does not reseek. Rows
2183 /// past `idx` move down by one: a caller holding a picked row (the export's
2184 /// subtitle pick) has to fix it up or drop it; the placements on the lanes
2185 /// are walked down with it and need no fixing.
2186 ///
2187 /// One undo step, and the reindex with it ([`Project::remove_subtitles`]'s
2188 /// own entry): every step in the history names its tracks by index into the
2189 /// palette, so an entry carries the palette it was taken beside its lanes --
2190 /// which is what lets a `z` put this row back, and every placement that
2191 /// moved down with it. What that entry cannot bring back is the *pick*: it
2192 /// is the caller's, and a caller holding one fixes it up or drops it
2193 /// ([`crate::subs::sub_pick_after_restore`]).
2194 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
2195 self.project.remove_subtitles(idx)
2196 }
2197
2198 /// Writes the timeline to `path` as a `.edith`, atomically (see
2199 /// [`crate::edith`]). Sources no clip plays from are left out, and the
2200 /// playhead is saved with it so a reopened project resumes where it stood.
2201 ///
2202 /// Refused, writing nothing, for a session whose library is empty (every
2203 /// row removed, [`Project::remove_source`]): a file naming no source has no
2204 /// timeline in it and [`open_project`](Self::open_project) could only
2205 /// refuse it, so the refusal belongs here, where nothing has been
2206 /// overwritten yet.
2207 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
2208 if self.project.sources().is_empty() {
2209 return Err("this project names no file: there is nothing to save".into());
2210 }
2211 self.save_project_noted(path).map(|_| ())
2212 }
2213
2214 /// [`save_project`](Self::save_project) that also returns what it had to change
2215 /// to write the file, one plain sentence per clip, for the front-end to show. A
2216 /// clip that runs past its source's end (a placement or an edit that used the
2217 /// wrong length, or a project saved before the walls held) is shortened to the
2218 /// source's end on the way out, never refused: the user's work is saved, and the
2219 /// note says what was shortened.
2220 pub fn save_project_noted(&self, path: &Path) -> crate::Result<Vec<String>> {
2221 if self.project.sources().is_empty() {
2222 return Err("this project names no file: there is nothing to save".into());
2223 }
2224 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
2225 let mut notes = Vec::new();
2226 let mut main = self.project.clone();
2227 notes.extend(self.wall_notes(&main.clamp_to_walls(&picture, &sound), None));
2228 // The parked sequences are saved whole too, so they are held to the same walls.
2229 let mut parked = Vec::new();
2230 for (id, name, active) in self.project.sequence_rows() {
2231 if !active {
2232 let mut other = self.project.as_sequence(id)?;
2233 notes.extend(self.wall_notes(&other.clamp_to_walls(&picture, &sound), Some(&name)));
2234 parked.push((id, other));
2235 }
2236 }
2237 self.write_project(path, &main, &parked)?;
2238 Ok(notes)
2239 }
2240
2241 /// One plain sentence per clip [`Project::clamp_to_walls`] shortened, naming the
2242 /// clip by its file's name and its lane. `seq` names a parked sequence.
2243 fn wall_notes(&self, clamps: &[crate::project::WallClamp], seq: Option<&str>) -> Vec<String> {
2244 let of = seq.map_or_else(String::new, |n| format!(" in sequence \"{n}\""));
2245 clamps
2246 .iter()
2247 .map(|c| {
2248 let path = &self.project.sources()[c.source].path;
2249 let name = path.file_stem().map_or_else(
2250 || path.display().to_string(),
2251 |s| s.to_string_lossy().into_owned(),
2252 );
2253 let what = match c.lane.kind {
2254 LaneKind::Audio => "sound",
2255 _ => "picture",
2256 };
2257 format!(
2258 "The {what} of \"{name}\" on {} runs past the end of its file{of}. It was shortened to fit.",
2259 c.lane.label(),
2260 )
2261 })
2262 .collect()
2263 }
2264
2265 /// Writes the timeline to `path` for an autosave: exactly what
2266 /// [`save_project`](Self::save_project) writes, minus its wall check. A clip
2267 /// that runs past its source is written as it is, not refused, so an
2268 /// autosave can never fail on a session's state -- the one place a refusal
2269 /// would lose the edits it was meant to keep. [`open_project`](Self::open_project)
2270 /// already clamps such a clip to its source with a warning when the file is
2271 /// read back, so the file still opens.
2272 ///
2273 /// The one refusal kept is an empty library ([`save_project`](Self::save_project)):
2274 /// a file that names no source has no timeline in it to write.
2275 pub fn save_autosave(&self, path: &Path) -> crate::Result<()> {
2276 if self.project.sources().is_empty() {
2277 return Err("this project names no file: there is nothing to save".into());
2278 }
2279 let mut parked = Vec::new();
2280 for (id, _, active) in self.project.sequence_rows() {
2281 if !active {
2282 parked.push((id, self.project.as_sequence(id)?));
2283 }
2284 }
2285 self.write_project(path, &self.project, &parked)
2286 }
2287
2288 /// The write [`save_project`](Self::save_project) and
2289 /// [`save_autosave`](Self::save_autosave) share: the project as it stands,
2290 /// atomically, with its playhead and settings.
2291 /// `main` is the active sequence as it is to be written and `parked` the others,
2292 /// by id, already held to their walls.
2293 fn write_project(&self, path: &Path, main: &Project, parked: &[(u32, Project)]) -> crate::Result<()> {
2294 let dir = crate::edith::project_dir(path);
2295 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
2296 .min(main.timeline_frames().saturating_sub(1));
2297 let main_bytes = self.encode_sequence(&dir, main, playhead);
2298 let main_bytes = crate::edith::binned(main_bytes, self.project.sources(), self.project.bins());
2299 let main_bytes = crate::edith::noted(main_bytes, self.project.notes(), self.project.still_secs());
2300 if !self.project.uses_sequences() {
2301 return crate::edith::write_atomic(path, &main_bytes);
2302 }
2303 // Several sequences: the active one is the body, the others follow as blocks of
2304 // their own, each a whole document (v45).
2305 let mut blocks = Vec::new();
2306 for (id, name, active) in self.project.sequence_rows() {
2307 if active {
2308 continue;
2309 }
2310 let Some((_, other)) = parked.iter().find(|(p, _)| *p == id) else { continue };
2311 let at = playhead.min(other.timeline_frames().saturating_sub(1));
2312 blocks.push(crate::edith::SeqBlock { id, name, bytes: self.encode_sequence(&dir, other, at) });
2313 }
2314 let order: Vec<u32> = self.project.sequence_rows().iter().map(|r| r.0).collect();
2315 let active = self.project.active_sequence();
2316 let name = self.project.sequence_name(active).unwrap_or("Sequence").to_string();
2317 let bytes = crate::edith::sequenced(main_bytes, (active, &name), &order, &blocks, &self.project.multicam_rows());
2318 crate::edith::write_atomic(path, &bytes)
2319 }
2320
2321 /// One sequence as the bytes of a standalone project document: `project` has that
2322 /// sequence active.
2323 fn encode_sequence(&self, dir: &Path, project: &Project, playhead: u32) -> Vec<u8> {
2324 let (sources, lanes, eq, color, transform) = project.without_orphan_sources();
2325 crate::edith::encode_flagged(
2326 dir,
2327 &sources,
2328 &lanes,
2329 // The lane volumes and the limiter with them: a mix that vanished
2330 // on a reload would be a mix nobody could keep, and both are the
2331 // project's, not this machine's (the monitoring volume is not
2332 // written and never will be).
2333 &project.lane_gains(),
2334 // ...and what is placed on each lane, in the same order again: the
2335 // captions, which are the only thing a subtitle lane holds.
2336 &project.lane_subs(),
2337 // The subtitle tracks with them, by reference: which file the cues
2338 // are in, never the cues (see [`crate::edith`]).
2339 project.subtitles(),
2340 &eq,
2341 &color,
2342 &transform,
2343 (self.meta.width, self.meta.height),
2344 // ...and the rate it was cut at, which nothing else in the file
2345 // says: a timeline of stills and songs used to come back at
2346 // whatever its scaffold implied (`open_project`).
2347 Some(self.meta.frame_rate),
2348 // ...and which rendition its HDR media is watched in, for the same
2349 // reason: a picked look that vanished on a reload is a look nobody
2350 // could keep.
2351 project.tone(),
2352 // ...and whether it is cut on the stand-ins, for the same reason.
2353 // *Which* files have one is not saved: [`crate::proxy`] finds that
2354 // out from the film itself, so nothing here can go stale.
2355 self.proxies,
2356 // ...and whether it makes them by itself, which is a different
2357 // question from whether it cuts on them and the only one an import
2358 // asks ([`Self::auto_proxies`]).
2359 self.auto_proxies,
2360 // ...and which encoder an export of it opens, for the same reason:
2361 // a project delivered on the software encoder is delivered on it
2362 // again after a reload.
2363 self.encoder_seat,
2364 project.limiter(),
2365 // ...and the rate the mix was picked to run at, for the same
2366 // reason: a project delivered at a chosen rate is delivered at it
2367 // again after a reload.
2368 self.sample_rate,
2369 playhead,
2370 // ...and each lane's switches, hidden, muted or locked, which a
2371 // reload has to hand back as they were left.
2372 &project.lane_flags(),
2373 // ...and each audio lane's duck, by the key lane it names, in the
2374 // same order again: a ducked music bed that came back unducked
2375 // would be a mix nobody could keep.
2376 &project.lane_ducks(),
2377 // ...and the cues somebody retyped, which live in no file: the words
2378 // a reload has to hand back as they were typed.
2379 project.cue_edits(),
2380 // ...and the cues added to a track, which no file has.
2381 project.cue_adds(),
2382 // ...and the title cards and text overlays, which are the project's own.
2383 project.titles(),
2384 // ...and the chapter markers, which are the project's own too.
2385 project.chapters(),
2386 // ...and the comment markers.
2387 project.markers(),
2388 &project.caption_style(),
2389 // ...and each audio lane's voice processors, which a reload has to
2390 // hand back as they were left (the noise profile included: it is
2391 // learned from the sound, and re-learning it would not be the same).
2392 &project.lane_voices(),
2393 // ...and the names the user gave the lanes.
2394 &project.lane_names(),
2395 )
2396 }
2397
2398 /// The next decoded frame, its `index` rewritten from a source frame to a
2399 /// *timeline* frame -- the only frame space that leaves the engine, and the
2400 /// one [`PlaybackSession::now`] is in.
2401 ///
2402 /// `None` means "nothing right now": the decoder is behind, or a clip
2403 /// boundary is being reopened -- and *that* now happens entirely on the new
2404 /// worker ([`DecodeSession::open_worker_deferred`]), so it costs this
2405 /// thread a thread spawn and the caller simply keeps showing its last frame
2406 /// for however long the source takes to open (hundreds of milliseconds on a
2407 /// big film, seconds off a cold cache). End of stream is
2408 /// [`PlaybackSession::is_eos`].
2409 pub fn try_frame(&mut self) -> Option<Frame> {
2410 self.publish_playhead();
2411 loop {
2412 match self.frames.try_recv() {
2413 Ok(mut frame) => {
2414 // A gap's worker indexes from zero, a decoder's from its in
2415 // point, and the span itself knows which: [`Span::timeline_at`]
2416 // is the *stamp*, and it is the ceil half of the pair whose
2417 // floor half an export encodes with -- so the frame the pump
2418 // is holding at any timeline frame is the very frame the
2419 // export writes there, at every rate
2420 // (`speed_maps_both_ways`). An empty timeline has no span,
2421 // and its one black frame is frame 0. Real time is the
2422 // arithmetic this always did, frame for frame.
2423 // ...through the file's own rate first, which is the ceil
2424 // half of *that* pair: the picture at source frame `i` is
2425 // due at the first timeline-rate frame that shows it, and a
2426 // slower file's picture is therefore held for the frames in
2427 // between. Real time for a gap and for a single-rate
2428 // project, where this is the identity.
2429 frame.index = self.stamp(frame.index);
2430 // The first picture out of the span now decoding ends its
2431 // prime ([`Self::span_priming`]).
2432 self.span_priming = false;
2433 // Inside the dissolve window this span's tail owes its
2434 // successor, if any: B's own decoder, graded and placed
2435 // exactly as an export would place it, blended over A's
2436 // already-converted picture -- the one blend point every
2437 // path to the screen goes through, playing or scrubbed,
2438 // since both drain this same channel one frame at a time.
2439 if self
2440 .dissolve
2441 .as_ref()
2442 .is_some_and(|d| frame.index >= d.tail_start)
2443 {
2444 self.open_dissolve_b();
2445 }
2446 if let Some(d) = self.dissolve.as_mut()
2447 && frame.index >= d.tail_start
2448 && let Some(b) = d.b.as_mut()
2449 {
2450 while let Ok(bf) = b.frames.try_recv() {
2451 b.held = Some(bf);
2452 }
2453 // The window's first tick, with B's decoder not yet
2454 // caught up: a paused or scrubbed preview gets no
2455 // later tick to correct itself on (nothing is due
2456 // while the clock is frozen -- `Player::pump`), so
2457 // this is the one chance to blend rather than show A
2458 // alone. Bounded so a source B cannot decode never
2459 // freezes the preview -- eager-opened in
2460 // `start_span`, B is normally already warm here and
2461 // this waits on nothing at all.
2462 if b.held.is_none() {
2463 b.held = b.frames.recv_timeout(DISSOLVE_B_TIMEOUT).ok();
2464 }
2465 if let Some(bf) = &b.held {
2466 let idx_in_window = (frame.index - d.tail_start).min(d.window - 1);
2467 let t = crate::export::dissolve_weight(idx_in_window, d.window);
2468 frame.bgra = match d.kind {
2469 crate::transitions::TransitionKind::Dissolve => {
2470 blend_bgra(&frame.bgra, &bf.bgra, t)
2471 }
2472 kind => crate::transitions::blend_bgra(
2473 kind,
2474 &frame.bgra,
2475 &bf.bgra,
2476 t,
2477 frame.width as usize,
2478 frame.height as usize,
2479 ),
2480 };
2481 }
2482 }
2483 // A picture fade is drawn toward black, the way export draws
2484 // it ([`crate::export::picture_fade_at`]): black is zero in
2485 // every colour channel of BGRA, the alpha byte left alone.
2486 // A layered picture's fades were applied per clip by its worker.
2487 let fade = match self.span.is_some_and(|s| {
2488 crate::export::layered_at(&self.project.render_view(), s.start)
2489 }) {
2490 true => None,
2491 false => crate::export::picture_fade_at(&self.project.render_view(), frame.index),
2492 };
2493 if let Some(k) = fade {
2494 for px in frame.bgra.as_chunks_mut::<4>().0 {
2495 for c in &mut px[..3] {
2496 *c = (f32::from(*c) * k).round() as u8;
2497 }
2498 }
2499 }
2500 return Some(frame);
2501 }
2502 Err(TryRecvError::Empty) => return None,
2503 // The worker stopped: at the end of its range, or on a decode
2504 // error -- which is why this skips the rest of a broken clip
2505 // rather than stalling on it.
2506 Err(TryRecvError::Disconnected) => {
2507 if !self.next_clip() {
2508 self.eos = true;
2509 self.eos_end =
2510 f64::from(self.project.timeline_frames()) / self.meta.frame_rate;
2511 return None;
2512 }
2513 }
2514 }
2515 }
2516 }
2517
2518 /// Whether the timeline has been played out: the picture worker ran to the
2519 /// end and there was no next clip. It is exactly that and nothing more,
2520 /// which is what decides who clears it -- **starting a picture does**
2521 /// (`start_picture`), so a seek clears it and so does every edit that
2522 /// rebuilds the picture (`Dirty::Picture`, `Dirty::Both` -- a paste or a
2523 /// placement past the end revives the session, and it has a new picture to
2524 /// show for it).
2525 ///
2526 /// A **sound-only** edit does not (`Dirty::Sound`: an equalizer, a fader):
2527 /// it rebuilds the sound where the playhead stands and starts no picture
2528 /// worker, so the last frame is still the last frame and this is still the
2529 /// end. A front-end's `Ended` therefore survives an EQ tweak made after the
2530 /// timeline ran out -- the parameters are on the project either way, and the
2531 /// next press restarts from the top with them, which is what `Ended` means.
2532 pub fn is_eos(&self) -> bool {
2533 self.eos
2534 }
2535
2536 /// Tells the decode worker which frame of its *file* the clock has reached,
2537 /// so the pictures it is holding that are already behind the playhead are
2538 /// dropped where they are cheap to drop -- before the conversion and before
2539 /// the queue -- instead of being converted, queued and thrown away by the
2540 /// caller one repaint later. The whole of the late-frame policy: a decoder
2541 /// that has fallen behind catches up by not painting what nobody can see,
2542 /// rather than by being restarted every two seconds (`Player::pump`).
2543 ///
2544 /// The stamp is the exact inverse of the one [`try_frame`](Self::try_frame)
2545 /// puts on a decoded frame: timeline frame -> the clip's own frames
2546 /// ([`Span::speed`]) -> the file's ([`Rate`]). A gap and the emptied
2547 /// timeline have no file to be inside of, and publish nothing.
2548 fn publish_playhead(&self) {
2549 // Backward the worker is not walking toward the clock but away from where
2550 // it started, and a stale picture is dropped by the pump instead.
2551 if !self.drop_late || self.backward() {
2552 return;
2553 }
2554 let Some(span) = self.span else { return };
2555 let Some((_, in_frame)) = span.from else {
2556 return;
2557 };
2558 let now = secs_to_frame(self.clock.now(), self.meta.frame_rate);
2559 let offset = now.saturating_sub(span.start).min(span.len);
2560 self.worker.playhead(
2561 self.span_rate
2562 .source_at(in_frame + span.source_offset(offset)),
2563 );
2564 }
2565
2566 /// Whether the clock runs backward: the picture is then drawn from the
2567 /// playhead down ([`Back`]) and a pump presents what is *at or after* the
2568 /// clock instead of at or before it.
2569 pub fn backward(&self) -> bool {
2570 self.clock.rate() < 0.0
2571 }
2572
2573 /// The playback rate: 1.0 is real time, negative is backward.
2574 pub fn rate(&self) -> f64 {
2575 self.clock.rate()
2576 }
2577
2578 /// The timeline frame a decoded frame numbered `idx` is due at, in the numbering
2579 /// the current worker was opened with ([`Back`]). Forward it is the ceil half
2580 /// of the pair an export encodes with ([`Span::timeline_at`]) through the
2581 /// file's own rate; backward the same mapping read off the file frame the
2582 /// stream really holds, so the stamps fall as the stream goes on.
2583 fn stamp(&self, idx: u32) -> u32 {
2584 let Some(s) = self.span else { return idx };
2585 let rate = self.span_rate;
2586 match self.back {
2587 Back::Off => s.timeline_at(rate.timeline_at(idx)),
2588 Back::Mirror { top } => {
2589 s.timeline_at(rate.timeline_at((2 * top).saturating_sub(idx)))
2590 }
2591 Back::Forward => {
2592 let first = s.from.map_or(0, |(_, f)| f);
2593 s.timeline_at((2 * first).saturating_sub(rate.timeline_at(idx)))
2594 }
2595 Back::Gap => s.start + s.len.saturating_sub(1).saturating_sub(idx),
2596 }
2597 }
2598
2599 /// Installs `replacement` as the decode worker, parking the outgoing one in
2600 /// [`retired`](Self::retired) rather than joining it here, and reaping the
2601 /// parked ones that have already returned.
2602 ///
2603 /// The sweep is what bounds the list: every worker in it was cancelled
2604 /// before this ran, and a cancelled worker is out within an access unit
2605 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's
2606 /// worker on this seek and the list stays a handful long. Nothing waits.
2607 fn retire(&mut self, replacement: Worker) {
2608 // A *replacement*, which is now the narrow case: a seek onto the file
2609 // the worker already has open steers it instead ([`Worker::reseek`])
2610 // and never comes here, so this count is the picture restarts that
2611 // really cost a thread and a decoder open -- which is what makes it
2612 // worth counting.
2613 self.restarts += 1;
2614 let mut outgoing = std::mem::replace(&mut self.worker, replacement);
2615 // Terminal, unlike the [`Worker::abandon`] a seek does: this worker is
2616 // being replaced rather than steered, so its thread has to end -- and
2617 // the cancel is what drops its command channel, without which a worker
2618 // parked between spans would sit in `recv` forever, never reaped here
2619 // and never joined in any bounded time at exit.
2620 outgoing.cancel();
2621 self.retired.push(outgoing);
2622 self.retired.retain(|w| !w.is_finished());
2623 }
2624
2625 /// Picture restarts so far; see [`restarts`](Self::restarts). The one place
2626 /// a worker is ever replaced counts them, so a seek, a resync and a clip
2627 /// boundary all land here and a measurement need not guess which it saw.
2628 #[doc(hidden)]
2629 pub fn restarts(&self) -> u64 {
2630 self.restarts
2631 }
2632
2633 /// Whether the picture span now decoding has yet to hand over a frame:
2634 /// true from the moment a span is started -- a seek, a clip boundary, a
2635 /// picture restart -- until that span's first frame arrives. Whatever
2636 /// lateness that first frame carries is the span's own reopen, not a
2637 /// decoder falling behind, so a front-end gating its late-picture restart
2638 /// on this answers a prime with the decode already on its way rather than
2639 /// with another restart of it.
2640 pub fn picture_priming(&self) -> bool {
2641 self.span_priming
2642 }
2643
2644 /// Whether the picture now playing is read off a render-cache segment
2645 /// ([`crate::render_cache`]) rather than composed live.
2646 pub fn playing_from_cache(&self) -> bool {
2647 matches!(self.feed, Feed::Cached { .. })
2648 }
2649
2650 /// The part of `span` a render-cache segment can stand in for, with the
2651 /// segment it comes from: the span's first frame must be inside a segment
2652 /// that matches the timeline now, and the span must be a forward clip at
2653 /// 1x through no dissolve. The returned span keeps the span's own start and
2654 /// its length up to the segment's end, and reads from the segment's own
2655 /// first frame ([`Feed::Cached`]), at real time, so the stamp is the identity.
2656 fn cached_cut(
2657 &self,
2658 span: Option<Span>,
2659 backward: bool,
2660 ) -> Option<(Span, crate::render_cache::Segment)> {
2661 let span = span?;
2662 if backward
2663 || self.dissolve.is_some()
2664 || span.reverse
2665 || span.ramp.is_some()
2666 || span.speed != Speed::NORMAL
2667 {
2668 return None;
2669 }
2670 let (source, _) = span.from?;
2671 let segment = crate::render_cache::at(&self.project, &self.meta, span.start)?;
2672 let len = span.end().min(segment.to) - span.start;
2673 let cut = Span {
2674 len,
2675 from: Some((source, span.start - segment.from)),
2676 ..span
2677 };
2678 Some((cut, segment))
2679 }
2680
2681 /// Starved audio callbacks since the device opened, and how far into the
2682 /// device's own playback (seconds) the last of them was -- `None` for a
2683 /// session with no device at all. The counter the plugin prints on drop,
2684 /// readable while the session runs: read it either side of a seek and the
2685 /// difference is what that seek cost the ear.
2686 #[doc(hidden)]
2687 pub fn audio_underruns(&self) -> Option<(u64, Option<f64>)> {
2688 let audio = self.audio.as_ref()?;
2689 let (count, last) = audio.ao.lock().unwrap().underruns();
2690 Some((count, last.map(|p| p as f64 / f64::from(audio.sample_rate))))
2691 }
2692
2693 /// How many threads this session still has running of its own: the decode
2694 /// worker, every retired one that has not returned yet, and the audio
2695 /// feeders still in the air. One for a session playing along quietly.
2696 ///
2697 /// The oracle a seek storm is judged by. `/proc/self/status` counts the
2698 /// *process*, and a suite decoding twenty files at once moves that number
2699 /// under a test that never touched them -- this counts only what the
2700 /// session in hand owns, so it says the same thing alone and in a crowd.
2701 #[doc(hidden)]
2702 pub fn live_workers(&self) -> usize {
2703 usize::from(!self.worker.is_finished())
2704 + self.retired.iter().filter(|w| !w.is_finished()).count()
2705 + self.audio.as_ref().map_or(0, Audio::live_feeders)
2706 }
2707
2708 /// Starts feeding whatever follows the current span on the timeline --
2709 /// another clip, or a gap, which is black frames from a worker that opens no
2710 /// file. `false` past the end. The next timeline frame is derived rather
2711 /// than remembered as a clip index, because a `split` while playing cuts the
2712 /// clip under the running worker and only the mapping stays true.
2713 fn next_clip(&mut self) -> bool {
2714 // No span is the emptied timeline: it was played out the moment its one
2715 // black frame went by, and there is no "next" to walk to.
2716 let backward = self.backward();
2717 let span = match (self.span, backward) {
2718 (None, _) => return false,
2719 // Backward the next stretch to draw is the one that ends just before
2720 // this one starts, and the start of the timeline is where it ends.
2721 (Some(span), true) => match span.start.checked_sub(1) {
2722 Some(frame) => back_span_at(&self.project.render_view(), frame),
2723 None => return false,
2724 },
2725 (Some(span), false) => crate::export::stack_span_at(&self.project.render_view(), span.end()),
2726 };
2727 let Some(span) = span else { return false };
2728 // We only get here on a disconnect, so the old span is already done;
2729 // abandon anyway, so `start_span` treats every path alike -- and the
2730 // *worker* is kept, because the next clip is very often the same file
2731 // (a split cuts one clip in two) and it already has it open.
2732 self.worker.abandon();
2733 self.start_span(Some(span));
2734 true
2735 }
2736
2737 /// Points the video worker at `span`: a decoder over its source range, or a
2738 /// black-frame generator for a gap -- and for `None`, the emptied timeline,
2739 /// which is one frame of black so the viewer shows the nothing that is
2740 /// there rather than the last picture of the clip that was deleted. The old
2741 /// worker must already have been cancelled -- this is the half both `seek`
2742 /// and `next_clip` share.
2743 ///
2744 /// A source that will not open leaves the *span* installed anyway: the
2745 /// timeline still moves, there are simply no more pictures, and the
2746 /// disconnected receiver carries the session on to the next span. For a
2747 /// video that is now the worker's own doing -- it opens the file, so it is
2748 /// the one that finds out -- and nothing on this thread waits to hear it.
2749 fn start_span(&mut self, span: Option<Span>) {
2750 // The viewer's own size, once one has said it ([`Self::set_view_size`]):
2751 // every picture below is painted at *this*, and the project's
2752 // resolution otherwise.
2753 let (canvas_w, canvas_h) = self.view_size();
2754 // The outgoing span's own dissolve, if it ever opened B's decoder:
2755 // that decoder's pictures were for a window this span is leaving
2756 // (played through, paused before, or seeked away from), and never
2757 // for the one about to start -- parked in `retired` exactly like the
2758 // picture worker below, so joining it costs this thread nothing.
2759 if let Some(Dissolve { b: Some(b), .. }) = self.dissolve.take() {
2760 let mut worker = b.worker;
2761 worker.cancel();
2762 self.retired.push(worker);
2763 self.retired.retain(|w| !w.is_finished());
2764 }
2765 // What the *new* span's own tail owes its successor -- checked here,
2766 // once, rather than every tick: adjacency can only change on an edit,
2767 // and every edit that could touches this span starts it over
2768 // ([`crate::export::dissolve_window`] makes the identical check for
2769 // the same reason, on export).
2770 let backward = self.backward();
2771 self.back = Back::Off;
2772 self.dissolve = span.filter(|_| !backward).and_then(|s| {
2773 crate::export::dissolve_window(&self.project.render_view(), &s).map(
2774 |(b_source, b_in_frame, window, b_start)| Dissolve {
2775 tail_start: s.start + s.len - window,
2776 window,
2777 b_source,
2778 b_in_frame,
2779 b_start,
2780 kind: crate::transitions::kind_at(&self.project.render_view(), s.start),
2781 b: None,
2782 },
2783 )
2784 });
2785 // B's decoder opens now, at the start of the *span*, rather than
2786 // waiting for the playhead to reach the window: the window is about a
2787 // second, which is exactly the head start a decoder open (VA-API
2788 // init measured 98ms worst case) needs to have a first picture ready
2789 // by the time playback -- or a seek straight into the window -- asks
2790 // for one. Without this a paused seek into the window met a `held`
2791 // that was still `None` and nothing ever asked again
2792 // (`try_frame`'s bounded wait below is the last-resort backstop for a
2793 // seek that lands inside the window before this head start pays off).
2794 if self.dissolve.is_some() {
2795 self.open_dissolve_b();
2796 }
2797 // Which file's frames the worker about to be opened will number its
2798 // pictures in: the span's own source, and real time for a gap, whose
2799 // black worker counts timeline frames already. Set before the open,
2800 // because the open is the first thing that converts with it.
2801 // A layered span's worker numbers its frames on the timeline itself
2802 // ([`crate::export::layered_stream`]), so it is read at real time.
2803 let layered = span.is_some_and(|s| crate::export::layered_at(&self.project.render_view(), s.start));
2804 // A field-mode clip of an interlaced file is decoded as fields, two to a
2805 // frame: the decoder's frame numbers are field numbers, so the file's
2806 // rate against the timeline doubles ([`crate::deinterlace::fields_rate`]).
2807 let deint = match span.and_then(|s| s.from) {
2808 Some((source, _)) if !layered => self.deint_at(source, span.map_or(0, |s| s.start)),
2809 _ => crate::project::Deinterlace::Frame,
2810 };
2811 self.span_rate = match span.and_then(|s| s.from) {
2812 Some((source, _)) if !layered => {
2813 let rate = self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME);
2814 crate::deinterlace::counted_rate(deint, rate)
2815 }
2816 _ => Rate::REAL_TIME,
2817 };
2818 // The new span owes its first picture from the moment it is asked for:
2819 // every path below, the reused worker as much as a fresh one
2820 // ([`Self::span_priming`]).
2821 self.span_priming = true;
2822 // A render-cache segment over this span's first frame plays the render
2823 // instead of compositing it ([`Feed::Cached`]). Only forward at 1x and
2824 // never through a dissolve; every other span stays on the live path.
2825 self.feed = Feed::Live;
2826 if let Some((cut, segment)) = self.cached_cut(span, backward) {
2827 let source_frame = cut.from.map_or(0, |(_, f)| f);
2828 let end = source_frame + cut.len;
2829 self.span_rate = Rate::REAL_TIME;
2830 // The render already holds the grade, transform, fit, tone and
2831 // effects, so the decoder applies none of them.
2832 let stream = DecodeSession::open_worker_deferred_with(
2833 &segment.path,
2834 source_frame,
2835 end,
2836 ColorParams::default(),
2837 TransformParams::default(),
2838 Composer::new(canvas_w, canvas_h, FitPolicy::default()),
2839 self.project.tone(),
2840 Speed::NORMAL,
2841 crate::project::Deinterlace::Frame,
2842 );
2843 self.frames = stream.frames;
2844 self.backend = stream.backend;
2845 self.retire(stream.worker);
2846 self.span = Some(cut);
2847 self.feed = Feed::Cached { segment: segment.path };
2848 return;
2849 }
2850 let opened = match span {
2851 // Two or more clips cover the span: its composed pictures come from a
2852 // stream of their own, each clip drawn over the ones beneath it as an
2853 // export draws them, at the viewer's size.
2854 Some(span) if layered => {
2855 let mut view_meta = self.meta;
2856 view_meta.width = canvas_w;
2857 view_meta.height = canvas_h;
2858 // Each clip's picture comes off its stand-in when the project is
2859 // cut on stand-ins, the way a single clip's does ([`picture_path`]).
2860 let paths = self.proxies.then(|| {
2861 self.project
2862 .sources()
2863 .iter()
2864 .map(|s| crate::proxy::cached(&s.path).unwrap_or_else(|| s.path.clone()))
2865 .collect()
2866 });
2867 Ok(crate::export::layered_stream(
2868 self.project.export_snapshot(),
2869 view_meta,
2870 crate::colorspace::ColorDescription::output_sized(self.meta.width, self.meta.height),
2871 span,
2872 paths,
2873 ))
2874 }
2875 // The grade is the composite's at this frame -- the same clip the
2876 // span itself came from -- and it is constant across the span, so
2877 // the worker carries it and every frame it converts wears it.
2878 Some(Span {
2879 start,
2880 from: Some((source, in_frame)),
2881 ..
2882 }) if crate::is_image(&self.project.sources()[source].path) => {
2883 // A still: the same grade and the same canvas as any other
2884 // clip, over a picture decoded once and repeated for the span.
2885 // As many pictures as the span reads *source* frames, so a still
2886 // is numbered like a decoder's output and a speed reaches it
2887 // through the same rewrite (`try_frame`) as any other clip.
2888 DecodeSession::open_still(
2889 &self.project.sources()[source].path,
2890 in_frame,
2891 span.expect("matched above").source_len(),
2892 self.project
2893 .composite_color_at(start)
2894 .copied()
2895 .unwrap_or_default(),
2896 self.project
2897 .composite_transform_at(start)
2898 .copied()
2899 .unwrap_or_default(),
2900 Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(start)),
2901 )
2902 .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}"))
2903 }
2904 Some(Span {
2905 start,
2906 from: Some((source, in_frame)),
2907 ..
2908 }) if crate::is_audio(&self.project.sources()[source].path)
2909 || self.project.render_view().composite_visualizer_at(start) & 1 != 0 =>
2910 {
2911 let (path, stream) = {
2912 let src = &self.project.sources()[source];
2913 (src.path.clone(), src.audio_stream)
2914 };
2915 DecodeSession::open_visualizer(
2916 &path,
2917 stream,
2918 in_frame,
2919 span.expect("matched above").source_len(),
2920 self.meta.frame_rate,
2921 self.project
2922 .composite_color_at(start)
2923 .copied()
2924 .unwrap_or_default(),
2925 self.project
2926 .composite_transform_at(start)
2927 .copied()
2928 .unwrap_or_default(),
2929 Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(start)),
2930 self.project.render_view().composite_visualizer_at(start),
2931 self.project.render_view().composite_viz_paint_at(start),
2932 )
2933 .inspect_err(|e| eprintln!("timeline frame {start}: visualizer open failed: {e}"))
2934 }
2935 Some(Span {
2936 start,
2937 from: Some((source, in_frame)),
2938 speed,
2939 ..
2940 }) => {
2941 // The stand-in where there is one and the switch is on, the
2942 // film itself otherwise -- the one place the picture's file is
2943 // decided ([`Self::picture_path`]). The sound is opened
2944 // elsewhere and is always the film's.
2945 //
2946 // It decides for the reuse door below as well, and that is what
2947 // makes the switch flippable while watching: a worker holding
2948 // the film is asked for a span of the stand-in, declines on the
2949 // path it already has ([`Worker::reseek`]), and the seek
2950 // [`Self::set_proxies`] does becomes a respawn on the other
2951 // file. Asking the *project* here instead would have left every
2952 // proxied span opening a worker from scratch.
2953 let path = self.picture_path(source);
2954 // The file's own frames, which is the only place they exist: a
2955 // clip counts the timeline's ([`Rate`]).
2956 let start_frame = self.span_rate.source_at(in_frame);
2957 // Source frames, which a speed makes more (or fewer) than the
2958 // timeline frames the span covers -- and which a file shot at
2959 // another rate makes fewer (or more) again. One past the last
2960 // frame this span shows, not one past its length: at another
2961 // rate those are two different frames.
2962 let end_frame = self.span_rate.source_at(
2963 in_frame + span.expect("matched above").source_len().saturating_sub(1),
2964 ) + 1;
2965 let color = self
2966 .project
2967 .composite_color_at(start)
2968 .copied()
2969 .unwrap_or_default();
2970 let transform = self
2971 .project
2972 .composite_transform_at(start)
2973 .copied()
2974 .unwrap_or_default();
2975 // ...and the canvas it is placed on: the project's resolution
2976 // and this clip's own fit policy, constant across the span for
2977 // the reason the grade is. Built where it is handed over rather
2978 // than kept in a local, because a `Composer` owns the scratch
2979 // buffers it places through -- the value is not copied about.
2980 let fit = self.project.render_view().composite_fit_at(start);
2981 let canvas = || Composer::new(canvas_w, canvas_h, fit);
2982 // ...and the rendition an HDR source among them is mapped to,
2983 // the project's own and constant across the span for that
2984 // reason too.
2985 let tone = self.project.tone();
2986 // At faster than real time several source frames decode to the
2987 // same timeline frame ([`Speed::timeline_at`]) and only the last
2988 // of a run is ever shown; the worker skips converting the rest
2989 // ([`crate::decode::skip_for_speed`]) rather than paying a full
2990 // colour convert and scale for a picture nothing displays.
2991 //
2992 // corner-cut: correct only when this file plays at the
2993 // timeline's own rate -- `skip_for_speed`'s own math is in the
2994 // file's frame numbers, which a `Rate` conversion would make a
2995 // different sequence than the timeline's. `Speed::NORMAL` (never
2996 // skip) covers that rarer case exactly as every frame was
2997 // delivered before this.
2998 let decode_speed = if self.span_rate.is_real_time() {
2999 speed
3000 } else {
3001 Speed::NORMAL
3002 };
3003 // Playing backward the span is the clip up to the playhead, drawn from
3004 // the playhead down: a forward clip is served last frame first, and a
3005 // reversed one -- whose backward is the file's forward -- first frame
3006 // first, in both cases over the window the span reads.
3007 let backward_window = backward.then(|| {
3008 let sp = span.expect("matched above");
3009 let (_, lo, hi) = sp.source_window().expect("a clip's span has a window");
3010 (
3011 self.span_rate.source_at(lo),
3012 self.span_rate.source_at(hi.saturating_sub(1)) + 1,
3013 )
3014 });
3015 if let Some((lo, hi)) = backward_window
3016 && !span.is_some_and(|s| s.reverse)
3017 {
3018 self.back = Back::Mirror { top: hi - 1 };
3019 let stream = DecodeSession::open_reversed_with(
3020 &path,
3021 hi - 1,
3022 hi - lo,
3023 color,
3024 transform,
3025 canvas(),
3026 tone,
3027 deint,
3028 );
3029 self.frames = stream.frames;
3030 self.backend = stream.backend;
3031 self.retire(stream.worker);
3032 self.span = span;
3033 return;
3034 }
3035 // ...and a reversed clip's backward is the file's forward: the same
3036 // worker as any clip, over the window, numbered by the file.
3037 let (start_frame, end_frame, decode_speed) = match backward_window {
3038 Some((lo, hi)) => {
3039 self.back = Back::Forward;
3040 (lo, hi, Speed::NORMAL)
3041 }
3042 None => (start_frame, end_frame, decode_speed),
3043 };
3044 // A reversed clip is served backwards from the file frame the span
3045 // starts on, a block at a time ([`DecodeSession::open_reversed`]); its
3046 // frames are numbered as a forward stream's would be, so the stamps
3047 // and drops below need no case of their own.
3048 if !backward && span.is_some_and(|s| s.reverse) {
3049 let stream = DecodeSession::open_reversed_with(
3050 &path,
3051 start_frame,
3052 end_frame.saturating_sub(start_frame).max(1),
3053 color,
3054 transform,
3055 canvas(),
3056 tone,
3057 deint,
3058 );
3059 self.frames = stream.frames;
3060 self.backend = stream.backend;
3061 self.retire(stream.worker);
3062 self.span = span;
3063 return;
3064 }
3065 // The worker already decoding this very file takes the new span
3066 // itself: no thread, no container parse, no VA-API init -- the
3067 // whole of what a seek used to cost. It answers `None` for any
3068 // other file (and for a worker whose thread has ended), and the
3069 // deferred opener below is then exactly the path it always was.
3070 if let Some((frames, backend)) = self.worker.reseek_with(
3071 &path,
3072 start_frame,
3073 end_frame,
3074 color,
3075 transform,
3076 canvas(),
3077 tone,
3078 decode_speed,
3079 deint,
3080 ) {
3081 self.frames = frames;
3082 self.backend = backend;
3083 self.span = span;
3084 return;
3085 }
3086 Ok(DecodeSession::open_worker_deferred_with(
3087 &path,
3088 start_frame,
3089 end_frame,
3090 color,
3091 transform,
3092 canvas(),
3093 tone,
3094 decode_speed,
3095 deint,
3096 ))
3097 }
3098 // A gap: black for as long as it runs. An emptied timeline has no
3099 // span at all and gets one frame of it -- enough to put black on
3100 // screen, and it ends where the timeline does, at once.
3101 gap => {
3102 if backward && gap.is_some() {
3103 self.back = Back::Gap;
3104 }
3105 Ok(DecodeSession::open_black(
3106 canvas_w,
3107 canvas_h,
3108 gap.map_or(1, |s| s.len),
3109 ))
3110 }
3111 };
3112 let Ok(stream) = opened else {
3113 // The file would not open. The span still goes in -- the timeline
3114 // moves on, there are simply no more pictures -- but the *frames*
3115 // must not: the old channel's pictures are numbered in the old
3116 // source's frames, and presenting them under the new mapping would
3117 // put the wrong picture at the wrong time (and leave
3118 // [`decode_backend`](Self::decode_backend) describing a worker that
3119 // is no longer feeding anything). A dead receiver instead, which is
3120 // what carries the session on to the next span. The old worker stays
3121 // parked in `self.worker`, where the caller has already abandoned
3122 // the span it was decoding ([`Worker::abandon`]) without ending the
3123 // thread; the next span reseeks it or retires it.
3124 self.frames = std::sync::mpsc::channel().1;
3125 self.backend = BackendCell::new(Backend::Gap);
3126 self.span = span;
3127 return;
3128 };
3129 // Receiver first, worker second: the drop of the *old* receiver is
3130 // what wakes the outgoing worker if it is parked in `send`, and only
3131 // then can it return and be reaped by a later sweep. Nothing here
3132 // joins, so this ordering costs the seek nothing.
3133 self.frames = stream.frames;
3134 self.backend = stream.backend;
3135 self.retire(stream.worker);
3136 self.span = span;
3137 }
3138
3139 /// The deinterlace setting of the clip on screen at `frame`, as it applies to
3140 /// the file `source`'s picture is decoded from (the stand-in when there is one):
3141 /// `Frame` for anything but interlaced H.264, which ignores the setting.
3142 fn deint_at(&self, source: usize, frame: u32) -> crate::project::Deinterlace {
3143 let mode = self.project.composite_clip_at(frame).map_or(crate::project::Deinterlace::Frame, |(lane, idx)| {
3144 self.project.deinterlace_of(lane, idx)
3145 });
3146 let path = &self.project.sources()[source].path;
3147 let file = self.proxies.then(|| crate::proxy::cached(path)).flatten().unwrap_or_else(|| path.clone());
3148 crate::deinterlace::effective(mode, &file)
3149 }
3150
3151 /// Opens B's own decoder for the current span's dissolve, the first time
3152 /// [`try_frame`](Self::try_frame) sees the playhead inside the window --
3153 /// a no-op once it is already open, or if this span has no dissolve at
3154 /// all. Everything [`start_span`](Self::start_span) works out for A's own
3155 /// decoder, worked out again for B: the stand-in switch
3156 /// ([`Self::picture_path`]), the file's own frame numbering
3157 /// ([`Self::rates`]), and B's *own* grade and fit, asked at B's own start
3158 /// on the timeline rather than at the position the blend writes to
3159 /// (still inside A's span) -- the same asymmetry
3160 /// [`crate::export`]'s own `Dissolve` is built with.
3161 fn open_dissolve_b(&mut self) {
3162 let (canvas_w, canvas_h) = self.view_size();
3163 let Some(d) = &self.dissolve else { return };
3164 if d.b.is_some() {
3165 return;
3166 }
3167 let (source, in_frame, window, b_start) = (d.b_source, d.b_in_frame, d.window, d.b_start);
3168 let path = self.picture_path(source);
3169 // B takes one picture per timeline frame: `Field` is its `Frame`; a clip with its
3170 // pulldown removed counts film frames.
3171 let b_deint = match self.deint_at(source, b_start) {
3172 crate::project::Deinterlace::Off => crate::project::Deinterlace::Off,
3173 crate::project::Deinterlace::Ivtc => crate::project::Deinterlace::Ivtc,
3174 _ => crate::project::Deinterlace::Frame,
3175 };
3176 let rate = crate::deinterlace::counted_rate(b_deint, self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME));
3177 let start_frame = rate.source_at(in_frame);
3178 let end_frame = rate.source_at(in_frame + window);
3179 let color = self
3180 .project
3181 .composite_color_at(b_start)
3182 .copied()
3183 .unwrap_or_default();
3184 let transform = self
3185 .project
3186 .composite_transform_at(b_start)
3187 .copied()
3188 .unwrap_or_default();
3189 let canvas = Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(b_start));
3190 let tone = self.project.tone();
3191 let stream = DecodeSession::open_worker_deferred_with(
3192 &path,
3193 start_frame,
3194 end_frame,
3195 color,
3196 transform,
3197 canvas,
3198 tone,
3199 Speed::NORMAL,
3200 b_deint,
3201 );
3202 if let Some(d) = self.dissolve.as_mut() {
3203 d.b = Some(DissolveB {
3204 frames: stream.frames,
3205 worker: stream.worker,
3206 held: None,
3207 });
3208 }
3209 }
3210
3211 /// Length of the edited timeline in seconds -- what a ruler shows, and it
3212 /// shrinks with every delete.
3213 pub fn timeline_duration(&self) -> f64 {
3214 f64::from(self.project.timeline_frames()) / self.meta.frame_rate
3215 }
3216
3217 /// Whether no lane holds anything: the emptied timeline, which plays black
3218 /// and silent and is zero seconds long. A state, not a failure -- but the
3219 /// one a caller with nothing to render (an export) has to refuse by name
3220 /// rather than write a file of no frames.
3221 pub fn is_empty(&self) -> bool {
3222 self.project.timeline_frames() == 0
3223 }
3224
3225 /// `(start, len)` per clip in timeline seconds, in order: what a clips lane
3226 /// needs to lay itself out. Selection is the caller's business.
3227 pub fn clip_spans(&self) -> Vec<(f64, f64)> {
3228 let fps = self.meta.frame_rate;
3229 self.project
3230 .clip_spans()
3231 .iter()
3232 .map(|&(start, len)| (f64::from(start) / fps, f64::from(len) / fps))
3233 .collect()
3234 }
3235
3236 /// [`clip_spans`](Self::clip_spans) plus the index into
3237 /// [`Project::sources`] each clip plays from -- what a lane needs to colour
3238 /// an imported clip differently from the file the session was opened with.
3239 pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> {
3240 self.lane_spans_by_source(Lane::V1)
3241 }
3242
3243 /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane,
3244 /// with each clip's group id -- what a two-lane front-end draws. The holes
3245 /// between consecutive entries are the gaps.
3246 pub fn lane_spans_by_source(&self, lane: Lane) -> Vec<(f64, f64, usize)> {
3247 let fps = self.meta.frame_rate;
3248 self.project
3249 .lane(lane)
3250 .iter()
3251 .map(|c| (f64::from(c.start) / fps, f64::from(c.len()) / fps, c.source))
3252 .collect()
3253 }
3254
3255 /// Every placement of one lane, in timeline order. What a two-lane
3256 /// front-end draws and nothing
3257 /// [`lane_spans_by_source`](Self::lane_spans_by_source) can answer: a clip
3258 /// carries its group id (which halves a click marks together) and its
3259 /// source range (where a waveform reads its peaks from) as well as its
3260 /// span. The holes between consecutive clips are the gaps.
3261 pub fn lane_clips(&self, lane: Lane) -> &[Clip] {
3262 self.project.lane(lane)
3263 }
3264
3265 /// The empty stretch of `lane` covering `frame`, or `None` when `frame`
3266 /// is inside a clip/caption placement or past the last one
3267 /// ([`Project::gap_at`]). What a right-click on empty bench space asks
3268 /// before offering to close it.
3269 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
3270 self.project.gap_at(lane, frame)
3271 }
3272
3273 /// The gap a Close gap verb closes on `lane` at `frame`: [`gap_at`](Self::gap_at), but
3274 /// only a gap that starts after frame 0. A lead-in before a lane's first clip is empty
3275 /// time, not a gap a hand made, so it is never closed.
3276 pub fn closable_gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
3277 self.gap_at(lane, frame).filter(|&(start, _)| start > 0)
3278 }
3279
3280 /// Closes the gap `(start, frames)` on `lane` and, when it borders a take, on the take's
3281 /// other lane too: the scope [`gap_take_scope`](Self::gap_take_scope) names, cut out by
3282 /// [`cut_regions`](Self::cut_regions). Returns that scope, so a caller can say what moved.
3283 /// The `Err` names what is in the way and nothing changes.
3284 pub fn close_gap_at(&mut self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
3285 let scope = self.gap_take_scope(lane, start, frames)?;
3286 self.cut_regions(&[(start, frames)], &scope)?;
3287 Ok(scope)
3288 }
3289
3290 /// How many bounded gaps that same right-click lane holds. The tail after
3291 /// the last placement is not counted, because nothing would ripple there.
3292 pub fn gap_count(&self, lane: Lane) -> usize {
3293 self.project.gap_count(lane)
3294 }
3295
3296 /// Every lane's handle, in display order -- what a front-end lays out top to
3297 /// bottom, and the list [`add_lane`](Self::add_lane) grows.
3298 pub fn lanes(&self) -> Vec<Lane> {
3299 self.project.lanes()
3300 }
3301
3302 /// The offline sources an export of `span` reads, as `(index, path)`, each source once and
3303 /// in the order the timeline meets them. `span` is the marked range, `None` for the whole
3304 /// timeline. A clip wholly outside the span does not count, so a file only such clips use
3305 /// does not stop the export.
3306 pub fn offline_in_span(&self, span: Option<(u32, u32)>) -> Vec<(usize, PathBuf)> {
3307 let offline = self.offline_sources();
3308 let mut out: Vec<(usize, PathBuf)> = Vec::new();
3309 if offline.is_empty() {
3310 return out;
3311 }
3312 for lane in self.lanes() {
3313 for clip in self.lane_clips(lane) {
3314 let (start, end) = (clip.start, clip.start.saturating_add(clip.frames()));
3315 if let Some((from, to)) = span
3316 && (end <= from || start >= to)
3317 {
3318 continue;
3319 }
3320 if let Some((i, path)) = offline.iter().find(|(i, _)| *i == clip.source)
3321 && !out.iter().any(|(_, p)| p == path)
3322 {
3323 out.push((*i, path.clone()));
3324 }
3325 }
3326 }
3327 out
3328 }
3329
3330 /// The sources whose files are not on disk, as `(index, saved path)`. Their
3331 /// clips stay on the timeline; a frame or an export that reads one is
3332 /// refused naming it.
3333 pub fn offline_sources(&self) -> Vec<(usize, PathBuf)> {
3334 self.project
3335 .sources()
3336 .iter()
3337 .enumerate()
3338 .filter(|(_, s)| !crate::source_present(&s.path))
3339 .map(|(i, s)| (i, s.path.clone()))
3340 .collect()
3341 }
3342
3343 /// Points source `index` at `path`, which must be the same material: the
3344 /// same kind (picture, sound or still), and a picture or sound at least as
3345 /// long as the furthest frame a clip reaches into the source (within a
3346 /// frame). Returns warnings: a length that differs by more than a frame from
3347 /// the file it replaces. The playhead is reopened on it. One undo step
3348 /// ([`Project::relink_source`]): undo points the source back at the old file
3349 /// and reads its length again. Nothing changes on a refusal.
3350 pub fn relink_source(&mut self, index: usize, path: &Path) -> crate::Result<Vec<String>> {
3351 let Some(old) = self.project.sources().get(index).cloned() else {
3352 return Err(format!("there is no source {index}").into());
3353 };
3354 if !path.is_file() {
3355 return Err(format!("{} is not a file", path.display()).into());
3356 }
3357 let kind = |p: &Path| {
3358 if crate::is_image(p) {
3359 "a still"
3360 } else if crate::is_audio(p) {
3361 "a sound file"
3362 } else {
3363 "a picture"
3364 }
3365 };
3366 if kind(&old.path) != kind(path) {
3367 return Err(format!(
3368 "source {index} is {} but {} is {}",
3369 kind(&old.path),
3370 path.display(),
3371 kind(path)
3372 )
3373 .into());
3374 }
3375 let candidate = Source::new(path, old.audio_stream);
3376 let (have, rate) = self.measure_source(&candidate)?;
3377 let expected = self.counts[index];
3378 // What the clips actually read: the furthest out-point any clip on any
3379 // lane takes from this source. A clip reading part of a source needs only
3380 // that part, so refusal is against the reach, not the whole length. Both
3381 // are in timeline-rate frames, the unit `have` is counted in.
3382 let reach = self
3383 .lanes()
3384 .into_iter()
3385 .flat_map(|lane| {
3386 self.lane_clips(lane)
3387 .iter()
3388 .filter(|c| c.source == index)
3389 .map(|c| c.out_frame)
3390 .collect::<Vec<_>>()
3391 })
3392 .max()
3393 .unwrap_or(0);
3394 if have + 1 < reach {
3395 return Err(format!(
3396 "{} has {have} frames but the clips on source {index} reach frame {reach}",
3397 path.display()
3398 )
3399 .into());
3400 }
3401 let mut warnings = Vec::new();
3402 if crate::source_present(&old.path) && have.abs_diff(expected) > 1 {
3403 warnings.push(format!(
3404 "{} has {have} frames; the file it replaces had {expected}",
3405 path.display()
3406 ));
3407 }
3408 self.project.relink_source(index, path)?;
3409 self.counts[index] = have;
3410 self.rates[index] = rate;
3411 let at = self.now();
3412 self.seek(at);
3413 Ok(warnings)
3414 }
3415
3416 /// Points several sources at copies of the same files ([`crate::collect`]) as one undo
3417 /// step. The copies are not measured against the clips: they are the same bytes. Their
3418 /// lengths are read again as an undo reads them, and the playhead is reopened. Returns how
3419 /// many sources moved.
3420 pub fn relink_all(&mut self, pairs: &[(usize, PathBuf)]) -> usize {
3421 let before = self.project.sources().to_vec();
3422 let moved = self.project.relink_sources(pairs);
3423 if moved > 0 {
3424 self.reread_sources(&before);
3425 self.invalidate(Dirty::Both);
3426 }
3427 moved
3428 }
3429
3430 /// Appends an empty lane and hands back its handle. One undo step
3431 /// ([`Project::add_lane`]), and no reseek: an empty lane changes nothing
3432 /// that plays until something is placed on it.
3433 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
3434 self.project.add_lane(kind)
3435 }
3436
3437 /// Drops that empty lane again, in [`Project::remove_lane`]'s words when it
3438 /// refuses. One undo step, and no reseek for the same reason the add needs
3439 /// none: an empty lane was playing nothing.
3440 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
3441 self.project.remove_lane(lane)
3442 }
3443
3444 /// Moves a whole track to display position `to`, clips and all
3445 /// ([`Project::move_lane`]), and hands back the handle it answers to
3446 /// afterwards -- `None` when nothing moved. One undo step.
3447 ///
3448 /// A *video* track that moves rebuilds the picture where the playhead
3449 /// stands, because display order is the stack and the frame on screen may
3450 /// be another lane's from here on; the sound plays on through it, untouched
3451 /// -- a mix is a sum, and a lane's gain travelled with it.
3452 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
3453 let moved = self.project.move_lane(lane, to)?;
3454 if lane.kind == LaneKind::Video {
3455 self.invalidate(Dirty::Picture);
3456 }
3457 Some(moved)
3458 }
3459
3460 /// The subtitle lanes in display order -- `S1..Sn`, the rows a front-end
3461 /// lays out beside the picture and sound ones
3462 /// ([`Project::subtitle_lanes`]). Empty until something adds one, which is
3463 /// [`add_lane`](Self::add_lane) with [`LaneKind::Subtitle`], and they come
3464 /// off, move and reorder through the very same doors every other lane does.
3465 pub fn subtitle_lanes(&self) -> Vec<Lane> {
3466 self.project.subtitle_lanes()
3467 }
3468
3469 /// What is placed on one subtitle lane, in timeline order: what a front-end
3470 /// draws as clips, each naming the palette row it plays
3471 /// ([`Self::subtitles`]) and the window of it it keeps
3472 /// ([`Project::sub_lane`]).
3473 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
3474 self.project.sub_lane(lane)
3475 }
3476
3477 /// Places a stretch of a subtitle track on `lane` at timeline frame `at`
3478 /// ([`Project::place_sub`], whose words a refusal is shown in). One undo
3479 /// step.
3480 ///
3481 /// No reseek and no invalidation, which is what the whole wrapper layer is
3482 /// here for: cues are drawn from [`sub_lane_cues`](Self::sub_lane_cues)
3483 /// over whatever picture is on screen, so nothing already decoded stops
3484 /// being right.
3485 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
3486 self.project.place_sub(lane, at, sub)
3487 }
3488
3489 /// Drags a placement to another subtitle lane or another frame
3490 /// ([`Project::move_sub`]). One undo step, and `Ok` with none for a drop
3491 /// that changed nothing. A caption in a group drags the group's clips with
3492 /// it -- a mapping change -- so this reseeks like a clip's drag does; a
3493 /// caption in no group moves nothing that plays and disturbs nothing.
3494 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
3495 let grouped = self.caption_grouped_with_clips(from, idx);
3496 let moved = self.project.move_sub(from, idx, to, start);
3497 if moved.is_ok() && grouped {
3498 self.invalidate(Dirty::Both);
3499 }
3500 moved
3501 }
3502
3503 /// Drags one edge of a placement to timeline frame `to`
3504 /// ([`Project::trim_sub`]), **at this timeline's own frame rate** -- a
3505 /// placement's position is in frames while its words are in microseconds,
3506 /// and the rate that joins them is the one thing a [`Project`] does not
3507 /// know. That is why a front-end trims through this door and never converts
3508 /// a cue's microseconds itself. One undo step. A caption in a group trims
3509 /// the group's clips with it, and that half reseeked; a lone caption's trim
3510 /// changes only the words, which are drawn over whatever is decoded.
3511 pub fn trim_sub(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> crate::Result<()> {
3512 let grouped = self.caption_grouped_with_clips(lane, idx);
3513 let trimmed = self
3514 .project
3515 .trim_sub(lane, idx, edge, to, self.meta.frame_rate);
3516 if trimmed.is_ok() && grouped {
3517 self.invalidate(Dirty::Both);
3518 }
3519 trimmed
3520 }
3521
3522 /// How far that edge may travel, `(first, last)` timeline frame inclusive
3523 /// ([`Project::trim_sub_room`]) -- what a front-end drawing the box during
3524 /// a drag asks, at this timeline's rate.
3525 pub fn trim_sub_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
3526 self.project
3527 .trim_sub_room(lane, idx, edge, self.meta.frame_rate)
3528 }
3529
3530 /// Takes one placement off a subtitle lane, leaving a gap
3531 /// ([`Project::lift_sub`]). One undo step; the palette row it played stays
3532 /// on this timeline's list.
3533 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
3534 self.project.lift_sub(lane, idx)
3535 }
3536
3537 /// What that subtitle lane shows on *this* timeline, in start order
3538 /// ([`Project::sub_lane_cues`] at this timeline's rate) -- the placed-clip
3539 /// counterpart of [`timeline_cues`](Self::timeline_cues), which carries a
3540 /// whole palette track through the spans that play its media. Pure, so a
3541 /// front-end may ask it per repaint.
3542 pub fn sub_lane_cues(&self, lane: Lane) -> Vec<crate::subtitle::Cue> {
3543 self.project.sub_lane_cues(lane, self.meta.frame_rate)
3544 }
3545
3546 /// Every cue on the subtitle lanes, in start order: the captions that File > Export
3547 /// captions and `export_captions` write as SRT or WebVTT ([`crate::subtitle::write_srt`]).
3548 pub fn caption_cues(&self) -> Vec<crate::subtitle::Cue> {
3549 let mut cues: Vec<crate::subtitle::Cue> = self.subtitle_lanes().into_iter().flat_map(|l| self.sub_lane_cues(l)).collect();
3550 cues.sort_by_key(|c| c.start_us);
3551 cues
3552 }
3553
3554 /// [`sub_lane_cues`](Self::sub_lane_cues) with the cue each one is, as
3555 /// `(start_us, end_us, track, cue)` in the same order ([`Project::sub_lane_cue_refs`]):
3556 /// what a front-end hit-tests a drawn cue against to find the words to edit.
3557 pub fn sub_lane_cue_refs(&self, lane: Lane) -> Vec<(i64, i64, usize, usize)> {
3558 self.project.sub_lane_cue_refs(lane, self.meta.frame_rate)
3559 }
3560
3561 /// [`sub_lane_cue_refs`](Self::sub_lane_cue_refs) with the part of each cue's own clock that
3562 /// is shown ([`Project::sub_lane_cue_spans`]), which its word times are moved by.
3563 pub fn sub_lane_cue_spans(&self, lane: Lane) -> Vec<crate::project::CueSpan> {
3564 self.project.sub_lane_cue_spans(lane, self.meta.frame_rate)
3565 }
3566
3567 /// Retypes one cue's words ([`Project::set_cue_text`]). One undo step, and
3568 /// `false` with none for a cue that is not there or already reads this.
3569 /// No invalidation: the picture's captions are drawn per repaint from the
3570 /// palette ([`sub_lane_cues`](Self::sub_lane_cues)), so the new words are on
3571 /// the next frame without a reseek.
3572 pub fn set_cue_text(&mut self, track: usize, cue: usize, text: &str) -> bool {
3573 self.project.set_cue_text(track, cue, text)
3574 }
3575
3576 /// Removes one cue from its track ([`Project::delete_cue`]): gone from every
3577 /// placement of the track, nothing moves. One undo step, and `false` with
3578 /// none for a cue that is not there.
3579 pub fn delete_cue(&mut self, track: usize, cue: usize) -> bool {
3580 self.project.delete_cue(track, cue)
3581 }
3582
3583 /// The room a cue has on the track's own clock ([`Project::cue_room`]).
3584 pub fn cue_room(&self, track: usize, cue: usize) -> Option<(i64, i64)> {
3585 self.project.cue_room(track, cue)
3586 }
3587
3588 /// Where timeline time `tl_us` is on the track's clock, through the placement on `lane`
3589 /// that shows the cue ([`Project::cue_track_us_at`]).
3590 pub fn cue_track_us_at(&self, lane: Lane, track: usize, cue: usize, tl_us: i64) -> Option<i64> {
3591 self.project.cue_track_us_at(lane, track, cue, tl_us, self.meta.frame_rate)
3592 }
3593
3594 /// Moves or trims one cue ([`Project::set_cue_times`]). One undo step.
3595 pub fn set_cue_times(&mut self, track: usize, cue: usize, start_us: i64, end_us: i64) -> crate::Result<bool> {
3596 self.project.set_cue_times(track, cue, start_us, end_us)
3597 }
3598
3599 /// Joins a cue with the one after it ([`Project::merge_cue_next`]). One undo step.
3600 pub fn merge_cue_next(&mut self, track: usize, cue: usize) -> crate::Result<()> {
3601 self.project.merge_cue_next(track, cue)
3602 }
3603
3604 /// Divides the cue straddling `t_us` on the track's clock ([`Project::split_cues_at`]). One undo step.
3605 pub fn split_cues_at(&mut self, track: usize, t_us: i64) -> bool {
3606 self.project.split_cues_at(track, t_us)
3607 }
3608
3609 /// Adds a cue to a track on the track's own clock ([`Project::add_cue`]): kept
3610 /// in the project and saved with it. One undo step; the index it lands at, or
3611 /// the refusal, which changes nothing.
3612 pub fn add_cue(&mut self, track: usize, start_us: i64, end_us: i64, text: &str, overwrite: bool) -> crate::Result<usize> {
3613 self.project.add_cue(track, start_us, end_us, text, overwrite)
3614 }
3615
3616 /// The title cards and text overlays, in draw order ([`Project::titles`]).
3617 pub fn titles(&self) -> &[crate::project::Title] {
3618 self.project.titles()
3619 }
3620
3621 /// The chapter markers, sorted by frame, at most one per frame
3622 /// ([`Project::chapters`]).
3623 pub fn chapters(&self) -> &[crate::project::Chapter] {
3624 self.project.chapters()
3625 }
3626
3627 /// The chapters as a YouTube description listing, `00:00 Intro` a line each, and the
3628 /// warnings its rules call for ([`chapter_listing`]). The whole timeline, never a range.
3629 pub fn youtube_chapters(&self) -> (String, Vec<String>) {
3630 let fps = self.meta.frame_rate;
3631 let end = (self.timeline_duration() * fps).round() as u32;
3632 let chapters: Vec<(u32, String)> = self.chapters().iter().map(|c| (c.frame, c.title.clone())).collect();
3633 chapter_listing(&chapters, fps, end)
3634 }
3635
3636 /// Adds a chapter at `frame` named `title`, and returns its index in
3637 /// [`chapters`](Self::chapters). One undo step; refused, with nothing changed,
3638 /// for a name the project refuses or a frame that already has a chapter.
3639 pub fn add_chapter(&mut self, frame: u32, title: &str) -> crate::Result<usize> {
3640 self.project.add_chapter(crate::project::Chapter { frame, title: title.to_string() })
3641 }
3642
3643 /// Takes the chapter at `idx` off the list. One undo step; `false`, with
3644 /// nothing changed, for an index that is not there.
3645 pub fn remove_chapter(&mut self, idx: usize) -> bool {
3646 self.project.remove_chapter(idx)
3647 }
3648
3649 /// Renames the chapter at `idx`. One undo step; `false` for an index that
3650 /// is not there, a name the project refuses, or the name it already has.
3651 pub fn set_chapter_title(&mut self, idx: usize, title: &str) -> bool {
3652 self.project.set_chapter_title(idx, title)
3653 }
3654
3655 /// Moves the chapter at `idx` to `frame`, and returns its new index. One undo
3656 /// step; refused for a frame another chapter already holds.
3657 pub fn move_chapter(&mut self, idx: usize, frame: u32) -> crate::Result<usize> {
3658 self.project.move_chapter(idx, frame)
3659 }
3660
3661 /// Maps every chapter's frame through `map` as one undo step, for an edit that
3662 /// moves time (see [`Project::remap_chapters`]). Returns how many chapters a
3663 /// landing on another's frame dropped.
3664 pub fn remap_chapters(&mut self, map: impl Fn(u32) -> u32) -> usize {
3665 self.project.remap_chapters(map)
3666 }
3667
3668 /// How burned captions animate ([`crate::captionanim`]).
3669 pub fn caption_style(&self) -> crate::captionanim::CaptionStyle {
3670 self.project.caption_style()
3671 }
3672
3673 /// Gives a caption track's cues the word times they were written from
3674 /// ([`Project::attach_cue_words`]); `auto_captions` calls it right after the import.
3675 pub fn attach_cue_words(&mut self, track: usize, timed: &[crate::subtitle::Cue]) {
3676 self.project.attach_cue_words(track, timed);
3677 }
3678
3679 /// Sets how burned captions animate; one undo step, `false` when it is already so.
3680 pub fn set_caption_style(&mut self, style: crate::captionanim::CaptionStyle) -> bool {
3681 self.project.set_caption_style(style)
3682 }
3683
3684 /// The comment markers, sorted by frame ([`Project::markers`]).
3685 pub fn markers(&self) -> &[crate::project::Marker] {
3686 self.project.markers()
3687 }
3688
3689 /// Adds a marker and returns its index in [`markers`](Self::markers). One undo step;
3690 /// refused, with nothing changed, for a marker the project refuses.
3691 pub fn add_marker(&mut self, marker: crate::project::Marker) -> crate::Result<usize> {
3692 self.project.add_marker(marker)
3693 }
3694
3695 /// Takes the marker at `idx` off. One undo step; `false` for an index that is not there.
3696 pub fn remove_marker(&mut self, idx: usize) -> bool {
3697 self.project.remove_marker(idx)
3698 }
3699
3700 /// Replaces the marker at `idx` and returns its new index. One undo step; refused for
3701 /// a marker the project refuses or one that changes nothing.
3702 pub fn set_marker(&mut self, idx: usize, marker: crate::project::Marker) -> crate::Result<usize> {
3703 self.project.set_marker(idx, marker)
3704 }
3705
3706 /// Maps every marker's start and end through `map` as one undo step, for an edit that
3707 /// moves time (see [`Project::remap_markers`]). `false` when nothing moved.
3708 pub fn remap_markers(&mut self, map: impl Fn(u32) -> u32) -> bool {
3709 self.project.remap_markers(map)
3710 }
3711
3712 /// The markers as a chapter list for an export of `range`, as [`chapter_list_ns`](Self::chapter_list_ns)
3713 /// lists chapters: `(start_ns, name)` pairs in frame order, the first marker on a frame
3714 /// winning when several share one (a chapter list holds one per instant).
3715 pub fn marker_list_ns(&self, range: Option<(u32, u32)>) -> Vec<(u64, String)> {
3716 let (from, to) = range.unwrap_or((0, u32::MAX));
3717 let fps = self.meta.frame_rate;
3718 let mut out: Vec<(u64, String)> = Vec::new();
3719 for m in self.project.markers().iter().filter(|m| m.frame >= from && m.frame < to) {
3720 let ns = (f64::from(m.frame - from) / fps * 1e9).round() as u64;
3721 if out.last().is_none_or(|(last, _)| *last != ns) {
3722 out.push((ns, m.name.clone()));
3723 }
3724 }
3725 out
3726 }
3727
3728 /// The chapter list an export of `range` (frames, as [`ExportSettings::range`]
3729 /// names it) writes: `(start_ns, name)` pairs in frame order. A chapter's time
3730 /// is measured from the start of the range, so an export that starts at frame
3731 /// 100 writes a chapter at frame 100 as the first one, at 0 ns. Chapters before
3732 /// the range or at or past its end are left out; with no range every chapter
3733 /// is listed from the start of the timeline.
3734 ///
3735 /// Ready for an export's chapter list: the codecs writers take the pairs as
3736 /// they are.
3737 pub fn chapter_list_ns(&self, range: Option<(u32, u32)>) -> Vec<(u64, String)> {
3738 let (from, to) = range.unwrap_or((0, u32::MAX));
3739 let fps = self.meta.frame_rate;
3740 self.project
3741 .chapters()
3742 .iter()
3743 .filter(|c| c.frame >= from && c.frame < to)
3744 .map(|c| {
3745 let ns = f64::from(c.frame - from) / fps * 1e9;
3746 (ns.round() as u64, c.title.clone())
3747 })
3748 .collect()
3749 }
3750
3751 /// Adds a title card or text overlay and recomposes the picture at the
3752 /// playhead. The index it lands at, or the refusal of [`Project::add_title`],
3753 /// which changes nothing.
3754 pub fn add_title(&mut self, title: crate::project::Title) -> crate::Result<usize> {
3755 let idx = self.project.add_title(title)?;
3756 self.invalidate(Dirty::Picture);
3757 Ok(idx)
3758 }
3759
3760 /// Replaces the title at `idx` -- see [`Project::set_title`]. One undo step
3761 /// and a recomposed picture.
3762 pub fn set_title(&mut self, idx: usize, title: crate::project::Title) -> bool {
3763 self.edit(Dirty::Picture, |p| p.set_title(idx, title))
3764 }
3765
3766 /// Takes the title at `idx` off -- see [`Project::remove_title`]. One undo
3767 /// step and a recomposed picture.
3768 pub fn remove_title(&mut self, idx: usize) -> bool {
3769 self.edit(Dirty::Picture, |p| p.remove_title(idx))
3770 }
3771
3772 /// Splits every lane at `timeline_secs`, so the two sides become two
3773 /// groups. Metadata only: a split never changes the timeline->source
3774 /// mapping, so the running decoder stays correct and playback does not
3775 /// blink. `false` at a clip start, in a gap and past the end, where there
3776 /// would be nothing to split off.
3777 pub fn cut_at(&mut self, timeline_secs: f64) -> bool {
3778 self.project
3779 .split(secs_to_frame(timeline_secs, self.meta.frame_rate))
3780 }
3781
3782 /// The frame nearest `frame` within `reach` frames at which [`cut_at`](Self::cut_at)
3783 /// lands cleanly on every lane ([`Project::cut_frame_near`]); `None` when none is that near.
3784 pub fn cut_frame_near(&self, frame: u32, reach: u32) -> Option<u32> {
3785 self.project.cut_frame_near(frame, reach)
3786 }
3787
3788 /// [`cut_at`](Self::cut_at) on the lanes in `lanes` only; the others keep
3789 /// their clips whole across the cut. Metadata only, like `cut_at`.
3790 pub fn cut_at_lanes(&mut self, timeline_secs: f64, lanes: &[Lane]) -> bool {
3791 self.project
3792 .split_on(secs_to_frame(timeline_secs, self.meta.frame_rate), lanes)
3793 }
3794
3795 /// The inverse of [`cut_at`](Self::cut_at): rejoins the clips that meet at
3796 /// `timeline_secs` in every lane and puts them back in one group. `false`
3797 /// unless a split could have produced what is there. Metadata only, like the
3798 /// split -- no reseek.
3799 pub fn regroup_at(&mut self, timeline_secs: f64) -> bool {
3800 self.project
3801 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))
3802 }
3803
3804 /// Takes that clip out of its group, so its picture and its sound are edited
3805 /// apart from here on. Metadata only like a cut -- no reseek -- and one undo
3806 /// step. `false` for a bad index and for a clip that is not grouped with
3807 /// anything, which is already detached.
3808 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
3809 self.project.ungroup(lane, idx)
3810 }
3811
3812 /// Puts two clips covering the same frames back into one group: the regroup
3813 /// of what [`ungroup`](Self::ungroup) took apart. Metadata only, one undo
3814 /// step, and the error says why when it refuses.
3815 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
3816 self.project.group(a, a_idx, b, b_idx)
3817 }
3818
3819 /// Puts every placement the picks name into one group
3820 /// ([`Project::group_all`]) -- the ctrl-click selection's own door, which
3821 /// may name clips and captions alike. Metadata only like the pair above:
3822 /// no reseek, one undo step, and the error says why when it refuses.
3823 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
3824 self.project.group_all(picks)
3825 }
3826
3827 /// [`delete_clip`](Self::delete_clip) for the caption the pick named: a
3828 /// caption in no group lifts exactly as [`lift_sub`](Self::lift_sub) lifts
3829 /// it -- no reseek, because nothing that plays has changed -- and a caption
3830 /// in a group takes the group with it, which ripples every member's own
3831 /// lane and reseeks like a delete. `false` for a bad index.
3832 pub fn delete_sub(&mut self, lane: Lane, idx: usize) -> bool {
3833 // Which of the two, asked before anything moves: the reseek a grouped
3834 // delete owes is the whole difference between the paths. A group of
3835 // captions alone (no clip on another lane) still ripples every
3836 // member's *own* sub lane closed (`Project::delete_sub_in`, since
3837 // cdc53a6), and a sub lane counts toward `timeline_frames` exactly
3838 // like a clip lane does -- so the timeline can shrink out from under
3839 // the playhead from a caption-only group too, not only a media one.
3840 // `caption_grouped_with_clips` answers a narrower question than the
3841 // one this dispatch needs; a caption carries a link at all only once
3842 // grouped (`place_sub` always starts one at `None`), so that alone is
3843 // "this delete ripples more than its own lane".
3844 match self
3845 .sub_lane(lane)
3846 .get(idx)
3847 .is_some_and(|s| s.link.is_some())
3848 {
3849 true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)),
3850 // A caption in no group is the plain lift that touches nothing
3851 // else: no reseek owed.
3852 false => self.project.delete_sub_in(lane, idx),
3853 }
3854 }
3855
3856 /// Whether the caption at `idx` of `lane` is grouped with clips on other
3857 /// lanes: the one question every caption edit that can move media has to
3858 /// ask first, because the answer is whether the edit owes a reseek -- and
3859 /// the front-end owes the same answer, asked before the edit moves the
3860 /// indices, so its flag reset matches the engine's reseek exactly.
3861 pub fn caption_grouped_with_clips(&self, lane: Lane, idx: usize) -> bool {
3862 self.project
3863 .sub_lane(lane)
3864 .get(idx)
3865 .and_then(|s| s.link)
3866 .is_some_and(|id| {
3867 self.project
3868 .lanes()
3869 .into_iter()
3870 .any(|l| l != lane && self.project.lane(l).iter().any(|c| c.link == Some(id)))
3871 })
3872 }
3873
3874 /// What the clip at `idx` of `lane` is equalized with, or `None` for one
3875 /// that plays flat -- what a card shows before it lets anyone drag a band.
3876 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
3877 self.project.eq_of(lane, idx)
3878 }
3879
3880 /// Gives that clip an equalizer, or takes it off with `None`. One undo step,
3881 /// like every other edit -- and it rebuilds the **sound** where the playhead
3882 /// is, so a band changed during playback is heard from the next chunk on
3883 /// rather than at the next play. The picture is not touched: the video
3884 /// worker keeps decoding through it ([`Dirty`]). `false` for a bad index or
3885 /// a non-finite band, and nothing changes.
3886 ///
3887 /// corner-cut: the audio rebuild is what makes it live, so the cost of a
3888 /// change is a decoder restart -- inaudible at a drag's end, but too much to
3889 /// call once per pointer sample (a caller commits one change per gesture).
3890 /// Upgrade path is the per-segment twin of [`crate::audio::MixControls`],
3891 /// which the lane worker would poll per chunk the way the mixer polls the
3892 /// gains.
3893 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
3894 self.edit(Dirty::Sound, |p| p.set_eq(lane, idx, params))
3895 }
3896
3897 /// The clip's own gain in dB at `idx` of `lane`, or `None` for an index
3898 /// that is not there ([`Project::clip_gain`]).
3899 pub fn clip_gain_of(&self, lane: Lane, idx: usize) -> Option<f32> {
3900 self.project.clip_gain(lane, idx)
3901 }
3902
3903 /// Sets that clip's gain in dB, clamped to the clip-gain range. One undo
3904 /// step, and the sound is rebuilt where the playhead is, as for
3905 /// [`set_eq`](Self::set_eq). `false` for a video lane, a bad index, a
3906 /// non-finite value, or a value already set.
3907 pub fn set_clip_gain(&mut self, lane: Lane, idx: usize, db: f32) -> bool {
3908 self.edit(Dirty::Sound, |p| p.set_clip_gain(lane, idx, db))
3909 }
3910
3911 /// Plays the timeline's sound at `at` (timeline seconds) for [`SCRUB_SECS`]: the audible
3912 /// half of a ruler scrub while paused. The decode happens on the scrub thread and nothing
3913 /// here waits for it, so a drag never stalls on the file; a request that arrives while an
3914 /// earlier one is still being read replaces it. Silent, and a no-op, past the end of the
3915 /// timeline or where nothing plays.
3916 pub fn scrub_audio(&mut self, at: f64) {
3917 if !(at.is_finite() && at >= 0.) {
3918 return;
3919 }
3920 let fps = self.meta.frame_rate;
3921 let target = (at * fps) as u32;
3922 let view = self.project.render_view();
3923 let segs = view.audio_segments_from(target, fps);
3924 if segs.is_empty() {
3925 return;
3926 }
3927 let eqs = view.audio_eqs_from(target, fps);
3928 let speeds = view.audio_speeds_from(target, fps);
3929 let fades = view.audio_fades_from(target, fps);
3930 let sources = self.project.audio_sources();
3931 let gains = self.mix_gains();
3932 let ducks = view.audio_ducks();
3933 let voices = view.audio_voices();
3934 let limiter = self.project.limiter();
3935 let sample_rate = self.sample_rate;
3936 let work: ScrubWork = Box::new(move || {
3937 let (meta, rx) = AudioSession::open_mixed_streams_live_fade(
3938 &sources,
3939 &segs,
3940 &eqs,
3941 &speeds,
3942 &fades,
3943 fps,
3944 &gains,
3945 &ducks,
3946 &voices,
3947 limiter,
3948 None,
3949 sample_rate,
3950 )
3951 .ok()??;
3952 let channels = usize::from(meta.channels).max(1);
3953 let want = (SCRUB_SECS * f64::from(meta.sample_rate)) as usize * channels;
3954 let mut buf = Vec::with_capacity(want);
3955 while buf.len() < want {
3956 match rx.recv_timeout(std::time::Duration::from_millis(500)) {
3957 Ok(chunk) => buf.extend_from_slice(&chunk.samples),
3958 Err(_) => break,
3959 }
3960 }
3961 buf.truncate(want);
3962 if buf.is_empty() {
3963 return None;
3964 }
3965 let fade = (SCRUB_FADE_SECS * f64::from(meta.sample_rate)) as usize;
3966 let samples = scrub_snippet(&buf, channels, fade);
3967 Some((meta.sample_rate, u32::from(meta.channels), samples))
3968 });
3969 let tx = self.scrub.tx.get_or_insert_with(|| {
3970 let (tx, rx) = std::sync::mpsc::channel();
3971 let _ = std::thread::Builder::new()
3972 .name("audio-scrub".into())
3973 .spawn(move || scrub_thread(rx));
3974 tx
3975 });
3976 let _ = tx.send(work);
3977 self.scrub.requests += 1;
3978 }
3979
3980 /// How many scrub snippets have been asked for on this session: the count a test reads to see
3981 /// that a drag did, or did not, play sound ([`PlaybackSession::scrub_audio`]).
3982 pub fn scrub_requests(&self) -> u64 {
3983 self.scrub.requests
3984 }
3985
3986 /// The clip's pitch shift in semitones at `idx` of `lane` ([`Project::clip_pitch`]).
3987 pub fn clip_pitch_of(&self, lane: Lane, idx: usize) -> Option<i8> {
3988 self.project.clip_pitch(lane, idx)
3989 }
3990
3991 /// Sets that clip's pitch in semitones, clamped to `-12..=12`. One undo step; the
3992 /// sound is rebuilt where the playhead is, as for [`set_clip_gain`](Self::set_clip_gain).
3993 /// `false` for a video lane, a bad index, or a value already set.
3994 pub fn set_clip_pitch(&mut self, lane: Lane, idx: usize, semitones: i32) -> bool {
3995 self.edit(Dirty::Sound, |p| p.set_clip_pitch(lane, idx, semitones))
3996 }
3997
3998 /// The clip's pan at `idx` of `lane`, `-1.0..=1.0` ([`Project::clip_pan`]).
3999 pub fn clip_pan_of(&self, lane: Lane, idx: usize) -> Option<f32> {
4000 self.project.clip_pan(lane, idx)
4001 }
4002
4003 /// Sets that clip's pan. One undo step; the sound is rebuilt where the playhead is, as for
4004 /// [`set_clip_gain`](Self::set_clip_gain). `false` for a video lane, a bad index, a
4005 /// non-finite value, or a value already set.
4006 pub fn set_clip_pan(&mut self, lane: Lane, idx: usize, pan: f32) -> bool {
4007 self.edit(Dirty::Sound, |p| p.set_clip_pan(lane, idx, pan))
4008 }
4009
4010 /// An audio lane's pan, `-1.0..=1.0` ([`Project::lane_pan`]).
4011 pub fn lane_pan(&self, lane: Lane) -> f32 {
4012 self.project.lane_pan(lane)
4013 }
4014
4015 /// Sets it. One undo step; the pan rides in each clip's envelope, so the sound is rebuilt
4016 /// where the playhead is (a caller commits one change per gesture).
4017 pub fn set_lane_pan(&mut self, lane: Lane, pan: f32) -> bool {
4018 self.edit(Dirty::Sound, |p| p.set_lane_pan(lane, pan))
4019 }
4020
4021 /// How loud that lane plays, in dB -- everything on it, every frequency of
4022 /// it. See [`Project::lane_gain_db`] for what it is *not*.
4023 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
4024 self.project.lane_gain_db(lane)
4025 }
4026
4027 /// Sets it. One undo step -- and **nothing is rebuilt**: a lane's volume
4028 /// lives at the sum, so the running mixer is handed the new number and
4029 /// picks it up at its next block ([`crate::audio::MixControls`]). A fader
4030 /// held down under an arrow key therefore moves the level and nothing else:
4031 /// no flush, no decoder restart, no hole in the sound and no blink in the
4032 /// picture.
4033 ///
4034 /// The one exception is the timeline that is not mixed at all -- a single
4035 /// audio lane at unity with the limiter off, which plays through the
4036 /// bit-exact single-stream path and has no mixer to talk to. Moving *that*
4037 /// off unity opens one, once; every move after it is live.
4038 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
4039 if !self.project.set_lane_gain_db(lane, db) {
4040 return false;
4041 }
4042 self.push_mix();
4043 true
4044 }
4045
4046 /// Sets or clears the auto-duck on an audio lane -- see
4047 /// [`Project::set_lane_duck`]. Live exactly as a volume is: the running
4048 /// mixer is handed the new duck and picks it up at its next block, and
4049 /// nothing is rebuilt.
4050 pub fn set_lane_duck(&mut self, lane: Lane, duck: Option<crate::duck::Duck>) -> bool {
4051 if !self.project.set_lane_duck(lane, duck) {
4052 return false;
4053 }
4054 self.push_mix();
4055 true
4056 }
4057
4058 /// The duck on `lane`, if it has one -- see [`Project::lane_duck`].
4059 pub fn lane_duck(&self, lane: Lane) -> Option<crate::duck::Duck> {
4060 self.project.lane_duck(lane)
4061 }
4062
4063 /// Every duck on `lane`, one per key -- see [`Project::lane_duck_list`].
4064 pub fn lane_duck_list(&self, lane: Lane) -> Vec<crate::duck::Duck> {
4065 self.project.lane_duck_list(lane)
4066 }
4067
4068 /// Removes the duck `lane` has under the key `under` (the key's
4069 /// [`Lane::ord`]) and keeps its others -- see [`Project::clear_lane_duck`].
4070 /// Live like [`set_lane_duck`](Self::set_lane_duck).
4071 pub fn clear_lane_duck(&mut self, lane: Lane, under: usize) -> bool {
4072 if !self.project.clear_lane_duck(lane, under) {
4073 return false;
4074 }
4075 self.push_mix();
4076 true
4077 }
4078
4079 /// The voice processors on `lane` -- see [`Project::lane_voice`].
4080 pub fn lane_voice(&self, lane: Lane) -> crate::voice::VoiceFx {
4081 self.project.lane_voice(lane)
4082 }
4083
4084 /// Sets the voice processors of an audio lane -- see [`Project::set_lane_voice`].
4085 /// One undo step. Not live: the processors run on the lane's own stream, so the
4086 /// sound is rebuilt where the playhead is, as for [`set_eq`](Self::set_eq).
4087 pub fn set_lane_voice(&mut self, lane: Lane, voice: crate::voice::VoiceFx) -> bool {
4088 self.edit(Dirty::Sound, |p| p.set_lane_voice(lane, voice))
4089 }
4090
4091 /// Learns a noise profile from `lane` -- the quietest half second of it, or the
4092 /// `range` (lane seconds) -- see [`crate::voice::learn_noise`]. Reads the lane as it
4093 /// plays and changes nothing.
4094 pub fn learn_noise(
4095 &self,
4096 lane: Lane,
4097 range: Option<(f64, f64)>,
4098 ) -> crate::Result<crate::voice::Learned> {
4099 crate::voice::learn_noise(&self.project, lane, self.meta.frame_rate, self.sample_rate, range)
4100 }
4101
4102 /// Whether the lane is hidden -- see [`Project::lane_hidden`].
4103 pub fn lane_hidden(&self, lane: Lane) -> bool {
4104 self.project.lane_hidden(lane)
4105 }
4106
4107 /// Whether the lane is muted -- see [`Project::lane_muted`].
4108 pub fn lane_muted(&self, lane: Lane) -> bool {
4109 self.project.lane_muted(lane)
4110 }
4111
4112 /// Whether the lane is locked -- see [`Project::lane_locked`]. Nothing here
4113 /// refuses an edit on it; the front-end does.
4114 pub fn lane_locked(&self, lane: Lane) -> bool {
4115 self.project.lane_locked(lane)
4116 }
4117
4118 /// Hides or shows a lane, live. A video lane's picture is recomposed at the
4119 /// playhead, the one rebuild this costs ([`Dirty::Picture`]); the sound keeps
4120 /// playing. A subtitle lane is drawn from the project at every repaint, so
4121 /// nothing is rebuilt for it at all.
4122 pub fn set_lane_hidden(&mut self, lane: Lane, hidden: bool) -> bool {
4123 if !self.project.set_lane_hidden(lane, hidden) {
4124 return false;
4125 }
4126 if lane.kind == LaneKind::Video {
4127 self.invalidate(Dirty::Picture);
4128 }
4129 true
4130 }
4131
4132 /// Mutes or unmutes an audio lane, live: the mix is handed its new gain at
4133 /// the next block exactly as a fader is ([`push_mix`](Self::push_mix)).
4134 pub fn set_lane_muted(&mut self, lane: Lane, muted: bool) -> bool {
4135 if !self.project.set_lane_muted(lane, muted) {
4136 return false;
4137 }
4138 self.push_mix();
4139 true
4140 }
4141
4142 /// Locks or unlocks a lane. Nothing plays differently, so nothing is
4143 /// touched -- it is in the lane list, so it is one undo step like the rest.
4144 pub fn set_lane_locked(&mut self, lane: Lane, locked: bool) -> bool {
4145 self.project.set_lane_locked(lane, locked)
4146 }
4147
4148 /// Names a lane ([`Project::set_lane_name`]). A label only: nothing is rebuilt.
4149 pub fn set_lane_name(&mut self, lane: Lane, name: &str) -> Result<bool, String> {
4150 self.project.set_lane_name(lane, name)
4151 }
4152
4153 /// The name given to a lane, `None` for none ([`Project::lane_name`]).
4154 pub fn lane_name(&self, lane: Lane) -> Option<&str> {
4155 self.project.lane_name(lane)
4156 }
4157
4158 /// What a lane header shows: the name, else the address ([`Project::lane_title`]).
4159 pub fn lane_title(&self, lane: Lane) -> String {
4160 self.project.lane_title(lane)
4161 }
4162
4163 /// Solos audio lanes for listening: while any is soloed, every other audio
4164 /// lane is silent in what this session plays. Monitoring only -- it is not
4165 /// project state, is not saved, and an export never reads it. Lanes that
4166 /// are not audio lanes are ignored, and an empty list clears the solo.
4167 /// `false` when nothing changes. A [`Lane`] is a handle into the lane list,
4168 /// so solo again after a lane is removed or moved.
4169 pub fn set_solo(&mut self, lanes: &[Lane]) -> bool {
4170 let solo: Vec<Lane> = self
4171 .project
4172 .audio_lanes()
4173 .into_iter()
4174 .filter(|lane| lanes.contains(lane))
4175 .collect();
4176 if solo == self.solo {
4177 return false;
4178 }
4179 self.solo = solo;
4180 self.push_mix();
4181 true
4182 }
4183
4184 /// The audio lanes soloed for listening, as [`set_solo`](Self::set_solo) took them.
4185 pub fn soloed(&self) -> &[Lane] {
4186 &self.solo
4187 }
4188
4189 /// The gains the sound plays: the project's own, with the audio lanes
4190 /// outside a solo silenced. A solo that names no audio lane any more is no
4191 /// solo, so a stale handle cannot silence everything. The export reads
4192 /// [`Project::audio_gains`] directly and never comes through here.
4193 fn mix_gains(&self) -> Vec<f32> {
4194 soloed_gains(
4195 self.project.render_view().audio_gains(),
4196 &self.project.render_view().audio_lanes(),
4197 &self.solo,
4198 )
4199 }
4200
4201 /// The level meters, as the sound has reached them since the last call, and
4202 /// starts them over: the highest level each audio lane reached after its own
4203 /// gain (mute and solo read as silence) and the master peak after the
4204 /// limiter, before the device's volume. The flat single-lane path has no
4205 /// mixer, and its one lane is the master. Cheap: atomics and one short lock,
4206 /// nothing on the device's callback.
4207 pub fn levels(&self) -> Levels {
4208 let master = self.audio.as_ref().map_or(0.0, |audio| {
4209 f32::from_bits(audio.peak.swap(0, Ordering::Relaxed))
4210 });
4211 let master_lr = self.master_peaks_lr();
4212 let mut lanes = match self.mix.as_ref() {
4213 Some(mix) => mix.take_lane_peaks(),
4214 None => vec![master],
4215 };
4216 lanes.resize(self.project.audio_lanes().len(), 0.0);
4217 Levels { lanes, master, master_lr }
4218 }
4219
4220 /// The master's left and right peaks since the last read (of this or of [`levels`](Self::levels)),
4221 /// and starts them over: the stereo transport meter's own door, which leaves the lane peaks and
4222 /// the mono master the mix card reads alone.
4223 pub fn master_peaks_lr(&self) -> [f32; 2] {
4224 self.audio.as_ref().map_or([0.0; 2], |audio| {
4225 [0, 1].map(|i| f32::from_bits(audio.peak_lr[i].swap(0, Ordering::Relaxed)))
4226 })
4227 }
4228
4229 /// Hands the mix the running mixer is reading its new settings -- the whole
4230 /// of what a fader and a ceiling cost. With no mixer listening (the
4231 /// single-lane flat path, and a session with no sound at all) the sound is
4232 /// rebuilt instead, which is what opens one.
4233 fn push_mix(&mut self) {
4234 let gains = self.mix_gains();
4235 let ducks = self.project.render_view().audio_ducks();
4236 let limiter = self.project.limiter();
4237 // A mixer reading these, or an open on its way to being one: either way
4238 // the number is heard without a rebuild, and *that* is what a handle
4239 // left over from an open that found nothing cannot do
4240 // ([`crate::audio::MixControls::is_reachable`]).
4241 if let Some(mix) = self.mix.as_ref().filter(|mix| mix.is_reachable()) {
4242 mix.set(gains, ducks, limiter);
4243 return;
4244 }
4245 // Nothing to hand it to. Only a setting that *needs* a mixer is worth
4246 // the flush and the re-open: a ceiling dragged with the limiter off, or
4247 // a fader put back to unity, changes not one sample of the flat
4248 // single-stream path the timeline is already playing
4249 // ([`AudioSession::is_mixed`]), and reseeking per nudge was a hole in
4250 // the sound for a change nobody could hear.
4251 if crate::audio::AudioSession::is_mixed(gains.len(), &gains, limiter, &self.project.render_view().audio_voices()) {
4252 self.reseek_audio();
4253 }
4254 }
4255
4256 /// The master limiter the whole mix is summed through.
4257 pub fn limiter(&self) -> crate::limiter::Limiter {
4258 self.project.limiter()
4259 }
4260
4261 /// Sets it, live like a lane volume and for the same reason -- the ceiling
4262 /// a person is dragging has to be the ceiling they are hearing. Nothing is
4263 /// rebuilt: the running limiter is *retuned* between two blocks
4264 /// ([`crate::limiter::LimiterState::retune`]), so its delay line keeps
4265 /// running and the sample count the master clock is made of does not move.
4266 ///
4267 /// corner-cut: not an undo step, and deliberately -- [`Project::undo`]
4268 /// restores the lane list, and the limiter is not in it, so snapshotting
4269 /// here would push a step whose undo changes nothing a person can see or
4270 /// hear (the twin [`set_lane_gain_db`](Self::set_lane_gain_db) *is*
4271 /// undoable only because a lane volume lives in that list). The project
4272 /// resolution is outside undo for the same reason and says so. Upgrade path
4273 /// is a history that carries the mix beside the lanes, which every existing
4274 /// snapshot site would then have to fill in.
4275 pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool {
4276 if !self.project.set_limiter(limiter) {
4277 return false;
4278 }
4279 self.push_mix();
4280 true
4281 }
4282
4283 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
4284 /// silence on the audio one, and nothing else moves. Reseeks, because what
4285 /// the playhead sits on has changed. `false` for a bad index -- the lift of
4286 /// the last placement there is empties the timeline, which is a state
4287 /// ([`is_empty`](Self::is_empty)) and one undo away.
4288 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {
4289 self.edit(Dirty::Both, |p| p.lift(lane, idx))
4290 }
4291
4292 /// [`swap_clips`](Self::swap_clips) without the ripple: each clip takes the
4293 /// other's head and nothing between them moves ([`Project::swap_in_place`]).
4294 /// The `Err` names the clip the longer one would overlap, and nothing changes.
4295 pub fn swap_clips_in_place(&mut self, lane: Lane, a: usize, b: usize) -> crate::Result<()> {
4296 self.project.swap_in_place(lane, a, b)?;
4297 self.invalidate(Dirty::Both);
4298 Ok(())
4299 }
4300
4301 /// Swaps two placements of one lane ([`Project::swap`]): `b` takes `a`'s
4302 /// start and the ones between them ripple by the difference. One undo step.
4303 pub fn swap_clips(&mut self, lane: Lane, a: usize, b: usize) -> bool {
4304 self.edit(Dirty::Both, |p| p.swap(lane, a, b))
4305 }
4306
4307 /// Moves that clip onto lane `to` with its head at timeline frame `start` --
4308 /// the drag that carries a take along its track or onto another one, and its
4309 /// whole group with it. See [`Project::move_clip`] for the walls `start` is
4310 /// clamped to and the ways a drop is refused. One undo step, and it reseeks
4311 /// like every other edit: which lane a clip sits on is what the compositor's
4312 /// topmost-lane-wins rule reads, and where it starts is what the playhead
4313 /// reads, so the frame on screen is recomposed at once.
4314 ///
4315 /// A *frame*, where the rest of this type takes seconds, for
4316 /// [`trim_clip`](Self::trim_clip)'s reason: the drag has already put the
4317 /// pointer on a frame, and converting it back through seconds would be a
4318 /// rounding step between the box let go of and the box committed.
4319 ///
4320 /// Across kinds (a picture onto an audio lane or back) the clip must fit
4321 /// the new lane's wall ([`held_to_lane`](Self::held_to_lane)): a clip past
4322 /// it is refused rather than cut, since a move is not an edit of its length.
4323 pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
4324 if from.kind != to.kind {
4325 let Some(clip) = self.lane_clips(from).get(idx).cloned() else {
4326 return false;
4327 };
4328 if self.held_to_lane(to, clip.clone()).out_frame != clip.out_frame {
4329 return false;
4330 }
4331 }
4332 self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start))
4333 }
4334
4335 /// [`move_clip_to`](Self::move_clip_to)'s general form: every one of
4336 /// `picks` travels the same frame delta as the dragged clip at `idx` of
4337 /// `from`, all-or-nothing, one undo step for the lot -- what a hand drags
4338 /// on a selection rather than a lone clip. See
4339 /// [`Project::move_selection`] for the clamp that makes it all-or-nothing.
4340 pub fn move_selection_to(
4341 &mut self,
4342 picks: &[(Lane, usize)],
4343 from: Lane,
4344 idx: usize,
4345 to: Lane,
4346 start: u32,
4347 ) -> bool {
4348 self.edit(Dirty::Both, |p| {
4349 p.move_selection(picks, from, idx, to, start)
4350 })
4351 }
4352
4353 /// [`trim_clip`](Self::trim_clip) as a ripple trim ([`Project::ripple_trim`]): the hole the
4354 /// edge leaves closes, or opens, and what follows moves with it. One undo step.
4355 pub fn ripple_trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
4356 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4357 if !self.project.ripple_trim_with_walls(lane, idx, edge, to, SourceWalls { picture: &picture, sound: &sound }) {
4358 return false;
4359 }
4360 let now = self.now();
4361 self.seek(now);
4362 true
4363 }
4364
4365 /// Drags one end of that clip to timeline frame `to`, changing how much of
4366 /// its source it plays and nothing else on the lane -- see [`Project::trim`]
4367 /// for the walls it is clamped by, which this fills the source lengths in
4368 /// for. One undo step per call, so a front-end calls it once, at the release
4369 /// of the drag. Reseeks like every other edit, which is what makes the
4370 /// picture (and the sound) follow a new in-point straight away. `false` for
4371 /// a bad index and for an edge already where it was asked to go.
4372 ///
4373 /// A *frame*, where the rest of this type takes seconds: a drag has already
4374 /// asked [`trim_room`](Self::trim_room) where the edge may land, and that
4375 /// answer is in frames -- converting it back through seconds would be a
4376 /// rounding step between the width drawn and the width committed.
4377 pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
4378 // Spelled out rather than through `edit`, whose closure cannot hold a
4379 // second borrow of the session while it has the project.
4380 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4381 if !self.project.trim_with_walls(lane, idx, edge, to, SourceWalls { picture: &picture, sound: &sound }) {
4382 return false;
4383 }
4384 let now = self.now();
4385 self.seek(now);
4386 true
4387 }
4388
4389 /// **Roll**: moves the cut at the end of the clip at `idx` of `lane` to timeline
4390 /// frame `to` ([`Project::roll`]): the out-point of that clip and the in-point of
4391 /// the one behind it move together. Returns where the cut is now; `None` for a
4392 /// clip with nothing abutting behind it. Reseeks, one undo step.
4393 pub fn roll_clip(&mut self, lane: Lane, idx: usize, to: u32) -> Option<u32> {
4394 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4395 let at = self.project.roll(lane, idx, to, SourceWalls { picture: &picture, sound: &sound })?;
4396 let now = self.now();
4397 self.seek(now);
4398 Some(at)
4399 }
4400
4401 /// Where that cut may travel, `(first, last)` frame inclusive ([`Project::roll_room`]).
4402 pub fn roll_room(&self, lane: Lane, idx: usize) -> Option<(u32, u32)> {
4403 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4404 self.project.roll_room(lane, idx, SourceWalls { picture: &picture, sound: &sound })
4405 }
4406
4407 /// **Slide**: starts that clip at timeline frame `to` between its neighbours
4408 /// ([`Project::slide`]). Returns where it starts now; `None` for a clip
4409 /// without a neighbour on both sides. Reseeks, one undo step.
4410 pub fn slide_clip(&mut self, lane: Lane, idx: usize, to: u32) -> Option<u32> {
4411 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4412 let at = self.project.slide(lane, idx, to, SourceWalls { picture: &picture, sound: &sound })?;
4413 let now = self.now();
4414 self.seek(now);
4415 Some(at)
4416 }
4417
4418 /// Where that clip may start when slid, `(first, last)` frame inclusive ([`Project::slide_room`]).
4419 pub fn slide_room(&self, lane: Lane, idx: usize) -> Option<(u32, u32)> {
4420 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4421 self.project.slide_room(lane, idx, SourceWalls { picture: &picture, sound: &sound })
4422 }
4423
4424 /// **Slip**: shifts that clip's source window by `by` source frames
4425 /// ([`Project::slip`]; [`slip_source_delta`](Self::slip_source_delta) turns timeline
4426 /// frames into them). Returns the frames it moved; `None` for a bad index or a
4427 /// still. Reseeks, one undo step.
4428 pub fn slip_clip(&mut self, lane: Lane, idx: usize, by: i64) -> Option<i64> {
4429 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4430 let moved = self.project.slip(lane, idx, by, SourceWalls { picture: &picture, sound: &sound })?;
4431 if moved != 0 {
4432 let now = self.now();
4433 self.seek(now);
4434 }
4435 Some(moved)
4436 }
4437
4438 /// How far that clip may slip, `(back, forward)` source frames ([`Project::slip_room`]).
4439 pub fn slip_room(&self, lane: Lane, idx: usize) -> Option<(i64, i64)> {
4440 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4441 self.project.slip_room(lane, idx, SourceWalls { picture: &picture, sound: &sound })
4442 }
4443
4444 /// The source frames `by` timeline frames are worth for that clip ([`Project::slip_source_delta`]).
4445 pub fn slip_source_delta(&self, lane: Lane, idx: usize, by: i64) -> Option<i64> {
4446 self.project.slip_source_delta(lane, idx, by)
4447 }
4448
4449 /// How fast the clip at `idx` of `lane` plays -- what a card shows before
4450 /// anyone drags it.
4451 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
4452 self.project.speed_of(lane, idx)
4453 }
4454
4455 /// Sets it, for that clip and its whole group ([`Project::set_speed`]): one
4456 /// undo step for the lot. Reseeks like every other edit, so the picture runs
4457 /// -- and the sound is resampled -- from the next frame on rather than at the
4458 /// next play. The `Err` names the clip in the way when slowing one down
4459 /// would run it into its neighbour, and nothing changes.
4460 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
4461 // Spelled out rather than through `edit`, whose closure hands back a
4462 // bool and would drop the refusal's own words. The playhead moves
4463 let at = self.project.speeded_playhead(
4464 lane,
4465 idx,
4466 speed,
4467 secs_to_frame(self.now(), self.meta.frame_rate),
4468 );
4469 self.project.set_speed(lane, idx, speed)?;
4470 let now = at.map_or_else(
4471 || self.now(),
4472 |frame| f64::from(frame) / self.meta.frame_rate,
4473 );
4474 self.seek(now);
4475 Ok(())
4476 }
4477
4478 /// Whether the clip at `idx` of `lane` plays backwards ([`Project::reversed_of`]).
4479 pub fn reversed_of(&self, lane: Lane, idx: usize) -> bool {
4480 self.project.reversed_of(lane, idx)
4481 }
4482
4483 /// Plays the clip and its whole group backwards, or forwards again
4484 /// ([`Project::set_reverse`]): one undo step, and a reseek at the playhead so
4485 /// the picture and the sound run the new way from the next frame on.
4486 pub fn set_reverse(&mut self, lane: Lane, idx: usize, on: bool) -> crate::Result<()> {
4487 self.project.set_reverse(lane, idx, on)?;
4488 let now = self.now();
4489 self.seek(now);
4490 Ok(())
4491 }
4492
4493 /// Gives the clip at `idx` of `lane` (and its group) a speed ramp, or clears it
4494 /// with empty `keys` ([`Project::set_speed_ramp`]). Reseeks like
4495 /// [`set_speed`](Self::set_speed), and the playhead holds where it stood.
4496 pub fn set_speed_ramp(
4497 &mut self,
4498 lane: Lane,
4499 idx: usize,
4500 keys: &[crate::project::SpeedKey],
4501 ) -> crate::Result<()> {
4502 self.project.set_speed_ramp(lane, idx, keys)?;
4503 let now = self.now();
4504 self.seek(now);
4505 Ok(())
4506 }
4507
4508 /// [`set_speed`](Self::set_speed) without the undo step -- the samples inside
4509 /// one drag ([`Project::set_speed_live`]). Reseeks like the committing one,
4510 /// which is what makes the bar move the picture under the hand.
4511 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
4512 // The mapping on every sample, not just at the commit: the bar moves
4513 // the rate live, and the scene has to stay put across the whole
4514 // gesture or the last picture before the release is not the one the
4515 // commit lands on.
4516 let at = self.project.speeded_playhead(
4517 lane,
4518 idx,
4519 speed,
4520 secs_to_frame(self.now(), self.meta.frame_rate),
4521 );
4522 self.project.set_speed_live(lane, idx, speed)?;
4523 let now = at.map_or_else(
4524 || self.now(),
4525 |frame| f64::from(frame) / self.meta.frame_rate,
4526 );
4527 self.seek(now);
4528 Ok(())
4529 }
4530
4531 /// The picture's source frame at `timeline_secs`: which source, and which
4532 /// frame of it -- the composite a viewer is looking at, through the same
4533 /// span math the decoder walks. What a test asks to prove a reseek kept
4534 /// the scene, and nothing in the editor itself reads.
4535 pub fn video_source_frame_at(&self, timeline_secs: f64) -> Option<(usize, u32)> {
4536 crate::export::stack_span_at(&self.project.render_view(), secs_to_frame(timeline_secs, self.meta.frame_rate))
4537 .and_then(|s| s.from)
4538 }
4539
4540 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
4541 /// together to keep every media take crossing it in sync
4542 /// ([`Project::gap_take_scope`]) -- what a right-click on empty bench
4543 /// space asks before offering to close it. Subtitle gaps stay on their own
4544 /// lane because captions are not A/V take halves.
4545 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
4546 self.project.gap_take_scope(lane, start, frames)
4547 }
4548
4549 /// Closes every bounded gap on one lane. Media lanes keep linked takes
4550 /// whole when the other half has the matching empty stretch and report the
4551 /// gaps that were not safe to close; subtitle lanes ripple captions only.
4552 pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> {
4553 let report = self.project.close_all_gaps_on_lane(lane)?;
4554 if report.closed > 0 {
4555 let now = self.now();
4556 self.seek(now);
4557 }
4558 Ok(report)
4559 }
4560
4561 /// Cuts every one of `regions` -- `(start, len)` in timeline frames -- out
4562 /// of the lanes in `scope` and closes each hole, as **one** edit
4563 /// ([`Project::cut_regions`]): the jumpcut a silence scan
4564 /// ([`crate::silence`]) asks for, one undo press however many silences it
4565 /// found. A lane outside `scope` does not move. Reseeks like every other
4566 /// edit, so what plays is the cut timeline from the playhead on. The `Err`
4567 /// names what is in the way and nothing changes.
4568 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
4569 // Spelled out rather than through `edit`, whose closure hands back a
4570 // bool and would drop the refusal's own words.
4571 self.project.cut_regions(regions, scope)?;
4572 let now = self.now();
4573 self.seek(now);
4574 Ok(())
4575 }
4576
4577 /// Plays every one of those regions at `speed` instead of cutting them,
4578 /// closing the room each one no longer needs ([`Project::speed_regions`]) --
4579 /// one edit, one undo press, and the same scope rule. The `Err` names the
4580 /// lane and frame in the way and nothing changes.
4581 pub fn speed_regions(
4582 &mut self,
4583 regions: &[(u32, u32)],
4584 speed: Speed,
4585 scope: &[Lane],
4586 ) -> crate::Result<()> {
4587 self.project.speed_regions(regions, speed, scope)?;
4588 let now = self.now();
4589 self.seek(now);
4590 Ok(())
4591 }
4592
4593 // The length of each source on a picture lane and on an audio lane
4594 // ([`wall_table`]): a linked take drags both edges together, so a trim
4595 // measures each lane's members against that lane's own length.
4596
4597 /// Where that edge may land, `(first, last)` timeline frame inclusive: what
4598 /// a drag clamps the pointer to so the box it draws is the box
4599 /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
4600 pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
4601 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4602 self.project.trim_room_with_walls(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound })
4603 }
4604
4605 /// [`trim_room`](Self::trim_room) with the walls named: which of the two is
4606 /// the source's media limit, so a drag that stops there can say so. `None`
4607 /// for a bad index.
4608 pub fn trim_walls(&self, lane: Lane, idx: usize, edge: Edge) -> Option<TrimWalls> {
4609 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4610 self.project.trim_walls_with_walls(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound })
4611 }
4612
4613 /// [`trim_walls`](Self::trim_walls) with each wall's bound named
4614 /// ([`Project::trim_bounds`]): the source, a neighbour at a frame, the
4615 /// timeline's first frame, a clip's minimum length or a still's cap. Asked
4616 /// before a trim, so the names are for the walls the trim is measured to.
4617 /// `None` for a bad index.
4618 pub fn trim_bounds(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(WallBound, WallBound)> {
4619 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4620 self.project
4621 .trim_bounds(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound })
4622 }
4623
4624 /// Records how long a source is and what rate it was shot at, for a source
4625 /// index that may be one `Project::import` just made or one it handed back.
4626 /// See [`Self::counts`] and [`Self::rates`], which are one table in two
4627 /// vectors and grow together.
4628 fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) {
4629 if source == self.counts.len() {
4630 self.counts.push(frames);
4631 self.rates.push(rate);
4632 }
4633 debug_assert_eq!(self.counts.len(), self.project.sources().len());
4634 debug_assert_eq!(self.rates.len(), self.counts.len());
4635 // A source just joined, which is the one moment the session's audio
4636 // device may need arming ([`Self::arm_audio`]).
4637 self.arm_audio();
4638 }
4639
4640 /// Opens the audio device for the first source in the library that has a
4641 /// track, when this session has none.
4642 ///
4643 /// A session opened silent -- its first file carried no sound, so
4644 /// [`Self::open_library`]/[`Self::open`] had no track to open a device on
4645 /// -- must not stay silent once a source *with* sound joins it: every later
4646 /// clip's audio would go unheard for the rest of the session. That is
4647 /// exactly what the walk [`Self::open_project`] makes at open prevents for
4648 /// a loaded project (c581d41); this is the same walk at the add door, and
4649 /// [`Self::note_frames`] is the one place a source joins.
4650 ///
4651 /// A no-op once a device is open, so it costs a scan of `is_some` on every
4652 /// later import. The clock stays on wall time until the next seek
4653 /// ([`Self::seek`]'s own `switch_to_audio`), which is the seek a front-end
4654 /// makes as it places the file it just imported.
4655 fn arm_audio(&mut self) {
4656 // A device that is there but *dead* is not a device: the walk below
4657 // opens another one, which is also what clears the notice a death put up
4658 // ([`Self::tick`]).
4659 let carried = self
4660 .audio
4661 .as_ref()
4662 .map(|audio| audio.gain.load(Ordering::Acquire));
4663 if let Some(audio) = &self.audio
4664 && !audio.died.load(Ordering::Acquire)
4665 {
4666 return;
4667 }
4668 for source in self
4669 .project
4670 .sources()
4671 .iter()
4672 .filter(|s| !crate::is_image(&s.path))
4673 {
4674 let (audio, disabled) = open_audio(&source.path, source.audio_stream);
4675 if let Some(audio) = audio {
4676 // The device is being replaced under a session that may already
4677 // be running at a level the user chose, so that level comes
4678 // across with it ([`Audio::gain`]) rather than the fresh
4679 // stream's 1.0.
4680 if let Some(bits) = carried {
4681 audio.gain.store(bits, Ordering::Release);
4682 audio.ao.lock().unwrap().set_volume(f32::from_bits(bits));
4683 }
4684 self.audio = Some(audio);
4685 self.audio_disabled = disabled;
4686 return;
4687 }
4688 }
4689 }
4690
4691 /// Opens the output again for a stream that died, at the rate and channel
4692 /// count it carried, and clears the flag that stopped the session feeding.
4693 ///
4694 /// An output that goes away -- a PipeWire daemon restarting, a sink node
4695 /// removed and put back -- leaves every stream that was open on it dead for
4696 /// good: its position is frozen, so the clock can only fall to wall time, and
4697 /// a session that never opens another device is silent for the rest of its
4698 /// life, through every seek and every pause/play, with nothing said about it.
4699 ///
4700 /// The device *only*, never the file: the feeder is [`Self::start_audio`]'s,
4701 /// at the seek that follows. That is what lets [`Self::tick`] call this too,
4702 /// once a frame -- a tick is not a seek and must not reseek the timeline. The
4703 /// clock is on wall time by then and stays there until a seek comes, which is
4704 /// the seek whose feeder opens in step with the picture.
4705 ///
4706 /// `if_idle_for` is the cooldown: a tick passes [`AUDIO_REARM_AFTER`], because
4707 /// sixty opens a second against a device that is gone for good is a spin; a
4708 /// seek passes zero, because that one is a person asking.
4709 ///
4710 /// `false` when there is nothing to open, nothing came back, or the cooldown
4711 /// has not passed -- and the flag stays standing for the next attempt.
4712 fn rearm_audio(&mut self, if_idle_for: Duration) -> bool {
4713 let Some(audio) = &self.audio else {
4714 return false;
4715 };
4716 if !audio.died.load(Ordering::Acquire) {
4717 return true;
4718 }
4719 {
4720 let mut at = audio.rearm_at.lock().unwrap();
4721 if at.is_some_and(|at| at.elapsed() < if_idle_for) {
4722 return false;
4723 }
4724 *at = Some(Instant::now());
4725 }
4726 let Some(ao) = AoSession::open(audio.sample_rate, audio.channels as u32) else {
4727 return false;
4728 };
4729 // A stream comes up streaming and a session starts paused: the fresh one
4730 // is silenced until the seek that feeds it says otherwise, which is the
4731 // same two steps [`open_audio`] takes on the way in.
4732 ao.set_active(false);
4733 // A fresh stream comes up at full volume, so the level this session was
4734 // already running at is put back onto it before it is installed: a
4735 // muted session that lost its device to a daemon restart would
4736 // otherwise come back loud while the window still reads "muted".
4737 ao.set_volume(f32::from_bits(audio.gain.load(Ordering::Acquire)));
4738 // Replacing the session is what closes the dead stream, so it is done
4739 // under the device lock the feeder writes through.
4740 *audio.ao.lock().unwrap() = ao;
4741 // The clock anchor and the played-out arithmetic both belong to the
4742 // stream that died: the new one stamps its own first sample
4743 // ([`Audio::content_at`]), and `start_audio` re-bases the count from the
4744 // device's own position.
4745 audio.content_at.store(-1, Ordering::Release);
4746 audio.died.store(false, Ordering::Release);
4747 if self.audio_disabled.as_deref() == Some(AUDIO_LOST) {
4748 self.audio_disabled = None;
4749 }
4750 true
4751 }
4752
4753 /// The rate noted for whichever source plays `path`, by
4754 /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however
4755 /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session
4756 /// has never taken in.
4757 fn file_rate(&self, path: &Path) -> Rate {
4758 self.source_of(path)
4759 .map_or(Rate::REAL_TIME, |i| self.rates[i])
4760 }
4761
4762 /// Which file this source's **picture** is decoded from: its stand-in when
4763 /// the project is cut on stand-ins and one has been made for it, and the
4764 /// film itself in every other case ([`crate::proxy`]).
4765 ///
4766 /// One `stat` per span open, against a decoder open that costs milliseconds
4767 /// -- so a proxy that appeared (or was deleted) since the last seek is
4768 /// picked up at this one, and no table of attachments exists to disagree
4769 /// with the cache.
4770 ///
4771 /// The sound never comes through here: [`open_audio`] is given the
4772 /// project's own source path, so a mix is the film's however this answers.
4773 pub fn picture_path(&self, source: usize) -> PathBuf {
4774 let path = &self.project.sources()[source].path;
4775 let Some(proxy) = self.proxies.then(|| crate::proxy::cached(path)).flatten() else {
4776 return path.clone();
4777 };
4778 // Said out loud, once per span opened, because "the picture came off
4779 // the stand-in and the delivery did not" is a claim somebody has to be
4780 // able to check: `export` prints the file *it* reads by the same rule.
4781 eprintln!("picture: proxy {}", proxy.display());
4782 proxy
4783 }
4784
4785 /// Whether the picture comes off the stand-ins ([`Self::set_proxies`]).
4786 pub fn proxies(&self) -> bool {
4787 self.proxies
4788 }
4789
4790 /// Cut on the stand-ins, or on the films themselves. Reseeks, so the very
4791 /// next picture comes from the other file -- which is what makes this a
4792 /// switch a person can flip while watching.
4793 ///
4794 /// Says nothing about *which* films have one: a source with no stand-in
4795 /// keeps playing its own pictures either way, and one made while this is on
4796 /// is picked up at the next seek.
4797 ///
4798 /// One undo step ([`Project::push_settings_step`]), and the seek below is
4799 /// what makes the undo of it land on the picture: it reopens the span
4800 /// through [`picture_path`](Self::picture_path), which reads this switch.
4801 pub fn set_proxies(&mut self, on: bool) {
4802 if self.proxies == on {
4803 return;
4804 }
4805 let from = self.settings_value();
4806 self.proxies = on;
4807 self.step_settings(from);
4808 let now = self.now();
4809 self.seek(now);
4810 }
4811
4812 /// Which encoder an export of this project would open its picture on
4813 /// ([`crate::export::EncoderSeat`]). What a front-end puts into the
4814 /// [`ExportSettings`](crate::export::ExportSettings) it starts an export
4815 /// with -- and what the export card shows -- so the pick, the prediction
4816 /// and the file are one answer.
4817 pub fn encoder_seat(&self) -> crate::export::EncoderSeat {
4818 self.encoder_seat
4819 }
4820
4821 /// Gives a loaded project the window's seat when it carries none of its own: nobody
4822 /// picked it, so it is no undo step. Its own copy of the settings is kept in step with
4823 /// the session, as [`Self::set_encoder_seat`] keeps it, and nothing else moves.
4824 pub fn default_encoder_seat(&mut self, seat: crate::export::EncoderSeat) {
4825 if self.encoder_seat == seat {
4826 return;
4827 }
4828 self.encoder_seat = seat;
4829 self.project.mirror_settings(self.settings_value());
4830 }
4831
4832 /// Pick the seat. Nothing to reseek and nothing to re-probe here: this
4833 /// decides what an *export* opens, never what plays. One undo step, like
4834 /// every other pick on the project.
4835 pub fn set_encoder_seat(&mut self, seat: crate::export::EncoderSeat) {
4836 if self.encoder_seat == seat {
4837 return;
4838 }
4839 let from = self.settings_value();
4840 self.encoder_seat = seat;
4841 self.step_settings(from);
4842 }
4843
4844 /// The rate this project's mix was picked to run at
4845 /// ([`Self::set_sample_rate`]), or `None` for the rate the first audio
4846 /// source derives it to.
4847 pub fn sample_rate(&self) -> Option<u32> {
4848 self.sample_rate
4849 }
4850
4851 /// Pick the mix's own rate, overriding the derived one. Nothing to reseek
4852 /// here: it takes effect at the next audio rebuild (a seek, an edit, a
4853 /// reopen), not on the device already playing. One undo step, like every
4854 /// other pick on the project.
4855 pub fn set_sample_rate(&mut self, rate: Option<u32>) {
4856 if self.sample_rate == rate {
4857 return;
4858 }
4859 let from = self.settings_value();
4860 self.sample_rate = rate;
4861 self.step_settings(from);
4862 }
4863
4864 /// Whether an imported film that wants a stand-in gets one made for it
4865 /// there and then ([`Self::set_auto_proxies`]).
4866 pub fn auto_proxies(&self) -> bool {
4867 self.auto_proxies
4868 }
4869
4870 /// Make the stand-ins on import, or make none until asked. Nothing to
4871 /// reseek: this decides what is *started*, never what is decoded -- a proxy
4872 /// already in the cache is still cut on while [`Self::proxies`] is on.
4873 ///
4874 /// One undo step, like every other switch on the project.
4875 pub fn set_auto_proxies(&mut self, on: bool) {
4876 if self.auto_proxies == on {
4877 return;
4878 }
4879 let from = self.settings_value();
4880 self.auto_proxies = on;
4881 self.step_settings(from);
4882 }
4883
4884 /// Which source `path` is, canonicalising only if it has to: a source's own
4885 /// path is canonical ([`Source::new`]), so a caller handing one back from
4886 /// [`sources`](Self::sources) -- which is every library row -- hits on the
4887 /// first walk and never pays for the `canonicalize` syscall the second one
4888 /// makes. One rule, so a path that names a length names a rate too.
4889 fn source_of(&self, path: &Path) -> Option<usize> {
4890 let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted);
4891 at(path).or_else(|| at(&Source::new(path, 0).path))
4892 }
4893
4894 /// How long the whole of `path` is, in timeline frames: the length noted
4895 /// when it became a source, so a file sitting in the library with no clip
4896 /// anywhere still knows how much of itself there is to place. `0` for a
4897 /// file this session has never taken in.
4898 ///
4899 /// By path and not by stream, because a file is one length however many
4900 /// audio tracks it carries -- the picture's frame count for an mp4, the
4901 /// playing time for a song.
4902 pub fn file_frames(&self, path: &Path) -> u32 {
4903 self.source_of(path).map_or(0, |i| self.counts[i])
4904 }
4905
4906 /// What rate the file at `path` was *shot* at, in frames per second -- which
4907 /// is the timeline's own rate for every source that shares it, and is not
4908 /// for one placed at another ([`Rate`]). By path like
4909 /// [`file_frames`](Self::file_frames), and the timeline's rate for a file
4910 /// this session has never taken in (and for a still and a song, which were
4911 /// shot at no rate at all).
4912 ///
4913 /// What a library row names the file with: the timeline's rate there would
4914 /// be a lie about a 23.976 fps file the moment one can join.
4915 pub fn file_fps(&self, path: &Path) -> f64 {
4916 self.file_rate(path).as_f64() * self.meta.frame_rate
4917 }
4918
4919 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
4920 /// on and its index there, by the same topmost-lane-wins rule the decoder
4921 /// follows. `None` over a gap and past the end. What a card that grades
4922 /// "this clip" opens on when nothing has been clicked.
4923 pub fn video_clip_at(&self, timeline_secs: f64) -> Option<(Lane, usize)> {
4924 self.project
4925 .composite_clip_at(secs_to_frame(timeline_secs, self.meta.frame_rate))
4926 }
4927
4928 /// Which clip of `lane` sits at `timeline_secs`, by the same rule
4929 /// [`video_clip_at`](Self::video_clip_at) picks the picture's with -- per
4930 /// lane, so a keyboard walking the lanes for something to select asks the
4931 /// engine rather than re-deriving where a clip ends.
4932 pub fn lane_clip_at(&self, lane: Lane, timeline_secs: f64) -> Option<usize> {
4933 self.project
4934 .lane_clip_at(lane, secs_to_frame(timeline_secs, self.meta.frame_rate))
4935 }
4936
4937 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
4938 /// as it was shot -- what a colour card reads when it opens.
4939 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
4940 self.project.color_of(lane, idx)
4941 }
4942
4943 /// Grades that clip, or takes the grade off with `None`. One undo step like
4944 /// every other edit, and it reseeks like one too -- which is what puts the
4945 /// new grade on the frame that is already on screen, paused or playing,
4946 /// without the caller having to nudge the playhead itself. `false` for an
4947 /// index that is not there and for a value that is not finite.
4948 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
4949 self.edit(Dirty::Picture, |p| p.set_color(lane, idx, params))
4950 }
4951
4952 /// The same grade and the same reseek without the undo step
4953 /// ([`Project::set_color_live`]): what the samples inside one slider drag go
4954 /// through, so the frame regrades under the hand and the whole gesture is
4955 /// still a single `z`.
4956 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
4957 self.edit(Dirty::Picture, |p| p.set_color_live(lane, idx, params))
4958 }
4959
4960 /// [`Project::lut_problems`]: the `.cube` files clips name that cannot be used, and why.
4961 pub fn lut_problems(&self) -> Vec<(PathBuf, String)> {
4962 self.project.lut_problems()
4963 }
4964
4965 /// [`Project::luts`]: every `.cube` file a clip's grade names.
4966 pub fn luts(&self) -> Vec<crate::cube::LutRef> {
4967 self.project.luts()
4968 }
4969
4970 /// [`Project::relink_lut`], with the reseek every picture edit makes.
4971 pub fn relink_lut(&mut self, from: &std::path::Path, to: &std::path::Path) -> usize {
4972 let mut n = 0;
4973 self.edit(Dirty::Picture, |p| {
4974 n = p.relink_lut(from, to);
4975 n > 0
4976 });
4977 n
4978 }
4979
4980 /// Where the clip at `idx` of `lane` is placed -- [`color_of`](Self::color_of)'s
4981 /// twin for geometry instead of grade.
4982 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
4983 self.project.transform_of(lane, idx)
4984 }
4985
4986 /// Moves/scales/rotates/crops that clip, or takes the placement off with
4987 /// `None` -- [`set_color`](Self::set_color)'s twin, one undo step and one
4988 /// reseek.
4989 pub fn set_transform(
4990 &mut self,
4991 lane: Lane,
4992 idx: usize,
4993 params: Option<TransformParams>,
4994 ) -> bool {
4995 self.edit(Dirty::Picture, |p| p.set_transform(lane, idx, params))
4996 }
4997
4998 /// The placement animation of the clip at `idx` of `lane`, in source order
4999 /// ([`Project::transform_keys_of`]).
5000 pub fn transform_keys_of(&self, lane: Lane, idx: usize) -> &[crate::transform::TransformKey] {
5001 self.project.transform_keys_of(lane, idx)
5002 }
5003
5004 /// Replaces the clip's placement animation, or clears it with an empty list
5005 /// ([`Project::set_transform_keys`]). One undo step and one reseek.
5006 pub fn set_transform_keys(
5007 &mut self,
5008 lane: Lane,
5009 idx: usize,
5010 keys: Vec<crate::transform::TransformKey>,
5011 ) -> bool {
5012 self.edit(Dirty::Picture, |p| p.set_transform_keys(lane, idx, keys))
5013 }
5014
5015 /// The opacity animation of the clip at `idx` of `lane`, in source order
5016 /// ([`Project::opacity_keys_of`]).
5017 pub fn opacity_keys_of(&self, lane: Lane, idx: usize) -> &[crate::transform::OpacityKey] {
5018 self.project.opacity_keys_of(lane, idx)
5019 }
5020
5021 /// Replaces the clip's opacity animation, or clears it with an empty list
5022 /// ([`Project::set_opacity_keys`]). One undo step and one reseek.
5023 pub fn set_opacity_keys(
5024 &mut self,
5025 lane: Lane,
5026 idx: usize,
5027 keys: Vec<crate::transform::OpacityKey>,
5028 ) -> bool {
5029 self.edit(Dirty::Picture, |p| p.set_opacity_keys(lane, idx, keys))
5030 }
5031
5032 /// The colour animation of the clip at `idx` of `lane`, in source order
5033 /// ([`Project::color_keys_of`]).
5034 pub fn color_keys_of(&self, lane: Lane, idx: usize) -> &[crate::color::ColorKey] {
5035 self.project.color_keys_of(lane, idx)
5036 }
5037
5038 /// Replaces the clip's colour animation, or clears it with an empty list
5039 /// ([`Project::set_color_keys`]). One undo step and one reseek.
5040 pub fn set_color_keys(
5041 &mut self,
5042 lane: Lane,
5043 idx: usize,
5044 keys: Vec<crate::color::ColorKey>,
5045 ) -> bool {
5046 self.edit(Dirty::Picture, |p| p.set_color_keys(lane, idx, keys))
5047 }
5048
5049 /// The effects stack of the clip at `idx` of `lane` ([`Project::effects_of`]).
5050 pub fn effects_of(&self, lane: Lane, idx: usize) -> &[crate::effects::Effect] {
5051 self.project.effects_of(lane, idx)
5052 }
5053
5054 /// The keys of the effect at stack position `slot` ([`Project::effect_keys_of`]).
5055 pub fn effect_keys_of(&self, lane: Lane, idx: usize, slot: usize) -> &[crate::effects::EffectKey] {
5056 self.project.effect_keys_of(lane, idx, slot)
5057 }
5058
5059 /// Replaces the keys of the effect at stack position `slot`, or clears them with an
5060 /// empty list ([`Project::set_effect_keys`]). One undo step and one reseek.
5061 pub fn set_effect_keys(&mut self, lane: Lane, idx: usize, slot: usize, keys: Vec<crate::effects::EffectKey>) -> bool {
5062 self.edit(Dirty::Picture, |p| p.set_effect_keys(lane, idx, slot, keys))
5063 }
5064
5065 /// Replaces the clip's effects stack ([`Project::set_effects`]). One undo
5066 /// step and one reseek.
5067 pub fn set_effects(&mut self, lane: Lane, idx: usize, effects: Vec<crate::effects::Effect>) -> bool {
5068 self.edit(Dirty::Picture, |p| p.set_effects(lane, idx, effects))
5069 }
5070
5071 /// [`Project::key_source_frame`].
5072 pub fn key_source_frame(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<u32> {
5073 self.project.key_source_frame(lane, idx, timeline_frame)
5074 }
5075
5076 /// [`Project::is_keyed`].
5077 pub fn is_keyed(&self, lane: Lane, idx: usize, kind: crate::project::KeyKind) -> bool {
5078 self.project.is_keyed(lane, idx, kind)
5079 }
5080
5081 /// [`Project::key_ease_at`].
5082 pub fn key_ease_at(
5083 &self,
5084 lane: Lane,
5085 idx: usize,
5086 kind: crate::project::KeyKind,
5087 timeline_frame: u32,
5088 ) -> Option<crate::transform::KeyEase> {
5089 self.project.key_ease_at(lane, idx, kind, timeline_frame)
5090 }
5091
5092 /// The stopwatch ([`Project::toggle_key`]). One undo step and one reseek.
5093 pub fn toggle_key(
5094 &mut self,
5095 lane: Lane,
5096 idx: usize,
5097 kind: crate::project::KeyKind,
5098 timeline_frame: u32,
5099 ) -> Option<bool> {
5100 let mut out = None;
5101 self.edit(Dirty::Picture, |p| {
5102 out = p.toggle_key(lane, idx, kind, timeline_frame);
5103 out.is_some()
5104 });
5105 out
5106 }
5107
5108 /// [`Project::set_key_ease_at`]. One undo step and one reseek.
5109 pub fn set_key_ease_at(
5110 &mut self,
5111 lane: Lane,
5112 idx: usize,
5113 kind: crate::project::KeyKind,
5114 timeline_frame: u32,
5115 ease: crate::transform::KeyEase,
5116 ) -> bool {
5117 self.edit(Dirty::Picture, |p| p.set_key_ease_at(lane, idx, kind, timeline_frame, ease))
5118 }
5119
5120 /// [`Project::put_transform_key_at`]; `snapshot` false is the live write of a drag.
5121 pub fn put_transform_key_at(
5122 &mut self,
5123 lane: Lane,
5124 idx: usize,
5125 timeline_frame: u32,
5126 params: TransformParams,
5127 snapshot: bool,
5128 ) -> bool {
5129 self.edit(Dirty::Picture, |p| p.put_transform_key_at(lane, idx, timeline_frame, params, snapshot))
5130 }
5131
5132 /// [`Project::put_opacity_key_at`]; `snapshot` false is the live write of a drag.
5133 pub fn put_opacity_key_at(
5134 &mut self,
5135 lane: Lane,
5136 idx: usize,
5137 timeline_frame: u32,
5138 opacity: f32,
5139 snapshot: bool,
5140 ) -> bool {
5141 self.edit(Dirty::Picture, |p| p.put_opacity_key_at(lane, idx, timeline_frame, opacity, snapshot))
5142 }
5143
5144 /// [`Project::put_color_key_at`]; `snapshot` false is the live write of a drag.
5145 pub fn put_color_key_at(
5146 &mut self,
5147 lane: Lane,
5148 idx: usize,
5149 timeline_frame: u32,
5150 params: ColorParams,
5151 snapshot: bool,
5152 ) -> bool {
5153 self.edit(Dirty::Picture, |p| p.put_color_key_at(lane, idx, timeline_frame, params, snapshot))
5154 }
5155
5156 /// The placement the clip shows at timeline `timeline_frame`, keys evaluated
5157 /// ([`Project::transform_at`]).
5158 pub fn transform_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<TransformParams> {
5159 self.project.transform_at(lane, idx, timeline_frame)
5160 }
5161
5162 /// The grade the clip shows at `timeline_frame`, keys evaluated ([`Project::color_at`]).
5163 pub fn color_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<ColorParams> {
5164 self.project.color_at(lane, idx, timeline_frame)
5165 }
5166
5167 /// The opacity the clip shows at `timeline_frame`, keys evaluated, fades not
5168 /// counted ([`Project::opacity_at`]).
5169 pub fn opacity_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> f32 {
5170 self.project.opacity_at(lane, idx, timeline_frame)
5171 }
5172
5173 /// The same placement and the same reseek without the undo step
5174 /// ([`Project::set_transform_live`]) -- [`set_color_live`](Self::set_color_live)'s
5175 /// twin for a slider drag.
5176 pub fn set_transform_live(
5177 &mut self,
5178 lane: Lane,
5179 idx: usize,
5180 params: Option<TransformParams>,
5181 ) -> bool {
5182 self.edit(Dirty::Picture, |p| p.set_transform_live(lane, idx, params))
5183 }
5184
5185 /// The project's resolution: what every clip is composed onto, what the
5186 /// window is sized to and what an export writes -- *not* any one file's.
5187 /// It starts as source 0's picture, which is what a project meant before it
5188 /// could have a resolution of its own.
5189 pub fn resolution(&self) -> (u32, u32) {
5190 (self.meta.width, self.meta.height)
5191 }
5192
5193 /// Source 0's own picture size -- what the project resolution started as,
5194 /// and the one size a caller offering a list of them must not leave out.
5195 pub fn native_resolution(&self) -> (u32, u32) {
5196 self.native
5197 }
5198
5199 /// Sets it. Rebuilds the **picture** where the playhead is, so the frame on
5200 /// screen is recomposed at the new size at once, paused or playing -- and
5201 /// the sound is not touched at all: the size of the canvas is not something
5202 /// a sample can carry, so resizing a 4K film mid-play costs neither a hole
5203 /// in the audio nor an offset against it ([`Dirty`]). `false` for a size
5204 /// that is not a picture -- zero either way, or past 8K, which is where the
5205 /// per-frame buffers stop being a sane thing to allocate from a keystroke.
5206 ///
5207 /// One undo step: the resolution is the project's own, so it rides in the
5208 /// entry beside the lanes and a `z` takes the canvas back to the size it
5209 /// was ([`Project::push_settings_step`]).
5210 pub fn set_resolution(&mut self, width: u32, height: u32) -> bool {
5211 if !crate::is_resolution(width, height) {
5212 return false;
5213 }
5214 if (width, height) == (self.meta.width, self.meta.height) {
5215 return false;
5216 }
5217 let from = self.settings_value();
5218 self.meta.width = width;
5219 self.meta.height = height;
5220 self.step_settings(from);
5221 self.invalidate(Dirty::Picture);
5222 true
5223 }
5224
5225 /// Which HDR-to-SDR rendition this project is watched and exported in
5226 /// ([`crate::tonemap::Preset`]) -- the reference one until somebody picks
5227 /// another, and a setting on the project rather than on any clip.
5228 pub fn tone(&self) -> crate::tonemap::Preset {
5229 self.project.tone()
5230 }
5231
5232 /// The project's notes ([`Project::notes`]).
5233 pub fn notes(&self) -> &str {
5234 self.project.notes()
5235 }
5236
5237 /// Sets the project's notes ([`Project::set_notes`]): one undo step, `false` for the text
5238 /// already in force.
5239 pub fn set_notes(&mut self, notes: &str) -> bool {
5240 self.project.set_notes(notes)
5241 }
5242
5243 /// How long a still is placed for, in seconds ([`Project::still_secs`]).
5244 pub fn still_secs(&self) -> f64 {
5245 self.project.still_secs()
5246 }
5247
5248 /// Sets the still length ([`Project::set_still_secs`]): one undo step, `false` for the length
5249 /// already in force. Stills placed after this take it; clips already on the timeline keep theirs.
5250 pub fn set_still_secs(&mut self, secs: f64) -> bool {
5251 self.project.set_still_secs(secs)
5252 }
5253
5254 /// What source 0's own file declared about how bright it gets
5255 /// ([`ContentLight`]): a property of the film, read once at open, and
5256 /// entirely absent (every field `None`) for an SDR file, a song or a
5257 /// still. Read-only -- the number a file carries, never a project setting
5258 /// a user can override, since nothing in [`Project`] holds one to persist.
5259 pub fn content_light(&self) -> ContentLight {
5260 self.content_light
5261 }
5262
5263 /// Picks one. Rebuilds the **picture** where the playhead is, exactly as
5264 /// [`set_resolution`](Self::set_resolution) does -- the frame on screen is
5265 /// remapped at once, paused or playing, and the sound is not touched: a
5266 /// rendition is not something a sample can carry. `false` for the rendition
5267 /// already in force.
5268 ///
5269 /// An SDR project is unmoved by this by construction: no clip of it builds a
5270 /// tone map at all ([`crate::tonemap`]), so the reseek recomposes the very
5271 /// same bytes.
5272 ///
5273 /// corner-cut: not an undo step, for the reason the resolution is not
5274 /// ([`Project::set_tone`]).
5275 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
5276 if !self.project.set_tone(preset) {
5277 return false;
5278 }
5279 self.invalidate(Dirty::Picture);
5280 true
5281 }
5282
5283 /// The scaffolding source's own frame rate -- what the project rate started
5284 /// as, and the one rate a caller offering a list of them must not leave out
5285 /// ([`native_resolution`](Self::native_resolution)'s reason).
5286 pub fn native_frame_rate(&self) -> f64 {
5287 self.native_fps
5288 }
5289
5290 /// Cuts this timeline at `fps` from here on: every clip is *conformed* to
5291 /// the new rate ([`Project::retime`]), every source is read through a
5292 /// [`Rate`] against it, and an export written from this session comes out at
5293 /// it. The edit survives as the same seconds of the same footage on a finer
5294 /// or coarser grid -- a 30 fps take on a timeline moved to 24 keeps its
5295 /// length and its sync, it is simply counted in 24ths now.
5296 ///
5297 /// Reseeks like [`set_resolution`](Self::set_resolution), so the picture and
5298 /// the sound under the playhead are already the new rate's when this
5299 /// returns. `false` -- changing nothing -- for a rate that is not a rate, for
5300 /// the one already in force, and for one no timescale can name
5301 /// ([`crate::mux::frame_timing`], the same wall a file of an unnameable rate
5302 /// is refused at).
5303 ///
5304 /// One undo step, and the entry it takes is the whole of the change: the
5305 /// lanes as they were in the *old* rate's numbering, with that rate beside
5306 /// them, so a `z` restores the two together ([`Project::retime`]). The
5307 /// step is taken before the retime rather than after, since this is the one
5308 /// settings door that moves the lanes the step holds. Picking the old rate
5309 /// back is still within a frame of where it started rather than on it: the
5310 /// *lanes* come home exactly out of the entry, and the per-source lengths
5311 /// are the half that goes through the map twice
5312 /// ([`PlaybackSession::adopt_settings`]).
5313 pub fn set_frame_rate(&mut self, fps: f64) -> bool {
5314 if !fps.is_finite() || fps <= 0.0 || fps == self.meta.frame_rate || self.project.rate_locked() {
5315 return false;
5316 }
5317 // Old timeline frames per new one, exactly -- the one map every frame
5318 // number on every lane goes through. Built before anything is touched,
5319 // since a rate no timescale can name is a refusal and not a half-retimed
5320 // project.
5321 let Ok(k) = Rate::from_fps(self.meta.frame_rate, fps) else {
5322 return false;
5323 };
5324 let from = self.settings_value();
5325 self.project.push_settings_step(from.clone(), from);
5326 // Lengths first: the retime holds every clip inside its source's *new*
5327 // length, so a clip that played to the last frame of its file still
5328 // does rather than naming one past the end.
5329 for count in &mut self.counts {
5330 *count = k.timeline_nearest(*count).max(1);
5331 }
5332 self.project.retime(k, &self.counts);
5333 // A file's own rate has not changed; what it is *against* has.
5334 for rate in &mut self.rates {
5335 *rate = rate.then(k);
5336 }
5337 self.meta.frame_rate = fps;
5338 self.meta.frame_count = k.timeline_nearest(self.meta.frame_count).max(1);
5339 // The copy the project keeps, now that the change has landed: what the
5340 // next lane edit's entry carries.
5341 self.project.mirror_settings(self.settings_value());
5342 let now = self.now();
5343 self.seek(now);
5344 true
5345 }
5346
5347 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
5348 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
5349 self.project.fit_of(lane, idx)
5350 }
5351
5352 /// Sets that clip's fit policy. One undo step and a reseek, exactly like a
5353 /// grade: the picture on screen is recomposed through the new policy without
5354 /// the caller nudging the playhead. `false` for an index that is not there.
5355 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
5356 self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit))
5357 }
5358
5359 /// [`Project::set_stabilise`]. Reseeks like a grade. The analysis it needs is
5360 /// started in the background ([`Self::stabilise_start`]); until it is done the
5361 /// clip plays as it is.
5362 pub fn set_stabilise(&mut self, lane: Lane, idx: usize, st: Option<crate::stabilise::Stabilise>) -> bool {
5363 let done = self.edit(Dirty::Picture, |p| p.set_stabilise(lane, idx, st));
5364 if done && st.is_some() {
5365 self.stabilise_start(lane, idx);
5366 }
5367 done
5368 }
5369
5370 /// The generator of kind `name` ([`crate::generate::KINDS`]) at its defaults, drawn for this
5371 /// timeline's canvas and rate.
5372 pub fn generator_named(&self, name: &str) -> Option<crate::generate::Gen> {
5373 crate::generate::Gen::named(name, self.meta.width, self.meta.height, self.meta.frame_rate)
5374 }
5375
5376 /// Places a generated clip ([`crate::generate`]) `secs` long on the video lane `onto` (`V1`
5377 /// when none), at `timeline_secs`, like a still. A countdown with no length asked for runs
5378 /// its own count. Overwrites what the stretch lands on, as a still does. `false` when the
5379 /// lane or the place is refused.
5380 pub fn place_generated(&mut self, spec: crate::generate::Gen, timeline_secs: f64, secs: Option<f64>, onto: Option<Lane>) -> crate::Result<bool> {
5381 let fps = self.meta.frame_rate;
5382 let source = self.generator_source(spec);
5383 let secs = secs.unwrap_or(match spec.kind {
5384 crate::generate::Kind::Countdown { from, .. } => f64::from(from),
5385 _ => self.project.still_secs(),
5386 });
5387 let wall = self.counts[source];
5388 let out = ((secs * fps).round() as u32).clamp(1, wall.max(1));
5389 let lane = match onto {
5390 Some(lane) if lane.kind == LaneKind::Video => lane,
5391 Some(_) => return Err("a generated clip goes on a video lane".into()),
5392 None => Lane::V1,
5393 };
5394 if self.project.lane(lane).is_empty() && !self.project.lanes().contains(&lane) {
5395 return Err(format!("{lane:?} is not a lane of this timeline").into());
5396 }
5397 Ok(self.place_at(lane, timeline_secs, Clip::source_range(source, 0, out)))
5398 }
5399
5400 /// Places a test tone ([`crate::generate::Tone`]) `secs` long on the audio lane `onto` (`A1`
5401 /// when none), at `timeline_secs`, as a sound file's stream is placed. The tone's file is made
5402 /// in `dir` the first time (the project's folder for a saved project, else the data folder).
5403 /// `false` when the place is refused.
5404 pub fn place_tone(&mut self, tone: crate::generate::Tone, timeline_secs: f64, secs: u32, onto: Option<Lane>, dir: &std::path::Path) -> crate::Result<bool> {
5405 let path = tone.write(dir, secs)?;
5406 let lane = match onto {
5407 Some(lane) if lane.kind == LaneKind::Audio => lane,
5408 Some(_) => return Err("a tone goes on an audio lane".into()),
5409 None => Lane::A1,
5410 };
5411 // A tone is a standalone audio file: taken into the library the first time it is
5412 // placed (as a song is), so the placement below finds it.
5413 if self.file_frames(&path) == 0 {
5414 self.import(&path)?;
5415 }
5416 self.place_stream_at(timeline_secs, &path, 0, Some(lane))
5417 }
5418
5419 /// The source index of `spec`, taken into the library the first time it is used.
5420 fn generator_source(&mut self, spec: crate::generate::Gen) -> usize {
5421 let source = self.project.import(spec.path(), 0);
5422 self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME);
5423 source
5424 }
5425
5426 /// Changes the generator the clip at `idx` of `lane` is, keeping its place and length.
5427 /// One undo step; `false` for a clip that is not there or no change.
5428 pub fn set_generator(&mut self, lane: Lane, idx: usize, spec: crate::generate::Gen) -> bool {
5429 let source = self.generator_source(spec);
5430 self.edit(Dirty::Picture, |p| p.set_clip_source(lane, idx, source))
5431 }
5432
5433 /// The generator the clip at `idx` of `lane` is, `None` for a clip made from a file.
5434 pub fn generator_of(&self, lane: Lane, idx: usize) -> Option<crate::generate::Gen> {
5435 let src = self.project.sources().get(self.project.lane(lane).get(idx)?.source)?;
5436 crate::generate::Gen::parse(&src.path)
5437 }
5438
5439 /// [`Project::set_label`].
5440 pub fn set_label(&mut self, lane: Lane, idx: usize, label: u8) -> bool {
5441 self.project.set_label(lane, idx, label)
5442 }
5443
5444 /// [`Project::set_enabled`]: a switched-off clip is skipped by picture and sound.
5445 pub fn set_enabled(&mut self, lane: Lane, idx: usize, enabled: bool) -> bool {
5446 self.edit(Dirty::Both, |p| p.set_enabled(lane, idx, enabled))
5447 }
5448
5449 /// [`Project::mark_of`].
5450 pub fn mark_of(&self, lane: Lane, idx: usize) -> crate::project::ClipMark {
5451 self.project.mark_of(lane, idx)
5452 }
5453
5454 /// [`Project::set_deinterlace`]. Stored only; the render reads it once the engine acts on it.
5455 pub fn set_deinterlace(&mut self, lane: Lane, idx: usize, mode: crate::project::Deinterlace) -> bool {
5456 self.project.set_deinterlace(lane, idx, mode)
5457 }
5458
5459 /// [`Project::deinterlace_of`].
5460 pub fn deinterlace_of(&self, lane: Lane, idx: usize) -> crate::project::Deinterlace {
5461 self.project.deinterlace_of(lane, idx)
5462 }
5463
5464 /// [`Project::stabilise_of`].
5465 pub fn stabilise_of(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Stabilise> {
5466 self.project.stabilise_of(lane, idx)
5467 }
5468
5469 /// The source and file-frame range the clip at `idx` of `lane` is analysed
5470 /// over, `None` for no clip or one that is not footage (a still, a song).
5471 pub fn stabilise_range(&self, lane: Lane, idx: usize) -> Option<(std::path::PathBuf, u32, u32)> {
5472 let c = self.project.lane(lane).get(idx)?;
5473 let path = &self.project.sources().get(c.source)?.path;
5474 if crate::is_image(path) || crate::is_audio(path) {
5475 return None;
5476 }
5477 let (lo, hi) = crate::stabilise::clip_range(path, c, self.meta.frame_rate);
5478 Some((path.clone(), lo, hi))
5479 }
5480
5481 /// Where the clip's stabilisation analysis stands ([`crate::stabilise::status`]).
5482 pub fn stabilise_status(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Status> {
5483 let (path, lo, hi) = self.stabilise_range(lane, idx)?;
5484 Some(crate::stabilise::status(&path, lo, hi))
5485 }
5486
5487 /// Starts the clip's stabilisation analysis in the background unless it is
5488 /// cached or running ([`crate::stabilise::start`]).
5489 pub fn stabilise_start(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Status> {
5490 let (path, lo, hi) = self.stabilise_range(lane, idx)?;
5491 Some(crate::stabilise::start(&path, lo, hi))
5492 }
5493
5494 /// Stops the clip's running analysis. `false` when none runs.
5495 pub fn stabilise_cancel(&self, lane: Lane, idx: usize) -> bool {
5496 self.stabilise_range(lane, idx).is_some_and(|(path, lo, hi)| crate::stabilise::cancel(&path, lo, hi))
5497 }
5498
5499 /// What auto reframe needs of the clip at `idx` of `lane`: its file range and the
5500 /// geometry its keys are made for ([`crate::reframe`]). `None` for no clip, a
5501 /// still or a song.
5502 pub fn reframe_job(&self, lane: Lane, idx: usize) -> Option<crate::reframe::ReframeJob> {
5503 let (path, lo, hi) = self.stabilise_range(lane, idx)?;
5504 let c = self.project.lane(lane).get(idx)?;
5505 let shown = crate::demux::Demuxer::open(&path).ok()?.0;
5506 let target = crate::reframe::Target {
5507 src_w: shown.width,
5508 src_h: shown.height,
5509 canvas_w: self.meta.width,
5510 canvas_h: self.meta.height,
5511 base: self.project.transform_of(lane, idx).copied().unwrap_or_default(),
5512 in_frame: c.in_frame,
5513 out_frame: c.out_frame,
5514 };
5515 Some(crate::reframe::ReframeJob { path, lo, hi, target })
5516 }
5517
5518 /// Writes reframe `keys` on the clip, and puts it on [`FitPolicy::Fit`] -- the
5519 /// placement they are made for. One undo step; `false` when the keys are refused.
5520 pub fn apply_reframe(&mut self, lane: Lane, idx: usize, keys: Vec<crate::transform::TransformKey>) -> bool {
5521 self.begin_batch();
5522 self.set_fit(lane, idx, FitPolicy::Fit);
5523 let done = self.set_transform_keys(lane, idx, keys);
5524 self.end_batch();
5525 done
5526 }
5527
5528 /// Redraws the picture once an analysis finished, so a stabilised clip shows
5529 /// its correction without an edit.
5530 pub fn stabilise_refresh(&mut self) {
5531 self.invalidate(Dirty::Picture);
5532 }
5533
5534 /// Starts following the rect or ellipse mask at stack position `slot` of the clip at
5535 /// `idx` of `lane` ([`crate::track`]) from source frame `from` to `to`, either order.
5536 /// The mask's centre at `from` is where the feature is; [`Self::track_mask_apply`]
5537 /// writes the path back once the track has finished.
5538 pub fn track_mask_start(&self, lane: Lane, idx: usize, slot: usize, from: u32, to: u32) -> Result<TrackJob, String> {
5539 use crate::effects::EffectKind;
5540 let c = self.project.lane(lane).get(idx).ok_or("there is no clip there")?;
5541 let e = c.effects.get(slot).ok_or("there is no effect in that stack position")?;
5542 if !matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask) {
5543 return Err("only a rect or ellipse mask can be tracked".into());
5544 }
5545 let (path, lo, hi) = self.stabilise_range(lane, idx).ok_or("a still or a song has no picture to track")?;
5546 let (from, to) = (from.clamp(lo, hi - 1), to.clamp(lo, hi - 1));
5547 if from == to {
5548 return Err("a track needs two frames: from and to are the same frame".into());
5549 }
5550 let forward = to > from;
5551 let range = if forward { (from, to + 1) } else { (to, from + 1) };
5552 let at = e.posed(f64::from(from));
5553 let (x, y) = (at.values[0], at.values[1]);
5554 let region = crate::track::Region { x, y, w: at.values[2], h: at.values[3] };
5555 // The placement the renderer gives the clip, so the track's points land on the canvas
5556 // where the mask is drawn: the base transform and its keys, on this canvas.
5557 let pose = crate::track::Pose {
5558 base: self.transform_of(lane, idx).copied().unwrap_or_default(),
5559 keys: self.transform_keys_of(lane, idx).to_vec(),
5560 canvas: self.resolution(),
5561 fit: crate::scale::FitPolicy::default(),
5562 };
5563 let id = crate::track::start(&path, range, from, forward, region, pose);
5564 Ok(TrackJob { lane, idx, slot, id, from, anchor: (x, y) })
5565 }
5566
5567 /// Writes every finished track in `jobs` onto its mask ([`Self::track_mask_apply`]) and
5568 /// takes it out of `jobs`; running ones stay. Each landing is one undo step. Returns one
5569 /// entry per track that ended.
5570 pub fn track_settle(&mut self, jobs: &mut Vec<TrackJob>) -> Vec<TrackDone> {
5571 let mut done = Vec::new();
5572 let mut running = Vec::new();
5573 for job in std::mem::take(jobs) {
5574 let result = match crate::track::status(job.id) {
5575 crate::track::Status::Running(_) => {
5576 running.push(job);
5577 continue;
5578 }
5579 crate::track::Status::Gone => continue,
5580 crate::track::Status::Finished => match crate::track::take(job.id) {
5581 None => continue,
5582 Some(Err(e)) => Err(e),
5583 Some(Ok(t)) => self.track_mask_apply(&job, &t).map(|keys| {
5584 let frames = t.points.iter().map(|p| p.0);
5585 TrackOutcome {
5586 keys,
5587 from: frames.clone().min().unwrap_or(job.from),
5588 to: frames.max().unwrap_or(job.from),
5589 lost_at: t.lost_at,
5590 }
5591 }),
5592 },
5593 };
5594 done.push(TrackDone { lane: job.lane, idx: job.idx, slot: job.slot, result });
5595 }
5596 *jobs = running;
5597 done
5598 }
5599
5600 /// Writes a finished track onto its mask: the mask's centre moves by the feature's
5601 /// displacement from where it was at the start, and its size and soft edge keep the
5602 /// values they have at each frame. Keys inside the tracked frames are replaced and
5603 /// keys outside them stay. Returns how many keys were written. One undo step.
5604 pub fn track_mask_apply(&mut self, job: &TrackJob, track: &crate::track::Track) -> Result<usize, String> {
5605 use crate::effects::EffectKey;
5606 use crate::track::{KEY_TOLERANCE, simplify};
5607 use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS};
5608 let Some(&(_, x0, y0)) = track.points.first() else {
5609 return Err("the track has no points".into());
5610 };
5611 let mut pts: Vec<(u32, f32, f32)> = track
5612 .points
5613 .iter()
5614 .map(|&(f, x, y)| (f, job.anchor.0 + x - x0, job.anchor.1 + y - y0))
5615 .collect();
5616 pts.sort_by_key(|p| p.0);
5617 let (first, last) = (pts[0].0, pts[pts.len() - 1].0);
5618 let outside: Vec<EffectKey> =
5619 self.effect_keys_of(job.lane, job.idx, job.slot).iter().filter(|k| k.at < first || k.at > last).copied().collect();
5620 let room = MAX_TRANSFORM_KEYS.saturating_sub(outside.len()).max(2);
5621 let mut tolerance = KEY_TOLERANCE;
5622 let mut kept = simplify(&pts, tolerance);
5623 while kept.len() > room {
5624 tolerance *= 2.0;
5625 kept = simplify(&pts, tolerance);
5626 }
5627 let mut keys = {
5628 let e = self
5629 .project
5630 .lane(job.lane)
5631 .get(job.idx)
5632 .and_then(|c| c.effects.get(job.slot))
5633 .ok_or("the mask is gone")?;
5634 kept.iter()
5635 .map(|&i| {
5636 let (f, x, y) = pts[i];
5637 let mut values = e.posed(f64::from(f)).values;
5638 values[0] = x;
5639 values[1] = y;
5640 EffectKey { at: f, values, ease: KeyEase::Linear }
5641 })
5642 .collect::<Vec<_>>()
5643 };
5644 keys.extend(outside);
5645 keys.sort_by_key(|k| k.at);
5646 let count = keys.len();
5647 if !self.set_effect_keys(job.lane, job.idx, job.slot, keys) {
5648 return Err("the engine refused the keys (is the mask still there?)".into());
5649 }
5650 Ok(count)
5651 }
5652
5653 /// Waveform flags on a visualizer clip. Reseeks like a grade: the
5654 /// painter reads them on the next picture.
5655 pub fn set_visualizer(&mut self, lane: Lane, idx: usize, flags: u8) -> bool {
5656 self.edit(Dirty::Picture, |p| p.set_visualizer(lane, idx, flags))
5657 }
5658
5659 pub fn set_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
5660 self.edit(Dirty::Picture, |p| p.set_viz_paint(lane, idx, paint))
5661 }
5662
5663 /// The same look and the same repaint without the undo step
5664 /// ([`Project::set_viz_paint_live`]): what the samples inside one drag
5665 /// across the colour wheel go through, so the picture follows the hand and
5666 /// the whole gesture is still a single `z`.
5667 pub fn set_viz_paint_live(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
5668 self.edit(Dirty::Picture, |p| p.set_viz_paint_live(lane, idx, paint))
5669 }
5670
5671 /// Timeline frames of ramp-up from silence at the start of the clip at
5672 /// `idx` of `lane`. `0` for an index that is not there.
5673 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
5674 self.project.fade_in_of(lane, idx)
5675 }
5676
5677 /// The volume envelope of the clip at `idx` of `lane`
5678 /// ([`Project::gain_keys_of`]).
5679 pub fn gain_keys_of(&self, lane: Lane, idx: usize) -> &[GainKey] {
5680 self.project.gain_keys_of(lane, idx)
5681 }
5682
5683 /// Replaces the clip's whole volume envelope ([`Project::set_gain_keys`]).
5684 /// A sound-only edit: no reseek of the picture.
5685 pub fn set_gain_keys(&mut self, lane: Lane, idx: usize, keys: Vec<GainKey>) -> bool {
5686 self.edit(Dirty::Sound, |p| p.set_gain_keys(lane, idx, keys))
5687 }
5688
5689 /// Puts one point into the clip's volume envelope ([`Project::add_gain_key`]).
5690 pub fn add_gain_key(&mut self, lane: Lane, idx: usize, key: GainKey) -> bool {
5691 self.edit(Dirty::Sound, |p| p.add_gain_key(lane, idx, key))
5692 }
5693
5694 /// Takes the point at source frame `at` out of the clip's volume envelope
5695 /// ([`Project::remove_gain_key`]).
5696 pub fn remove_gain_key(&mut self, lane: Lane, idx: usize, at: u32) -> bool {
5697 self.edit(Dirty::Sound, |p| p.remove_gain_key(lane, idx, at))
5698 }
5699
5700 /// The effective envelope dB at a timeline frame, keys and clip gain but not
5701 /// the fades ([`Project::gain_db_at`]).
5702 pub fn gain_db_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<f32> {
5703 self.project.gain_db_at(lane, idx, timeline_frame)
5704 }
5705
5706 /// Sets that clip's fade-in, clamped to its own length. A sound-only
5707 /// edit, same as an equalizer or a fader: no reseek needed.
5708 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5709 self.edit(Dirty::Sound, |p| p.set_fade_in(lane, idx, frames))
5710 }
5711
5712 /// Timeline frames of ramp-down to silence at the end of the clip at
5713 /// `idx` of `lane`. `0` for an index that is not there.
5714 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
5715 self.project.fade_out_of(lane, idx)
5716 }
5717
5718 /// Sets that clip's fade-out. Same promises as [`Self::set_fade_in`].
5719 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5720 self.edit(Dirty::Sound, |p| p.set_fade_out(lane, idx, frames))
5721 }
5722
5723 /// Crossfades the audio clip at `idx` of `lane` into its neighbour, over
5724 /// `frames`. Same promises as [`Project::crossfade`].
5725 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5726 self.edit(Dirty::Sound, |p| p.crossfade(lane, idx, frames))
5727 }
5728
5729 /// Timeline frames of dissolve at the end of the clip at `idx` of `lane`,
5730 /// into its neighbour. `0` for an index that is not there.
5731 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
5732 self.project.transition_out_of(lane, idx)
5733 }
5734
5735 /// The kind of the transition that clip plays into its neighbour.
5736 pub fn transition_kind_of(&self, lane: Lane, idx: usize) -> crate::transitions::TransitionKind {
5737 self.project.transition_kind_of(lane, idx)
5738 }
5739
5740 /// Sets that clip's transition into its neighbour, kind and length in one
5741 /// undo step. A picture edit, like [`Self::set_transition_out`].
5742 pub fn set_transition(
5743 &mut self,
5744 lane: Lane,
5745 idx: usize,
5746 kind: crate::transitions::TransitionKind,
5747 frames: u32,
5748 ) -> bool {
5749 self.edit(Dirty::Picture, |p| p.set_transition(lane, idx, kind, frames))
5750 }
5751
5752 /// Sets that clip's dissolve into its neighbour, clamped to its own
5753 /// length. A picture edit -- same as a grade or fit policy.
5754 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5755 self.edit(Dirty::Picture, |p| p.set_transition_out(lane, idx, frames))
5756 }
5757
5758 /// The clip at `idx` -- what a caller copies. It is a pair of source frame
5759 /// numbers and nothing else, so a copy stays valid after the clip it came
5760 /// from is deleted. `None` past the end.
5761 pub fn clip_at(&self, idx: usize) -> Option<Clip> {
5762 self.project.clips().get(idx).cloned()
5763 }
5764
5765 /// Inserts `clip` at the playhead, splitting the clip under it. Like a
5766 /// delete this moves every following frame, so the session reseeks; past
5767 /// the end of the timeline the clip is appended. One undo step.
5768 pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool {
5769 // The clipboard's own rule, and only the clipboard's: a paste past the
5770 // end is an append, never a clip with black in front of it. The frame
5771 // itself is honoured in [`Project::paste`], because a *drop* names a
5772 // place on the bed and means it.
5773 let at =
5774 secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames());
5775 let clip = self.held_to_take(clip);
5776 self.edit(Dirty::Both, |p| p.paste(at, clip))
5777 }
5778
5779 /// [`paste_at`](Self::paste_at)'s general form: [`Project::paste_set`]'s
5780 /// door, clamped to the timeline's own end the same way -- a set let go
5781 /// past the last frame lands there rather than carrying black in front of
5782 /// it, exactly as a lone clip's paste does.
5783 pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool {
5784 let at =
5785 secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames());
5786 // Each item is held to its own lane's wall, as a lone placement is.
5787 let items: Vec<(Lane, Clip)> = items
5788 .iter()
5789 .map(|(lane, clip)| (*lane, self.held_to_lane(*lane, clip.clone())))
5790 .collect();
5791 self.edit(Dirty::Both, |p| p.paste_set(at, &items))
5792 }
5793
5794 /// Places the whole of `path` played on its audio `stream` at
5795 /// `timeline_secs`, the way [`paste_at`](Self::paste_at) places a copy --
5796 /// the door a library row goes through, and the only way a stream other
5797 /// than the one an import brought in reaches the timeline. The `(file,
5798 /// stream)` pair becomes a source if it is not one already.
5799 ///
5800 /// Refused, changing nothing, unless that stream can join *this* timeline:
5801 /// same audio parameters as the first source, in the same words
5802 /// [`import`](Self::import) refuses a file with. One output device and one
5803 /// copied AAC track mean one *layout* for the whole timeline, so a mono
5804 /// track cannot join a stereo one. Its sample rate may be its own: the
5805 /// segment's resampler conforms it at the decoder's door.
5806 /// A front-end greys such a row out; this is the backstop that keeps a
5807 /// stale one from making the whole timeline silent.
5808 ///
5809 /// Which lane it lands on is decided here, from the file and from `onto` --
5810 /// the lane it was let go over, if it was let go over one at all: a file
5811 /// with a picture asked for by no lane, or for one of the first pair, is
5812 /// pasted across `V1` and `A1` as a grouped take; asked for by a further
5813 /// *video* lane it is *placed* there with its sound on that lane's own audio
5814 /// row (`V2` -> `A2`, added if it is not there yet), overwriting what the two
5815 /// halves land on and rippling nothing; asked for by a further audio lane it
5816 /// is that file's sound alone. A file with no picture ([`crate::is_audio`]) is placed
5817 /// on the audio lane it was asked for, or on `A1`, and never on a video
5818 /// lane. A still image ([`crate::is_image`]) is its mirror: the video lane
5819 /// it was asked for or `V1`, never an audio one, and it goes down
5820 /// the project's still length ([`Project::still_secs`]) long rather than at the length it is
5821 /// *allowed* to be trimmed out to. A caller never has to ask.
5822 pub fn place_stream_at(
5823 &mut self,
5824 timeline_secs: f64,
5825 path: &Path,
5826 stream: usize,
5827 onto: Option<Lane>,
5828 ) -> crate::Result<bool> {
5829 self.place_stream_mode(timeline_secs, path, stream, onto, None)
5830 }
5831
5832 /// [`place_stream_at`](Self::place_stream_at) as an **overwrite**: what the file lands on
5833 /// is replaced for its length and nothing is pushed along ([`SourceEdit::Overwrite`]). The
5834 /// lanes it lands on are chosen exactly as `place_stream_at` chooses them, and a refusal
5835 /// comes back with the engine's own words.
5836 pub fn place_stream_overwrite_at(
5837 &mut self,
5838 timeline_secs: f64,
5839 path: &Path,
5840 stream: usize,
5841 onto: Option<Lane>,
5842 ) -> crate::Result<bool> {
5843 self.place_stream_mode(timeline_secs, path, stream, onto, Some(crate::SourceEdit::Overwrite))
5844 }
5845
5846 /// The one placement behind both doors: `overwrite` of `None` is the insert-and-paste
5847 /// `place_stream_at` has always made; `Some` replaces what is there through
5848 /// [`edit_from_source_at`](Self::edit_from_source_at).
5849 fn place_stream_mode(
5850 &mut self,
5851 timeline_secs: f64,
5852 path: &Path,
5853 stream: usize,
5854 onto: Option<Lane>,
5855 overwrite: Option<crate::SourceEdit>,
5856 ) -> crate::Result<bool> {
5857 let wanted = Source::new(path, stream);
5858 // Another stream of a file this session has taken in: that is what a
5859 // library row is, and it is why nothing here has to check dimensions or
5860 // frame rate -- the file passed that at import. Its length is the one
5861 // the import noted, so a source that has never been placed is as
5862 // placeable as one that is already on a lane.
5863 let frames = self.file_frames(&wanted.path);
5864 if frames == 0 {
5865 return Err(format!("{} is not on this timeline", path.display()).into());
5866 }
5867 // A still has no sound to hold to the timeline's -- and no length
5868 // either, so it goes down at the project's still length rather than at the
5869 // ten minutes it is *allowed* to be dragged out to.
5870 let image = crate::is_image(path);
5871 if !image {
5872 let first = self.first_audio()?;
5873 self.audio_matches_cached(&wanted, &first)?;
5874 }
5875 let rate = self.file_rate(&wanted.path);
5876 let source = self.project.import(path, stream);
5877 self.note_frames(source, frames, rate);
5878 let clip = Clip {
5879 speed_keys: Vec::new(),
5880 reversed: false,
5881 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5882 angle: Default::default(),
5883 fade_in: 0,
5884 fade_out: 0,
5885 transition_out: 0,
5886 transition_kind: Default::default(),
5887 visualizer: 0,
5888 viz_paint: 0,
5889 gain_db: 0.0,
5890 gain_keys: Vec::new(),
5891 pan: 0,
5892 transform_keys: Vec::new(),
5893 opacity_keys: Vec::new(),
5894 color_keys: Vec::new(),
5895 effects: Vec::new(),
5896 start: 0,
5897 in_frame: 0,
5898 out_frame: match image {
5899 true => place_frames(frames, self.meta.frame_rate, self.project.still_secs()),
5900 false => sound_held_frames(path, stream, frames, self.meta.frame_rate),
5901 },
5902 source,
5903 link: None,
5904 eq: None,
5905 color: None,
5906 transform: None,
5907 fit: FitPolicy::default(),
5908 speed: Speed::NORMAL,
5909 pitch: 0,
5910 };
5911 // Which lane a source may land on is decided here and only here, so a
5912 // front-end never has to make the same call twice: a file with no
5913 // picture goes on an audio lane alone, overwriting and rippling
5914 // nothing, because there is nothing on the video lane to move along
5915 // with it. A lane of the source's own kind takes it as it is dropped;
5916 // only `V1` means the grouped take, since that is the pair the paste
5917 // spans and a second video lane is a layer of its own.
5918 // ...and a still is the mirror of a song: a picture and no sound, so a
5919 // video lane and nothing else -- never the grouped take, which would
5920 // put a clip on `A1` for a source the audio worker cannot open.
5921 if image {
5922 let lane = match onto {
5923 Some(lane) if lane.kind == LaneKind::Video => lane,
5924 _ => Lane::V1,
5925 };
5926 if let Some(edit) = overwrite {
5927 self.edit_from_source_at(edit, timeline_secs, &[(lane, clip)])?;
5928 return Ok(true);
5929 }
5930 return Ok(self.place_at(lane, timeline_secs, clip));
5931 }
5932 let onto = match (sound_only(path), onto) {
5933 // No picture: an audio lane and nothing else, whichever one was
5934 // asked for -- `A1` when none was.
5935 (true, Some(lane)) if lane.kind == LaneKind::Audio => Some(lane),
5936 (true, _) => Some(Lane::A1),
5937 // A picture: the lane it was let go over, unless that is one of the
5938 // first pair. Those two are the grouped take a paste spans, and a
5939 // further lane is a layer of its own -- its picture on `V2`, its
5940 // sound on `A2` (below).
5941 (false, Some(lane)) if lane.ord > 0 => Some(lane),
5942 (false, _) => None,
5943 };
5944 // An overwrite lays the same lanes down as an insert would, replacing what is under
5945 // them: a picture and its sound as one take (a link on both halves), a sound alone
5946 // on its audio lane.
5947 if let Some(edit) = overwrite {
5948 let items: Vec<(Lane, Clip)> = match onto {
5949 Some(lane) if lane.kind == LaneKind::Audio => vec![(lane, clip)],
5950 Some(lane) if lane.kind == LaneKind::Video => vec![
5951 (lane, clip.clone()),
5952 (Lane::new(LaneKind::Audio, lane.ord), clip),
5953 ],
5954 _ => vec![(Lane::V1, clip.clone()), (Lane::A1, clip)],
5955 };
5956 self.edit_from_source_at(edit, timeline_secs, &items)?;
5957 return Ok(true);
5958 }
5959 Ok(match onto {
5960 // A picture let go over a further *video* track lands there with the
5961 // sound it came with -- `V2`'s picture, `A2`'s sound, one take and
5962 // one undo step ([`Project::place_take`]). Dropped on a further
5963 // audio lane it is the sound alone, which is what asking an audio
5964 // row for an mp4 means.
5965 Some(lane) if lane.kind == LaneKind::Video => {
5966 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
5967 let clip = self.held_to_take(clip);
5968 self.edit(Dirty::Both, |p| p.place_take(lane, at, clip))
5969 }
5970 Some(lane) => self.place_at(lane, timeline_secs, clip),
5971 // The grouped take, at the frame it was let go on -- past the last
5972 // clip included, where the bed is black and the ghost was drawn.
5973 // Not [`Self::paste_at`]: that door clamps to the end for the
5974 // clipboard, and a drop that named a place is not a paste.
5975 None => {
5976 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
5977 let clip = self.held_to_take(clip);
5978 self.edit(Dirty::Both, |p| p.paste(at, clip))
5979 }
5980 })
5981 }
5982
5983 /// Takes `path` played on `stream` out of the library -- the door a library
5984 /// row's own remove goes through, naming the row exactly as
5985 /// [`place_stream_at`](Self::place_stream_at) does. Refused in
5986 /// [`Project::remove_source`]'s words while a clip still plays from it, and
5987 /// for a row this timeline does not have.
5988 ///
5989 /// Reseeks like an edit even though nothing playable changed: the clip
5990 /// indexes into the source list have just moved, and the running workers
5991 /// were opened against the old numbering.
5992 ///
5993 /// The index that went, because everything past it moved down: a caller
5994 /// holding a source index of its own (a clipboard) has to fix it up or drop
5995 /// it, or it names a different file afterwards. The **last** row goes like
5996 /// any other and leaves a session with an empty library -- silent, empty of
5997 /// clips, and unsaveable ([`save_project`](Self::save_project)); a
5998 /// front-end showing one is showing an empty window.
5999 /// [`remove_source`](Self::remove_source) for the one source that may go
6000 /// without clearing undo: the **last** entry, when no clip and no undo or
6001 /// redo step names it ([`Project::remove_unused_source`]). Nothing playable
6002 /// changes, so there is no reseek and the timeline and its history stay as
6003 /// they were. Used to roll back a batch that imported a source and then
6004 /// failed, where clearing history would also wipe the user's undo.
6005 pub fn remove_unused_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> {
6006 let wanted = Source::new(path, stream);
6007 let idx = self
6008 .project
6009 .sources()
6010 .iter()
6011 .position(|s| *s == wanted)
6012 .ok_or_else(|| format!("{} is not on this timeline", path.display()))?;
6013 self.project.remove_unused_source(idx)?;
6014 if idx < self.counts.len() {
6015 self.counts.remove(idx);
6016 self.rates.remove(idx);
6017 }
6018 Ok(idx)
6019 }
6020
6021 pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> {
6022 let wanted = Source::new(path, stream);
6023 let idx = self
6024 .project
6025 .sources()
6026 .iter()
6027 .position(|s| *s == wanted)
6028 .ok_or_else(|| format!("{} is not on this timeline", path.display()))?;
6029 self.project.remove_source(idx)?;
6030 // The one thing that shortens the source list, so the one place
6031 // [`Self::counts`] shortens with it: left behind, the gone file's length
6032 // would become the wall a *surviving* source is trimmed against
6033 // ([`trim_room`](Self::trim_room)) and the next import would land its
6034 // count one index late.
6035 if idx < self.counts.len() {
6036 self.counts.remove(idx);
6037 self.rates.remove(idx);
6038 }
6039 let now = self.now();
6040 self.seek(now);
6041 Ok(idx)
6042 }
6043
6044 /// What the timeline's audio *is*: the chosen stream of the first source
6045 /// that could have any ([`audio_source_of`]), probed. Every other source is
6046 /// held to it.
6047 ///
6048 /// Through the session's own memo ([`probes`](Self::probes)), because this
6049 /// is asked on the render thread: the free [`first_audio_of`] is the one a
6050 /// worker with no session to reach for calls.
6051 fn first_audio(&mut self) -> crate::Result<Option<crate::AudioProbe>> {
6052 match audio_source_of(self.project.sources()) {
6053 Some(first) => {
6054 let (path, stream) = (first.path.clone(), first.audio_stream);
6055 self.probe_cached(&path, stream)
6056 }
6057 None => Ok(None),
6058 }
6059 }
6060
6061 /// One audio header, read at most once per session per `(path, stream)`.
6062 fn probe_cached(
6063 &mut self,
6064 path: &Path,
6065 stream: usize,
6066 ) -> crate::Result<Option<crate::AudioProbe>> {
6067 let key = (path.to_path_buf(), stream);
6068 if let Some(probe) = self.probes.get(&key) {
6069 return Ok(*probe);
6070 }
6071 let probe = AudioSession::probe(path, stream)?;
6072 self.probes.insert(key, probe);
6073 Ok(probe)
6074 }
6075
6076 /// [`audio_matches`] with this session's memo behind the new file's own
6077 /// header too -- the second of the two opens a place or an import pays.
6078 fn audio_matches_cached(
6079 &mut self,
6080 source: &Source,
6081 first: &Option<crate::AudioProbe>,
6082 ) -> crate::Result<()> {
6083 let probe = self.probe_cached(&source.path, source.audio_stream)?;
6084 audio_matches_probed(probe, first)
6085 }
6086
6087 /// Places `clip` on `lane` alone at the playhead, overwriting what it lands
6088 /// on and rippling nothing -- the one-lane insert a source with no picture
6089 /// makes, and the only way an audio-only file reaches the timeline. The
6090 /// placement belongs to no group (see [`Project::place`]). One undo step,
6091 /// and it reseeks like every other edit.
6092 ///
6093 /// The clip is held to `lane`'s own wall first ([`held_to_lane`](Self::held_to_lane)):
6094 /// a caller's `out_frame` past the source's length on that lane is cut back
6095 /// to it, so no door places a clip the save would refuse.
6096 pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool {
6097 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6098 let clip = self.held_to_lane(lane, clip);
6099 self.edit(Dirty::Both, |p| p.place(lane, at, clip))
6100 }
6101
6102 /// [`Project::edit_from_source`]'s door: an insert or an overwrite of the
6103 /// halves in `items` at `timeline_secs`. Each half is held to its own lane's
6104 /// wall -- and a take of a picture and its sound to the shorter of the two,
6105 /// so the halves run the same length and stay one link. One undo step; it
6106 /// reseeks like every other edit. The error says why it refused.
6107 pub fn edit_from_source_at(
6108 &mut self,
6109 kind: crate::SourceEdit,
6110 timeline_secs: f64,
6111 items: &[(Lane, Clip)],
6112 ) -> crate::Result<()> {
6113 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6114 let both = items.iter().any(|(l, _)| l.kind == LaneKind::Video)
6115 && items.iter().any(|(l, _)| l.kind == LaneKind::Audio);
6116 let items: Vec<(Lane, Clip)> = items
6117 .iter()
6118 .map(|(lane, clip)| {
6119 let held = if both {
6120 self.held_to_take(clip.clone())
6121 } else {
6122 self.held_to_lane(*lane, clip.clone())
6123 };
6124 (*lane, held)
6125 })
6126 .collect();
6127 let mut result = Ok(());
6128 let done = self.edit(Dirty::Both, |p| match p.edit_from_source(kind, at, &items) {
6129 Ok(()) => true,
6130 Err(e) => {
6131 result = Err(e);
6132 false
6133 }
6134 });
6135 match (done, result) {
6136 (_, Err(e)) => Err(e),
6137 (false, Ok(())) => Err("the edit changed nothing".into()),
6138 (true, Ok(())) => Ok(()),
6139 }
6140 }
6141
6142 /// The longest `clip` may run on `lane`: its source's length on that lane's
6143 /// kind -- the picture's on a video lane, the sound's on an audio lane
6144 /// ([`lane_walls`]), the two tables [`save_project`](Self::save_project)
6145 /// checks each lane against. `out_frame` is held to that wall; a clip the
6146 /// wall leaves no frame of is one [`Project::place`] refuses.
6147 fn held_to_lane(&self, lane: Lane, mut clip: Clip) -> Clip {
6148 let (picture, sound) =
6149 lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
6150 let table = match lane.kind {
6151 LaneKind::Audio => sound,
6152 _ => picture,
6153 };
6154 if let Some(&wall) = table.get(clip.source) {
6155 clip.out_frame = clip.out_frame.min(wall);
6156 }
6157 clip
6158 }
6159
6160 /// [`held_to_lane`](Self::held_to_lane) for a clip placed as one take: a
6161 /// picture on a video lane and its sound on an audio lane, so it is held to
6162 /// the shorter of the source's two walls. Both halves of a take share the
6163 /// one clip, so neither may run past its own lane.
6164 fn held_to_take(&self, mut clip: Clip) -> Clip {
6165 let (picture, sound) =
6166 lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
6167 let wall = [picture.get(clip.source), sound.get(clip.source)]
6168 .into_iter()
6169 .flatten()
6170 .min();
6171 if let Some(&wall) = wall {
6172 clip.out_frame = clip.out_frame.min(wall);
6173 }
6174 clip
6175 }
6176
6177 /// Places a waveform-visualizer clip of `path`'s audio on a video lane.
6178 /// The picture is painted from the sound ([`DecodeSession::open_visualizer`]);
6179 /// this does not also put a copy on an audio lane.
6180 pub fn place_visualizer(
6181 &mut self,
6182 start: u32,
6183 path: &Path,
6184 stream: usize,
6185 in_frame: u32,
6186 out_frame: u32,
6187 onto: Option<Lane>,
6188 ) -> crate::Result<bool> {
6189 if out_frame <= in_frame {
6190 return Err("visualizer clip is empty".into());
6191 }
6192 let wanted = Source::new(path, stream);
6193 let first = self.first_audio()?;
6194 self.audio_matches_cached(&wanted, &first)?;
6195 let frames = match self.file_frames(&wanted.path) {
6196 0 => {
6197 let n = audio_frames(path, self.meta.frame_rate)?;
6198 let source = self.project.import(path, stream);
6199 self.note_frames(source, n, Rate::REAL_TIME);
6200 n
6201 }
6202 n => n,
6203 };
6204 let out_frame = out_frame.min(frames);
6205 if out_frame <= in_frame {
6206 return Err("visualizer clip is empty".into());
6207 }
6208 let source = self.project.import(path, stream);
6209 let clip = Clip {
6210 speed_keys: Vec::new(),
6211 reversed: false,
6212 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
6213 angle: Default::default(),
6214 fade_in: 0,
6215 fade_out: 0,
6216 transition_out: 0,
6217 transition_kind: Default::default(),
6218 visualizer: 1,
6219 viz_paint: 0,
6220 gain_db: 0.0,
6221 gain_keys: Vec::new(),
6222 pan: 0,
6223 transform_keys: Vec::new(),
6224 opacity_keys: Vec::new(),
6225 color_keys: Vec::new(),
6226 effects: Vec::new(),
6227 start: 0,
6228 in_frame,
6229 out_frame,
6230 source,
6231 link: None,
6232 eq: None,
6233 color: None,
6234 transform: None,
6235 fit: FitPolicy::default(),
6236 speed: Speed::NORMAL,
6237 pitch: 0,
6238 };
6239 let end = start + clip.frames();
6240 let overlaps = |lane: Lane| {
6241 self.project
6242 .lane(lane)
6243 .iter()
6244 .any(|c| c.start < end && start < c.end())
6245 };
6246 let lane = match onto {
6247 Some(lane) if lane.kind == LaneKind::Video && !overlaps(lane) => lane,
6248 _ => self
6249 .project
6250 .lanes()
6251 .into_iter()
6252 .filter(|l| l.kind == LaneKind::Video)
6253 .find(|&l| !overlaps(l))
6254 .unwrap_or_else(|| self.add_lane(LaneKind::Video)),
6255 };
6256 let clip = self.held_to_lane(lane, clip);
6257 Ok(self.edit(Dirty::Both, |p| p.place(lane, start, clip)))
6258 }
6259
6260 /// Removes `lane`'s clip at `idx` and everything under it, closing the gap
6261 /// on every lane. Unlike a split this *does* move every following frame, so
6262 /// the session reseeks to wherever the playhead now points.
6263 /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead.
6264 /// `false` for a bad index; the last remaining clip goes like any other and
6265 /// leaves the timeline empty ([`is_empty`](Self::is_empty)).
6266 ///
6267 /// The lane travels because the index is a lane's own: `V2`'s third clip is
6268 /// not `V1`'s, and a front-end that could only say "the third clip" would
6269 /// delete the wrong one the moment a second lane exists.
6270 pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool {
6271 self.edit(Dirty::Both, |p| p.delete_in(lane, idx))
6272 }
6273
6274 /// Undoes the last successful edit, and reseeks like a delete. A step on
6275 /// the project's own settings comes back the same way: the canvas, the
6276 /// rate and the switches are put back on the session here
6277 /// ([`Self::adopt_settings`]), so a `z` after a resolution pick, an
6278 /// encoder pick or a proxy switch lands exactly as one after a cut does.
6279 pub fn undo(&mut self) -> bool {
6280 self.restored_step(Project::undo)
6281 }
6282
6283 /// Redoes the last edit [`undo`](Self::undo) took back, and reseeks like
6284 /// a delete -- settings included, exactly as `undo` takes them back.
6285 pub fn redo(&mut self) -> bool {
6286 self.restored_step(Project::redo)
6287 }
6288
6289 /// Every sequence in tab order ([`Project::sequences`]).
6290 pub fn sequences(&self) -> Vec<crate::project::SequenceInfo> {
6291 self.project.sequences()
6292 }
6293
6294 /// The active sequence's id.
6295 pub fn active_sequence(&self) -> u32 {
6296 self.project.active_sequence()
6297 }
6298
6299 /// The name of sequence `id`.
6300 pub fn sequence_name(&self, id: u32) -> Option<String> {
6301 self.project.sequence_name(id).map(str::to_string)
6302 }
6303
6304 /// The sequence called `name`.
6305 pub fn sequence_named(&self, name: &str) -> Option<u32> {
6306 self.project.sequence_named(name)
6307 }
6308
6309 /// See [`Project::source_uses_parked`].
6310 pub fn source_uses_parked(&self, source: usize) -> Vec<(u32, usize)> {
6311 self.project.source_uses_parked(source)
6312 }
6313
6314 /// See [`Project::compound_pieces`].
6315 pub fn compound_pieces(&self, kind: LaneKind, clip: &Clip) -> Vec<Clip> {
6316 self.project.compound_pieces(kind, clip)
6317 }
6318
6319 /// The sequence the compound clip at `lane`/`idx` plays.
6320 pub fn compound_at(&self, lane: Lane, idx: usize) -> Option<u32> {
6321 self.project.compound_at(lane, idx)
6322 }
6323
6324 /// The angle names of sequence `id` when it is a multicam source ([`Project::angle_names`]).
6325 pub fn angle_names(&self, id: u32) -> Option<Vec<String>> {
6326 self.project.angle_names(id).map(<[String]>::to_vec)
6327 }
6328
6329 /// The multicam source the clip at `lane`/`idx` plays and its angle names, when it is a
6330 /// multicam clip.
6331 pub fn multicam_at(&self, lane: Lane, idx: usize) -> Option<(u32, Vec<String>)> {
6332 let c = self.project.lane(lane).get(idx)?;
6333 self.project.multicam_of(c).map(|(id, n)| (id, n.to_vec()))
6334 }
6335
6336 /// Whether the rate and other time-scaled settings are fixed because the
6337 /// project holds more than one sequence.
6338 pub fn rate_locked(&self) -> bool {
6339 self.project.rate_locked()
6340 }
6341
6342 /// An edit that can be refused with a reason: the picture and the sound are
6343 /// rebuilt when it was made.
6344 fn edit_try<T>(&mut self, f: impl FnOnce(&mut Project) -> crate::Result<T>) -> crate::Result<T> {
6345 let made = f(&mut self.project)?;
6346 self.invalidate(Dirty::Both);
6347 Ok(made)
6348 }
6349
6350 /// Adds an empty sequence; see [`Project::new_sequence`]. Not switched to.
6351 pub fn new_sequence(&mut self, name: Option<&str>) -> crate::Result<u32> {
6352 self.edit_try(|p| p.new_sequence(name))
6353 }
6354
6355 /// Makes an editor timeline a new sequence and switches to it ([`crate::interchange::build`]).
6356 /// Each file it names is taken in as a library file is; one that is gone is offline, as a
6357 /// missing file is in a saved project. One undo step.
6358 pub fn import_timeline(&mut self, t: &crate::interchange::Timeline) -> crate::Result<u32> {
6359 let mut reach: Vec<(PathBuf, u32)> = Vec::new();
6360 for item in t.tracks.iter().flat_map(|tr| &tr.items) {
6361 if let crate::interchange::Item::Clip(c) = item {
6362 match reach.iter_mut().find(|(p, _)| *p == c.path) {
6363 Some((_, r)) => *r = (*r).max(c.out_frame),
6364 None => reach.push((c.path.clone(), c.out_frame)),
6365 }
6366 }
6367 }
6368 for (path, furthest) in &reach {
6369 if self.source_of(path).is_some() {
6370 continue;
6371 }
6372 if crate::source_present(path) {
6373 self.import(path)?;
6374 } else {
6375 let source = self.project.import(path, 0);
6376 self.note_frames(source, *furthest, Rate::REAL_TIME);
6377 }
6378 }
6379 self.begin_batch();
6380 let made = self.edit_try(|p| crate::interchange::build(p, t));
6381 self.end_batch();
6382 made
6383 }
6384
6385 /// See [`Project::rename_sequence`].
6386 pub fn rename_sequence(&mut self, id: u32, name: &str) -> crate::Result<()> {
6387 self.edit_try(|p| p.rename_sequence(id, name))
6388 }
6389
6390 /// See [`Project::duplicate_sequence`].
6391 pub fn duplicate_sequence(&mut self, id: u32) -> crate::Result<u32> {
6392 self.edit_try(|p| p.duplicate_sequence(id))
6393 }
6394
6395 /// See [`Project::delete_sequence`]. The picture and sound follow the
6396 /// sequence that is active afterwards.
6397 pub fn delete_sequence(&mut self, id: u32) -> crate::Result<u32> {
6398 self.edit_try(|p| p.delete_sequence(id))
6399 }
6400
6401 /// Makes `id` the sequence on the timeline and in the picture and sound. Not an undo step.
6402 pub fn switch_sequence(&mut self, id: u32) -> crate::Result<()> {
6403 if id == self.project.active_sequence() {
6404 return Ok(());
6405 }
6406 self.edit_try(|p| p.switch_sequence(id))
6407 }
6408
6409 /// See [`Project::nest`].
6410 pub fn nest(&mut self, picks: &[(Lane, usize)], name: Option<&str>) -> crate::Result<crate::project::Nested> {
6411 self.edit_try(|p| p.nest(picks, name))
6412 }
6413
6414 /// See [`Project::break_apart`].
6415 pub fn break_apart(&mut self, picks: &[(Lane, usize)]) -> crate::Result<Vec<(Lane, usize)>> {
6416 self.edit_try(|p| p.break_apart(picks))
6417 }
6418
6419 /// Syncs the sources `picks` and makes a multicam clip of them at `timeline_secs` on `lane`
6420 /// ([`Project::make_multicam`]). With [`MulticamSync::Audio`] every camera is lined up with
6421 /// the first one that has sound by the loudness curve of its track
6422 /// ([`crate::multisync`]); a camera that cannot be matched (no sound, or too weak a match)
6423 /// starts with the others and the report says so. One undo step.
6424 pub fn make_multicam_at(
6425 &mut self,
6426 picks: &[usize],
6427 sync: MulticamSync,
6428 name: Option<&str>,
6429 lane: Lane,
6430 timeline_secs: f64,
6431 ) -> crate::Result<MulticamReport> {
6432 let job = self.multicam_job(picks, sync)?;
6433 let plan = job.run(&std::sync::atomic::AtomicU32::new(0), &std::sync::atomic::AtomicBool::new(false))?;
6434 self.apply_multicam(&plan, name, lane, timeline_secs)
6435 }
6436
6437 /// The part of [`make_multicam_at`](Self::make_multicam_at) that only reads the sources, as a
6438 /// value that can be run on a thread of its own ([`MulticamJob::run`]) while the window stays
6439 /// live; [`apply_multicam`](Self::apply_multicam) then makes the clip, one undo step.
6440 pub fn multicam_job(&self, picks: &[usize], sync: MulticamSync) -> crate::Result<MulticamJob> {
6441 let mut seen = Vec::new();
6442 let mut sources = Vec::new();
6443 for &p in picks {
6444 let Some(src) = self.project.sources().get(p) else {
6445 return Err(format!("source {p} is not in the project").into());
6446 };
6447 if seen.contains(&p) {
6448 return Err(format!("source {p} is picked twice: an angle is one camera").into());
6449 }
6450 seen.push(p);
6451 sources.push(MulticamJobSource {
6452 index: p,
6453 path: src.path.clone(),
6454 audio_stream: src.audio_stream,
6455 frames: self.counts.get(p).copied().unwrap_or(0).max(1),
6456 });
6457 }
6458 Ok(MulticamJob { sources, sync, fps: self.meta.frame_rate })
6459 }
6460
6461 /// The library's bins ([`Project::bins`]).
6462 pub fn bins(&self) -> &[crate::project::Bin] {
6463 self.project.bins()
6464 }
6465
6466 /// Makes a bin; see [`Project::create_bin`]. A label only: nothing is rebuilt.
6467 pub fn create_bin(&mut self, name: &str, parent: u32) -> Result<u32, String> {
6468 self.project.create_bin(name, parent)
6469 }
6470
6471 /// See [`Project::rename_bin`].
6472 pub fn rename_bin(&mut self, id: u32, name: &str) -> Result<bool, String> {
6473 self.project.rename_bin(id, name)
6474 }
6475
6476 /// See [`Project::remove_bin`].
6477 pub fn remove_bin(&mut self, id: u32) -> Result<usize, String> {
6478 self.project.remove_bin(id)
6479 }
6480
6481 /// See [`Project::move_to_bin`].
6482 pub fn move_to_bin(&mut self, srcs: &[usize], bin: u32) -> Result<usize, String> {
6483 self.project.move_to_bin(srcs, bin)
6484 }
6485
6486 /// See [`Project::set_favourite`].
6487 pub fn set_favourite(&mut self, srcs: &[usize], on: bool) -> Result<usize, String> {
6488 self.project.set_favourite(srcs, on)
6489 }
6490
6491 /// Makes the multicam clip a [`MulticamJob::run`] measured, at `timeline_secs` on `lane`. One
6492 /// undo step. Refused when the project's sources are no longer the ones that were measured.
6493 pub fn apply_multicam(&mut self, plan: &MulticamPlan, name: Option<&str>, lane: Lane, timeline_secs: f64) -> crate::Result<MulticamReport> {
6494 for a in &plan.sources {
6495 if self.project.sources().get(a.index).map(|s| &s.path) != Some(&a.path) {
6496 return Err("the media list changed while the angles were being synced".into());
6497 }
6498 }
6499 let fps = self.meta.frame_rate;
6500 let at = secs_to_frame(timeline_secs, fps);
6501 let made = self.edit_try(|p| p.make_multicam(name, &plan.angles, lane, at))?;
6502 Ok(MulticamReport { made, how: plan.how.clone(), offsets_secs: plan.offsets.clone(), starts: plan.angles.iter().map(|a| a.start).collect() })
6503 }
6504
6505 /// See [`Project::switch_angle`], at `timeline_secs`.
6506 pub fn switch_angle_at(
6507 &mut self,
6508 lane: Option<Lane>,
6509 timeline_secs: f64,
6510 video: Option<u8>,
6511 audio: Option<Option<u8>>,
6512 ) -> crate::Result<Vec<(Lane, u32)>> {
6513 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6514 self.edit_try(|p| p.switch_angle(lane, at, video, audio))
6515 }
6516
6517 /// The multicam clip under timeline `frame`, if any ([`Project::multicam_under`]).
6518 pub fn multicam_under(&self, frame: u32) -> Option<crate::project::MulticamUnder> {
6519 self.project.multicam_under(frame)
6520 }
6521
6522 /// One flattened project per angle of the multicam clip under `frame` and the timeline meta
6523 /// to compose them with ([`crate::export::compose_at`]): the angle monitor's tiles, composed
6524 /// off the window's thread.
6525 pub fn angle_views(&self, frame: u32) -> Option<(crate::project::MulticamUnder, Vec<crate::project::Project>, VideoMeta)> {
6526 self.project.angle_views(frame).map(|(u, v)| (u, v, self.meta))
6527 }
6528
6529 /// See [`Project::flatten_multicam`].
6530 pub fn flatten_multicam(&mut self, lane: Lane, idx: usize) -> crate::Result<Vec<(Lane, usize)>> {
6531 self.edit_try(|p| p.flatten_multicam(lane, idx))
6532 }
6533
6534 /// See [`Project::place_sequence`], at `timeline_secs`.
6535 pub fn place_sequence_at(&mut self, seq: u32, lane: Lane, timeline_secs: f64) -> crate::Result<()> {
6536 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6537 self.edit_try(|p| p.place_sequence(seq, lane, at))
6538 }
6539
6540 /// The project as an edit sees it, compound clips and all, with the undo history left out
6541 /// (what a "did this batch change anything" comparison reads; [`export_snapshot`](Self::export_snapshot)
6542 /// is the expanded one a render reads).
6543 pub fn raw_snapshot(&self) -> (crate::project::Project, VideoMeta) {
6544 (self.project.raw_snapshot(), self.meta)
6545 }
6546
6547 /// [`export_snapshot`](Self::export_snapshot) of sequence `seq` (the active one for `None`).
6548 pub fn export_snapshot_of(&self, seq: Option<u32>) -> crate::Result<(crate::project::Project, VideoMeta)> {
6549 Ok((self.project.render_snapshot(seq)?, self.meta))
6550 }
6551
6552 /// Starts a batch: the edits until [`end_batch`](Self::end_batch) are one
6553 /// undo step, taken before the first of them. Only the caller that opens a
6554 /// batch sees the difference; the GUI never calls this, so its steps stay one per edit.
6555 pub fn begin_batch(&mut self) {
6556 self.project.begin_batch();
6557 }
6558
6559 /// Ends the batch [`begin_batch`](Self::begin_batch) opened.
6560 pub fn end_batch(&mut self) {
6561 self.project.end_batch();
6562 }
6563
6564 /// The mark an action takes before it edits, for [`Self::name_step`].
6565 pub fn step_mark(&mut self) -> u64 {
6566 self.project.step_mark()
6567 }
6568
6569 /// Names the step the action that took `mark` pushed, so Undo and Redo can say what
6570 /// they take back. An action that pushed nothing names nothing.
6571 pub fn name_step(&mut self, mark: u64, label: &str) {
6572 self.project.name_step(mark, label);
6573 }
6574
6575 /// What [`undo`](Self::undo) takes back, when the step was named.
6576 pub fn undo_label(&self) -> Option<&str> {
6577 self.project.undo_label()
6578 }
6579
6580 /// What [`redo`](Self::redo) walks forward to, when the step was named.
6581 pub fn redo_label(&self) -> Option<&str> {
6582 self.project.redo_label()
6583 }
6584
6585 /// The names of the steps [`undo`](Self::undo) can take back, oldest first
6586 /// ([`Project::undo_labels`]).
6587 pub fn undo_labels(&self) -> Vec<Option<String>> {
6588 self.project.undo_labels()
6589 }
6590
6591 /// The names of the steps [`redo`](Self::redo) can walk forward to, the next one last
6592 /// ([`Project::redo_labels`]).
6593 pub fn redo_labels(&self) -> Vec<Option<String>> {
6594 self.project.redo_labels()
6595 }
6596
6597 /// Moves through the undo history by `index` steps from where it stands: negative undoes that
6598 /// many, positive redoes. Each step goes through [`undo`](Self::undo) or [`redo`](Self::redo),
6599 /// so it reseeks like them. Returns how many steps were taken; it stops early at either end.
6600 pub fn jump_to(&mut self, index: isize) -> usize {
6601 let mut taken = 0;
6602 for _ in 0..index.unsigned_abs() {
6603 let moved = match index < 0 {
6604 true => self.undo(),
6605 false => self.redo(),
6606 };
6607 if !moved {
6608 break;
6609 }
6610 taken += 1;
6611 }
6612 taken
6613 }
6614
6615 /// How many steps [`undo`](Self::undo) can still take.
6616 pub fn undo_depth(&self) -> usize {
6617 self.project.history_len()
6618 }
6619
6620 /// How many steps [`redo`](Self::redo) can still take.
6621 pub fn redo_depth(&self) -> usize {
6622 self.project.redo_len()
6623 }
6624
6625 /// Which state the timeline is in ([`Project::revision`]): equal before and
6626 /// after an undo means the undo walked back to the same timeline, so a save
6627 /// taken at one can tell whether the timeline has since moved off it.
6628 pub fn revision(&self) -> u64 {
6629 self.project.revision()
6630 }
6631
6632 /// Every undo snapshot the session has pushed, including those the
6633 /// [`HISTORY_CAP`](crate::project) has since dropped. Unlike
6634 /// [`undo_depth`](Self::undo_depth) it keeps rising at the cap, so a caller
6635 /// counts a batch's steps as the difference of two reads of it.
6636 pub fn history_pushes(&self) -> u64 {
6637 self.project.history_pushes()
6638 }
6639
6640 /// Drops the redo stack with no step taken. For a caller that rolled its own
6641 /// trial edits back: the undone states they left are not a branch to redo.
6642 pub fn clear_redo(&mut self) {
6643 self.project.clear_redo();
6644 }
6645
6646 /// Moves the redo stack out ([`RedoCheckpoint`]) with no step taken, for a
6647 /// caller whose trial edits may be rolled back. The trial's own edits clear
6648 /// it and its rollback fills it, so [`restore_redo`](Self::restore_redo)
6649 /// puts back exactly what was there before the trial.
6650 pub fn take_redo(&mut self) -> RedoCheckpoint {
6651 self.project.take_redo()
6652 }
6653
6654 /// Puts back the redo stack [`take_redo`](Self::take_redo) took out.
6655 pub fn restore_redo(&mut self, cp: RedoCheckpoint) {
6656 self.project.restore_redo(cp);
6657 }
6658
6659 /// Opens (`true`) or closes (`false`) a trial batch's hold on the undo cap:
6660 /// while held, its steps evict nothing, so a rolled-back trial leaves the
6661 /// history exactly as it found it. Closing trims back to the cap.
6662 pub fn hold_history(&mut self, hold: bool) {
6663 self.project.hold_history(hold);
6664 }
6665
6666 /// Takes `path` into the **library**: it becomes a source of this session,
6667 /// with its length noted ([`file_frames`](Self::file_frames)), and nothing
6668 /// is placed on any lane. What reaches the timeline is decided afterwards,
6669 /// by dragging the row onto a lane
6670 /// ([`place_stream_at`](Self::place_stream_at)) -- importing a file is not
6671 /// a decision about where it plays.
6672 ///
6673 /// The source index, new or the one this file already had: importing twice
6674 /// registers once. *Not* an undo step -- a source entry alone changes
6675 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take
6676 /// back, and nothing reseeks.
6677 ///
6678 /// Refused unless it can join the timeline -- a decoder this machine can
6679 /// open, and audio parameters that agree or none at all; the `Err` names
6680 /// the property that disagrees,
6681 /// for a caller to show. Nothing is changed by a refusal. A *resolution* of
6682 /// its own is not a refusal: the clip is placed on the project canvas by its
6683 /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame
6684 /// rate* of its own: the file is placed for the seconds it lasts and read at
6685 /// [`Rate`] against the timeline's rate, so it plays at the speed it was
6686 /// shot at.
6687 /// [`import`](Self::import), with what the import cannot do for the file
6688 /// said back as warnings rather than left on stderr. A file whose sound is in
6689 /// a codec this build does not decode (DTS, say) imports with its picture and
6690 /// plays silent: the one warning is that sentence, naming the track. Empty
6691 /// for a file with nothing to warn about.
6692 pub fn import_with_warnings(&mut self, path: &Path) -> crate::Result<(usize, Vec<String>)> {
6693 let source = self.import(path)?;
6694 let warnings = AudioSession::unsupported(path)
6695 .ok()
6696 .flatten()
6697 .map(|why| format!("{}: {why}; its sound will be silent", path.display()))
6698 .into_iter()
6699 .collect();
6700 Ok((source, warnings))
6701 }
6702
6703 pub fn import(&mut self, path: &Path) -> crate::Result<usize> {
6704 if crate::is_audio(path) {
6705 return self.import_audio(path);
6706 }
6707 // One frame of a numbered run is the whole run: a clip of its frames, asked nothing.
6708 if let Some(run) = crate::sequence::Run::parse(path).or_else(|| crate::sequence::Run::detect(path)) {
6709 return self.import_run(&run);
6710 }
6711 if crate::is_image(path) {
6712 return self.import_image(path);
6713 }
6714 // Both halves on this thread, which is what a caller with nothing else
6715 // to do wants; a front-end splits them across a worker instead
6716 // ([`probe_import`](Self::probe_import)).
6717 // A container with sound but no picture is a song wearing a video
6718 // extension -- the same fallback `open_stream` and the project
6719 // scaffold make, so every door in agrees on what the file is.
6720 match Self::probe_import(self.import_gate(), path) {
6721 Ok(probe) => Ok(self.take_probe(path, probe)),
6722 Err(e) if crate::demux::NoVideoTrack::is_it(&e) => self.import_audio(path),
6723 Err(e) => Err(e),
6724 }
6725 }
6726
6727 /// Everything an import is *checked against*, taken off this timeline in
6728 /// one owned piece: the sources its audio must agree with and the meta its
6729 /// rate is read against. Costs two clones and touches no disk, so the
6730 /// thread holding the session can hand it to a worker and go on painting.
6731 pub fn import_gate(&self) -> ImportGate {
6732 ImportGate {
6733 sources: self.project.sources().to_vec(),
6734 timeline: self.meta,
6735 }
6736 }
6737
6738 /// The reading half of [`import`](Self::import), with no session in it: the
6739 /// container's header, the decoder this machine would open it with, and the
6740 /// audio check against the gate -- every read an import pays.
6741 ///
6742 /// This is the half that costs. Measured on a 24 GB 4K HEVC remux: 21.4 s of
6743 /// header with the pages cold, 429 ms warm, plus 1-4 s of probing the
6744 /// timeline's own first source. So a front-end runs *this* on its background
6745 /// executor and hands what comes back to
6746 /// [`import_probed`](Self::import_probed), which costs a push -- the same
6747 /// split [`parse_subtitles`](Self::parse_subtitles) makes, for the same
6748 /// reason.
6749 ///
6750 /// The container fork only: a song and a still fork before the demuxer
6751 /// ([`import`](Self::import)) and pay a header read of their own.
6752 ///
6753 /// The `Err` is the refusal [`import`](Self::import) would have given, in
6754 /// the same words -- nothing is refused twice and nothing is worded twice.
6755 pub fn probe_import(gate: ImportGate, path: &Path) -> crate::Result<ImportProbe> {
6756 let (meta, _) = Demuxer::open(path)?;
6757 let first = first_audio_of(&gate.sources)?;
6758 // Stream 0: an import brings a file in on its first audio track, and
6759 // [`place_stream_at`](Self::place_stream_at) is how any other one of
6760 // its streams reaches the timeline afterwards.
6761 // ...and the rate it will be read at comes back from the check that
6762 // accepted it, so the number the refusal was decided on is the number
6763 // the file is played by.
6764 let rate = matches_timeline(&Source::new(path, 0), &meta, &gate.timeline, &first)?;
6765 Ok(ImportProbe { gate, meta, rate })
6766 }
6767
6768 /// Registers a file already read by [`probe_import`](Self::probe_import).
6769 /// The whole of what an import costs the thread that calls it: a source
6770 /// entry and its length, no open, no seek, no decode -- which is why the
6771 /// probe is a separate door.
6772 ///
6773 /// The timeline may have moved while the worker read: a source removed or a
6774 /// file opened is a different set of things the probe was checked against,
6775 /// so the probe is re-read here ([`ImportGate`]) and a stale one is simply
6776 /// imported the slow way rather than trusted. Same answer either way, so no
6777 /// caller has to know which arm it took.
6778 pub fn import_probed(&mut self, path: &Path, probe: ImportProbe) -> crate::Result<usize> {
6779 match probe.gate.sources == self.project.sources() && probe.gate.timeline == self.meta {
6780 true => Ok(self.take_probe(path, probe)),
6781 false => self.import(path),
6782 }
6783 }
6784
6785 /// The push both import doors end at.
6786 fn take_probe(&mut self, path: &Path, probe: ImportProbe) -> usize {
6787 let source = self.project.import(path, 0);
6788 // Its length *on this timeline*: a file shot slower than the timeline
6789 // runs covers more frames than it holds, which is the whole of what
6790 // placing it at another rate means ([`Rate`]).
6791 self.note_frames(
6792 source,
6793 probe.rate.timeline_at(probe.meta.frame_count),
6794 probe.rate,
6795 );
6796 source
6797 }
6798
6799 /// The same registration for a standalone audio file: a song has no
6800 /// picture, so the length noted for it is its playing time rounded up to
6801 /// whole frames, which is the only frame count such a source has.
6802 ///
6803 /// Refused in the same words as any other import when its layout disagrees
6804 /// with the timeline's track -- one output device, one layout. A silent
6805 /// timeline has no track to disagree with, so a song joins it and *is* its
6806 /// sound ([`Self::arm_audio`]). Nothing is changed by a refusal.
6807 fn import_audio(&mut self, path: &Path) -> crate::Result<usize> {
6808 let first = self.first_audio()?;
6809 // Stream 0, and there is no other: a standalone audio file carries one
6810 // track (`AudioSession::probe_streams`), so nothing here has a stream
6811 // to pick the way `place_stream_at` does for an mp4.
6812 self.audio_matches_cached(&Source::new(path, 0), &first)?;
6813 let frames = audio_frames(path, self.meta.frame_rate)?;
6814 let source = self.project.import(path, 0);
6815 self.note_frames(source, frames, Rate::REAL_TIME);
6816 Ok(source)
6817 }
6818
6819 /// The registration of a numbered run ([`crate::sequence`]): one source named for the whole
6820 /// run, held to as many frames as the run holds, at the timeline's rate. The first frame is
6821 /// what a refusal is decided on -- a run of pictures this engine cannot compose is refused in
6822 /// the words a single still would be.
6823 fn import_run(&mut self, run: &crate::sequence::Run) -> crate::Result<usize> {
6824 let (width, height) = crate::decode::image_size(&run.frame(0))?;
6825 if !crate::is_resolution(width, height) {
6826 return Err(format!(
6827 "{} is {width}x{height}, which is not a picture this engine composes",
6828 run.frame(0).display()
6829 )
6830 .into());
6831 }
6832 let source = self.project.import(run.spelled(), 0);
6833 self.note_frames(source, run.count, Rate::REAL_TIME);
6834 Ok(source)
6835 }
6836
6837 /// The same registration for a still image, and the shortest of the three:
6838 /// a picture has nothing to agree with. No frame rate (it is one picture),
6839 /// no audio (it is silent), and a resolution of its own is what every
6840 /// import is allowed -- the clip is placed on the project canvas by its fit
6841 /// policy. The one refusal left is a file that is not a picture at all, or
6842 /// one too big to compose ([`crate::is_resolution`]), and the header alone
6843 /// answers both.
6844 ///
6845 /// The length noted is the wall a trim is held to, not a duration the file
6846 /// has: see [`image_frames`].
6847 fn import_image(&mut self, path: &Path) -> crate::Result<usize> {
6848 let (width, height) = crate::decode::image_size(path)?;
6849 if !crate::is_resolution(width, height) {
6850 return Err(format!(
6851 "{} is {width}x{height}, which is not a picture this engine composes",
6852 path.display()
6853 )
6854 .into());
6855 }
6856 let source = self.project.import(path, 0);
6857 self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME);
6858 Ok(source)
6859 }
6860
6861 /// Applies an edit and, if it took, rebuilds **what it dirtied** and nothing
6862 /// else ([`Dirty`]). A structural edit reseeks: `seek` clamps to the new
6863 /// duration and keeps playing playing, so a delete that shortens the
6864 /// timeline past the playhead lands on the last frame. A grade or a fit
6865 /// policy rebuilds the picture where it stands, with the sound running
6866 /// through it untouched -- no flush, no re-open, no hole -- and an
6867 /// equalizer the other way round.
6868 /// The project's own settings as this session has them now
6869 /// ([`ProjectSettings`]): the canvas and the rate are `meta`'s, the
6870 /// switches are this session's own fields, and the rendition and the
6871 /// limiter are the project's -- two halves of one header, which is what
6872 /// every history entry carries beside the lanes ([`Project::snapshot`]).
6873 fn settings_value(&self) -> ProjectSettings {
6874 ProjectSettings {
6875 resolution: (self.meta.width, self.meta.height),
6876 frame_rate: self.meta.frame_rate,
6877 encoder_seat: self.encoder_seat,
6878 sample_rate: self.sample_rate,
6879 proxies: self.proxies,
6880 auto_proxies: self.auto_proxies,
6881 tone: self.project.tone(),
6882 limiter: self.project.limiter(),
6883 caption_style: self.project.caption_style(),
6884 notes: self.project.notes().to_string(),
6885 still_secs: self.project.still_secs(),
6886 }
6887 }
6888
6889 /// One undo step for a change to the project's own settings, taken after
6890 /// the change: `from` is the state the door found, and what the project
6891 /// does with the two values is [`Project::push_settings_step`]'s.
6892 fn step_settings(&mut self, from: ProjectSettings) {
6893 let now = self.settings_value();
6894 self.project.push_settings_step(from, now);
6895 }
6896
6897 /// Puts the project's settings back on this session -- what a step that
6898 /// restored them leaves for the player to take up. The canvas, the rate and
6899 /// the switches live here, and the rendition and the limiter are the
6900 /// project's own, already back in place by the time this runs. Every lane
6901 /// edit's entry comes through here too and moves nothing, which is the
6902 /// common case; the *rate* is the one that needs more than the fields,
6903 /// because every source's frame count is held against it and the conform
6904 /// that scaled them is not in the entry.
6905 fn adopt_settings(&mut self) {
6906 let s = self.project.settings_now();
6907 // A project nobody has handed a canvas to: a fresh [`Project`] carries
6908 // the placeholder ([`ProjectSettings::placeholder`]) and no session is
6909 // on one -- the entries pushed before the first settings door hold lane
6910 // edits and that placeholder, and adopting it would zero the canvas.
6911 if s.frame_rate <= 0.0 {
6912 return;
6913 }
6914 let was = self.meta.frame_rate;
6915 self.meta.width = s.resolution.0;
6916 self.meta.height = s.resolution.1;
6917 self.meta.frame_rate = s.frame_rate;
6918 self.encoder_seat = s.encoder_seat;
6919 self.sample_rate = s.sample_rate;
6920 self.proxies = s.proxies;
6921 self.auto_proxies = s.auto_proxies;
6922 if s.frame_rate != was {
6923 // Within a frame, like the way out ([`Self::set_frame_rate`]'s own
6924 // caveat): the lane frame numbers came home exactly, out of the
6925 // entry, and only the per-source lengths are re-derived through the
6926 // map back.
6927 let Ok(k) = Rate::from_fps(was, s.frame_rate) else {
6928 return;
6929 };
6930 for count in &mut self.counts {
6931 *count = k.timeline_nearest(*count).max(1);
6932 }
6933 for rate in &mut self.rates {
6934 *rate = rate.then(k);
6935 }
6936 self.meta.frame_count = k.timeline_nearest(self.meta.frame_count).max(1);
6937 }
6938 }
6939
6940 /// [`Self::undo`] and [`Self::redo`] themselves: the project's own step,
6941 /// and then whatever it restored for the session to take up
6942 /// ([`Self::adopt_settings`]). Reseeks both halves, so a canvas that moved
6943 /// is repainted and a proxy switch that flipped reopens the file.
6944 fn restored_step(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool {
6945 let before = self.project.sources().to_vec();
6946 if !f(&mut self.project) {
6947 return false;
6948 }
6949 // Adopted *before* the reseek below, never after it: everything the
6950 // reseek reads is one of the settings the entry just put back --
6951 // `landing` the rate and the frame count, `picture_path` the switches,
6952 // the sound the sample rate -- so a landing computed from the values
6953 // the step *undid* lands on the wrong frame of the right project (and
6954 // reopens the file through the switch that just went back).
6955 self.adopt_settings();
6956 // A step that put a relinked file's old path back is read again here,
6957 // before the reseek opens it.
6958 self.reread_sources(&before);
6959 self.invalidate(Dirty::Both);
6960 true
6961 }
6962
6963 /// Takes `other`'s timeline over as one undo step ([`Project::adopt_as_step`]),
6964 /// the way a recovery puts an autosave's edits on the saved project it opened.
6965 /// The settings are adopted and the sources read again exactly as an undo
6966 /// does it. `false`, with nothing changed, when the project refuses it.
6967 pub fn adopt_as_step(&mut self, other: &PlaybackSession) -> bool {
6968 let before = self.project.sources().to_vec();
6969 if !self.project.adopt_as_step(&other.project) {
6970 return false;
6971 }
6972 self.adopt_settings();
6973 self.reread_sources(&before);
6974 self.invalidate(Dirty::Both);
6975 true
6976 }
6977
6978 /// Measures the sources a step moved or added, against the timeline as it
6979 /// stands. `before` is the list the step started from: a source whose path
6980 /// or stream differs from it (a relink undone or redone, an entry adopted
6981 /// from another project) has its length and rate read again, and so does
6982 /// one past the end of the counts. A file that can no longer be read keeps
6983 /// the length it had, or a whole picture's for an entry it never had.
6984 fn reread_sources(&mut self, before: &[Source]) {
6985 let now = self.project.sources().to_vec();
6986 self.counts.truncate(now.len());
6987 self.rates.truncate(now.len());
6988 for (i, source) in now.iter().enumerate() {
6989 if i < self.counts.len() && before.get(i) == Some(source) {
6990 continue;
6991 }
6992 let (count, rate) = match self.measure_source(source) {
6993 Ok(measured) => measured,
6994 Err(_) => (
6995 self.counts.get(i).copied().unwrap_or(self.meta.frame_count),
6996 self.rates.get(i).copied().unwrap_or(Rate::REAL_TIME),
6997 ),
6998 };
6999 if i < self.counts.len() {
7000 self.counts[i] = count;
7001 self.rates[i] = rate;
7002 } else {
7003 self.counts.push(count);
7004 self.rates.push(rate);
7005 }
7006 }
7007 }
7008
7009 /// The frame count and the rate `source`'s file has on this timeline: what a
7010 /// relink measures a new file by, and what an undo measures the file it puts
7011 /// back by. The file must be the kind and the material the timeline holds,
7012 /// as [`Self::relink_source`] checks it.
7013 fn measure_source(&mut self, source: &Source) -> crate::Result<(u32, Rate)> {
7014 let path = source.path.as_path();
7015 let first = self.first_audio()?;
7016 if crate::is_image(path) {
7017 crate::decode::image_size(path)?;
7018 Ok((image_frames(self.meta.frame_rate), Rate::REAL_TIME))
7019 } else if crate::is_audio(path) {
7020 audio_matches(source, &first)?;
7021 Ok((audio_frames(path, self.meta.frame_rate)?, Rate::REAL_TIME))
7022 } else {
7023 let (other, _) = Demuxer::open(path)?;
7024 let rate = matches_timeline(source, &other, &self.meta, &first)?;
7025 Ok((rate.timeline_at(other.frame_count), rate))
7026 }
7027 }
7028
7029 fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool {
7030 let done = f(&mut self.project);
7031 self.project.settle();
7032 if !done {
7033 return false;
7034 }
7035 self.invalidate(dirty);
7036 true
7037 }
7038
7039 /// Where an edit rebuilds from: the clock, except at the end of a played-out
7040 /// timeline, where the clock has kept running on wall time and the edit
7041 /// resumes at the end the viewer saw (so a paste there plays the pasted clip).
7042 fn playhead(&self) -> f64 {
7043 match self.eos {
7044 true => self.now().min(self.eos_end),
7045 false => self.now(),
7046 }
7047 }
7048
7049 /// Rebuilds the dirtied half (or both) at the playhead.
7050 fn invalidate(&mut self, dirty: Dirty) {
7051 match dirty {
7052 Dirty::Picture => {
7053 let (_, target) = self.landing(self.playhead());
7054 self.start_picture(target);
7055 }
7056 Dirty::Sound => self.reseek_audio(),
7057 Dirty::Both => {
7058 let now = self.playhead();
7059 self.seek(now);
7060 }
7061 }
7062 }
7063
7064 /// Says how big the picture is on screen, in device pixels -- what a
7065 /// front-end showing this session pushes once it knows where the picture
7066 /// actually lands. Rendering a 1080p project's visualizer for a 600 px
7067 /// preview costs nine times the pixels for nothing the eye can see; a
7068 /// window that is fullscreen gets the project's own size back by pushing
7069 /// it. `true` when the size moved enough to be worth a new picture: under
7070 /// 8 px on both axes is a resize nobody can see, and a window being
7071 /// dragged would otherwise restart the picture every tick.
7072 pub fn set_view_size(&mut self, width: u32, height: u32) -> bool {
7073 let want = self.view_want(width, height);
7074 match self.view {
7075 Some(now) if now.0.abs_diff(want.0) < 8 && now.1.abs_diff(want.1) < 8 => false,
7076 _ => {
7077 self.view = Some(want);
7078 true
7079 }
7080 }
7081 }
7082
7083 /// [`Self::set_view_size`] with no deadband: what asks for the *exact*
7084 /// size rather than one within 8 px of it. A still saved at the project's
7085 /// own pixels is a file whose dimensions are read back, so "close enough
7086 /// to be invisible" is not close enough to be right. `true` when the view
7087 /// moved, `false` when it was already there -- which is also the answer
7088 /// that lets a caller skip waiting for a frame it already has.
7089 pub fn set_view_size_exact(&mut self, width: u32, height: u32) -> bool {
7090 let want = self.view_want(width, height);
7091 match self.view {
7092 Some(now) if now == want => false,
7093 _ => {
7094 self.view = Some(want);
7095 true
7096 }
7097 }
7098 }
7099
7100 /// The size a push of `(width, height)` settles on: even on both axes
7101 /// (YUV 4:2:0 has no odd chroma) and never past the project's own.
7102 fn view_want(&self, width: u32, height: u32) -> (u32, u32) {
7103 let fit = |n: u32, cap: u32| (n & !1).clamp(2, cap.max(2));
7104 (fit(width, self.meta.width), fit(height, self.meta.height))
7105 }
7106
7107 /// The canvas a span's pictures are painted at: [`Self::set_view_size`]'s
7108 /// size once one has been pushed, the project's own otherwise.
7109 pub fn view_size(&self) -> (u32, u32) {
7110 self.view.unwrap_or((self.meta.width, self.meta.height))
7111 }
7112
7113 /// Current timeline position in seconds.
7114 pub fn now(&self) -> f64 {
7115 self.clock.now()
7116 }
7117
7118 pub fn is_playing(&self) -> bool {
7119 self.clock.is_playing()
7120 }
7121
7122 pub fn play(&mut self) {
7123 if self.clock.is_playing() {
7124 return;
7125 }
7126 // Invariant: the clock is positioned *before* audio restarts. Audio
7127 // reports are relative to the first one after that, so a seek would go
7128 // here too -- `clock.seek_to(t)` and then `set_active(true)`.
7129 self.clock.play();
7130 // Above or below 1x the sound stays off: `set_rate(1.0)` brings it back.
7131 if let Some(audio) = self.audio.as_ref().filter(|_| self.clock.rate() == 1.0) {
7132 audio.set_playing(true);
7133 }
7134 }
7135
7136 /// Sets the playback speed: 1.0 is real time, 2/4/8 forward, -1/-2 backward.
7137 ///
7138 /// Anything but 1x runs the clock on wall time at that rate and keeps the
7139 /// sound silent -- audio cannot play backward or fast without a stretch the
7140 /// engine does not do here. Going back to 1x reopens the sound at the
7141 /// current position, as a seek does. Drawing the picture backward is not
7142 /// done for the sound; the picture is, from the playhead down ([`Back`]), and
7143 /// turning the clock round restarts it there.
7144 pub fn set_rate(&mut self, rate: f64) {
7145 if !rate.is_finite() || rate == 0.0 || rate == self.clock.rate() {
7146 return;
7147 }
7148 let was_backward = self.backward();
7149 if rate != 1.0 {
7150 if let Some(audio) = &self.audio {
7151 audio.set_playing(false);
7152 }
7153 self.clock.set_rate(rate);
7154 } else {
7155 self.clock.set_rate(1.0);
7156 if self.audio.is_some() {
7157 self.reseek_audio();
7158 }
7159 }
7160 if was_backward != self.backward() {
7161 let (_, target) = self.landing(self.now());
7162 self.start_picture(target);
7163 }
7164 }
7165
7166 pub fn pause(&mut self) {
7167 if !self.clock.is_playing() {
7168 return;
7169 }
7170 if let Some(audio) = &self.audio {
7171 audio.set_playing(false);
7172 }
7173 self.clock.pause();
7174 }
7175
7176 pub fn toggle(&mut self) {
7177 if self.clock.is_playing() {
7178 self.pause()
7179 } else {
7180 self.play()
7181 }
7182 }
7183
7184 /// Stops the transport where the timeline stops: the clock is paused and put
7185 /// on the out point.
7186 ///
7187 /// Playing past the last frame is wall time counting on past the end of the
7188 /// media -- there is no picture left to pace it -- so a session left at EOF
7189 /// reports a `now()` that walks off the end of the timeline in real time,
7190 /// and a caller that reads the playhead (a cut, a paste, an insert) then
7191 /// acts at a position no clip is at. How far off depends only on how long
7192 /// the window was left open, so no clamp in a caller is worth writing.
7193 ///
7194 /// End of stream is deliberately left set: the picture is still the last
7195 /// frame and this is still the end. That is what makes it safe to call on
7196 /// the crossing into it -- the state the transport shows does not change,
7197 /// only the running clock stops.
7198 /// Carries the clock on past the last frame, on wall time from where it stands, for a
7199 /// take that runs longer than the timeline. The audio is stopped with it: nothing is
7200 /// left to play. A no-op unless the clock runs on the audio device.
7201 pub fn run_past_end(&mut self) {
7202 if self.clock.source() != ClockSource::Audio {
7203 return;
7204 }
7205 if let Some(audio) = &self.audio {
7206 audio.set_playing(false);
7207 }
7208 self.clock.switch_to_wall();
7209 }
7210
7211 pub fn halt_at_end(&mut self) {
7212 self.pause();
7213 // Played backward the end it ran into is the start, and the rate goes back
7214 // to real time there: the next press plays on from the top.
7215 if self.backward() {
7216 self.set_rate(1.0);
7217 self.clock.seek_to(0.0);
7218 // The picture restart above cleared it; this is still the end.
7219 self.eos = true;
7220 return;
7221 }
7222 self.clock.seek_to(self.timeline_duration());
7223 }
7224
7225 /// The gain this session's device is running at, read back from the device
7226 /// rather than remembered here: `None` with no audio output, or a plugin
7227 /// too old to answer -- the two cases where a remembered answer would be a
7228 /// claim nothing can check.
7229 pub fn gain(&self) -> Option<f32> {
7230 self.audio.as_ref()?.ao.lock().unwrap().gain()
7231 }
7232
7233 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
7234 /// one knob, because muting and turning it down are the same thing to the
7235 /// device, and *which* the user meant is a question only the UI can answer
7236 /// -- it keeps the level to come back to.
7237 ///
7238 /// The level is remembered for as long as this session lives
7239 /// ([`Audio::gain`]) and only so that a device which is *replaced* under
7240 /// the session -- re-armed after a death, armed by a late import -- comes
7241 /// back at the level the session was already running at. It is still not
7242 /// project state: a fresh session starts at 1.0, so a caller still pushes
7243 /// it once per session, and an export -- which renders the file rather
7244 /// than what the speakers are doing -- can never pick it up. Silent with
7245 /// no audio device, which is also the only honest answer there.
7246 ///
7247 /// Mute is not pause: the samples are still consumed and the device clock
7248 /// still runs, so the picture keeps playing against it.
7249 pub fn set_gain(&self, gain: f32) -> bool {
7250 match &self.audio {
7251 // The device is the owner and is told first: a remembered level
7252 // that says something the device does not agree with is worse
7253 // than no memory at all, because the next replacement would
7254 // restore the wrong number.
7255 Some(audio) if audio.ao.lock().unwrap().set_volume(gain) => {
7256 audio.gain.store(gain.to_bits(), Ordering::Release);
7257 true
7258 }
7259 _ => false,
7260 }
7261 }
7262
7263 /// A copy of the most recent mono samples the device was handed, and the
7264 /// rate they play at: the signal *after* every clip's equalizer, speed and
7265 /// the mix, which is what an analyser drawn behind an EQ curve has to show.
7266 /// `None` with no audio output at all, and empty until the feeder has
7267 /// written once (right after a seek, for instance).
7268 ///
7269 /// Never blocks anything that matters: the feeder holds this lock for one
7270 /// memcpy and the device's own callback lives in the plugin, on the far
7271 /// side of a ring buffer, where it cannot see this at all.
7272 pub fn audio_tap(&self) -> Option<(Vec<f32>, u32)> {
7273 let audio = self.audio.as_ref()?;
7274 let tap = audio.tap.lock().unwrap().clone();
7275 Some((tap, audio.sample_rate))
7276 }
7277
7278 /// Says that this session is being **watched in real time**, so a picture
7279 /// whose moment has passed is worth nothing and the decode worker may drop
7280 /// it where it is cheap to drop -- before the conversion (a full BGRA pass
7281 /// over 8 MB at 1080p) and before the queue.
7282 ///
7283 /// Off by default, and that is the contract every *pull* consumer relies on:
7284 /// an export, the file-level [`DecodeSession`] API and a test draining as
7285 /// fast as it can all ask for a range of frames and must be given every one
7286 /// of them, in order. Only a viewer has a moment for a picture to be past.
7287 ///
7288 /// A front-end that turns this on was dropping those very frames itself, one
7289 /// repaint later (`Player::pump` takes everything due and shows the last):
7290 /// what changes is where the work stops, and therefore how quickly a decoder
7291 /// that fell behind catches up.
7292 ///
7293 /// It does not replace [`resync_picture`](Self::resync_picture): both
7294 /// mechanisms are live and this one is the first line. It catches up without
7295 /// restarting anything, which is why the front-end's resync -- a picture
7296 /// restart, once per `RESYNC_GAP` -- now fires only where dropping was not
7297 /// enough (a decoder so far behind that even one picture in nine
7298 /// ([`crate::decode`]'s `LATE_RUN`) cannot close the gap).
7299 pub fn drop_late_pictures(&mut self, on: bool) {
7300 self.drop_late = on;
7301 }
7302
7303 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
7304 /// workers are replaced rather than steered: a fresh channel cannot hold a
7305 /// stale frame, and it works just as well after EOF, where the old workers
7306 /// have already exited.
7307 ///
7308 /// Playing stays playing and paused stays paused -- but a paused seek still
7309 /// decodes, so the caller can show the frame it landed on.
7310 pub fn seek(&mut self, secs: f64) {
7311 let (t, target) = self.landing(secs);
7312 let was_playing = self.clock.is_playing();
7313 self.stop_audio();
7314 self.start_picture(target);
7315 if self.clock.rate() != 1.0 {
7316 // Sound stays silent off-speed; `set_rate(1.0)` reopens it here.
7317 self.clock.seek_to(t);
7318 return;
7319 }
7320 let audio_running = self.start_audio(target);
7321 // Same invariant as `play`: position the clock before audio restarts.
7322 if audio_running && self.clock.source() != ClockSource::Audio {
7323 self.clock.switch_to_audio();
7324 }
7325 self.clock.seek_to(t);
7326 self.resume(was_playing);
7327 }
7328
7329 /// Abandons whatever the picture worker still owes and restarts it at the
7330 /// clock. The sound and the clock are untouched -- this is the *video*
7331 /// catching up to its master, not a seek -- so nothing the ear is following
7332 /// moves, and a caller that is behind by more than it can watch calls this
7333 /// instead of waiting for a decoder that only falls further back
7334 /// (`Player::pump`).
7335 pub fn resync_picture(&mut self) {
7336 self.invalidate(Dirty::Picture);
7337 }
7338
7339 /// Where a seek to `secs` lands: the clamped timeline position and the
7340 /// timeline frame it means. The one place the clamp lives, so every
7341 /// invalidation below lands on the same frame a seek would.
7342 fn landing(&self, secs: f64) -> (f64, u32) {
7343 let fps = self.meta.frame_rate;
7344 let total = self.project.timeline_frames();
7345 let t = secs.clamp(0.0, f64::from(total) / fps);
7346 (t, secs_to_frame(t, fps).min(total.saturating_sub(1)))
7347 }
7348
7349 /// Rebuilds the **picture** at `target` and touches nothing else: the sound
7350 /// keeps playing out of the same stream, the clock keeps running, and a
7351 /// grade dragged during playback is therefore silent.
7352 fn start_picture(&mut self, target: u32) {
7353 // Abandon first, drop second: the old worker may be parked in `send` on
7354 // the bounded channel, where only the disconnect wakes it -- and it
7355 // then finds the span already superseded. The *thread* is kept, and
7356 // with it the open file and the open decoder, so a seek onto the same
7357 // source costs a demuxer seek and a decoder flush rather than the
7358 // VA-API init (98 ms) a new worker would pay; a worker that cannot take
7359 // the new span is retired by [`retire`](Self::retire) instead, and
7360 // nothing on this thread joins either way.
7361 self.worker.abandon();
7362 // The span runs from `target` to the end of whatever it landed in -- a
7363 // clip, or a gap, which starts a black-frame worker instead. `None` is
7364 // the emptied timeline, black too, and `start_span` says so.
7365 let span = match self.backward() {
7366 true => back_span_at(&self.project.render_view(), target),
7367 false => crate::export::stack_span_at(&self.project.render_view(), target),
7368 };
7369 self.start_span(span);
7370 self.eos = false;
7371 }
7372
7373 /// Silences the device and supersedes whatever is feeding it: the first half
7374 /// of every audio restart, and the only thing that ever discards queued
7375 /// sound.
7376 fn stop_audio(&mut self) {
7377 self.mix = None;
7378 if let Some(audio) = &self.audio {
7379 let ao = audio.ao.lock().unwrap();
7380 ao.set_active(false);
7381 // Bumped and flushed while holding the device lock, because the
7382 // feeder re-checks the epoch inside that same lock: whatever it is
7383 // carrying can no longer reach the ring after this point.
7384 audio.epoch.fetch_add(1, Ordering::Release);
7385 // Nothing of the new stream has been played yet, by definition.
7386 audio.content_at.store(-1, Ordering::Release);
7387 ao.flush();
7388 // The flushed samples are not being played any more, so nothing may
7389 // still be drawn from them.
7390 audio.tap.lock().unwrap().clear();
7391 }
7392 }
7393
7394 /// Puts the device back where it was: playing if it was playing, and with
7395 /// the clock held until the new stream is really audible (see
7396 /// [`Audio::content_at`]).
7397 ///
7398 /// Only the *intent* is set here: the open runs on the feeder
7399 /// ([`start_audio`](Self::start_audio)), so the device is started by that
7400 /// stream's first real sample instead ([`Audio::wants_active`]). A device
7401 /// made active over an empty ring plays its own silence and counts one
7402 /// underrun per starved quantum -- a scripted cold play-seek-scrub session
7403 /// used to go from 5 to 1721 of them -- while the ear hears the same silence
7404 /// either way, so nothing is gained for the count that is lost.
7405 fn resume(&mut self, was_playing: bool) {
7406 self.priming = true;
7407 if let Some(audio) = &self.audio {
7408 audio.set_playing(was_playing);
7409 }
7410 }
7411
7412 /// Rebuilds the **sound** from `target` -- the second half of a restart --
7413 /// and says whether a feeder took the job. Not whether it will find
7414 /// anything to play: the stream is opened on that feeder
7415 /// ([`Audio::spawn_feeder_deferred`]), so a silent timeline is heard of
7416 /// there, not here. Nothing on this thread reads the file.
7417 ///
7418 /// The clock is unaffected by the wait, which is the reason it may be a
7419 /// long one: it holds where the seek put it until the *first real sample*
7420 /// is queued ([`Audio::content_at`], [`tick`](Self::tick)), whether that is
7421 /// ten milliseconds later or ten seconds.
7422 ///
7423 /// `true` is therefore *optimistic*, and the callers' `switch_to_audio` with
7424 /// it: a timeline that turns out to have nothing to play ends its feeder at
7425 /// once, which sets `fed_all` and hands the clock back to wall time at the
7426 /// next tick, from where it stood ([`PlaybackClock::switch_to_wall`] is
7427 /// continuous, so nothing jumps).
7428 fn start_audio(&mut self, target: u32) -> bool {
7429 let fps = self.meta.frame_rate;
7430 let mut audio_running = false;
7431 let mut live = None;
7432 // A dead output gets an attempt here without waiting out the cooldown: a
7433 // seek is a person asking, and this is the one moment the sound can come
7434 // back into step with the picture, because the feeder opened below starts
7435 // at the target. If it does not come back the flag stands and the guard
7436 // under it leaves the clock on wall time.
7437 self.rearm_audio(Duration::ZERO);
7438 if let Some(audio) = &self.audio
7439 && !audio.died.load(Ordering::Acquire)
7440 {
7441 // The device position keeps counting across a flush, so re-basing
7442 // `fed` on it is what keeps `played_out` exact for the new stream.
7443 let played = audio.ao.lock().unwrap().position().unwrap_or(0).max(0) as u64;
7444 audio.fed.store(played * audio.channels, Ordering::Relaxed);
7445 audio.fed_all.store(false, Ordering::Release);
7446 // One worker for the whole rest of the timeline, so the joins
7447 // between clips are gapless: the video reopens at a boundary, the
7448 // ear never hears it -- and a join between two *files* is just
7449 // another segment, because every segment names its own source.
7450 // One play list per audio lane, summed by the mixer: what the ear
7451 // hears is every lane at once, and a lane's own gaps are silence in
7452 // it rather than a hole in the count the master clock keeps.
7453 let segs = self.project.render_view().audio_segments_from(target, fps);
7454 // The equalizers beside them, one per segment: the worker filters a
7455 // segment's own samples before the mix, so a clip's curve reaches
7456 // that clip and stops. Rebuilt on every seek, which is what makes an
7457 // EQ edit audible at once -- `edit` reseeks, so the drag that
7458 // changed a band restarts the workers with the new curve already in
7459 // them, and no live channel has to reach into a running one.
7460 let eqs = self.project.render_view().audio_eqs_from(target, fps);
7461 // ...and the rates, the same way again: a speeded segment is
7462 // resampled inside its own worker, before the mix, so what the ear
7463 // hears is what the timeline shows. Empty for a project nobody has
7464 // speeded, which is the path that decodes the same samples it always
7465 // did.
7466 let speeds = self.project.render_view().audio_speeds_from(target, fps);
7467 // ...and the fades, the same way again: a clip's own envelope runs
7468 // inside its worker, after the rate and the equalizer, so a fade
7469 // edit is audible at once exactly as an EQ edit is.
7470 let fades = self.project.render_view().audio_fades_from(target, fps);
7471 // Each source on the stream it was placed with: what plays is what
7472 // the library row said, and what an export copies (`export::run`).
7473 let sources = self.project.audio_sources();
7474 // ...and the mix settings over the lot: each lane's own volume on
7475 // its way into the sum and the master limiter over the sum. These
7476 // two are handed over *live* as well as at the open: they sit at
7477 // the sum, where nothing is decoded, so a fader moved later is a
7478 // number the running mixer picks up rather than a stream rebuilt
7479 // under the ear ([`crate::audio::MixControls`]).
7480 let gains = self.mix_gains();
7481 let ducks = self.project.render_view().audio_ducks();
7482 // ...and the voice processors, which are not live: an edit to one
7483 // rebuilds the sound like an equalizer edit does.
7484 let voices = self.project.render_view().audio_voices();
7485 let limiter = self.project.limiter();
7486 let controls = crate::audio::MixControls::new(gains.clone(), ducks.clone(), limiter);
7487 // Only a mixed timeline has a mixer to talk to; the single-lane
7488 // flat path is the bit-exact one and has none. Decided here from
7489 // the very lists the open is about to be handed
7490 // ([`AudioSession::is_mixed`]) rather than read off the handle
7491 // afterwards, because there *is* no afterwards on this thread any
7492 // more -- the open runs on the feeder.
7493 let mixed = crate::audio::AudioSession::is_mixed(segs.len(), &gains, limiter, &voices);
7494 let worker_controls = Arc::clone(&controls);
7495 // ...and the rate the mix runs at, if the project picked one: the
7496 // same override [`crate::edith::save`] writes and [`Self::open_project`]
7497 // reads back.
7498 let sample_rate = self.sample_rate;
7499 // ...and the open itself -- every track a segment names, its packet
7500 // table, its priming -- happens there too. That is the whole point:
7501 // one `pread` on a cold 25 GB film is seconds, and this is called
7502 // from a ruler drag ([`Audio::spawn_feeder_deferred`]).
7503 audio_running = audio.spawn_feeder_deferred(move || {
7504 match AudioSession::open_mixed_streams_live_fade(
7505 &sources,
7506 &segs,
7507 &eqs,
7508 &speeds,
7509 &fades,
7510 fps,
7511 &gains,
7512 &ducks,
7513 &voices,
7514 limiter,
7515 Some(&worker_controls),
7516 sample_rate,
7517 ) {
7518 Ok(Some((_, rx))) => Some(rx),
7519 // A silent timeline, and a source that will not open: both
7520 // feed nothing, which the feeder itself reports by ending.
7521 // The mix goes with them -- no mixer was started, so a fader
7522 // moved later must rebuild the sound rather than hand its
7523 // number to a thread that does not exist
7524 // ([`crate::audio::MixControls::detach`]).
7525 Ok(None) => {
7526 worker_controls.detach();
7527 None
7528 }
7529 Err(e) => {
7530 worker_controls.detach();
7531 // A read this session abandoned on purpose -- the seek
7532 // after it, or the session going away -- is not a file
7533 // that would not open, and says nothing.
7534 if !crate::demux::is_cancelled(&e) && std::env::var_os("EDITH_DEBUG").is_some() {
7535 eprintln!("timeline audio open failed: {e}");
7536 }
7537 None
7538 }
7539 }
7540 });
7541 live = (audio_running && mixed).then_some(controls);
7542 if !audio_running {
7543 // Nothing will ever be fed again; let `tick` fall to wall time
7544 // instead of waiting on a device that has no more work coming.
7545 audio.fed_all.store(true, Ordering::Release);
7546 }
7547 }
7548 self.mix = live;
7549 audio_running
7550 }
7551
7552 /// Rebuilds the sound alone, from where the playhead is: what a change that
7553 /// no picture can show goes through. The video worker is left decoding, so
7554 /// the picture does not blink -- and the clock, held still by
7555 /// [`resume`](Self::resume) until the new stream is audible, puts the sound
7556 /// back exactly where the picture already is.
7557 ///
7558 /// End of stream is deliberately left alone -- no picture worker is started
7559 /// here, so a timeline that was played out still is; see
7560 /// [`is_eos`](Self::is_eos).
7561 fn reseek_audio(&mut self) {
7562 if self.clock.rate() != 1.0 {
7563 // Off-speed the sound is silent and `set_rate(1.0)` rebuilds it, so a
7564 // change to it now has nothing to rebuild.
7565 return;
7566 }
7567 let (t, target) = self.landing(self.now());
7568 let was_playing = self.clock.is_playing();
7569 self.stop_audio();
7570 let audio_running = self.start_audio(target);
7571 if audio_running && self.clock.source() != ClockSource::Audio {
7572 self.clock.switch_to_audio();
7573 }
7574 self.clock.seek_to(t);
7575 self.resume(was_playing);
7576 }
7577
7578 /// Renders the edited timeline to `out` on a worker thread. The session is
7579 /// untouched -- the export decodes the source file for itself -- but a
7580 /// caller should still [`pause`](PlaybackSession::pause) first, because
7581 /// playback and export otherwise fight over the same decoder hardware.
7582 ///
7583 /// Later edits do not reach a running export: it works from a snapshot of
7584 /// the edit list taken here.
7585 ///
7586 /// corner-cut: this defaults the settings; the app still calls it that way,
7587 /// and the export options card replaces the call with
7588 /// [`export_to_with`](PlaybackSession::export_to_with).
7589 pub fn export_to(&self, out: &Path) -> crate::ExportHandle {
7590 self.export_to_with(out, &crate::export::ExportSettings::default())
7591 }
7592
7593 /// [`export_to`](PlaybackSession::export_to) with the output settings spelled
7594 /// out rather than defaulted.
7595 pub fn export_to_with(
7596 &self,
7597 out: &Path,
7598 settings: &crate::export::ExportSettings,
7599 ) -> crate::ExportHandle {
7600 // The chapter marks, measured from the export's own start (the range's
7601 // `from`, the same clock `chapter_list_ns` uses). A caller's list wins.
7602 let mut settings = settings.clone();
7603 if settings.chapters.is_empty() {
7604 settings.chapters = self.chapter_list_ns(settings.range);
7605 }
7606 let mut snapshot = self.project.export_snapshot();
7607 // A range that never reads a missing file is written without opening it.
7608 if let Some(range) = settings.range {
7609 snapshot.drop_offline_outside(range, crate::source_present);
7610 }
7611 crate::export::start(snapshot, self.meta, out, &settings, self.sample_rate)
7612 }
7613
7614 /// Moves the clock forward; the caller runs this once per rendered frame.
7615 /// Costs an atomic load, and once per session a mode switch.
7616 pub fn tick(&mut self) {
7617 // Before every early return below: where the playhead stands is what the
7618 // decode worker drops its stale pictures against, and a front-end that
7619 // repaints without draining (a slow frame, a busy render thread) must
7620 // still be moving it -- otherwise the queue fills with pictures whose
7621 // moment passed while nobody was taking them.
7622 self.publish_playhead();
7623 // Before the clock-source guard below, and not after it: a dead output is
7624 // what *puts* the clock on wall time, so this branch has to keep running
7625 // while it is there -- the one attempt that can bring the sound back is
7626 // in it.
7627 if self
7628 .audio
7629 .as_ref()
7630 .is_some_and(|audio| audio.died.load(Ordering::Acquire))
7631 {
7632 // Output died mid-stream: its position will never reach `fed`, so the
7633 // EOF comparison below is unreachable. Wall time takes over from
7634 // wherever the clock last stood, and the session says so rather than
7635 // going silent for good without a word: a front-end already has a
7636 // line for a silent session ([`Self::audio_disabled_reason`]).
7637 if self.audio_disabled.is_none() {
7638 self.audio_disabled = Some(AUDIO_LOST.to_string());
7639 }
7640 self.clock.switch_to_wall();
7641 // ...and the output is offered another open, once a second: a
7642 // restarting daemon takes a moment, and this runs once a frame. A
7643 // re-arm that takes is what clears the notice, and the next seek
7644 // feeds it.
7645 self.rearm_audio(AUDIO_REARM_AFTER);
7646 return;
7647 }
7648 let Some(audio) = &self.audio else {
7649 return; // wall time from the start, nothing to poll
7650 };
7651 if self.clock.source() != ClockSource::Audio {
7652 return;
7653 }
7654 // `None` until the device's first callback: the clock holds at its
7655 // anchor rather than guessing, which is why playback starts on time
7656 // instead of a quantum early.
7657 let Some(position) = audio.ao.lock().unwrap().position() else {
7658 return;
7659 };
7660 if audio.played_out(position) {
7661 // Audio EOF. Wall time carries the same timeline on from here, with
7662 // no jump, and this branch cannot be reached again.
7663 //
7664 // The device is stopped with it: nothing will ever be queued for
7665 // this stream again, so every quantum it would go on playing is
7666 // silence counted as a decoder that fell behind -- the tail of a
7667 // stream, where [`crate::ao`]'s own `primed` covers the head of
7668 // one. A seek from here starts it again like any other
7669 // ([`resume`](Self::resume)), which is why the stamp goes with it:
7670 // there is no sample of *this* stream left to start on.
7671 audio.set_playing(false);
7672 audio.content_at.store(-1, Ordering::Release);
7673 self.clock.switch_to_wall();
7674 return;
7675 }
7676 if self.priming {
7677 // A stream that has been started and has not been heard yet: the
7678 // device is playing the silence of its own restart, and none of it
7679 // is timeline time ([`Audio::content_at`]). The clock holds where
7680 // the seek left it -- so the picture holds too, on the frame it
7681 // landed on, rather than sliding ahead of a sound that has not
7682 // started.
7683 let started = audio.content_at.load(Ordering::Acquire);
7684 if started < 0 {
7685 return;
7686 }
7687 // ...and then the *first sample of the stream* becomes the
7688 // reference, not whatever position this poll happened to catch: the
7689 // clock's own anchor is its first report ([`PlaybackClock`]), and
7690 // anchoring it here is what makes a mid-play edit cost no offset.
7691 //
7692 // corner-cut: `started` is the position when the sample was queued,
7693 // and it is heard at the next callback -- up to one quantum (5-21
7694 // ms) later, so that much of the restart is still counted. Upgrade
7695 // path is the position at the first *pop* of real audio, which only
7696 // the plugin's RT thread can see.
7697 self.clock
7698 .set_audio_position(started as u64, audio.sample_rate);
7699 self.priming = false;
7700 }
7701 self.clock
7702 .set_audio_position(position as u64, audio.sample_rate);
7703 }
7704}
7705
7706impl Drop for PlaybackSession {
7707 /// The video workers -- the running one and every cancelled one still in
7708 /// [`retired`](PlaybackSession::retired) -- cancel and join themselves when
7709 /// those fields drop right after this, the running one behind its receiver
7710 /// so a `send` cannot hold the join. *That* is what a session must not exit
7711 /// without: no decode worker outlives it, so none can be inside libva when
7712 /// Mesa's `atexit` handlers free the state under it.
7713 ///
7714 /// This is the audio half: bumping the epoch retires the feeder at its next write,
7715 /// which drops the decode receiver with it. Neither is waited for -- no
7716 /// driver state is torn down on the audio side.
7717 fn drop(&mut self) {
7718 if let Some(audio) = &self.audio {
7719 audio.epoch.fetch_add(1, Ordering::Release);
7720 }
7721 }
7722}
7723
7724/// Whether `path`, already demuxed to `meta`, may join a timeline whose
7725/// parameters are `timeline` and whose audio probes as `first`: a decoder this
7726/// machine can open, audio parameters that agree (or no audio at all), and a
7727/// frame rate that can be named
7728/// against the timeline's. The [`Rate`] it will be read at comes back with the
7729/// answer, so the number the check was decided on is the number it plays by.
7730///
7731/// *Not* the same size any more. A project has its own resolution
7732/// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its
7733/// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
7734/// letterboxed clip rather than a refusal, and so is a frame rate of its own:
7735/// the timeline keeps its own rate and the file is read at [`Rate`] against it
7736/// ([`PlaybackSession::import`] notes how long it is *here*). Nor the same
7737/// codec: every clip opens its own decoder, so a mixed-codec timeline is a
7738/// decoder each rather than a refusal.
7739///
7740/// The `Err` names the property that disagrees, and those strings are what a
7741/// front-end shows verbatim; [`PlaybackSession::import`] and
7742/// [`PlaybackSession::open_project`] share them so a file refused at import is
7743/// refused in the same words at load.
7744fn matches_timeline(
7745 source: &Source,
7746 meta: &VideoMeta,
7747 timeline: &VideoMeta,
7748 first: &Option<crate::AudioProbe>,
7749) -> crate::Result<Rate> {
7750 // The codec is *not* held to the timeline's -- every clip opens its own
7751 // decoder, so an H.264 take and an HEVC one play on one timeline. What the
7752 // codec gate was really protecting against stays, in the one place that
7753 // can actually answer it: on a machine without the VA-API plugin an HEVC
7754 // or VP8 clip would be black frames with the refusal on stderr alone,
7755 // so the file is asked for a decoder *here*, at the door, where the `Err`
7756 // is still something a front-end can show. A zero-length range probes and
7757 // starts no
7758 // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`]
7759 // only enters VA-API off that path.
7760 DecodeSession::open_worker(
7761 &source.path,
7762 0,
7763 0,
7764 ColorParams::default(),
7765 TransformParams::default(),
7766 Composer::passthrough(),
7767 // A zero-length range decodes nothing, so no table is built and the
7768 // rendition cannot matter here.
7769 crate::tonemap::Preset::default(),
7770 )?;
7771 // The frame rate is *not* a refusal any more: a file shot at another rate is
7772 // placed for the seconds it lasts and read through [`Rate`] at the
7773 // decoder's door, so it plays at the speed it was shot at on a timeline
7774 // that counts frames faster or slower.
7775 //
7776 // A rate that cannot be *named* still is, and this is the one place it is
7777 // caught: `Rate::from_fps` builds itself out of the muxer's own timescales,
7778 // and a file whose rate has none of those (a container that says nothing and
7779 // holds one block, so the demuxer measures 0 fps) would otherwise be read
7780 // 1:1 in silence -- the old rate gate refused those too, by arithmetic
7781 // accident. The `Err` is `mux::frame_timing`'s own words.
7782 let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?;
7783 audio_matches(source, first)?;
7784 Ok(rate)
7785}
7786
7787/// Whether a candidate's audio may join a timeline whose first source probes as
7788/// `first`: same layout -- or no audio of its own at all, which is silence over
7789/// the clip's span and agrees with everything. One output device and one
7790/// exported track is all there is, so one width; the *rate* is conformed rather
7791/// than matched ([`crate::audio::Resample`]), which is why it is not asked
7792/// about here.
7793///
7794/// The audio half of [`matches_timeline`], which a stream placed on its own
7795/// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
7796/// comes with is already on the timeline.
7797///
7798/// The format itself is deliberately *not* part of this: an mp3 that agrees on
7799/// layout plays alongside a timeline of mp4s perfectly well. What it
7800/// cannot do is be copied into an export, which is a refusal of its own, at
7801/// export time (`AudioSession::copy_multi_streams`).
7802/// What a timeline's audio is held to: the probe of the first source that could
7803/// have any track.
7804///
7805/// The probe of the first source that really **has a track**, walking forward
7806/// past a still (no track by definition) and past a source whose file carries
7807/// none (a screen recording with no sound). A silent leading source must not
7808/// pin the timeline's layout: pinned to it, a later file with sound could never
7809/// be admitted, and the layout a *following* file is held to would be the
7810/// silent source's `None`. This is the same walk
7811/// [`PlaybackSession::open_project`] makes when it opens the device -- the two
7812/// have to agree, so probing and opening can never name different sources.
7813///
7814/// `Ok(None)` for a timeline with no track anywhere: nothing but stills, with
7815/// no file at all, or every non-still source silent. That is a silent timeline,
7816/// and a file with sound is admitted onto it -- it *becomes* the timeline's
7817/// sound ([`PlaybackSession::arm_audio`] opens the device for it), exactly the
7818/// c581d41 rule ("a later source with real audio must be heard") at the add
7819/// door.
7820fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
7821 for source in sources
7822 .iter()
7823 .filter(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
7824 {
7825 if let Some(probe) = AudioSession::probe(&source.path, source.audio_stream)? {
7826 return Ok(Some(probe));
7827 }
7828 }
7829 Ok(None)
7830}
7831
7832/// Whether a file is sound and no picture, which decides the lane it goes on.
7833/// The extension answers for a song; an mp4 or Matroska file is asked of its
7834/// header the way [`PlaybackSession::import`] asks it, so an audio-only mp4
7835/// lands on an audio lane exactly as it imports and reopens.
7836fn sound_only(path: &Path) -> bool {
7837 if crate::is_audio(path) {
7838 return true;
7839 }
7840 if crate::is_image(path) {
7841 return false;
7842 }
7843 matches!(Demuxer::open(path), Err(ref e) if NoVideoTrack::is_it(e))
7844}
7845
7846/// *Which* source that is: the first one that is not a still. The single answer
7847/// to "what does this timeline's sound come from", so that probing it
7848/// ([`first_audio_of`]) and opening the device on it
7849/// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only
7850/// the scaffolding file until a save renumbers it or a library removal takes it
7851/// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the
7852/// device is a timeline that plays silent although every clip on it has sound.
7853///
7854/// `None` for a library of nothing but stills, and for one with no file at all:
7855/// both are silent timelines.
7856fn audio_source_of(sources: &[Source]) -> Option<&Source> {
7857 sources
7858 .iter()
7859 .find(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
7860}
7861
7862fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
7863 let probe = AudioSession::probe(&source.path, source.audio_stream)?;
7864 audio_matches_probed(probe, first)
7865}
7866
7867/// The verdict alone, once the file's own header is in hand: the half a session
7868/// with a memo behind it ([`PlaybackSession::audio_matches_cached`]) does not
7869/// have to open the file for.
7870fn audio_matches_probed(
7871 probe: Option<crate::AudioProbe>,
7872 first: &Option<crate::AudioProbe>,
7873) -> crate::Result<()> {
7874 // The layout, which the audio worker holds every source to anyway -- and not
7875 // the rate any more: a file written at another one is resampled to the
7876 // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as
7877 // a file shot at another frame rate is read through [`Rate`]. Both silent is
7878 // a match.
7879 if probe.map(|p| p.channels) == first.map(|p| p.channels) {
7880 return Ok(());
7881 }
7882 // A mono file joins a wider timeline: [`crate::audio::widen`] duplicates
7883 // its one channel into every channel the timeline carries, the inverse of
7884 // the [`crate::audio::downmix`] a wider file already folds through. A
7885 // wider file onto a mono timeline -- beyond a stereo pair -- stays refused
7886 // below; the stereo pair is narrowed by [`crate::audio::widen`] (below).
7887 if let (Some(p), Some(b)) = (probe, first)
7888 && p.channels == 1
7889 && b.channels > 1
7890 {
7891 return Ok(());
7892 }
7893 // ...and a stereo file joins a mono timeline: [`crate::audio::widen`]
7894 // averages its pair into the one channel the timeline carries. Import and
7895 // open both come through here, so a project this accepts always reopens.
7896 if let (Some(p), Some(b)) = (probe, first)
7897 && p.channels == 2
7898 && b.channels == 1
7899 {
7900 return Ok(());
7901 }
7902 // ...and a *silent* file joins whatever the timeline is: it contributes
7903 // silence over its span, which is the very thing both audio paths already
7904 // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays
7905 // it, `AudioSession::copy_multi_streams` writes it). There is no rate and
7906 // no layout to disagree about, so there is nothing left to refuse.
7907 let Some(probe) = probe else {
7908 return Ok(());
7909 };
7910 // The timeline has no track anywhere (nothing but stills, or every
7911 // non-image source silent): there is no layout to disagree with, and the
7912 // arriving file with sound *becomes* the timeline's sound --
7913 // [`PlaybackSession::arm_audio`] opens the device for it, exactly the walk
7914 // [`PlaybackSession::open_project`] makes. Refusing here ("the file has
7915 // audio, the timeline is silent") pinned the timeline to its silent first
7916 // source for good: remove that file and add another, and the second file's
7917 // sound could never be heard.
7918 let Some(b) = first else {
7919 return Ok(());
7920 };
7921 Err(format!(
7922 "audio {} ch does not match the timeline's {} ch",
7923 probe.channels, b.channels
7924 )
7925 .into())
7926}
7927
7928/// How many timeline frames a still image is *held to*: [`IMAGE_MAX_SECS`] of
7929/// them, since an image has no length of its own. The number a source's own
7930/// entry in [`PlaybackSession::counts`] gets, so a trim may drag an image out
7931/// to ten minutes and no further -- and so a saved project reloads, because
7932/// [`PlaybackSession::open_project`] recomputes exactly this and refuses a clip
7933/// that ends past it.
7934fn image_frames(fps: f64) -> u32 {
7935 ((IMAGE_MAX_SECS * fps)
7936 .ceil()
7937 .clamp(1.0, f64::from(u32::MAX))) as u32
7938}
7939
7940/// How long a still is placed for: `secs` (the project's still length), never past the length
7941/// it is held to and never zero (a clip is never empty).
7942fn place_frames(count: u32, fps: f64, secs: f64) -> u32 {
7943 ((secs * fps)
7944 .ceil()
7945 .clamp(1.0, f64::from(count.max(1)))) as u32
7946}
7947
7948/// The project one document of a file describes, on the canvas and rate `meta` gives it.
7949fn project_of(doc: crate::edith::Document, meta: &VideoMeta) -> crate::Result<Project> {
7950 let subtitles = crate::subtitle::open_all(&doc.subtitles);
7951 Ok(
7952Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)?
7953 .with_mix(&doc.gains, doc.limiter)
7954 .with_ducks(&doc.ducks)
7955 .with_voices(&doc.voices)
7956 .with_lane_names(&doc.names)
7957 .with_bins(doc.bins)
7958 .with_lane_flags(&doc.flags)
7959 .with_tone(doc.tone)
7960 .with_notes(doc.notes)
7961 .with_still_secs(doc.still_secs)
7962 // The palette before what is placed on it: a caption names a row of
7963 // it, and [`Project::with_subs`] refuses one naming a row that is
7964 // not there.
7965 .with_subtitles(subtitles)
7966 .with_sub_langs(&doc.sub_langs)
7967 // The cue overrides, over the words the files gave: a retyped
7968 // cue comes back as it was typed.
7969 .with_cue_edits(&doc.cue_edits)
7970 // ...and the cues added to a track, after the file's own, each at
7971 // its start (see [`crate::edith`]'s `cueadd` lines).
7972 .with_cue_adds(&doc.cue_adds)
7973 // The title cards and text overlays, in the order the file has them.
7974 .with_titles(doc.titles)
7975 // The chapter markers, in frame order (see [`crate::edith`]'s `chapter` lines).
7976 .with_chapters(doc.chapters)
7977 // The comment markers, in frame order (`marker` lines).
7978 .with_markers(doc.markers)
7979 .with_cue_words(&doc.cue_words)
7980 .with_caption_style(doc.caption_style)
7981 .with_subs(doc.subs)?
7982 // The header a load puts back: the canvas and rate above, which a
7983 // save's own `resolution`/`fps` lines may have moved off the
7984 // scaffold's, and the switches the literal below carries -- handed
7985 // in here because they are the project's own and a door that moved
7986 // one after this would snapshot whatever copy it holds, which until
7987 // this line is the placeholder's. No undo step for
7988 // [`Project::with_mix`]'s reason: a project that arrived one `z`
7989 // from a state it was never in is a project whose first undo is a
7990 // surprise.
7991 .with_canvas(meta.width, meta.height, meta.frame_rate)
7992 .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate)
7993 )
7994}
7995
7996/// The two tables a trim measures by, `(picture, sound)`: [`wall_table`] for a
7997/// video lane and for an audio one, so a linked take's members each meet their
7998/// own lane's length. Borrows `counts` only, so the caller may hold them across
7999/// a `&mut` to the project.
8000fn lane_walls<'a>(
8001 sources: &[Source],
8002 counts: &'a [u32],
8003 fps: f64,
8004) -> (Cow<'a, [u32]>, Cow<'a, [u32]>) {
8005 (
8006 wall_table(sources, counts, fps, Lane::V1),
8007 wall_table(sources, counts, fps, Lane::A1),
8008 )
8009}
8010
8011/// The length each source's clips are walled by on `lane`, in timeline frames.
8012/// A clip on an audio lane takes the sound, so a video source's own audio stream
8013/// sets its length there (the picture's frame count is the length everywhere
8014/// else, and `counts` is that table). Stills and audio files already are their
8015/// sound's length in `counts`, and a source with no audio stream keeps its
8016/// `counts` entry. Mirrors the length `place` gives an audio-lane placement in
8017/// the MCP (`source_frames`).
8018fn wall_table<'a>(sources: &[Source], counts: &'a [u32], fps: f64, lane: Lane) -> Cow<'a, [u32]> {
8019 if lane.kind != LaneKind::Audio {
8020 return Cow::Borrowed(counts);
8021 }
8022 Cow::Owned(
8023 sources
8024 .iter()
8025 .zip(counts)
8026 .map(|(source, &frames)| {
8027 if crate::is_image(&source.path) || crate::is_audio(&source.path) {
8028 return frames;
8029 }
8030 match audio_stream_secs(&source.path, source.audio_stream) {
8031 Some(secs) if secs > 0.0 => (secs * fps).ceil().clamp(1.0, f64::from(u32::MAX)) as u32,
8032 _ => frames,
8033 }
8034 })
8035 .collect(),
8036 )
8037}
8038
8039/// How long a placed file's clip is: its picture's frame count, held to the length
8040/// its sound is walled by ([`wall_table`]) when it has one. A grouped take puts the
8041/// same clip on the picture lane and the sound lane, so a 2.002 s picture beside a
8042/// 2.000 s sound is 60 frames, not 61 -- the sound's own wall is what the load and
8043/// save checks hold the audio lane to, and one clip must satisfy both lanes.
8044fn sound_held_frames(path: &Path, stream: usize, frames: u32, fps: f64) -> u32 {
8045 if crate::is_image(path) || crate::is_audio(path) {
8046 return frames.max(1);
8047 }
8048 match audio_stream_secs(path, stream) {
8049 Some(secs) if secs > 0.0 => {
8050 let held = (secs * fps).ceil().clamp(1.0, f64::from(u32::MAX)) as u32;
8051 frames.min(held).max(1)
8052 }
8053 _ => frames.max(1),
8054 }
8055}
8056
8057/// [`AudioSession::stream_duration_secs`] for one stream, remembered per file:
8058/// a trim asks for it on every drag step. Only a found length is kept; a file
8059/// that cannot be read now may be back in a moment.
8060fn audio_stream_secs(path: &Path, stream: usize) -> Option<f64> {
8061 static SECS: std::sync::OnceLock<Mutex<std::collections::HashMap<(PathBuf, usize), f64>>> =
8062 std::sync::OnceLock::new();
8063 let cache = SECS.get_or_init(Default::default);
8064 let key = (path.to_path_buf(), stream);
8065 if let Some(&secs) = cache.lock().ok()?.get(&key) {
8066 return Some(secs);
8067 }
8068 let secs = AudioSession::stream_duration_secs(path, stream).ok()??;
8069 cache.lock().ok()?.insert(key, secs);
8070 Some(secs)
8071}
8072
8073/// How many timeline frames a standalone audio file occupies: its playing time
8074/// rounded *up*, so the last partial frame is still covered rather than cut off,
8075/// and never zero (a clip is never empty).
8076fn audio_frames(path: &Path, fps: f64) -> crate::Result<u32> {
8077 let secs = AudioSession::duration_secs(path)?
8078 .ok_or_else(|| format!("{} has no audio track", path.display()))?;
8079 let frames = (secs * fps).ceil();
8080 if !frames.is_finite() || frames < 0.0 || frames > f64::from(u32::MAX) {
8081 return Err(format!(
8082 "{} is {secs} s long, which is not a timeline",
8083 path.display()
8084 )
8085 .into());
8086 }
8087 Ok((frames as u32).max(1))
8088}
8089
8090/// `None` for a silent session -- no audio track, no plugin, no daemon, or a
8091/// track the decoder refuses. Dropping the receiver on the way out stops the
8092/// audio decode worker, so a failure here leaves nothing running.
8093///
8094/// The second half is why, for the cases the *file* is to blame for: those are
8095/// a surprise worth showing (see
8096/// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a
8097/// file with no audio at all and a machine with no output device are not.
8098fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
8099 let sources = [(path.to_path_buf(), stream)];
8100 let (meta, rx) =
8101 match AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) {
8102 Ok(Some(opened)) => opened,
8103 // No AAC track: silent by nature, or sound in a codec we do not
8104 // have -- and only the second of those is worth a word.
8105 Ok(None) => {
8106 let reason = AudioSession::unsupported(path).ok().flatten();
8107 if let Some(reason) = &reason {
8108 crate::audio::debug_once(format!("audio disabled: {reason}"));
8109 }
8110 return (None, reason);
8111 }
8112 Err(e) => {
8113 crate::audio::debug_once(format!("audio disabled: {e}"));
8114 return (None, Some(e.to_string()));
8115 }
8116 };
8117 let Some(ao) = AoSession::open(meta.sample_rate, u32::from(meta.channels)) else {
8118 return (None, None); // no device: the machine's business, not the file's
8119 };
8120 // The stream comes up streaming; a session starts paused, so silence the
8121 // device until `play`. The feeder still fills the ring in the meantime.
8122 ao.set_active(false);
8123
8124 let audio = Audio {
8125 ao: Arc::new(Mutex::new(ao)),
8126 sample_rate: meta.sample_rate,
8127 channels: u64::from(meta.channels),
8128 fed: Arc::new(AtomicU64::new(0)),
8129 fed_all: Arc::new(AtomicBool::new(false)),
8130 died: Arc::new(AtomicBool::new(false)),
8131 epoch: Arc::new(AtomicU64::new(0)),
8132 content_at: Arc::new(AtomicI64::new(-1)),
8133 gain: Arc::new(AtomicU32::new(1.0f32.to_bits())),
8134 wants_active: Arc::new(AtomicBool::new(false)),
8135 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),
8136 peak: Arc::new(AtomicU32::new(0)),
8137 peak_lr: Arc::new([AtomicU32::new(0), AtomicU32::new(0)]),
8138 feeders: Arc::new(AtomicUsize::new(0)),
8139 rearm_at: Arc::new(Mutex::new(None)),
8140 };
8141 (audio.spawn_feeder(rx).then_some(audio), None)
8142}
8143
8144/// Pours decoded chunks into the device, keeping whatever the ring would not
8145/// take. Ends when the decoder is done, the output dies, or a seek supersedes
8146/// this feeder.
8147fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
8148 let mut pending: Vec<f32> = Vec::new();
8149 loop {
8150 if pending.is_empty() {
8151 match rx.recv() {
8152 Ok(chunk) => pending = chunk.samples,
8153 Err(_) => {
8154 // Decoder finished or went away. What is in the ring still
8155 // plays out; what comes after it is the end of the timeline
8156 // and not a decoder that fell behind, so the device is told
8157 // to stop counting it. Under the lock and past the epoch,
8158 // like every other word this thread has with the device: a
8159 // superseded feeder must not say this about the stream that
8160 // replaced it.
8161 let ao = audio.ao.lock().unwrap();
8162 if audio.epoch.load(Ordering::Acquire) == epoch {
8163 ao.stream_ended();
8164 }
8165 return;
8166 }
8167 }
8168 }
8169 let accepted = {
8170 let mut ao = audio.ao.lock().unwrap();
8171 // Under the lock, immediately before the write: `seek` bumps the
8172 // epoch and flushes the ring holding this very lock, so past this
8173 // check no stale sample can be queued behind the flush.
8174 if audio.epoch.load(Ordering::Acquire) != epoch {
8175 return;
8176 }
8177 let accepted = match ao.write(&pending) {
8178 Some(n) => n,
8179 None => {
8180 // Output died; flag it so `tick` moves the clock to wall time.
8181 audio.died.store(true, Ordering::Release);
8182 return;
8183 }
8184 };
8185 // The first sample of this stream to reach the ring, stamped with
8186 // what the device had played by then: everything before it was the
8187 // silence of the restart, and [`PlaybackSession::tick`] anchors the
8188 // clock here so that silence is never timeline time. Under the
8189 // device lock, with the epoch already checked, so the stamp and the
8190 // sample belong to the same stream.
8191 if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 {
8192 let at = ao.position().unwrap_or(0).max(0);
8193 audio.content_at.store(at, Ordering::Release);
8194 // ...and the device position this stream's samples are counted
8195 // from ([`Audio::played_out`]). Rebased *here* rather than at
8196 // the seek, because the open runs on this thread now: every
8197 // millisecond it took is device time nobody fed, and counting
8198 // it would make the stream read as played out that long before
8199 // it really is -- an early hand-off to wall time at the end of
8200 // the timeline. The seek's own rebase still stands for the
8201 // stream that never queues a sample at all.
8202 audio
8203 .fed
8204 .store(at as u64 * audio.channels, Ordering::Relaxed);
8205 // ...and *this* is where a playing timeline's device starts: on
8206 // the first sample there is to play, under the same lock and
8207 // past the same epoch check as the stamp, so the silence of the
8208 // open was never played and never counted
8209 // ([`Audio::wants_active`]).
8210 if audio.wants_active.load(Ordering::Acquire) {
8211 ao.set_active(true);
8212 }
8213 } else if accepted == 0 && audio.content_at.load(Ordering::Acquire) < 0 {
8214 // Nothing taken with nothing yet queued is the *flush* of the
8215 // restart still standing: the ring refuses a write until a
8216 // callback has consumed the flag (`engine_audio::accept`), and
8217 // only a running device has callbacks. So the device is started
8218 // here too -- there is a sample in hand, which is what the wait
8219 // was for -- and the quantum or two of that handshake is the
8220 // silence `Shared::primed` does not count.
8221 if audio.wants_active.load(Ordering::Acquire) {
8222 ao.set_active(true);
8223 }
8224 }
8225 accepted
8226 };
8227 audio.fed.fetch_add(accepted as u64, Ordering::Relaxed);
8228 audio.note_tap(&pending[..accepted]);
8229 pending.drain(..accepted);
8230 if !pending.is_empty() {
8231 // Ring full: nothing to do but let the device drain it. Except when
8232 // *nothing* was taken, which after a flush means the ring is still
8233 // waiting for the device to consume the flush flag rather than
8234 // being full: that is the head of a restart, and every millisecond
8235 // spent parked there is a millisecond of silence.
8236 match accepted {
8237 0 => thread::sleep(FLUSH_WAIT),
8238 _ => thread::sleep(RING_FULL_WAIT),
8239 }
8240 }
8241 }
8242}
8243
8244/// The stretch of the timeline that ends at `frame` (inclusive) and starts where
8245/// whatever is shown there starts: [`crate::export::stack_span_at`] at that
8246/// start, cut short at `frame`. What a backward play draws, from `frame` down.
8247fn back_span_at(project: &Project, frame: u32) -> Option<crate::project::Span> {
8248 let mut lo = 0;
8249 let visible = project
8250 .lanes()
8251 .into_iter()
8252 .filter(|lane| lane.kind == LaneKind::Video && !project.lane_hidden(*lane));
8253 for lane in visible {
8254 let clips = project.lane(lane);
8255 let from = match project.lane_clip_at(lane, frame) {
8256 Some(idx) => clips[idx].start,
8257 None => clips.iter().rfind(|c| c.end() <= frame).map_or(0, |c| c.end()),
8258 };
8259 lo = lo.max(from);
8260 }
8261 let mut span = crate::export::stack_span_at(project, lo)?;
8262 span.len = span.len.min(frame + 1 - lo);
8263 Some(span)
8264}
8265
8266/// Timeline seconds to a 0-based frame index, floor semantics: position `t`
8267/// shows the frame whose interval contains it. The epsilon absorbs float error
8268/// at exact frame boundaries -- `123.0/30.0 * 30.0` is `122.999...`, and a
8269/// bare truncation would land one frame early (S6 finding: 4 of every 300
8270/// frames round-trip wrong through `clip_spans()` seconds without this).
8271fn secs_to_frame(secs: f64, fps: f64) -> u32 {
8272 (secs * fps + 1e-6).floor().max(0.0) as u32
8273}
8274
8275/// Per-byte lerp of two same-sized BGRA8 frames -- [`crate::scale::blend_i420`]'s
8276/// interleaved-buffer twin. By the time a picture reaches [`try_frame`]
8277/// (`PlaybackSession::try_frame`) it is already colour-converted for the
8278/// screen, so there are no separate Y/U/V planes left to blend, only the one
8279/// buffer; straight alpha survives the lerp untouched (255 against 255 is
8280/// still 255). `t` is B's weight, [`crate::export::dissolve_weight`]'s own
8281/// convention.
8282fn blend_bgra(a: &[u8], b: &[u8], t: f32) -> Vec<u8> {
8283 let t = t.clamp(0.0, 1.0);
8284 assert_eq!(a.len(), b.len(), "blend_bgra: mismatched frame sizes");
8285 a.iter()
8286 .zip(b)
8287 .map(|(&av, &bv)| (av as f32 + (bv as f32 - av as f32) * t).round() as u8)
8288 .collect()
8289}
8290
8291/// A chapter time as YouTube writes one in a description: `MM:SS`, or `H:MM:SS` from an hour on.
8292/// The frame is floored to whole seconds.
8293pub fn youtube_time(frame: u32, fps: f64) -> String {
8294 let secs = (f64::from(frame) / fps).floor() as u64;
8295 let (h, m, sec) = (secs / 3600, (secs % 3600) / 60, secs % 60);
8296 if h > 0 {
8297 format!("{h}:{m:02}:{sec:02}")
8298 } else {
8299 format!("{m:02}:{sec:02}")
8300 }
8301}
8302
8303/// The YouTube description listing for `chapters` (frame, name, sorted by frame) and the warnings
8304/// its rules call for: the first chapter at 00:00, each chapter at least 10 seconds long (the last
8305/// runs to `end`), and at least 3 chapters. Empty when there are none.
8306pub fn chapter_listing(chapters: &[(u32, String)], fps: f64, end: u32) -> (String, Vec<String>) {
8307 if chapters.is_empty() {
8308 return (String::new(), Vec::new());
8309 }
8310 let listing = chapters
8311 .iter()
8312 .map(|(f, t)| format!("{} {t}", youtube_time(*f, fps)))
8313 .collect::<Vec<_>>()
8314 .join("\n");
8315 let mut warnings = Vec::new();
8316 if chapters[0].0 != 0 {
8317 warnings.push(format!(
8318 "the first chapter starts at {}, not 00:00: YouTube needs one at 00:00",
8319 youtube_time(chapters[0].0, fps)
8320 ));
8321 }
8322 for (i, (frame, title)) in chapters.iter().enumerate() {
8323 let next = chapters.get(i + 1).map_or(end, |c| c.0);
8324 let secs = f64::from(next.saturating_sub(*frame)) / fps;
8325 if secs < 10.0 {
8326 warnings.push(format!("chapter \"{title}\" at {} lasts {secs:.1} s: YouTube wants 10 s or more", youtube_time(*frame, fps)));
8327 }
8328 }
8329 if chapters.len() < 3 {
8330 warnings.push(format!("YouTube needs at least 3 chapters; this timeline has {}", chapters.len()));
8331 }
8332 (listing, warnings)
8333}
8334
8335#[cfg(test)]
8336mod tests {
8337 use super::{
8338 SCRUB_SECS, scrub_snippet, AUDIO_LOST, Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of,
8339 blend_bgra, secs_to_frame,
8340 };
8341 use std::path::PathBuf;
8342 use std::sync::atomic::Ordering;
8343
8344 fn asset(name: &str) -> PathBuf {
8345 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8346 .join("../../assets")
8347 .join(name)
8348 }
8349
8350 /// A scrub snippet is the window it was cut from, as long as [`SCRUB_SECS`], and it rises
8351 /// from silence and falls to it again over its fades, so no edge of it can click.
8352 #[test]
8353 fn a_scrub_snippet_is_the_window_long_and_faded_at_both_ends() {
8354 let rate = 48_000u32;
8355 let frames = (SCRUB_SECS * f64::from(rate)) as usize;
8356 assert_eq!(frames, 3360, "70 ms at 48 kHz");
8357 let fade = (0.01 * f64::from(rate)) as usize;
8358 let src = vec![1.0f32; frames * 2];
8359 let out = scrub_snippet(&src, 2, fade);
8360 assert_eq!(out.len(), frames * 2, "the window's length, both channels");
8361 assert!(out[0].abs() < 0.01 && out[1].abs() < 0.01, "starts at silence: {:?}", &out[..2]);
8362 let last = out.len() - 2;
8363 assert!(out[last].abs() < 0.01 && out[last + 1].abs() < 0.01, "ends at silence");
8364 let mid = frames / 2 * 2;
8365 assert_eq!((out[mid], out[mid + 1]), (1.0, 1.0), "the middle is untouched");
8366 for f in 1..fade {
8367 assert!(out[2 * f] >= out[2 * (f - 1)], "the fade in rises at frame {f}");
8368 let tail = out.len() - 2 * (f + 1);
8369 assert!(out[tail] >= out[tail + 2], "the fade out falls toward the end at frame {f}");
8370 }
8371 // A window shorter than twice the fade has its fade held to half of it.
8372 let short = scrub_snippet(&[1.0; 8], 1, 100);
8373 assert_eq!(short.len(), 8);
8374 assert!(short[0].abs() < 0.5 && short[7].abs() < 0.5, "{short:?}");
8375 assert!(scrub_snippet(&[1.0; 8], 0, 2).len() == 8, "a zero width is read as mono");
8376 }
8377
8378 /// The crash path: a saved project with several sequences (one of them a compound clip
8379 /// over another, plus a marker) is written as an autosave and read back, and the autosave
8380 /// on top of the saved file recovers to the same sequences, compound clips and markers.
8381 #[test]
8382 fn autosave_round_trips_every_sequence_compound_and_marker() {
8383 let dir = crate::scratch::Scratch::dir("ve_sidecar_round_trip");
8384 let media = dir.join("film.mp4");
8385 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture");
8386 let path = dir.join("proj.edith");
8387 let s = PlaybackSession::open(&media).expect("open the fixture");
8388 s.set_gain(0.0);
8389 s.save_project_noted(&path).expect("save the base");
8390 let mut s = PlaybackSession::open_project(&path).expect("reopen the base");
8391 let b = s.new_sequence(Some("Cut B")).expect("a second sequence");
8392 s.switch_sequence(b).expect("switch to it");
8393 assert!(s.place_stream_at(0.0, &media, 0, None).expect("placeable"));
8394 let copy = s.duplicate_sequence(b).expect("duplicate it");
8395 s.switch_sequence(copy).expect("switch to the copy");
8396 s.nest(&[(Lane::V1, 0)], Some("Inner")).expect("nest a clip");
8397 assert_eq!(s.project.sequences().len(), 4, "the base, B, its copy and the nested one");
8398 s.add_marker(crate::project::Marker {
8399 frame: 3,
8400 length: 0,
8401 name: "beat".into(),
8402 note: String::new(),
8403 color: crate::project::MarkerColor::Red,
8404 })
8405 .expect("a marker");
8406 assert_eq!(s.project.markers().len(), 1, "the marker is on the sequence being edited");
8407 let sidecar = dir.join("proj.autosave.edith");
8408 s.save_autosave(&sidecar).expect("the autosave");
8409 let back = PlaybackSession::open_project(&sidecar).expect("the autosave opens");
8410 assert_eq!(back.project.sequences(), s.project.sequences(), "the same sequences, in order");
8411 assert_eq!(back.project.active_sequence(), s.project.active_sequence());
8412 assert_eq!(back.project.markers().len(), 1, "the marker comes back");
8413 assert_eq!(back.project.markers()[0].name, "beat");
8414 // The recovery path: the saved file, with the autosave on top of it.
8415 let mut saved = PlaybackSession::open_project(&path).expect("the saved file");
8416 assert!(saved.adopt_as_step(&back), "the autosave lands on the saved file");
8417 assert_eq!(saved.project.sequences(), s.project.sequences(), "recovery holds every sequence");
8418 assert_eq!(saved.project.markers().len(), 1, "and the marker");
8419 }
8420
8421 /// A clip past its source's end in a parked sequence is shortened on save, just as in the
8422 /// active one, and the save says which sequence it was in. It is never refused.
8423 #[test]
8424 fn save_shortens_the_parked_sequences_over_wall_clips() {
8425 let dir = crate::scratch::Scratch::dir("ve_save_parked_walls");
8426 let media = dir.join("film.mp4");
8427 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture");
8428 let mut s = PlaybackSession::open(&media).expect("open the fixture");
8429 s.set_gain(0.0);
8430 let copy = s.duplicate_sequence(s.project.active_sequence()).expect("duplicate");
8431 let copy_name = s.project.sequence_name(copy).expect("the copy is named").to_string();
8432 let path = dir.join("proj.edith");
8433 assert!(s.save_project_noted(&path).expect("whole walls save").is_empty());
8434 s.counts[0] = 1;
8435 let notes = s.save_project_noted(&path).expect("the save never refuses");
8436 assert!(notes.iter().any(|n| n.contains(&format!("in sequence \"{copy_name}\""))), "{notes:?}");
8437 assert!(notes.iter().all(|n| !n.contains("frame")), "no frame numbers in a note: {notes:?}");
8438 PlaybackSession::open_project(&path).expect("the saved file opens");
8439 }
8440
8441 /// A video file whose sound is shorter than its picture (a 22.96 s picture under 20.67 s of
8442 /// sound): the timeline it opens to holds the grouped take to the sound's length, so an
8443 /// edit chain that splits, ripple-deletes and dissolves saves without a refusal and leaves
8444 /// no audio clip past the sound's end.
8445 #[test]
8446 fn a_picture_longer_than_its_sound_saves_after_edits() {
8447 let dir = crate::scratch::Scratch::dir("ve_short_sound_edits");
8448 let media = dir.join("speech.mp4");
8449 let made = std::process::Command::new("ffmpeg")
8450 .args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=160x120:rate=25:duration=22.96",
8451 "-f", "lavfi", "-i", "sine=frequency=440:duration=20.67", "-c:v", "mpeg4", "-c:a", "aac"])
8452 .arg(&media)
8453 .status()
8454 .map(|s| s.success() && media.exists())
8455 .unwrap_or(false);
8456 if !made {
8457 eprintln!("no ffmpeg: a picture longer than its sound cannot be generated, skipping");
8458 return;
8459 }
8460 let mut s = PlaybackSession::open(&media).expect("open the fixture");
8461 s.set_gain(0.0);
8462 let sound_frames = 517;
8463 assert_eq!(s.lane_clips(Lane::A1)[0].out_frame, sound_frames, "the opened take is the sound's length");
8464 assert_eq!(s.lane_clips(Lane::V1)[0].out_frame, sound_frames, "and so is its picture");
8465
8466 let path = dir.join("proj.edith");
8467 assert!(s.cut_at(5.0));
8468 assert!(s.cut_regions(&[(50, 100)], &[Lane::V1, Lane::A1]).is_ok());
8469 assert!(s.set_transition_out(Lane::V1, 0, 10));
8470 assert!(s.place_stream_at(0.0, &media, 0, None).expect("placeable"));
8471 let notes = s.save_project_noted(&path).expect("the edited take saves");
8472 assert!(notes.is_empty(), "nothing needed shortening: {notes:?}");
8473 for lane in [Lane::V1, Lane::A1] {
8474 for c in s.lane_clips(lane) {
8475 assert!(c.out_frame <= sound_frames, "{lane:?} clip ends at {} past the sound", c.out_frame);
8476 }
8477 }
8478 }
8479
8480 /// A relink is one undo step on the session too: undo points the source back at the old file,
8481 /// which reads again (no longer offline), and redo points it at the new one.
8482 #[test]
8483 fn undoing_a_relink_reads_the_old_file_again() {
8484 let dir = crate::scratch::Scratch::dir("ve_relink_undo_session");
8485 let media = dir.join("film.mp4");
8486 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture");
8487 let session = PlaybackSession::open(&media).expect("open the fixture");
8488 session.set_gain(0.0);
8489 let path = dir.join("proj.edith");
8490 session.save_project(&path).expect("save");
8491 let moved = dir.join("moved.mp4");
8492 std::fs::rename(&media, &moved).expect("move the media");
8493
8494 let mut s = PlaybackSession::open_project(&path).expect("opens offline");
8495 assert_eq!(s.offline_sources().len(), 1);
8496 s.relink_source(0, &moved).expect("relinks");
8497 assert!(s.offline_sources().is_empty());
8498 std::fs::copy(&moved, &media).expect("the old file is back beside it");
8499 assert!(s.undo());
8500 assert_eq!(s.sources()[0].path, std::fs::canonicalize(&media).expect("canonical"));
8501 assert!(s.offline_sources().is_empty(), "the old file reads again");
8502 assert!(s.redo());
8503 assert_eq!(s.sources()[0].path, std::fs::canonicalize(&moved).expect("canonical"));
8504 }
8505
8506 /// A dead output is not the end of a session's sound.
8507 ///
8508 /// The stream is stopped the way a seek stops one and then flagged the way a
8509 /// failed write flags it ([`feed`]): nothing is feeding and nothing will. The
8510 /// session must say so -- a dead output used to hand the clock to wall time
8511 /// in silence, for the rest of the session's life, through every seek -- and
8512 /// the play (and the seek after it) must put the output back, which is read
8513 /// off the tap: the samples that actually reached the device. A session that
8514 /// only switched the clock leaves the tap empty.
8515 ///
8516 /// The tick below runs with the cooldown already spent (an attempt stamped
8517 /// just now), which is what makes the notice observable at all *and* what
8518 /// proves the one thing a frame-rate poll must not do: open a device that is
8519 /// gone for good sixty times a second.
8520 #[test]
8521 fn a_dead_output_is_rearmed_and_the_sound_comes_back() {
8522 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8523 assert!(
8524 session.audio_tap().is_some(),
8525 "test_av.mp4 carries an audio track, which is what this drives"
8526 );
8527
8528 session.stop_audio();
8529 let audio = session.audio.as_ref().expect("audio");
8530 audio.died.store(true, Ordering::Release);
8531 *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now());
8532
8533 session.tick();
8534 assert_eq!(
8535 session.audio_disabled_reason(),
8536 Some(AUDIO_LOST),
8537 "a dead output went to wall time without a word"
8538 );
8539 assert!(
8540 session
8541 .audio
8542 .as_ref()
8543 .expect("audio")
8544 .died
8545 .load(Ordering::Acquire),
8546 "a tick opened the output again inside the cooldown"
8547 );
8548 assert!(
8549 session.audio_tap().expect("audio").0.is_empty(),
8550 "something was still feeding the device"
8551 );
8552
8553 // Playing is the ask that is not throttled: the output is opened again,
8554 // the flag clears and a feeder fills the device -- asynchronously, so the
8555 // tap is waited on.
8556 session.play();
8557 session.seek(1.0);
8558 let mut fed = Vec::new();
8559 for _ in 0..200 {
8560 fed = session.audio_tap().expect("audio").0;
8561 if !fed.is_empty() {
8562 break;
8563 }
8564 std::thread::sleep(std::time::Duration::from_millis(5));
8565 }
8566 assert!(
8567 !fed.is_empty(),
8568 "playing after a dead output fed nothing: the session cannot come back"
8569 );
8570 assert!(
8571 !session
8572 .audio
8573 .as_ref()
8574 .expect("audio")
8575 .died
8576 .load(Ordering::Acquire),
8577 "the death flag stood after the output was replaced"
8578 );
8579 assert_eq!(
8580 session.audio_disabled_reason(),
8581 None,
8582 "the notice was left standing over a session that is playing again"
8583 );
8584 }
8585
8586 /// A monitoring level is state, and a device replaced under the session is
8587 /// a new object that knows nothing about it: the re-armed stream came up
8588 /// at full volume, so a session playing muted while PipeWire restarted
8589 /// came back loud with the toolbar still reading "muted". The gain is
8590 /// therefore read back *from the device* ([`PlaybackSession::gain`]) and
8591 /// put back onto the replacement.
8592 ///
8593 /// The silent sink is what makes this a state round-trip rather than a
8594 /// claim about ears: it keeps the gain it was given, so the level after a
8595 /// re-arm is a number this process can read, and a plain open with no gain
8596 /// ever pushed is the control that says 1.0 is a real default rather than
8597 /// a leftover.
8598 #[test]
8599 fn a_rearmed_output_comes_back_at_the_level_the_session_was_running() {
8600 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8601 // The control: a session nobody has pushed a level at is at full
8602 // volume, which is what a *fresh* device is expected to be.
8603 assert_eq!(
8604 session.gain(),
8605 Some(1.0),
8606 "a session that never had a gain pushed is not at full volume"
8607 );
8608 assert!(
8609 session.set_gain(0.0),
8610 "a muted push was refused by the silent sink"
8611 );
8612 assert_eq!(
8613 session.gain(),
8614 Some(0.0),
8615 "the push did not reach the device"
8616 );
8617
8618 // The device goes away the way a daemon restart takes it: the stream is
8619 // stopped and flagged dead, with the cooldown already spent. The
8620 // replacement is opened by the door the sibling re-arm witness drives
8621 // -- a play and the seek that follows, which is `start_audio`'s
8622 // unthrottled attempt -- and the death flag clearing is what says a new
8623 // device really was installed, rather than the read below passing over
8624 // the old one.
8625 session.stop_audio();
8626 let audio = session.audio.as_ref().expect("audio");
8627 audio.died.store(true, Ordering::Release);
8628 *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now());
8629 session.play();
8630 session.seek(1.0);
8631 assert!(
8632 !session
8633 .audio
8634 .as_ref()
8635 .expect("audio")
8636 .died
8637 .load(Ordering::Acquire),
8638 "the device was never replaced, so the level below says nothing about \
8639 a re-armed stream"
8640 );
8641
8642 assert_eq!(
8643 session.gain(),
8644 Some(0.0),
8645 "the replacement device came up at full volume: a muted session \
8646 that lost its output came back loud while the window still said muted"
8647 );
8648 }
8649
8650 /// The seat declares the canvas's own size; the painter masks the planes it
8651 /// returns to even dimensions, and a canvas the two disagree about used to
8652 /// take the picture down between them. On the revision before the seat masked
8653 /// what it declares, a 1920x1 canvas died *in the painter* -- `decode.rs`
8654 /// clamped the zero line of an h of 0: `max = -1`, `min > max` -- and a
8655 /// 321x181 one died in the conversion on the *canvas's* chroma plane, one row
8656 /// past the masked source's: `index out of bounds: the len is 14400 but the
8657 /// index is 14400`, a full plane and not an empty one.
8658 ///
8659 /// This drives the same path a front-end does (`set_resolution`, then frames
8660 /// out of the session). It is a guard against the shape coming back rather
8661 /// than a reproduction: a frame does still arrive on the parent revision
8662 /// (which is why the masking, not this test, is the fix).
8663 #[test]
8664 fn a_visualizer_seat_paints_a_canvas_it_cannot_evenly_divide() {
8665 for (w, h) in [(1920, 1), (1921, 1081), (320, 1), (321, 181)] {
8666 let mut session =
8667 PlaybackSession::open(asset("test_tone.mp3")).expect("open the audio fixture");
8668 assert!(
8669 session.set_resolution(w, h),
8670 "{w}x{h} should be a resolution this session takes"
8671 );
8672 let mut frame = None;
8673 for _ in 0..400 {
8674 if let Some(f) = session.try_frame() {
8675 frame = Some(f);
8676 break;
8677 }
8678 std::thread::sleep(std::time::Duration::from_millis(5));
8679 }
8680 let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas"));
8681 assert_eq!(
8682 (frame.width, frame.height),
8683 (w, h),
8684 "a frame at the canvas's own size"
8685 );
8686 }
8687 }
8688
8689 /// `blend_bgra` at the two ends and the midpoint of its weight -- `t=0` is
8690 /// pure A, `t=1` is pure B, `t=0.5` rounds each byte to its own midpoint.
8691 /// Straight alpha (255 in both) survives every weight, which is the one
8692 /// channel a wrong blend would otherwise fog.
8693 #[test]
8694 fn blend_bgra_interpolates_every_byte_including_alpha() {
8695 let a = [10u8, 20, 30, 255];
8696 let b = [110u8, 120, 130, 255];
8697 assert_eq!(blend_bgra(&a, &b, 0.0), a);
8698 assert_eq!(blend_bgra(&a, &b, 1.0), b);
8699 assert_eq!(blend_bgra(&a, &b, 0.5), [60, 70, 80, 255]);
8700 }
8701
8702 /// A still wants the project's own pixels, not a view near them.
8703 /// [`PlaybackSession::set_view_size`] calls under 8 px no change at all (a
8704 /// window being dragged must not restart the picture every tick), so a
8705 /// caller that means "paint at the project's size" has to say it through
8706 /// [`PlaybackSession::set_view_size_exact`] -- and read its `false` as "the
8707 /// view is already there, the frame in hand is the one wanted", which is
8708 /// what stops it waiting for a picture nothing will reseek into existence.
8709 #[test]
8710 fn a_still_gets_the_exact_view_size_where_a_push_settles_for_near() {
8711 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8712 assert!(session.set_resolution(1920, 1080));
8713 let (w, h) = session.resolution();
8714 assert_eq!((w, h), (1920, 1080));
8715 // A preview-sized push, then the ask a still makes: two pixels short on
8716 // each axis, which the deadbanded push calls no change at all.
8717 assert!(session.set_view_size(1918, 1078));
8718 assert!(
8719 std::ops::Not::not(session.set_view_size(w, h)),
8720 "the push's deadband is exactly what a still cannot use"
8721 );
8722 assert_eq!(
8723 session.view_size(),
8724 (1918, 1078),
8725 "the push left the view near, not at, full -- so a still written now would be short"
8726 );
8727 assert!(
8728 session.set_view_size_exact(w, h),
8729 "the exact setter must move a view the push called close enough"
8730 );
8731 assert_eq!(session.view_size(), (w, h));
8732 // ...and at the size already it says so rather than repainting: that
8733 // `false` is the caller's "write the frame you have".
8734 assert!(std::ops::Not::not(session.set_view_size_exact(w, h)));
8735 }
8736
8737 /// The dissolve window's own edges, in the units [`PlaybackSession::start_span`]
8738 /// computes them in: a `tail_start` of `span.start + span.len - window`
8739 /// puts the very first output frame of the window at `idx_in_window == 0`
8740 /// and the very last at `window - 1`, clamped rather than overrun by a
8741 /// frame that lands exactly on the span's own end -- the same off-by-one
8742 /// a stray `%` or unclamped subtraction would have shown on screen as a
8743 /// blend that never quite reached full B.
8744 #[test]
8745 fn dissolve_window_edges_index_zero_to_window_minus_one() {
8746 let (span_start, span_len, window) = (100u32, 30u32, 10u32);
8747 let tail_start = span_start + span_len - window;
8748 assert_eq!(tail_start, 120);
8749 let idx_in_window = |frame: u32| (frame - tail_start).min(window - 1);
8750 assert_eq!(idx_in_window(120), 0, "first frame of the window");
8751 assert_eq!(idx_in_window(129), 9, "last frame of the window");
8752 assert_eq!(
8753 idx_in_window(130),
8754 9,
8755 "one past the span's own end clamps rather than panics"
8756 );
8757 }
8758
8759 /// A picked project rate overrides the derived one, and its absence leaves
8760 /// the source's own -- the seam every explicit-sample-rate caller
8761 /// (playback rebuild, both export encoders) goes through
8762 /// ([`crate::AudioSession::open_multi_streams_speed_at`]). The per-segment
8763 /// conform chain resamples to whatever `meta` names, so the meta *is* the
8764 /// behaviour.
8765 #[test]
8766 fn a_picked_sample_rate_overrides_the_derived_one() {
8767 let file = asset("test_av.mp4");
8768 let sources = [(file, 0)];
8769 let segs = [(Some(0), 0., 1.)];
8770 let derived =
8771 crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], None)
8772 .expect("open the fixture")
8773 .expect("the fixture has sound")
8774 .0
8775 .sample_rate;
8776 let picked = crate::AudioSession::open_multi_streams_speed_at(
8777 &sources,
8778 &segs,
8779 &[],
8780 &[],
8781 Some(32000),
8782 )
8783 .expect("open the fixture")
8784 .expect("the fixture has sound")
8785 .0
8786 .sample_rate;
8787 assert_ne!(
8788 derived, 32000,
8789 "a fixture at the picked rate proves nothing"
8790 );
8791 assert_eq!(picked, 32000);
8792 }
8793
8794 /// Which source the timeline's sound is opened on -- the one rule
8795 /// [`open_project`](PlaybackSession::open_project), the probe every import
8796 /// is held to and the audio worker all read through. A still at index 0 is
8797 /// a picture, not a silent timeline: opening the device on it is a project
8798 /// that plays silent although every clip on it has sound.
8799 #[test]
8800 fn the_audio_reference_is_never_a_still() {
8801 let (video, still) = (asset("test_av.mp4"), asset("test_still.png"));
8802 let sources = [Source::new(&still, 0), Source::new(&video, 3)];
8803 assert_eq!(
8804 audio_source_of(&sources).map(|s| (&s.path, s.audio_stream)),
8805 Some((&sources[1].path, 3)),
8806 "the first source that could have a track, with its own stream"
8807 );
8808 assert!(
8809 audio_source_of(&sources[..1]).is_none(),
8810 "nothing but stills"
8811 );
8812 assert!(audio_source_of(&[]).is_none(), "and no file at all");
8813 }
8814
8815 /// What a front end's "resolution/rate picked before any file is open"
8816 /// setting costs the engine: nothing new. `open` then `set_resolution`/
8817 /// `set_frame_rate` right after construction -- the app's technique for
8818 /// applying a pre-import pick to the session it just made, mirroring
8819 /// [`PlaybackSession::open_project`]'s own `doc.resolution`/`doc.fps`
8820 /// override -- lands exactly where either setter lands it whenever it is
8821 /// called, and a later `import` of another file leaves both untouched: an
8822 /// import registers a source and its length, and never writes `meta.width`,
8823 /// `meta.height` or `meta.frame_rate`.
8824 #[test]
8825 fn a_pre_import_setting_survives_construction_and_a_later_import() {
8826 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8827 let native = session.native_resolution();
8828 let native_fps = session.native_frame_rate();
8829 // The explicit picks a pre-import setting would apply, distinct from
8830 // the fixture's own so a no-op would be caught.
8831 let (picked_w, picked_h) = (1920, 1080);
8832 assert_ne!((picked_w, picked_h), native, "the test needs a real change");
8833 let picked_fps = 24.0;
8834 assert_ne!(picked_fps, native_fps, "the test needs a real change");
8835 assert!(session.set_resolution(picked_w, picked_h));
8836 assert!(session.set_frame_rate(picked_fps));
8837 assert_eq!(session.resolution(), (picked_w, picked_h));
8838 assert_eq!(session.meta().frame_rate, picked_fps);
8839
8840 // A second file joining the timeline is exactly the case the front end
8841 // worried a later import could silently override the explicit pick --
8842 // it cannot, because `import` never touches the canvas.
8843 session
8844 .import(&asset("test_av2.mp4"))
8845 .expect("av2 matches the timeline it was set to");
8846 assert_eq!(
8847 session.resolution(),
8848 (picked_w, picked_h),
8849 "an import must not move the project's own canvas size"
8850 );
8851 assert_eq!(
8852 session.meta().frame_rate,
8853 picked_fps,
8854 "an import must not move the project's own rate"
8855 );
8856 }
8857
8858 #[test]
8859 fn an_audio_lane_walls_a_video_by_its_sound_and_a_video_lane_by_its_picture() {
8860 // A 2 s picture under 60 s of sound: the A1 half of a placed take can be
8861 // trimmed out to the sound's end, the V1 half only to the picture's.
8862 let path = asset("test_short_video_long_audio.mp4");
8863 let mut session = PlaybackSession::open(&path).expect("open the fixture");
8864 session.set_gain(0.0);
8865 let fps = session.meta().frame_rate;
8866 // Placed at the end, so nothing sits in front of it and the walls are the
8867 // source's own, not a neighbour's.
8868 let end = session.timeline_duration();
8869 assert!(
8870 session
8871 .place_stream_at(end, &path, 0, Some(Lane::A1))
8872 .expect("a file on this timeline is placeable")
8873 );
8874 let a1 = session.lane_clips(Lane::A1).len() - 1;
8875 let v1 = session.lane_clips(Lane::V1).len() - 1;
8876
8877 let audio = session.trim_walls(Lane::A1, a1, Edge::End).expect("A1 clip");
8878 let picture = session.trim_walls(Lane::V1, v1, Edge::End).expect("V1 clip");
8879 let placed = (end * fps).round();
8880 assert!(
8881 audio.hi as f64 >= placed + 59.0 * fps,
8882 "the sound is 60 s: the A1 end may reach {} frames at {fps} fps",
8883 audio.hi
8884 );
8885 assert!(
8886 (picture.hi as f64) < placed + 3.0 * fps,
8887 "the picture is 2 s: the V1 end stops at {} frames",
8888 picture.hi
8889 );
8890 assert!(
8891 session.trim_clip(Lane::A1, a1, Edge::End, (placed + 40.0 * fps) as u32),
8892 "the A1 clip trims to 40 s"
8893 );
8894 assert_eq!(session.lane_clips(Lane::A1)[a1].len(), (40.0 * fps) as u32);
8895 }
8896
8897 /// The seam between the two lists a source index reaches: dropping a file
8898 /// from the library shortens `sources`, and `counts` -- the frame length
8899 /// per source, which is what a trim is walled by -- has to lose the same
8900 /// entry. Left behind, the dead file's length would wall the survivor.
8901 #[test]
8902 fn removing_a_source_takes_its_frame_count_with_it() {
8903 // Source 0 is 5 s, source 1 is 4 s: two different walls, so a stale
8904 // count cannot pass for the right one.
8905 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8906 session.set_gain(0.0);
8907 // Imported, then dragged onto the end -- an import alone places nothing
8908 // ([`PlaybackSession::import`]), and this test needs both takes there.
8909 session.import(&asset("test_av2.mp4")).expect("av2 matches");
8910 let end = session.timeline_duration();
8911 assert!(
8912 session
8913 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
8914 .expect("a file just imported is on this timeline")
8915 );
8916 let (long, short) = (session.counts[0], session.counts[1]);
8917 assert!(long > short, "{long} vs {short}");
8918
8919 // Clear source 0's take, then take the file itself out: av2's clip is
8920 // the only one left and it is source 0 now.
8921 assert!(session.delete_clip(Lane::V1, 0));
8922 session
8923 .remove_source(&asset("test_av.mp4"), 0)
8924 .expect("nothing plays it any more");
8925 assert_eq!(session.counts, vec![short], "the dead length went with it");
8926 assert_eq!(session.sources().len(), session.counts.len());
8927
8928 // The wall is the surviving file's own length, not the gone one's: a
8929 // whole-file clip cannot be dragged out any further at all.
8930 let clip = session.lane_clips(Lane::V1)[0].clone();
8931 assert_eq!(clip.len(), short, "av2's take, whole");
8932 assert_eq!(
8933 session.trim_room(Lane::V1, 0, Edge::End),
8934 Some((clip.start + 1, clip.end()))
8935 );
8936 assert!(
8937 !session.trim_clip(Lane::V1, 0, Edge::End, clip.end() + 30),
8938 "past the file's last frame is refused, by ITS length"
8939 );
8940
8941 // ...and the next import still lines the two lists up, which is the
8942 // alignment `note_frames` asserts on.
8943 session
8944 .import(&asset("test_av.mp4"))
8945 .expect("it may come back");
8946 assert_eq!(session.counts, vec![short, long]);
8947 assert_eq!(session.sources().len(), session.counts.len());
8948 }
8949
8950 /// The two headers a place reads are read *once*: an mp4 dropped on a lane
8951 /// used to open its own container and the timeline's first source every
8952 /// time, both on the thread that draws, and a film whose pages have gone
8953 /// cold is 1.7 s of that.
8954 ///
8955 /// Proved by answering, not by timing: the memo is filled with a layout the
8956 /// file does not have, and the place is refused. Only a door that read the
8957 /// remembered header rather than the disk can refuse it.
8958 #[test]
8959 fn a_place_reads_each_audio_header_once() {
8960 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8961 session.set_gain(0.0);
8962 session.import(&asset("test_av2.mp4")).expect("av2 matches");
8963 let end = session.timeline_duration();
8964 assert!(
8965 session
8966 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
8967 .expect("a file just imported is on this timeline")
8968 );
8969 assert_eq!(
8970 session.probes.len(),
8971 2,
8972 "the timeline's first source and the file placed, once each"
8973 );
8974
8975 // Now say av2 is 5.1. Nothing on disk changed, so a door that opens the
8976 // file still matches; one that trusts the memo refuses by layout.
8977 // Keyed exactly as a [`Source`] names a file -- canonical, symlinks
8978 // resolved -- which is the key the doors look up.
8979 let av2 = Source::new(asset("test_av2.mp4"), 0).path;
8980 session.probes.insert(
8981 (av2, 0),
8982 Some(crate::AudioProbe {
8983 sample_rate: 48_000,
8984 channels: 6,
8985 }),
8986 );
8987 let refused = session
8988 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
8989 .expect_err("the remembered layout disagrees with the timeline's");
8990 assert!(
8991 refused.to_string().contains("6 ch"),
8992 "refused in the layout's own words: {refused}"
8993 );
8994 assert_eq!(session.probes.len(), 2, "and nothing was opened to say so");
8995 }
8996
8997 /// The door a library preview opens a chosen stream through: `test_multiaudio.mp4`
8998 /// has stream 0 stereo and stream 1 mono
8999 /// ([`crate::waveform::tests::each_stream_of_a_file_has_its_own_envelope`]
9000 /// names the same fixture), so a session that actually bound the stream it
9001 /// was asked for plays a different layout than one that did not -- and
9002 /// plain [`PlaybackSession::open`] still lands on stream 0, unchanged.
9003 #[test]
9004 fn open_with_audio_stream_binds_the_named_track() {
9005 let multi = asset("test_multiaudio.mp4");
9006 let zero = PlaybackSession::open_with_audio_stream(&multi, 0).expect("stream 0 opens");
9007 let one = PlaybackSession::open_with_audio_stream(&multi, 1).expect("stream 1 opens");
9008 let default = PlaybackSession::open(&multi).expect("default open");
9009 let (Some(a0), Some(a1), Some(ad)) = (
9010 zero.audio.as_ref(),
9011 one.audio.as_ref(),
9012 default.audio.as_ref(),
9013 ) else {
9014 // No audio device on this machine: nothing further to check --
9015 // the device is the machine's business, not this door's.
9016 return;
9017 };
9018 assert_eq!(a0.channels, 2, "stream 0 is the stereo pair");
9019 assert_eq!(a1.channels, 1, "stream 1 is the mono track");
9020 assert_ne!(a0.channels, a1.channels, "the two streams must differ");
9021 assert_eq!(
9022 ad.channels, a0.channels,
9023 "open() still defaults to stream 0"
9024 );
9025 }
9026
9027 /// The bug this regression pins: a preview paused (or scrubbed) to a
9028 /// frame inside a dissolve window used to show plain A forever, because
9029 /// B's decoder only opened on the tick that landed in the window and
9030 /// nothing polled `try_frame` again while the clock stood still
9031 /// (`Player::pump` only drains while playing or a seek is owed, and one
9032 /// delivered frame clears "owed"). Two clips of real fixtures, touching,
9033 /// with a dissolve set on the join -- seeking into the window and taking
9034 /// exactly one frame (no play, no second tick) must already show a blend:
9035 /// the same position with the dissolve turned off must differ from it.
9036 #[test]
9037 fn a_single_paused_tick_inside_the_dissolve_window_is_already_blended() {
9038 let window = 6u32;
9039 let build = |transition: u32| {
9040 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open a");
9041 s.set_gain(0.0);
9042 s.import(&asset("test_av2.mp4")).expect("av2 matches");
9043 let end = s.timeline_duration();
9044 assert!(
9045 s.place_stream_at(end, &asset("test_av2.mp4"), 0, None)
9046 .expect("av2, placed right after a")
9047 );
9048 if transition > 0 {
9049 assert!(s.set_transition_out(Lane::V1, 0, transition));
9050 }
9051 s
9052 };
9053 let mut on = build(window);
9054 let mut off = build(0);
9055
9056 let fps = on.meta().frame_rate;
9057 let clip0_len = on.lane_clips(Lane::V1)[0].len();
9058 assert!(
9059 clip0_len > window,
9060 "the fixture needs to outlast the window"
9061 );
9062 let mid_of_window = clip0_len - window / 2;
9063 let t = f64::from(mid_of_window) / fps;
9064
9065 // One seek, then one frame -- exactly what a paused preview's single
9066 // repaint asks the engine for. Polled rather than taken on the first
9067 // call because the seek itself just restarted the decoder
9068 // (`start_span`) and its first picture is not synchronous; once
9069 // *a* frame lands this is the one tick under test.
9070 let frame_at = |s: &mut PlaybackSession| -> crate::decode::Frame {
9071 s.seek(t);
9072 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
9073 loop {
9074 if let Some(f) = s.try_frame() {
9075 return f;
9076 }
9077 assert!(
9078 std::time::Instant::now() < deadline,
9079 "no frame within 120s of the seek"
9080 );
9081 std::thread::sleep(std::time::Duration::from_millis(10));
9082 }
9083 };
9084
9085 let off_frame = frame_at(&mut off);
9086 let on_frame = frame_at(&mut on);
9087 assert_eq!(on_frame.index, off_frame.index, "same timeline position");
9088 assert_ne!(
9089 on_frame.bgra, off_frame.bgra,
9090 "paused inside the window, the dissolve must already show B blended in"
9091 );
9092 }
9093
9094 #[test]
9095 fn boundary_seconds_round_trip_to_their_own_frame() {
9096 for f in 0u32..300 {
9097 let secs = f64::from(f) / 30.0;
9098 assert_eq!(secs_to_frame(secs, 30.0), f, "frame {f}");
9099 }
9100 // Mid-frame positions still floor, and negatives clamp.
9101 assert_eq!(secs_to_frame(10.5 / 30.0, 30.0), 10);
9102 assert_eq!(secs_to_frame(-0.2, 30.0), 0);
9103 }
9104
9105 /// A paused transform nudge -- `set_transform_live` at the position the
9106 /// picture already stands on -- never pays a full decoder restart: the
9107 /// worker is reused (`Worker::reseek`), never replaced
9108 /// (`PlaybackSession::retire`), so `restarts()` does not move. Guards the
9109 /// path a card's live edits go through against a future change routing
9110 /// them back through `seek`/a fresh worker, and a gap left between two
9111 /// edits (a person's think-time between nudges) longer than the *old*
9112 /// hardware-idle window still counts zero restarts -- a decoder worker
9113 /// outliving its span is not a "restart" this counter (or a caller) sees,
9114 /// whatever the hardware session inside it did.
9115 #[test]
9116 fn a_paused_transform_nudge_reuses_the_worker_not_a_restart() {
9117 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
9118 s.set_gain(0.0);
9119 let poll = |s: &mut PlaybackSession| -> crate::decode::Frame {
9120 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
9121 loop {
9122 if let Some(f) = s.try_frame() {
9123 return f;
9124 }
9125 assert!(std::time::Instant::now() < deadline, "no frame within 120s");
9126 std::thread::sleep(std::time::Duration::from_millis(10));
9127 }
9128 };
9129 let first = poll(&mut s);
9130 let before = s.restarts();
9131
9132 // A gap past the pre-fix 2s hardware-idle window: the whole point of
9133 // widening it is that a nudge landing here still reuses the worker.
9134 std::thread::sleep(std::time::Duration::from_millis(2500));
9135
9136 let clip = s.video_clip_at(s.now()).expect("a clip under the playhead");
9137 let params = TransformParams {
9138 scale: 1.2,
9139 ..Default::default()
9140 };
9141 assert!(
9142 s.set_transform_live(clip.0, clip.1, Some(params)),
9143 "the edit took"
9144 );
9145 let next = poll(&mut s);
9146
9147 assert_eq!(
9148 before,
9149 s.restarts(),
9150 "a live transform edit must reuse the worker"
9151 );
9152 assert_eq!(
9153 next.index, first.index,
9154 "paused: same timeline position before and after"
9155 );
9156 }
9157
9158 /// A rate undo lands the picture where the playhead is, in the rate that
9159 /// came *back*: the entry a pick takes carries the old numbering beside the
9160 /// old rate, so an undo restores both and the reseek has to be computed
9161 /// after the restore. Computed before it, the landing is the pre-undo
9162 /// rate's reading of the post-undo project -- `now` clamps to the pre-undo
9163 /// rate's idea of the timeline's end and the worker is handed the last
9164 /// frame of a five-second timeline for a playhead at three seconds.
9165 #[test]
9166 fn a_rate_undo_reseeks_at_the_rate_it_restored() {
9167 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
9168 s.set_gain(0.0);
9169 let poll = |s: &mut PlaybackSession| -> crate::decode::Frame {
9170 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
9171 loop {
9172 if let Some(f) = s.try_frame() {
9173 return f;
9174 }
9175 assert!(std::time::Instant::now() < deadline, "no frame within 120s");
9176 std::thread::sleep(std::time::Duration::from_millis(10));
9177 }
9178 };
9179 let native = s.native_frame_rate();
9180 s.seek(3.0);
9181 assert_eq!(s.now(), 3.0, "the fixture is five seconds long");
9182 assert!(s.set_frame_rate(native * 2.0), "the rate pick");
9183 assert!(s.undo(), "the pick is one step");
9184 assert_eq!(s.meta().frame_rate, native, "the rate came back");
9185 assert_eq!(
9186 s.now(),
9187 3.0,
9188 "the playhead is the seconds it was, read at the rate that came back"
9189 );
9190 // The worker's own landing, which is the half the clock alone cannot
9191 // show: a frame 149 of 150 is exactly the pre-undo rate's clamp.
9192 assert_eq!(
9193 s.span.expect("a span for the picture").start,
9194 secs_to_frame(3.0, native),
9195 "the picture was asked for the playhead's own frame"
9196 );
9197 let frame = poll(&mut s);
9198 assert_eq!(
9199 frame.index,
9200 secs_to_frame(3.0, native),
9201 "and that is the frame that arrived"
9202 );
9203 }
9204
9205 /// The session's live look samples leave its history exactly where the
9206 /// press left it -- the colour-wheel drag's twin for the packed look, and
9207 /// what lets the app drive one from a pointer: `z` after a drag lands
9208 /// before the press, not one sample back down the drag.
9209 #[test]
9210 fn a_live_look_drag_is_one_step_of_the_sessions_history() {
9211 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
9212 let (lane, idx) = s.video_clip_at(s.now()).expect("a clip under the playhead");
9213 let look = |hue: u8| crate::decode::with_viz_paint_hue(crate::decode::VIZ_PAINT_AZURE, hue);
9214 assert!(s.set_viz_paint(lane, idx, look(1)), "the press");
9215 for hue in 2..=6u8 {
9216 assert!(s.set_viz_paint_live(lane, idx, look(hue)), "a sample");
9217 }
9218 assert_eq!(s.project.lane(lane)[idx].viz_paint, look(6));
9219 assert!(s.undo(), "the drag's own step");
9220 assert_eq!(
9221 s.project.lane(lane)[idx].viz_paint,
9222 0,
9223 "one undo is the whole drag"
9224 );
9225 }
9226
9227 #[test]
9228 fn solo_keeps_only_the_soloed_audio_lanes_audible() {
9229 use super::soloed_gains;
9230 use crate::project::LaneKind;
9231 let a1 = Lane::new(LaneKind::Audio, 0);
9232 let a2 = Lane::new(LaneKind::Audio, 1);
9233 let a3 = Lane::new(LaneKind::Audio, 2);
9234 let v1 = Lane::new(LaneKind::Video, 0);
9235 let audio = [a1, a2, a3];
9236 let gains = vec![1.0, 0.5, 0.0];
9237 assert_eq!(
9238 soloed_gains(gains.clone(), &audio, &[a2]),
9239 vec![0.0, 0.5, 0.0],
9240 "the others go silent, the soloed one keeps its own gain"
9241 );
9242 assert_eq!(
9243 soloed_gains(gains.clone(), &audio, &[]),
9244 vec![1.0, 0.5, 0.0],
9245 "no solo changes nothing"
9246 );
9247 assert_eq!(
9248 soloed_gains(gains.clone(), &audio, &[v1]),
9249 vec![1.0, 0.5, 0.0],
9250 "a video lane is no audio solo"
9251 );
9252 assert_eq!(
9253 soloed_gains(gains.clone(), &[a1, a3], &[a2]),
9254 vec![1.0, 0.5, 0.0],
9255 "a solo naming no audio lane any more is no solo"
9256 );
9257 }
9258}