forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBbcb4dc5Tahinli21 days ago1034 commits

playback.rs9282 lines, 437.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 .with_speech(doc.speech_model, doc.speech_device);
1441 session.counts = counts;
1442 session.rates = rates;
1443 Ok(session)
1444 }
1445
1446 pub fn open_project_relinked(path: &Path, relinks: &[(PathBuf, PathBuf)]) -> crate::Result<Self> {
1447 let mut doc = crate::edith::load(path)?;
1448 for source in doc.sources.iter_mut() {
1449 if let Some((_, found)) = relinks
1450 .iter()
1451 .find(|(saved, _)| crate::project::canonical(saved) == source.path)
1452 {
1453 *source = Source { fav: source.fav, bin: source.bin, ..Source::new(found, source.audio_stream) };
1454 }
1455 }
1456 if doc.sources.iter().all(|s| !crate::source_present(&s.path)) && !doc.sources.is_empty() {
1457 return Self::open_all_offline(doc);
1458 }
1459 // *Which* source scaffolds it: the first that is not a still, and index
1460 // 0 only when there is no other. A still defines no frame rate -- it is
1461 // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps
1462 // footage off a PNG that was imported first and so sits at index 0
1463 // (`Project::without_orphan_sources` keeps every source in session
1464 // order, so whatever was imported first is saved first) reads the
1465 // timeline as 30 fps and then refuses every file on it for not
1466 // matching. The rule this and
1467 // [`audio_source_of`] share: nothing may assume what source 0 *is*.
1468 //
1469 // A v9 file says what rate it was cut at, and that answer beats the
1470 // scaffold's *where the scaffold has none to give*: a still and a song
1471 // are both given a made-up rate (`IMAGE_ONLY_RATE`,
1472 // `AUDIO_ONLY_CANVAS`), so a timeline of nothing but those used to come
1473 // back at 30 fps however it was cut. A scaffold with a picture keeps
1474 // defining the timeline as it always did -- it is the file every clip
1475 // on the lane was conformed to, and the two agree by construction.
1476 let saved_fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0);
1477 // An offline source cannot scaffold: the first present non-still does,
1478 // then the first present anything.
1479 let scaffold = doc
1480 .sources
1481 .iter()
1482 .position(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
1483 .or_else(|| doc.sources.iter().position(|s| crate::source_present(&s.path)))
1484 .unwrap_or(0);
1485 // Owned: the sources move into the `Project` below, and the device is
1486 // opened after that (see the comment there).
1487 let first = doc
1488 .sources
1489 .get(scaffold)
1490 .cloned()
1491 .ok_or("the project names no sources")?;
1492 // The scaffolding source both defines the timeline and is what the
1493 // playhead's first picture comes from, so it is opened for playback
1494 // rather than merely probed.
1495 // One value, not two locals: everything below this line can refuse, and
1496 // locals drop in reverse declaration order -- a bare worker would join
1497 // its decode thread while the receiver next to it was still holding
1498 // that thread parked in `send`, which is a hang (see [`FrameStream`]).
1499 // Ungraded, and superseded before a frame of it is shown: the `seek` at
1500 // the end of this function reopens the playhead's span through
1501 // `start_span`, which is where a saved grade reaches the picture.
1502 // ...unless it has no picture to open: a project whose source 0 is a
1503 // song scaffolds the canvas the same way a fresh audio-only open does
1504 // ([`open_audio_only`](Self::open_audio_only)), and the placeholder
1505 // black stream is superseded by the `seek` at the end of this function
1506 // like every other worker opened here.
1507 // What source 0's own file declares about its light level, read the
1508 // same way [`open_stream`](Self::open_stream) reads it for a fresh
1509 // open: [`ContentLight::default()`] for a song or a still, neither of
1510 // which is graded.
1511 let content_light = if crate::is_audio(&first.path) || crate::is_image(&first.path) {
1512 ContentLight::default()
1513 } else {
1514 Demuxer::open(&first.path)
1515 .map(|(_, d)| d.light())
1516 .unwrap_or_default()
1517 };
1518 // The extension's word, corrected below the moment the header disagrees
1519 // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every
1520 // later question in this function about source 0 asks *this*, not
1521 // `crate::is_audio` again, so a discovered song stays one for the rest
1522 // of the scaffold.
1523 let mut audio_only = crate::is_audio(&first.path);
1524 let (mut meta, stream) = match audio_only {
1525 true => {
1526 let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS;
1527 let frame_rate = saved_fps.unwrap_or(canvas_fps);
1528 let meta = VideoMeta {
1529 width,
1530 height,
1531 frame_rate,
1532 frame_count: audio_frames(&first.path, frame_rate)
1533 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
1534 codec: Codec::H264,
1535 color: ColorDescription::default(),
1536 matrix_assumed: false,
1537 rotation: Rotation::None,
1538 // No container said anything about these: the canvas this engine drew
1539 // itself is square pixels at the size it was drawn at.
1540 coded_width: width,
1541 coded_height: height,
1542 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1543 };
1544 (meta, DecodeSession::open_black(width, height, 1))
1545 }
1546 // ...and a still scaffolds its own picture as the canvas, exactly
1547 // as a fresh `open_image_only` does, with the same placeholder
1548 // stream the `seek` at the end supersedes.
1549 false if crate::is_image(&first.path) => {
1550 let still = crate::decode::Still::open(&first.path)
1551 .map_err(|e| format!("source {}: {e}", first.path.display()))?;
1552 let frame_rate = saved_fps.unwrap_or(IMAGE_ONLY_RATE);
1553 let meta = VideoMeta {
1554 width: still.width,
1555 height: still.height,
1556 frame_rate,
1557 frame_count: image_frames(frame_rate),
1558 codec: Codec::H264,
1559 color: ColorDescription::default(),
1560 matrix_assumed: false,
1561 // `Rotation::None` is honest, not a shrug: `Still::open`
1562 // made the file's own turn before these planes were
1563 // written, so the pair below is already the displayed one.
1564 rotation: Rotation::None,
1565 // No container said anything about these: the picture this
1566 // engine decoded itself is square pixels at its own size.
1567 coded_width: still.width,
1568 coded_height: still.height,
1569 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1570 };
1571 let stream = DecodeSession::open_still(
1572 &first.path,
1573 0,
1574 1,
1575 ColorParams::default(),
1576 TransformParams::default(),
1577 Composer::passthrough(),
1578 )?;
1579 (meta, stream)
1580 }
1581 false => match DecodeSession::open_worker(
1582 &first.path,
1583 0,
1584 u32::MAX,
1585 ColorParams::default(),
1586 TransformParams::default(),
1587 Composer::passthrough(),
1588 // The saved rendition, from the document rather than from the
1589 // project (which is built below): this placeholder is what the
1590 // window shows until the `seek` at the end reopens the span.
1591 doc.tone,
1592 ) {
1593 Ok(opened) => opened,
1594 // A saved source whose extension named a film but whose header
1595 // names no picture: the same door a fresh open falls to
1596 // (`open_stream`), so a project first cut around a song muxed
1597 // into an `.mp4` reloads instead of refusing on a track that was
1598 // never there to begin with.
1599 Err(e) if NoVideoTrack::is_it(&e) => {
1600 audio_only = true;
1601 let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS;
1602 let frame_rate = saved_fps.unwrap_or(canvas_fps);
1603 let meta = VideoMeta {
1604 width,
1605 height,
1606 frame_rate,
1607 frame_count: audio_frames(&first.path, frame_rate)
1608 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
1609 codec: Codec::H264,
1610 color: ColorDescription::default(),
1611 matrix_assumed: false,
1612 rotation: Rotation::None,
1613 // No container said anything about these: the canvas this engine drew
1614 // itself is square pixels at the size it was drawn at.
1615 coded_width: width,
1616 coded_height: height,
1617 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1618 };
1619 (meta, DecodeSession::open_black(width, height, 1))
1620 }
1621 Err(e) => return Err(format!("source {}: {e}", first.path.display()).into()),
1622 },
1623 };
1624 // The project's own resolution, which is source 0's picture unless the
1625 // file says otherwise -- every dialect before v7 had no way to say it,
1626 // and that default is exactly what those projects meant.
1627 let native = (meta.width, meta.height);
1628 if let Some((width, height)) = doc.resolution {
1629 meta.width = width;
1630 meta.height = height;
1631 }
1632 // ...and the project's own *rate*, which is the scaffold's unless the
1633 // file says otherwise. The two made-up rates above already took the
1634 // saved one (their counts are computed from it); a scaffold with a
1635 // picture keeps its own here, so a project cut at a rate nobody picked
1636 // is the file it always was -- and one where a rate *was* picked
1637 // ([`set_frame_rate`](Self::set_frame_rate)) comes back at it rather
1638 // than at the media's, which would leave every clip number counted in
1639 // frames the timeline no longer has.
1640 let native_fps = match audio_only {
1641 true => AUDIO_ONLY_CANVAS.2,
1642 false if crate::is_image(&first.path) => IMAGE_ONLY_RATE,
1643 false => meta.frame_rate,
1644 };
1645 if let Some(fps) = saved_fps {
1646 meta.frame_rate = fps;
1647 }
1648 // A song and a still have no rate of their own to be conformed from:
1649 // their length above was counted in the timeline's frames already,
1650 // whatever those are. A file with pictures is read through [`Rate`] like
1651 // any other source when the project is cut at another rate.
1652 let made_up = audio_only || crate::is_image(&first.path);
1653 let scaffold_rate = match made_up || native_fps == meta.frame_rate {
1654 true => Rate::REAL_TIME,
1655 false => Rate::from_fps(native_fps, meta.frame_rate)
1656 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
1657 };
1658 let first_audio = first_audio_of(&doc.sources)?;
1659
1660 // In source order, with the scaffold's own count in its own slot: the
1661 // clip check below indexes this list by source, so it must line up with
1662 // `doc.sources` whichever entry the scaffolding came from.
1663 let mut counts = Vec::with_capacity(doc.sources.len());
1664 // Beside it, one entry per source, grown at every `push` below: the
1665 // scaffold defines the rate, so it is read frame for frame; every other
1666 // one is however long it is *in this timeline's frames*, which is the
1667 // length `import` noted for it and the wall the clip check below holds
1668 // it to.
1669 let mut rates = Vec::with_capacity(doc.sources.len());
1670 for (i, source) in doc.sources.iter().enumerate() {
1671 if i == scaffold {
1672 counts.push(scaffold_rate.timeline_at(meta.frame_count));
1673 rates.push(scaffold_rate);
1674 continue;
1675 }
1676 // Offline: nothing to check it against. Its length is the furthest
1677 // frame a clip reaches into it, so the clip check below holds.
1678 if !crate::source_present(&source.path) {
1679 let reach = doc
1680 .lanes
1681 .iter()
1682 .flat_map(|(_, clips)| clips)
1683 .filter(|clip| clip.source == i)
1684 .map(|clip| clip.out_frame)
1685 .max()
1686 .unwrap_or(0);
1687 counts.push(reach);
1688 rates.push(Rate::REAL_TIME);
1689 continue;
1690 }
1691 // A still has neither a rate to match nor a track to match with:
1692 // its length is the one it is held to, recomputed exactly as the
1693 // import that first noted it did ([`image_frames`]), which is what
1694 // makes the clip check below meaningful on a reload.
1695 if crate::is_image(&source.path) {
1696 crate::decode::image_size(&source.path)
1697 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1698 counts.push(image_frames(meta.frame_rate));
1699 rates.push(Rate::REAL_TIME);
1700 continue;
1701 }
1702 // A source with no picture is checked on what it does have, and
1703 // its length is its playing time -- the same two answers `import`
1704 // gave it when it first joined the timeline.
1705 if crate::is_audio(&source.path) {
1706 audio_matches(source, &first_audio)
1707 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1708 counts.push(audio_frames(&source.path, meta.frame_rate)?);
1709 rates.push(Rate::REAL_TIME);
1710 continue;
1711 }
1712 // A container with sound but no picture (an audio-only mp4 behind a
1713 // video extension) is held and counted exactly as `import_audio` holds
1714 // and counts it when it first joins the timeline -- the same door
1715 // `import` takes, so a file that imports always reopens.
1716 let (other, _) = match Demuxer::open(&source.path) {
1717 Ok(opened) => opened,
1718 Err(e) if NoVideoTrack::is_it(&e) => {
1719 audio_matches(source, &first_audio)
1720 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1721 counts.push(audio_frames(&source.path, meta.frame_rate)?);
1722 rates.push(Rate::REAL_TIME);
1723 continue;
1724 }
1725 Err(e) => return Err(format!("source {}: {e}", source.path.display()).into()),
1726 };
1727 let rate = matches_timeline(source, &other, &meta, &first_audio)
1728 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1729 counts.push(rate.timeline_at(other.frame_count));
1730 rates.push(rate);
1731 }
1732 // A still is silent, so a clip playing one on an audio lane is a
1733 // segment the audio worker would open a PNG for. Refused by name
1734 // here, which is the one door it can arrive through
1735 // (`place_stream_at` never puts one there). An audio file on a
1736 // *video* lane used to be refused the same way; it plays as a
1737 // waveform visualizer now ([`DecodeSession::open_visualizer`]).
1738 for (kind, clip) in doc
1739 .lanes
1740 .iter()
1741 .chain(doc.sequences.iter().flat_map(|s| s.doc.lanes.iter()))
1742 .flat_map(|(kind, clips)| clips.iter().map(move |clip| (*kind, clip)))
1743 .filter(|(_, clip)| !crate::project::is_sequence_source(clip.source))
1744 {
1745 let path = &doc.sources[clip.source].path;
1746 if kind == LaneKind::Audio && crate::is_image(path) {
1747 return Err(format!(
1748 "{} is a still image: it can only play on a video lane",
1749 path.display()
1750 )
1751 .into());
1752 }
1753 }
1754 // Each lane is held to the length its own clips are walled by ([`wall_table`]).
1755 // A clip that runs past its source is clamped to the source's end and
1756 // reported in `warnings`, not refused: a project that was saved with one
1757 // (a placement or a trim that used the wrong length) must still open, and
1758 // the clamp is the one change that keeps every later edit's walls true.
1759 let audio_walls = wall_table(&doc.sources, &counts, meta.frame_rate, Lane::A1);
1760 let mut warnings = Vec::new();
1761 let mut i = 0;
1762 let sources = doc.sources.clone();
1763 for (kind, clips) in doc
1764 .lanes
1765 .iter_mut()
1766 .chain(doc.sequences.iter_mut().flat_map(|s| s.doc.lanes.iter_mut()))
1767 {
1768 let walls: &[u32] = if *kind == LaneKind::Audio { &audio_walls } else { &counts };
1769 for clip in clips.iter_mut() {
1770 let n = i;
1771 i += 1;
1772 if crate::project::is_sequence_source(clip.source) {
1773 continue;
1774 }
1775 let wall = walls[clip.source];
1776 if clip.out_frame > wall && wall > 0 {
1777 warnings.push(format!(
1778 "clip {n} ended at frame {} but {} has {wall} frames: clamped to {wall}",
1779 clip.out_frame,
1780 sources[clip.source].path.display(),
1781 ));
1782 clip.out_frame = wall;
1783 if clip.in_frame >= clip.out_frame {
1784 clip.in_frame = clip.out_frame - 1;
1785 }
1786 }
1787 }
1788 }
1789 // The subtitle files are read here rather than in the parser: a
1790 // `.edith` names them and holds no cues. One that has gone missing, or
1791 // whose track is a codec of pictures, comes back listed and refused by
1792 // name ([`crate::subtitle::open_all`]) -- a project does not stop
1793 // opening over a subtitle, and a re-save does not lose the row.
1794 //
1795 // All of them in one call, in saved order, because a file is walked
1796 // whole to reach one track: a film whose project names many of its
1797 // tracks is one walk here rather than one per row.
1798 let playhead = doc.playhead;
1799 let (proxy, auto_proxy, encoder, sample_rate) = (doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate);
1800 let seq_active = doc.seq_active.take();
1801 let seq_order = std::mem::take(&mut doc.seq_order);
1802 let seq_docs = std::mem::take(&mut doc.sequences);
1803 let mcams = std::mem::take(&mut doc.mcams);
1804 let mut project = project_of(doc, &meta)?;
1805 if let Some((active, name)) = seq_active {
1806 // The fresh project's placeholder sequence is not the file's: the file's
1807 // sequences (the active one by `set_sequence_meta`) are all there is.
1808 project.clear_sequences();
1809 for sd in seq_docs {
1810 let other = project_of(sd.doc, &meta)?;
1811 project.absorb_sequence(sd.id, &sd.name, other)?;
1812 }
1813 project.set_sequence_meta(active, &name, &seq_order);
1814 project.set_multicam(&mcams)?;
1815 project.check_sequences()?;
1816 }
1817 let span = crate::export::stack_span_at(&project.render_view(), 0);
1818 // Last, because it is the one thing here that cannot be taken back: the
1819 // feeder thread outlives the `Audio` value (it holds its own clones) and
1820 // only a session's `drop` retires it, so a refusal above this line would
1821 // leave a PipeWire stream and a thread behind for a project that never
1822 // opened. Nothing before it needs the device.
1823 //
1824 // On the source the timeline's *sound* is defined by, which is the
1825 // scaffold unless that one is a still ([`audio_source_of`]): opening a
1826 // PNG as the device is a session with no audio at all, however many
1827 // clips with sound are on its lanes.
1828 //
1829 // `audio_source_of` alone only rules out a still; it says nothing
1830 // about whether the file it lands on actually *has* a track. A device
1831 // pinned to the first candidate that opens silent (no track, or one
1832 // the decoder refuses) would leave every later clip's sound unheard
1833 // for the rest of the session, however many other sources on the
1834 // timeline have real audio -- so this walks forward past a silent
1835 // candidate to the first source that really opens a device, and keeps
1836 // only the last attempt's reason when none of them do (a later
1837 // source's silence is not worth reporting over an earlier one's).
1838 let (audio, audio_disabled) = {
1839 let mut opened = (None, None);
1840 for source in project
1841 .sources()
1842 .iter()
1843 .filter(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
1844 {
1845 opened = open_audio(&source.path, source.audio_stream);
1846 if opened.0.is_some() {
1847 break;
1848 }
1849 }
1850 opened
1851 };
1852 let mut session = Self {
1853 scrub: Scrub::default(),
1854 meta,
1855 load_warnings: warnings,
1856 content_light,
1857 native,
1858 native_fps,
1859 frames: stream.frames,
1860 worker: stream.worker,
1861 backend: stream.backend,
1862 video_failure: stream.failure,
1863 retired: Vec::new(),
1864 restarts: 0,
1865 clock: PlaybackClock::new(match audio {
1866 Some(_) => ClockSource::Audio,
1867 None => ClockSource::Wall,
1868 }),
1869 audio,
1870 audio_disabled,
1871 project,
1872 counts,
1873 probes: std::collections::HashMap::new(),
1874 rates,
1875 span_rate: Rate::REAL_TIME,
1876 span,
1877 span_priming: true,
1878 feed: Feed::Live,
1879 back: Back::Off,
1880 dissolve: None,
1881 view: None,
1882 eos: false,
1883 eos_end: 0.0,
1884 mix: None,
1885 solo: Vec::new(),
1886 priming: false,
1887 drop_late: false,
1888 // What the file says, and `false` for every dialect before v12:
1889 // a project cut on the films themselves opens on them.
1890 proxies: proxy,
1891 // ...and what it says about making them, which is "yes" for every
1892 // dialect before v13 and for one that leaves the line out.
1893 auto_proxies: auto_proxy,
1894 // ...and which encoder it exports with, which is the seat this
1895 // machine has for every dialect before v14.
1896 encoder_seat: encoder,
1897 sample_rate,
1898 };
1899 // The scaffolding above opened source 0 from its first frame and the
1900 // whole of its audio; this puts both onto the clip the playhead is
1901 // actually in -- a seek replaces the decoder and supersedes the audio
1902 // worker by epoch, exactly as it does after an edit. It also clamps,
1903 // so a playhead past a hand-shortened timeline lands on the last frame.
1904 session.seek(f64::from(playhead) / meta.frame_rate);
1905 Ok(session)
1906 }
1907
1908 pub fn meta(&self) -> &VideoMeta {
1909 &self.meta
1910 }
1911
1912 /// What the pictures now arriving are being decoded by: the clip under the
1913 /// playhead, since one video worker feeds the composite at a time. An
1914 /// atomic load -- a front-end may ask it every repaint -- and it is what
1915 /// *opened*, so a clip whose hardware session fell back to software reads
1916 /// [`Backend::Software`] from the frame that fallback happened.
1917 pub fn decode_backend(&self) -> Backend {
1918 self.backend.get()
1919 }
1920
1921 /// What an export of this timeline would encode the *sound* with, before
1922 /// one is started: the copy an mp4 normally makes, or the software encoder
1923 /// the format (or an equalized lane) forces. Pure -- no probe, no file
1924 /// opened -- so a card may ask it per repaint; the picture's half costs a
1925 /// plugin open and lives in [`crate::export::planned_video`].
1926 pub fn planned_audio(&self, format: crate::export::Format, ranged: bool) -> &'static str {
1927 crate::export::planned_audio(&self.project.render_view(), format, ranged)
1928 }
1929
1930 /// The timeline an export started right now would be run against, owned:
1931 /// what lets a front-end ask [`crate::export::planned_seats`] what that
1932 /// export would open *off* its render thread, which is the only way to ask
1933 /// a question that opens files. The very snapshot
1934 /// [`export_to_with`](Self::export_to_with) hands the worker, so the answer
1935 /// is about the export that would really start.
1936 pub fn export_snapshot(&self) -> (crate::project::Project, VideoMeta) {
1937 (self.project.export_snapshot(), self.meta)
1938 }
1939
1940 /// The timeline's frame rate: what an editor timeline is read at ([`crate::interchange::otio::read`]).
1941 pub fn timeline_frame_rate(&self) -> f64 {
1942 self.meta.frame_rate
1943 }
1944
1945 /// The active sequence as an editor timeline, for the interchange formats ([`crate::interchange`]).
1946 pub fn timeline_snapshot(&self) -> crate::interchange::Timeline {
1947 let (project, meta) = self.export_snapshot();
1948 crate::interchange::of_project(&project, meta.frame_rate, (meta.width, meta.height))
1949 }
1950
1951 /// The composed picture at timeline `frame`, headless and exact: what
1952 /// export writes for that frame, scaled to fit `width` x `height`. Does not
1953 /// touch the playback clock. See [`crate::export::compose_at`].
1954 pub fn compose_at(
1955 &self,
1956 frame: u32,
1957 width: u32,
1958 height: u32,
1959 ) -> crate::Result<crate::decode::Frame> {
1960 let (project, meta) = self.export_snapshot();
1961 crate::export::compose_at(&project, &meta, frame, width, height)
1962 }
1963
1964 /// What an export would do about the tracks at `picks` --
1965 /// [`crate::export::planned_subtitles`], asked of the project a front-end is
1966 /// holding, and pure for the same reason. `picks` is any run of rows of
1967 /// [`subtitles`](Self::subtitles): the whole
1968 /// [`ExportSettings::subtitles`](crate::export::ExportSettings::subtitles)
1969 /// list a card is about to send (`picks.iter().copied()`) as much as a
1970 /// single `Some(row)`.
1971 pub fn planned_subtitles(
1972 &self,
1973 format: crate::export::Format,
1974 picks: impl IntoIterator<Item = usize>,
1975 ) -> String {
1976 crate::export::planned_subtitles(&self.project.render_view(), format, picks)
1977 }
1978
1979 /// Where the cues of the track at `pick` land on *this* timeline --
1980 /// [`crate::export::timeline_cues`], the very map an export writes the file
1981 /// with, so a front-end that draws these draws what the file will say. On a
1982 /// rippled or cut timeline that is the whole point: an embedded track rides
1983 /// the spans that still play it, and a standalone `.srt` keeps the
1984 /// timeline's own clock, clipped to its length.
1985 ///
1986 /// Empty for a row that is not there and for a track that could not be read.
1987 /// Pure and file-free, so it may be asked per repaint; the cost is a walk of
1988 /// the spans and of the cues.
1989 pub fn timeline_cues(&self, pick: usize) -> Vec<crate::subtitle::Cue> {
1990 self.project
1991 .subtitles()
1992 .get(pick)
1993 .map_or_else(Vec::new, |t| {
1994 crate::export::timeline_cues(&self.project.render_view(), t, self.meta.frame_rate)
1995 })
1996 }
1997
1998 /// Why the sound's rate is not a choice for this timeline in this format --
1999 /// [`crate::export::audio_rate_refusal`], asked of the project a front-end
2000 /// is holding, and pure for the same reason.
2001 pub fn audio_rate_refusal(
2002 &self,
2003 format: crate::export::Format,
2004 ranged: bool,
2005 ) -> Option<&'static str> {
2006 crate::export::audio_rate_refusal(&self.project.render_view(), format, ranged)
2007 }
2008
2009 /// Why this session plays silent although the file has sound -- an audio
2010 /// track in a codec we cannot decode, or one the decoder refused. `None`
2011 /// when there is audio, and for a file that never had any. A front-end
2012 /// shows it once, at open: without it the whole thing is a stderr line.
2013 pub fn audio_disabled_reason(&self) -> Option<&str> {
2014 self.audio_disabled.as_deref()
2015 }
2016
2017 /// Why the picture stopped short of the end of its range, if it did -- the
2018 /// video twin of [`Self::audio_disabled_reason`], and the reason a corrupt
2019 /// file used to be indistinguishable from a finished one.
2020 ///
2021 /// A closed frame channel is not an answer: a span that ran to the end of
2022 /// the file and a span that gave up on a broken packet both drop the
2023 /// sender, and [`Self::try_frame`] returns `None` for either. The app read
2024 /// that as end-of-stream, so a file with a damaged middle froze on its last
2025 /// good picture and the transport said ENDED -- no notice, no banner, and
2026 /// nothing on the screen to say the film had stopped being the film.
2027 ///
2028 /// `None` for a span that played its whole range, which is the ordinary
2029 /// case and the one that must stay silent: a notice that fires on every
2030 /// film is a notice nobody reads. The reason is the engine's own words, for
2031 /// the same reason the sound one is.
2032 pub fn video_failure_reason(&self) -> Option<String> {
2033 self.video_failure.reason()
2034 }
2035
2036 /// The files this timeline plays from, index 0 first -- a caller needs it
2037 /// to name an export or a window after the media rather than the project.
2038 pub fn sources(&self) -> &[Source] {
2039 self.project.sources()
2040 }
2041
2042 /// The subtitle tracks on this timeline, in the order they were added: what
2043 /// a front-end lists and what [`save_project`](Self::save_project) writes.
2044 /// A track that could not be read is *in* this list, saying why
2045 /// ([`crate::subtitle::SubtitleTrack::refused`]) -- listed and skipped, not
2046 /// dropped.
2047 pub fn subtitles(&self) -> &[crate::subtitle::SubtitleTrack] {
2048 self.project.subtitles()
2049 }
2050
2051 /// Adds subtitles from `path`: every subtitle track of a Matroska file, or
2052 /// the one track a standalone `.srt`/`.vtt`/`.ass` is. Hands back how many
2053 /// were added -- 0 for a file whose tracks are all on the timeline already,
2054 /// since importing the same file twice is the same subtitles.
2055 ///
2056 /// An error only when the file cannot be read *at all*; a track this cannot
2057 /// parse is added refused by name, for the reason
2058 /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves:
2059 /// subtitles are not clips and land on no lane.
2060 pub fn import_subtitles(&mut self, path: &Path) -> crate::Result<usize> {
2061 let tracks = Self::parse_subtitles(path)?;
2062 // A file that was walked and carries none is refused as *that*, because
2063 // the alternative -- 0 added -- is the very sentence a file whose tracks
2064 // are already on this timeline gets, and the two are opposite answers a
2065 // person acts differently on. Said only after the walk actually looked
2066 // ([`crate::subtitle::of_media`]); a *file* that is not a container at
2067 // all never reaches here, [`parse_subtitles`](Self::parse_subtitles)
2068 // refuses it in its own words.
2069 if tracks.is_empty() {
2070 return Err(Self::no_subtitles_in(path));
2071 }
2072 Ok(self.add_subtitle_tracks(tracks))
2073 }
2074
2075 /// The reading half of [`import_subtitles`](Self::import_subtitles), with no
2076 /// session in it: every subtitle track of a Matroska file, or the one track
2077 /// a standalone `.srt`/`.vtt`/`.ass` is, cues and all. Same refusal rule.
2078 ///
2079 /// This is the half that costs -- a walk of the whole container, measured at
2080 /// 210 ms on a 25 GB 35-track file and 1.3 s on a 3 GB one whose pages were
2081 /// cold -- so a front-end runs *this* on its background executor and hands
2082 /// what comes back to [`add_subtitle_tracks`](Self::add_subtitle_tracks),
2083 /// which costs a push. Both doors are this one function, so the import
2084 /// button and the background one cannot drift apart.
2085 pub fn parse_subtitles(path: &Path) -> crate::Result<Vec<crate::subtitle::SubtitleTrack>> {
2086 // The containers that carry subtitle tracks *inside* them: every
2087 // Matroska one ([`crate::demux::is_matroska`], which is where `.mks` --
2088 // the subtitles alone -- comes in) and the mp4 family, whose `tx3g`
2089 // timed text is what an mp4 export of this project's own writes, so a
2090 // file edith wrote is a file edith imports back. A transport stream
2091 // carries Blu-ray/AVCHD PGS bitmaps the same way.
2092 let tracks = match crate::demux::is_matroska(path)
2093 || crate::demux::is_mpegts(path)
2094 || path.extension().is_some_and(|e| {
2095 matches!(
2096 e.to_string_lossy().to_ascii_lowercase().as_str(),
2097 "mp4" | "m4v" | "mov" | "3gp" | "3g2"
2098 )
2099 }) {
2100 true => crate::subtitle::of_media(path)?,
2101 false => vec![crate::subtitle::open(path, None)],
2102 };
2103 // A standalone file that could not be parsed is a refusal here rather
2104 // than a row nobody asked for: the import is the moment to say so, and
2105 // the load is the moment to keep it.
2106 if let [one] = &tracks[..]
2107 && one.track.is_none()
2108 && let Some(why) = &one.refused
2109 {
2110 return Err(why.clone().into());
2111 }
2112 Ok(tracks)
2113 }
2114
2115 /// What a file the walk found no subtitle track in is refused with,
2116 /// wherever the refusal is worded: the engine's own door
2117 /// ([`import_subtitles`](Self::import_subtitles)) and a front-end that
2118 /// splits the walk from the push ([`parse_subtitles`](Self::parse_subtitles)
2119 /// then [`add_subtitle_tracks`](Self::add_subtitle_tracks)) must not tell a
2120 /// person two different stories about the same file.
2121 pub fn no_subtitles_in(path: &Path) -> crate::Error {
2122 format!("no subtitle tracks in {}", path.display()).into()
2123 }
2124
2125 /// Puts tracks already read by [`parse_subtitles`](Self::parse_subtitles)
2126 /// on this timeline, in the order given. Hands back how many actually went
2127 /// on: [`Project::add_subtitles`] drops the ones already here -- same file,
2128 /// same track number -- so 0 is "this file's subtitles are on the timeline
2129 /// already", which is the sentence a front-end says.
2130 ///
2131 /// The whole of what an import costs the thread that calls it, which is why
2132 /// the parse is a separate door: nothing here opens, seeks or decodes.
2133 /// Subtitles are not clips and land on no lane, so nothing playable changes
2134 /// and no undo step is pushed ([`Project::remove_subtitles`] says why).
2135 /// [`import_subtitles`](Self::import_subtitles) with a language on its tracks: `lang` as a
2136 /// person typed it, on every track, or else a standalone file's own name
2137 /// ([`crate::subtitle::import_language`]). Returns the count added and the language with where
2138 /// it came from, `None` when none was set. One undo step, as the import is.
2139 pub fn import_subtitles_as(
2140 &mut self,
2141 path: &Path,
2142 lang: Option<&str>,
2143 ) -> crate::Result<(usize, Option<(String, &'static str)>)> {
2144 let mut tracks = Self::parse_subtitles(path)?;
2145 if tracks.is_empty() {
2146 return Err(Self::no_subtitles_in(path));
2147 }
2148 let standalone = tracks.iter().all(|t| t.track.is_none());
2149 let named = if lang.is_some() || standalone {
2150 crate::subtitle::import_language(path, lang)?
2151 } else {
2152 None
2153 };
2154 if let Some((code, _)) = &named {
2155 for t in &mut tracks {
2156 if lang.is_some() || t.track.is_none() {
2157 crate::subtitle::set_language(t, code);
2158 }
2159 }
2160 }
2161 let n = self.add_subtitle_tracks(tracks);
2162 Ok((n, named))
2163 }
2164
2165 /// Names the language of subtitle track `track` ([`Project::set_subtitle_language`]). One undo step.
2166 pub fn set_subtitle_language(&mut self, track: usize, code: &str) -> bool {
2167 self.project.set_subtitle_language(track, code)
2168 }
2169
2170 pub fn add_subtitle_tracks(&mut self, tracks: Vec<crate::subtitle::SubtitleTrack>) -> usize {
2171 // One undo step for the whole import (see [`Project::add_subtitles_all`]).
2172 self.project.add_subtitles_all(&tracks)
2173 }
2174
2175 /// Takes the track at `idx` off this timeline -- the door a subtitle row's
2176 /// own remove goes through, the way [`import_subtitles`](
2177 /// Self::import_subtitles) is the door that puts one on. Refused in
2178 /// [`Project::remove_subtitles`]'s words for a row this timeline does not
2179 /// have, and for one a caption on a subtitle lane still plays -- delete
2180 /// those placements first, or the words under them would change.
2181 ///
2182 /// Nothing playable changes and no worker was opened against a cue, so
2183 /// unlike [`remove_source`](Self::remove_source) this does not reseek. Rows
2184 /// past `idx` move down by one: a caller holding a picked row (the export's
2185 /// subtitle pick) has to fix it up or drop it; the placements on the lanes
2186 /// are walked down with it and need no fixing.
2187 ///
2188 /// One undo step, and the reindex with it ([`Project::remove_subtitles`]'s
2189 /// own entry): every step in the history names its tracks by index into the
2190 /// palette, so an entry carries the palette it was taken beside its lanes --
2191 /// which is what lets a `z` put this row back, and every placement that
2192 /// moved down with it. What that entry cannot bring back is the *pick*: it
2193 /// is the caller's, and a caller holding one fixes it up or drops it
2194 /// ([`crate::subs::sub_pick_after_restore`]).
2195 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
2196 self.project.remove_subtitles(idx)
2197 }
2198
2199 /// Writes the timeline to `path` as a `.edith`, atomically (see
2200 /// [`crate::edith`]). Sources no clip plays from are left out, and the
2201 /// playhead is saved with it so a reopened project resumes where it stood.
2202 ///
2203 /// Refused, writing nothing, for a session whose library is empty (every
2204 /// row removed, [`Project::remove_source`]): a file naming no source has no
2205 /// timeline in it and [`open_project`](Self::open_project) could only
2206 /// refuse it, so the refusal belongs here, where nothing has been
2207 /// overwritten yet.
2208 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
2209 if self.project.sources().is_empty() {
2210 return Err("this project names no file: there is nothing to save".into());
2211 }
2212 self.save_project_noted(path).map(|_| ())
2213 }
2214
2215 /// [`save_project`](Self::save_project) that also returns what it had to change
2216 /// to write the file, one plain sentence per clip, for the front-end to show. A
2217 /// clip that runs past its source's end (a placement or an edit that used the
2218 /// wrong length, or a project saved before the walls held) is shortened to the
2219 /// source's end on the way out, never refused: the user's work is saved, and the
2220 /// note says what was shortened.
2221 pub fn save_project_noted(&self, path: &Path) -> crate::Result<Vec<String>> {
2222 if self.project.sources().is_empty() {
2223 return Err("this project names no file: there is nothing to save".into());
2224 }
2225 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
2226 let mut notes = Vec::new();
2227 let mut main = self.project.clone();
2228 notes.extend(self.wall_notes(&main.clamp_to_walls(&picture, &sound), None));
2229 // The parked sequences are saved whole too, so they are held to the same walls.
2230 let mut parked = Vec::new();
2231 for (id, name, active) in self.project.sequence_rows() {
2232 if !active {
2233 let mut other = self.project.as_sequence(id)?;
2234 notes.extend(self.wall_notes(&other.clamp_to_walls(&picture, &sound), Some(&name)));
2235 parked.push((id, other));
2236 }
2237 }
2238 self.write_project(path, &main, &parked)?;
2239 Ok(notes)
2240 }
2241
2242 /// One plain sentence per clip [`Project::clamp_to_walls`] shortened, naming the
2243 /// clip by its file's name and its lane. `seq` names a parked sequence.
2244 fn wall_notes(&self, clamps: &[crate::project::WallClamp], seq: Option<&str>) -> Vec<String> {
2245 let of = seq.map_or_else(String::new, |n| format!(" in sequence \"{n}\""));
2246 clamps
2247 .iter()
2248 .map(|c| {
2249 let path = &self.project.sources()[c.source].path;
2250 let name = path.file_stem().map_or_else(
2251 || path.display().to_string(),
2252 |s| s.to_string_lossy().into_owned(),
2253 );
2254 let what = match c.lane.kind {
2255 LaneKind::Audio => "sound",
2256 _ => "picture",
2257 };
2258 format!(
2259 "The {what} of \"{name}\" on {} runs past the end of its file{of}. It was shortened to fit.",
2260 c.lane.label(),
2261 )
2262 })
2263 .collect()
2264 }
2265
2266 /// Writes the timeline to `path` for an autosave: exactly what
2267 /// [`save_project`](Self::save_project) writes, minus its wall check. A clip
2268 /// that runs past its source is written as it is, not refused, so an
2269 /// autosave can never fail on a session's state -- the one place a refusal
2270 /// would lose the edits it was meant to keep. [`open_project`](Self::open_project)
2271 /// already clamps such a clip to its source with a warning when the file is
2272 /// read back, so the file still opens.
2273 ///
2274 /// The one refusal kept is an empty library ([`save_project`](Self::save_project)):
2275 /// a file that names no source has no timeline in it to write.
2276 pub fn save_autosave(&self, path: &Path) -> crate::Result<()> {
2277 if self.project.sources().is_empty() {
2278 return Err("this project names no file: there is nothing to save".into());
2279 }
2280 let mut parked = Vec::new();
2281 for (id, _, active) in self.project.sequence_rows() {
2282 if !active {
2283 parked.push((id, self.project.as_sequence(id)?));
2284 }
2285 }
2286 self.write_project(path, &self.project, &parked)
2287 }
2288
2289 /// The write [`save_project`](Self::save_project) and
2290 /// [`save_autosave`](Self::save_autosave) share: the project as it stands,
2291 /// atomically, with its playhead and settings.
2292 /// `main` is the active sequence as it is to be written and `parked` the others,
2293 /// by id, already held to their walls.
2294 fn write_project(&self, path: &Path, main: &Project, parked: &[(u32, Project)]) -> crate::Result<()> {
2295 let dir = crate::edith::project_dir(path);
2296 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
2297 .min(main.timeline_frames().saturating_sub(1));
2298 let main_bytes = self.encode_sequence(&dir, main, playhead);
2299 let main_bytes = crate::edith::binned(main_bytes, self.project.sources(), self.project.bins());
2300 let main_bytes = crate::edith::noted(main_bytes, self.project.notes(), self.project.still_secs(), self.project.speech_model(), self.project.speech_device());
2301 if !self.project.uses_sequences() {
2302 return crate::edith::write_atomic(path, &main_bytes);
2303 }
2304 // Several sequences: the active one is the body, the others follow as blocks of
2305 // their own, each a whole document (v45).
2306 let mut blocks = Vec::new();
2307 for (id, name, active) in self.project.sequence_rows() {
2308 if active {
2309 continue;
2310 }
2311 let Some((_, other)) = parked.iter().find(|(p, _)| *p == id) else { continue };
2312 let at = playhead.min(other.timeline_frames().saturating_sub(1));
2313 blocks.push(crate::edith::SeqBlock { id, name, bytes: self.encode_sequence(&dir, other, at) });
2314 }
2315 let order: Vec<u32> = self.project.sequence_rows().iter().map(|r| r.0).collect();
2316 let active = self.project.active_sequence();
2317 let name = self.project.sequence_name(active).unwrap_or("Sequence").to_string();
2318 let bytes = crate::edith::sequenced(main_bytes, (active, &name), &order, &blocks, &self.project.multicam_rows());
2319 crate::edith::write_atomic(path, &bytes)
2320 }
2321
2322 /// One sequence as the bytes of a standalone project document: `project` has that
2323 /// sequence active.
2324 fn encode_sequence(&self, dir: &Path, project: &Project, playhead: u32) -> Vec<u8> {
2325 let (sources, lanes, eq, color, transform) = project.without_orphan_sources();
2326 crate::edith::encode_flagged(
2327 dir,
2328 &sources,
2329 &lanes,
2330 // The lane volumes and the limiter with them: a mix that vanished
2331 // on a reload would be a mix nobody could keep, and both are the
2332 // project's, not this machine's (the monitoring volume is not
2333 // written and never will be).
2334 &project.lane_gains(),
2335 // ...and what is placed on each lane, in the same order again: the
2336 // captions, which are the only thing a subtitle lane holds.
2337 &project.lane_subs(),
2338 // The subtitle tracks with them, by reference: which file the cues
2339 // are in, never the cues (see [`crate::edith`]).
2340 project.subtitles(),
2341 &eq,
2342 &color,
2343 &transform,
2344 (self.meta.width, self.meta.height),
2345 // ...and the rate it was cut at, which nothing else in the file
2346 // says: a timeline of stills and songs used to come back at
2347 // whatever its scaffold implied (`open_project`).
2348 Some(self.meta.frame_rate),
2349 // ...and which rendition its HDR media is watched in, for the same
2350 // reason: a picked look that vanished on a reload is a look nobody
2351 // could keep.
2352 project.tone(),
2353 // ...and whether it is cut on the stand-ins, for the same reason.
2354 // *Which* files have one is not saved: [`crate::proxy`] finds that
2355 // out from the film itself, so nothing here can go stale.
2356 self.proxies,
2357 // ...and whether it makes them by itself, which is a different
2358 // question from whether it cuts on them and the only one an import
2359 // asks ([`Self::auto_proxies`]).
2360 self.auto_proxies,
2361 // ...and which encoder an export of it opens, for the same reason:
2362 // a project delivered on the software encoder is delivered on it
2363 // again after a reload.
2364 self.encoder_seat,
2365 project.limiter(),
2366 // ...and the rate the mix was picked to run at, for the same
2367 // reason: a project delivered at a chosen rate is delivered at it
2368 // again after a reload.
2369 self.sample_rate,
2370 playhead,
2371 // ...and each lane's switches, hidden, muted or locked, which a
2372 // reload has to hand back as they were left.
2373 &project.lane_flags(),
2374 // ...and each audio lane's duck, by the key lane it names, in the
2375 // same order again: a ducked music bed that came back unducked
2376 // would be a mix nobody could keep.
2377 &project.lane_ducks(),
2378 // ...and the cues somebody retyped, which live in no file: the words
2379 // a reload has to hand back as they were typed.
2380 project.cue_edits(),
2381 // ...and the cues added to a track, which no file has.
2382 project.cue_adds(),
2383 // ...and the title cards and text overlays, which are the project's own.
2384 project.titles(),
2385 // ...and the chapter markers, which are the project's own too.
2386 project.chapters(),
2387 // ...and the comment markers.
2388 project.markers(),
2389 &project.caption_style(),
2390 // ...and each audio lane's voice processors, which a reload has to
2391 // hand back as they were left (the noise profile included: it is
2392 // learned from the sound, and re-learning it would not be the same).
2393 &project.lane_voices(),
2394 // ...and the names the user gave the lanes.
2395 &project.lane_names(),
2396 )
2397 }
2398
2399 /// The next decoded frame, its `index` rewritten from a source frame to a
2400 /// *timeline* frame -- the only frame space that leaves the engine, and the
2401 /// one [`PlaybackSession::now`] is in.
2402 ///
2403 /// `None` means "nothing right now": the decoder is behind, or a clip
2404 /// boundary is being reopened -- and *that* now happens entirely on the new
2405 /// worker ([`DecodeSession::open_worker_deferred`]), so it costs this
2406 /// thread a thread spawn and the caller simply keeps showing its last frame
2407 /// for however long the source takes to open (hundreds of milliseconds on a
2408 /// big film, seconds off a cold cache). End of stream is
2409 /// [`PlaybackSession::is_eos`].
2410 pub fn try_frame(&mut self) -> Option<Frame> {
2411 self.publish_playhead();
2412 loop {
2413 match self.frames.try_recv() {
2414 Ok(mut frame) => {
2415 // A gap's worker indexes from zero, a decoder's from its in
2416 // point, and the span itself knows which: [`Span::timeline_at`]
2417 // is the *stamp*, and it is the ceil half of the pair whose
2418 // floor half an export encodes with -- so the frame the pump
2419 // is holding at any timeline frame is the very frame the
2420 // export writes there, at every rate
2421 // (`speed_maps_both_ways`). An empty timeline has no span,
2422 // and its one black frame is frame 0. Real time is the
2423 // arithmetic this always did, frame for frame.
2424 // ...through the file's own rate first, which is the ceil
2425 // half of *that* pair: the picture at source frame `i` is
2426 // due at the first timeline-rate frame that shows it, and a
2427 // slower file's picture is therefore held for the frames in
2428 // between. Real time for a gap and for a single-rate
2429 // project, where this is the identity.
2430 frame.index = self.stamp(frame.index);
2431 // The first picture out of the span now decoding ends its
2432 // prime ([`Self::span_priming`]).
2433 self.span_priming = false;
2434 // Inside the dissolve window this span's tail owes its
2435 // successor, if any: B's own decoder, graded and placed
2436 // exactly as an export would place it, blended over A's
2437 // already-converted picture -- the one blend point every
2438 // path to the screen goes through, playing or scrubbed,
2439 // since both drain this same channel one frame at a time.
2440 if self
2441 .dissolve
2442 .as_ref()
2443 .is_some_and(|d| frame.index >= d.tail_start)
2444 {
2445 self.open_dissolve_b();
2446 }
2447 if let Some(d) = self.dissolve.as_mut()
2448 && frame.index >= d.tail_start
2449 && let Some(b) = d.b.as_mut()
2450 {
2451 while let Ok(bf) = b.frames.try_recv() {
2452 b.held = Some(bf);
2453 }
2454 // The window's first tick, with B's decoder not yet
2455 // caught up: a paused or scrubbed preview gets no
2456 // later tick to correct itself on (nothing is due
2457 // while the clock is frozen -- `Player::pump`), so
2458 // this is the one chance to blend rather than show A
2459 // alone. Bounded so a source B cannot decode never
2460 // freezes the preview -- eager-opened in
2461 // `start_span`, B is normally already warm here and
2462 // this waits on nothing at all.
2463 if b.held.is_none() {
2464 b.held = b.frames.recv_timeout(DISSOLVE_B_TIMEOUT).ok();
2465 }
2466 if let Some(bf) = &b.held {
2467 let idx_in_window = (frame.index - d.tail_start).min(d.window - 1);
2468 let t = crate::export::dissolve_weight(idx_in_window, d.window);
2469 frame.bgra = match d.kind {
2470 crate::transitions::TransitionKind::Dissolve => {
2471 blend_bgra(&frame.bgra, &bf.bgra, t)
2472 }
2473 kind => crate::transitions::blend_bgra(
2474 kind,
2475 &frame.bgra,
2476 &bf.bgra,
2477 t,
2478 frame.width as usize,
2479 frame.height as usize,
2480 ),
2481 };
2482 }
2483 }
2484 // A picture fade is drawn toward black, the way export draws
2485 // it ([`crate::export::picture_fade_at`]): black is zero in
2486 // every colour channel of BGRA, the alpha byte left alone.
2487 // A layered picture's fades were applied per clip by its worker.
2488 let fade = match self.span.is_some_and(|s| {
2489 crate::export::layered_at(&self.project.render_view(), s.start)
2490 }) {
2491 true => None,
2492 false => crate::export::picture_fade_at(&self.project.render_view(), frame.index),
2493 };
2494 if let Some(k) = fade {
2495 for px in frame.bgra.as_chunks_mut::<4>().0 {
2496 for c in &mut px[..3] {
2497 *c = (f32::from(*c) * k).round() as u8;
2498 }
2499 }
2500 }
2501 return Some(frame);
2502 }
2503 Err(TryRecvError::Empty) => return None,
2504 // The worker stopped: at the end of its range, or on a decode
2505 // error -- which is why this skips the rest of a broken clip
2506 // rather than stalling on it.
2507 Err(TryRecvError::Disconnected) => {
2508 if !self.next_clip() {
2509 self.eos = true;
2510 self.eos_end =
2511 f64::from(self.project.timeline_frames()) / self.meta.frame_rate;
2512 return None;
2513 }
2514 }
2515 }
2516 }
2517 }
2518
2519 /// Whether the timeline has been played out: the picture worker ran to the
2520 /// end and there was no next clip. It is exactly that and nothing more,
2521 /// which is what decides who clears it -- **starting a picture does**
2522 /// (`start_picture`), so a seek clears it and so does every edit that
2523 /// rebuilds the picture (`Dirty::Picture`, `Dirty::Both` -- a paste or a
2524 /// placement past the end revives the session, and it has a new picture to
2525 /// show for it).
2526 ///
2527 /// A **sound-only** edit does not (`Dirty::Sound`: an equalizer, a fader):
2528 /// it rebuilds the sound where the playhead stands and starts no picture
2529 /// worker, so the last frame is still the last frame and this is still the
2530 /// end. A front-end's `Ended` therefore survives an EQ tweak made after the
2531 /// timeline ran out -- the parameters are on the project either way, and the
2532 /// next press restarts from the top with them, which is what `Ended` means.
2533 pub fn is_eos(&self) -> bool {
2534 self.eos
2535 }
2536
2537 /// Tells the decode worker which frame of its *file* the clock has reached,
2538 /// so the pictures it is holding that are already behind the playhead are
2539 /// dropped where they are cheap to drop -- before the conversion and before
2540 /// the queue -- instead of being converted, queued and thrown away by the
2541 /// caller one repaint later. The whole of the late-frame policy: a decoder
2542 /// that has fallen behind catches up by not painting what nobody can see,
2543 /// rather than by being restarted every two seconds (`Player::pump`).
2544 ///
2545 /// The stamp is the exact inverse of the one [`try_frame`](Self::try_frame)
2546 /// puts on a decoded frame: timeline frame -> the clip's own frames
2547 /// ([`Span::speed`]) -> the file's ([`Rate`]). A gap and the emptied
2548 /// timeline have no file to be inside of, and publish nothing.
2549 fn publish_playhead(&self) {
2550 // Backward the worker is not walking toward the clock but away from where
2551 // it started, and a stale picture is dropped by the pump instead.
2552 if !self.drop_late || self.backward() {
2553 return;
2554 }
2555 let Some(span) = self.span else { return };
2556 let Some((_, in_frame)) = span.from else {
2557 return;
2558 };
2559 let now = secs_to_frame(self.clock.now(), self.meta.frame_rate);
2560 let offset = now.saturating_sub(span.start).min(span.len);
2561 self.worker.playhead(
2562 self.span_rate
2563 .source_at(in_frame + span.source_offset(offset)),
2564 );
2565 }
2566
2567 /// Whether the clock runs backward: the picture is then drawn from the
2568 /// playhead down ([`Back`]) and a pump presents what is *at or after* the
2569 /// clock instead of at or before it.
2570 pub fn backward(&self) -> bool {
2571 self.clock.rate() < 0.0
2572 }
2573
2574 /// The playback rate: 1.0 is real time, negative is backward.
2575 pub fn rate(&self) -> f64 {
2576 self.clock.rate()
2577 }
2578
2579 /// The timeline frame a decoded frame numbered `idx` is due at, in the numbering
2580 /// the current worker was opened with ([`Back`]). Forward it is the ceil half
2581 /// of the pair an export encodes with ([`Span::timeline_at`]) through the
2582 /// file's own rate; backward the same mapping read off the file frame the
2583 /// stream really holds, so the stamps fall as the stream goes on.
2584 fn stamp(&self, idx: u32) -> u32 {
2585 let Some(s) = self.span else { return idx };
2586 let rate = self.span_rate;
2587 match self.back {
2588 Back::Off => s.timeline_at(rate.timeline_at(idx)),
2589 Back::Mirror { top } => {
2590 s.timeline_at(rate.timeline_at((2 * top).saturating_sub(idx)))
2591 }
2592 Back::Forward => {
2593 let first = s.from.map_or(0, |(_, f)| f);
2594 s.timeline_at((2 * first).saturating_sub(rate.timeline_at(idx)))
2595 }
2596 Back::Gap => s.start + s.len.saturating_sub(1).saturating_sub(idx),
2597 }
2598 }
2599
2600 /// Installs `replacement` as the decode worker, parking the outgoing one in
2601 /// [`retired`](Self::retired) rather than joining it here, and reaping the
2602 /// parked ones that have already returned.
2603 ///
2604 /// The sweep is what bounds the list: every worker in it was cancelled
2605 /// before this ran, and a cancelled worker is out within an access unit
2606 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's
2607 /// worker on this seek and the list stays a handful long. Nothing waits.
2608 fn retire(&mut self, replacement: Worker) {
2609 // A *replacement*, which is now the narrow case: a seek onto the file
2610 // the worker already has open steers it instead ([`Worker::reseek`])
2611 // and never comes here, so this count is the picture restarts that
2612 // really cost a thread and a decoder open -- which is what makes it
2613 // worth counting.
2614 self.restarts += 1;
2615 let mut outgoing = std::mem::replace(&mut self.worker, replacement);
2616 // Terminal, unlike the [`Worker::abandon`] a seek does: this worker is
2617 // being replaced rather than steered, so its thread has to end -- and
2618 // the cancel is what drops its command channel, without which a worker
2619 // parked between spans would sit in `recv` forever, never reaped here
2620 // and never joined in any bounded time at exit.
2621 outgoing.cancel();
2622 self.retired.push(outgoing);
2623 self.retired.retain(|w| !w.is_finished());
2624 }
2625
2626 /// Picture restarts so far; see [`restarts`](Self::restarts). The one place
2627 /// a worker is ever replaced counts them, so a seek, a resync and a clip
2628 /// boundary all land here and a measurement need not guess which it saw.
2629 #[doc(hidden)]
2630 pub fn restarts(&self) -> u64 {
2631 self.restarts
2632 }
2633
2634 /// Whether the picture span now decoding has yet to hand over a frame:
2635 /// true from the moment a span is started -- a seek, a clip boundary, a
2636 /// picture restart -- until that span's first frame arrives. Whatever
2637 /// lateness that first frame carries is the span's own reopen, not a
2638 /// decoder falling behind, so a front-end gating its late-picture restart
2639 /// on this answers a prime with the decode already on its way rather than
2640 /// with another restart of it.
2641 pub fn picture_priming(&self) -> bool {
2642 self.span_priming
2643 }
2644
2645 /// Whether the picture now playing is read off a render-cache segment
2646 /// ([`crate::render_cache`]) rather than composed live.
2647 pub fn playing_from_cache(&self) -> bool {
2648 matches!(self.feed, Feed::Cached { .. })
2649 }
2650
2651 /// The part of `span` a render-cache segment can stand in for, with the
2652 /// segment it comes from: the span's first frame must be inside a segment
2653 /// that matches the timeline now, and the span must be a forward clip at
2654 /// 1x through no dissolve. The returned span keeps the span's own start and
2655 /// its length up to the segment's end, and reads from the segment's own
2656 /// first frame ([`Feed::Cached`]), at real time, so the stamp is the identity.
2657 fn cached_cut(
2658 &self,
2659 span: Option<Span>,
2660 backward: bool,
2661 ) -> Option<(Span, crate::render_cache::Segment)> {
2662 let span = span?;
2663 if backward
2664 || self.dissolve.is_some()
2665 || span.reverse
2666 || span.ramp.is_some()
2667 || span.speed != Speed::NORMAL
2668 {
2669 return None;
2670 }
2671 let (source, _) = span.from?;
2672 let segment = crate::render_cache::at(&self.project, &self.meta, span.start)?;
2673 let len = span.end().min(segment.to) - span.start;
2674 let cut = Span {
2675 len,
2676 from: Some((source, span.start - segment.from)),
2677 ..span
2678 };
2679 Some((cut, segment))
2680 }
2681
2682 /// Starved audio callbacks since the device opened, and how far into the
2683 /// device's own playback (seconds) the last of them was -- `None` for a
2684 /// session with no device at all. The counter the plugin prints on drop,
2685 /// readable while the session runs: read it either side of a seek and the
2686 /// difference is what that seek cost the ear.
2687 #[doc(hidden)]
2688 pub fn audio_underruns(&self) -> Option<(u64, Option<f64>)> {
2689 let audio = self.audio.as_ref()?;
2690 let (count, last) = audio.ao.lock().unwrap().underruns();
2691 Some((count, last.map(|p| p as f64 / f64::from(audio.sample_rate))))
2692 }
2693
2694 /// How many threads this session still has running of its own: the decode
2695 /// worker, every retired one that has not returned yet, and the audio
2696 /// feeders still in the air. One for a session playing along quietly.
2697 ///
2698 /// The oracle a seek storm is judged by. `/proc/self/status` counts the
2699 /// *process*, and a suite decoding twenty files at once moves that number
2700 /// under a test that never touched them -- this counts only what the
2701 /// session in hand owns, so it says the same thing alone and in a crowd.
2702 #[doc(hidden)]
2703 pub fn live_workers(&self) -> usize {
2704 usize::from(!self.worker.is_finished())
2705 + self.retired.iter().filter(|w| !w.is_finished()).count()
2706 + self.audio.as_ref().map_or(0, Audio::live_feeders)
2707 }
2708
2709 /// Starts feeding whatever follows the current span on the timeline --
2710 /// another clip, or a gap, which is black frames from a worker that opens no
2711 /// file. `false` past the end. The next timeline frame is derived rather
2712 /// than remembered as a clip index, because a `split` while playing cuts the
2713 /// clip under the running worker and only the mapping stays true.
2714 fn next_clip(&mut self) -> bool {
2715 // No span is the emptied timeline: it was played out the moment its one
2716 // black frame went by, and there is no "next" to walk to.
2717 let backward = self.backward();
2718 let span = match (self.span, backward) {
2719 (None, _) => return false,
2720 // Backward the next stretch to draw is the one that ends just before
2721 // this one starts, and the start of the timeline is where it ends.
2722 (Some(span), true) => match span.start.checked_sub(1) {
2723 Some(frame) => back_span_at(&self.project.render_view(), frame),
2724 None => return false,
2725 },
2726 (Some(span), false) => crate::export::stack_span_at(&self.project.render_view(), span.end()),
2727 };
2728 let Some(span) = span else { return false };
2729 // We only get here on a disconnect, so the old span is already done;
2730 // abandon anyway, so `start_span` treats every path alike -- and the
2731 // *worker* is kept, because the next clip is very often the same file
2732 // (a split cuts one clip in two) and it already has it open.
2733 self.worker.abandon();
2734 self.start_span(Some(span));
2735 true
2736 }
2737
2738 /// Points the video worker at `span`: a decoder over its source range, or a
2739 /// black-frame generator for a gap -- and for `None`, the emptied timeline,
2740 /// which is one frame of black so the viewer shows the nothing that is
2741 /// there rather than the last picture of the clip that was deleted. The old
2742 /// worker must already have been cancelled -- this is the half both `seek`
2743 /// and `next_clip` share.
2744 ///
2745 /// A source that will not open leaves the *span* installed anyway: the
2746 /// timeline still moves, there are simply no more pictures, and the
2747 /// disconnected receiver carries the session on to the next span. For a
2748 /// video that is now the worker's own doing -- it opens the file, so it is
2749 /// the one that finds out -- and nothing on this thread waits to hear it.
2750 fn start_span(&mut self, span: Option<Span>) {
2751 // The viewer's own size, once one has said it ([`Self::set_view_size`]):
2752 // every picture below is painted at *this*, and the project's
2753 // resolution otherwise.
2754 let (canvas_w, canvas_h) = self.view_size();
2755 // The outgoing span's own dissolve, if it ever opened B's decoder:
2756 // that decoder's pictures were for a window this span is leaving
2757 // (played through, paused before, or seeked away from), and never
2758 // for the one about to start -- parked in `retired` exactly like the
2759 // picture worker below, so joining it costs this thread nothing.
2760 if let Some(Dissolve { b: Some(b), .. }) = self.dissolve.take() {
2761 let mut worker = b.worker;
2762 worker.cancel();
2763 self.retired.push(worker);
2764 self.retired.retain(|w| !w.is_finished());
2765 }
2766 // What the *new* span's own tail owes its successor -- checked here,
2767 // once, rather than every tick: adjacency can only change on an edit,
2768 // and every edit that could touches this span starts it over
2769 // ([`crate::export::dissolve_window`] makes the identical check for
2770 // the same reason, on export).
2771 let backward = self.backward();
2772 self.back = Back::Off;
2773 self.dissolve = span.filter(|_| !backward).and_then(|s| {
2774 crate::export::dissolve_window(&self.project.render_view(), &s).map(
2775 |(b_source, b_in_frame, window, b_start)| Dissolve {
2776 tail_start: s.start + s.len - window,
2777 window,
2778 b_source,
2779 b_in_frame,
2780 b_start,
2781 kind: crate::transitions::kind_at(&self.project.render_view(), s.start),
2782 b: None,
2783 },
2784 )
2785 });
2786 // B's decoder opens now, at the start of the *span*, rather than
2787 // waiting for the playhead to reach the window: the window is about a
2788 // second, which is exactly the head start a decoder open (VA-API
2789 // init measured 98ms worst case) needs to have a first picture ready
2790 // by the time playback -- or a seek straight into the window -- asks
2791 // for one. Without this a paused seek into the window met a `held`
2792 // that was still `None` and nothing ever asked again
2793 // (`try_frame`'s bounded wait below is the last-resort backstop for a
2794 // seek that lands inside the window before this head start pays off).
2795 if self.dissolve.is_some() {
2796 self.open_dissolve_b();
2797 }
2798 // Which file's frames the worker about to be opened will number its
2799 // pictures in: the span's own source, and real time for a gap, whose
2800 // black worker counts timeline frames already. Set before the open,
2801 // because the open is the first thing that converts with it.
2802 // A layered span's worker numbers its frames on the timeline itself
2803 // ([`crate::export::layered_stream`]), so it is read at real time.
2804 let layered = span.is_some_and(|s| crate::export::layered_at(&self.project.render_view(), s.start));
2805 // A field-mode clip of an interlaced file is decoded as fields, two to a
2806 // frame: the decoder's frame numbers are field numbers, so the file's
2807 // rate against the timeline doubles ([`crate::deinterlace::fields_rate`]).
2808 let deint = match span.and_then(|s| s.from) {
2809 Some((source, _)) if !layered => self.deint_at(source, span.map_or(0, |s| s.start)),
2810 _ => crate::project::Deinterlace::Frame,
2811 };
2812 self.span_rate = match span.and_then(|s| s.from) {
2813 Some((source, _)) if !layered => {
2814 let rate = self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME);
2815 crate::deinterlace::counted_rate(deint, rate)
2816 }
2817 _ => Rate::REAL_TIME,
2818 };
2819 // The new span owes its first picture from the moment it is asked for:
2820 // every path below, the reused worker as much as a fresh one
2821 // ([`Self::span_priming`]).
2822 self.span_priming = true;
2823 // A render-cache segment over this span's first frame plays the render
2824 // instead of compositing it ([`Feed::Cached`]). Only forward at 1x and
2825 // never through a dissolve; every other span stays on the live path.
2826 self.feed = Feed::Live;
2827 if let Some((cut, segment)) = self.cached_cut(span, backward) {
2828 let source_frame = cut.from.map_or(0, |(_, f)| f);
2829 let end = source_frame + cut.len;
2830 self.span_rate = Rate::REAL_TIME;
2831 // The render already holds the grade, transform, fit, tone and
2832 // effects, so the decoder applies none of them.
2833 let stream = DecodeSession::open_worker_deferred_with(
2834 &segment.path,
2835 source_frame,
2836 end,
2837 ColorParams::default(),
2838 TransformParams::default(),
2839 Composer::new(canvas_w, canvas_h, FitPolicy::default()),
2840 self.project.tone(),
2841 Speed::NORMAL,
2842 crate::project::Deinterlace::Frame,
2843 );
2844 self.frames = stream.frames;
2845 self.backend = stream.backend;
2846 self.retire(stream.worker);
2847 self.span = Some(cut);
2848 self.feed = Feed::Cached { segment: segment.path };
2849 return;
2850 }
2851 let opened = match span {
2852 // Two or more clips cover the span: its composed pictures come from a
2853 // stream of their own, each clip drawn over the ones beneath it as an
2854 // export draws them, at the viewer's size.
2855 Some(span) if layered => {
2856 let mut view_meta = self.meta;
2857 view_meta.width = canvas_w;
2858 view_meta.height = canvas_h;
2859 // Each clip's picture comes off its stand-in when the project is
2860 // cut on stand-ins, the way a single clip's does ([`picture_path`]).
2861 let paths = self.proxies.then(|| {
2862 self.project
2863 .sources()
2864 .iter()
2865 .map(|s| crate::proxy::cached(&s.path).unwrap_or_else(|| s.path.clone()))
2866 .collect()
2867 });
2868 Ok(crate::export::layered_stream(
2869 self.project.export_snapshot(),
2870 view_meta,
2871 crate::colorspace::ColorDescription::output_sized(self.meta.width, self.meta.height),
2872 span,
2873 paths,
2874 ))
2875 }
2876 // The grade is the composite's at this frame -- the same clip the
2877 // span itself came from -- and it is constant across the span, so
2878 // the worker carries it and every frame it converts wears it.
2879 Some(Span {
2880 start,
2881 from: Some((source, in_frame)),
2882 ..
2883 }) if crate::is_image(&self.project.sources()[source].path) => {
2884 // A still: the same grade and the same canvas as any other
2885 // clip, over a picture decoded once and repeated for the span.
2886 // As many pictures as the span reads *source* frames, so a still
2887 // is numbered like a decoder's output and a speed reaches it
2888 // through the same rewrite (`try_frame`) as any other clip.
2889 DecodeSession::open_still(
2890 &self.project.sources()[source].path,
2891 in_frame,
2892 span.expect("matched above").source_len(),
2893 self.project
2894 .composite_color_at(start)
2895 .copied()
2896 .unwrap_or_default(),
2897 self.project
2898 .composite_transform_at(start)
2899 .copied()
2900 .unwrap_or_default(),
2901 Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(start)),
2902 )
2903 .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}"))
2904 }
2905 Some(Span {
2906 start,
2907 from: Some((source, in_frame)),
2908 ..
2909 }) if crate::is_audio(&self.project.sources()[source].path)
2910 || self.project.render_view().composite_visualizer_at(start) & 1 != 0 =>
2911 {
2912 let (path, stream) = {
2913 let src = &self.project.sources()[source];
2914 (src.path.clone(), src.audio_stream)
2915 };
2916 DecodeSession::open_visualizer(
2917 &path,
2918 stream,
2919 in_frame,
2920 span.expect("matched above").source_len(),
2921 self.meta.frame_rate,
2922 self.project
2923 .composite_color_at(start)
2924 .copied()
2925 .unwrap_or_default(),
2926 self.project
2927 .composite_transform_at(start)
2928 .copied()
2929 .unwrap_or_default(),
2930 Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(start)),
2931 self.project.render_view().composite_visualizer_at(start),
2932 self.project.render_view().composite_viz_paint_at(start),
2933 )
2934 .inspect_err(|e| eprintln!("timeline frame {start}: visualizer open failed: {e}"))
2935 }
2936 Some(Span {
2937 start,
2938 from: Some((source, in_frame)),
2939 speed,
2940 ..
2941 }) => {
2942 // The stand-in where there is one and the switch is on, the
2943 // film itself otherwise -- the one place the picture's file is
2944 // decided ([`Self::picture_path`]). The sound is opened
2945 // elsewhere and is always the film's.
2946 //
2947 // It decides for the reuse door below as well, and that is what
2948 // makes the switch flippable while watching: a worker holding
2949 // the film is asked for a span of the stand-in, declines on the
2950 // path it already has ([`Worker::reseek`]), and the seek
2951 // [`Self::set_proxies`] does becomes a respawn on the other
2952 // file. Asking the *project* here instead would have left every
2953 // proxied span opening a worker from scratch.
2954 let path = self.picture_path(source);
2955 // The file's own frames, which is the only place they exist: a
2956 // clip counts the timeline's ([`Rate`]).
2957 let start_frame = self.span_rate.source_at(in_frame);
2958 // Source frames, which a speed makes more (or fewer) than the
2959 // timeline frames the span covers -- and which a file shot at
2960 // another rate makes fewer (or more) again. One past the last
2961 // frame this span shows, not one past its length: at another
2962 // rate those are two different frames.
2963 let end_frame = self.span_rate.source_at(
2964 in_frame + span.expect("matched above").source_len().saturating_sub(1),
2965 ) + 1;
2966 let color = self
2967 .project
2968 .composite_color_at(start)
2969 .copied()
2970 .unwrap_or_default();
2971 let transform = self
2972 .project
2973 .composite_transform_at(start)
2974 .copied()
2975 .unwrap_or_default();
2976 // ...and the canvas it is placed on: the project's resolution
2977 // and this clip's own fit policy, constant across the span for
2978 // the reason the grade is. Built where it is handed over rather
2979 // than kept in a local, because a `Composer` owns the scratch
2980 // buffers it places through -- the value is not copied about.
2981 let fit = self.project.render_view().composite_fit_at(start);
2982 let canvas = || Composer::new(canvas_w, canvas_h, fit);
2983 // ...and the rendition an HDR source among them is mapped to,
2984 // the project's own and constant across the span for that
2985 // reason too.
2986 let tone = self.project.tone();
2987 // At faster than real time several source frames decode to the
2988 // same timeline frame ([`Speed::timeline_at`]) and only the last
2989 // of a run is ever shown; the worker skips converting the rest
2990 // ([`crate::decode::skip_for_speed`]) rather than paying a full
2991 // colour convert and scale for a picture nothing displays.
2992 //
2993 // corner-cut: correct only when this file plays at the
2994 // timeline's own rate -- `skip_for_speed`'s own math is in the
2995 // file's frame numbers, which a `Rate` conversion would make a
2996 // different sequence than the timeline's. `Speed::NORMAL` (never
2997 // skip) covers that rarer case exactly as every frame was
2998 // delivered before this.
2999 let decode_speed = if self.span_rate.is_real_time() {
3000 speed
3001 } else {
3002 Speed::NORMAL
3003 };
3004 // Playing backward the span is the clip up to the playhead, drawn from
3005 // the playhead down: a forward clip is served last frame first, and a
3006 // reversed one -- whose backward is the file's forward -- first frame
3007 // first, in both cases over the window the span reads.
3008 let backward_window = backward.then(|| {
3009 let sp = span.expect("matched above");
3010 let (_, lo, hi) = sp.source_window().expect("a clip's span has a window");
3011 (
3012 self.span_rate.source_at(lo),
3013 self.span_rate.source_at(hi.saturating_sub(1)) + 1,
3014 )
3015 });
3016 if let Some((lo, hi)) = backward_window
3017 && !span.is_some_and(|s| s.reverse)
3018 {
3019 self.back = Back::Mirror { top: hi - 1 };
3020 let stream = DecodeSession::open_reversed_with(
3021 &path,
3022 hi - 1,
3023 hi - lo,
3024 color,
3025 transform,
3026 canvas(),
3027 tone,
3028 deint,
3029 );
3030 self.frames = stream.frames;
3031 self.backend = stream.backend;
3032 self.retire(stream.worker);
3033 self.span = span;
3034 return;
3035 }
3036 // ...and a reversed clip's backward is the file's forward: the same
3037 // worker as any clip, over the window, numbered by the file.
3038 let (start_frame, end_frame, decode_speed) = match backward_window {
3039 Some((lo, hi)) => {
3040 self.back = Back::Forward;
3041 (lo, hi, Speed::NORMAL)
3042 }
3043 None => (start_frame, end_frame, decode_speed),
3044 };
3045 // A reversed clip is served backwards from the file frame the span
3046 // starts on, a block at a time ([`DecodeSession::open_reversed`]); its
3047 // frames are numbered as a forward stream's would be, so the stamps
3048 // and drops below need no case of their own.
3049 if !backward && span.is_some_and(|s| s.reverse) {
3050 let stream = DecodeSession::open_reversed_with(
3051 &path,
3052 start_frame,
3053 end_frame.saturating_sub(start_frame).max(1),
3054 color,
3055 transform,
3056 canvas(),
3057 tone,
3058 deint,
3059 );
3060 self.frames = stream.frames;
3061 self.backend = stream.backend;
3062 self.retire(stream.worker);
3063 self.span = span;
3064 return;
3065 }
3066 // The worker already decoding this very file takes the new span
3067 // itself: no thread, no container parse, no VA-API init -- the
3068 // whole of what a seek used to cost. It answers `None` for any
3069 // other file (and for a worker whose thread has ended), and the
3070 // deferred opener below is then exactly the path it always was.
3071 if let Some((frames, backend)) = self.worker.reseek_with(
3072 &path,
3073 start_frame,
3074 end_frame,
3075 color,
3076 transform,
3077 canvas(),
3078 tone,
3079 decode_speed,
3080 deint,
3081 ) {
3082 self.frames = frames;
3083 self.backend = backend;
3084 self.span = span;
3085 return;
3086 }
3087 Ok(DecodeSession::open_worker_deferred_with(
3088 &path,
3089 start_frame,
3090 end_frame,
3091 color,
3092 transform,
3093 canvas(),
3094 tone,
3095 decode_speed,
3096 deint,
3097 ))
3098 }
3099 // A gap: black for as long as it runs. An emptied timeline has no
3100 // span at all and gets one frame of it -- enough to put black on
3101 // screen, and it ends where the timeline does, at once.
3102 gap => {
3103 if backward && gap.is_some() {
3104 self.back = Back::Gap;
3105 }
3106 Ok(DecodeSession::open_black(
3107 canvas_w,
3108 canvas_h,
3109 gap.map_or(1, |s| s.len),
3110 ))
3111 }
3112 };
3113 let Ok(stream) = opened else {
3114 // The file would not open. The span still goes in -- the timeline
3115 // moves on, there are simply no more pictures -- but the *frames*
3116 // must not: the old channel's pictures are numbered in the old
3117 // source's frames, and presenting them under the new mapping would
3118 // put the wrong picture at the wrong time (and leave
3119 // [`decode_backend`](Self::decode_backend) describing a worker that
3120 // is no longer feeding anything). A dead receiver instead, which is
3121 // what carries the session on to the next span. The old worker stays
3122 // parked in `self.worker`, where the caller has already abandoned
3123 // the span it was decoding ([`Worker::abandon`]) without ending the
3124 // thread; the next span reseeks it or retires it.
3125 self.frames = std::sync::mpsc::channel().1;
3126 self.backend = BackendCell::new(Backend::Gap);
3127 self.span = span;
3128 return;
3129 };
3130 // Receiver first, worker second: the drop of the *old* receiver is
3131 // what wakes the outgoing worker if it is parked in `send`, and only
3132 // then can it return and be reaped by a later sweep. Nothing here
3133 // joins, so this ordering costs the seek nothing.
3134 self.frames = stream.frames;
3135 self.backend = stream.backend;
3136 self.retire(stream.worker);
3137 self.span = span;
3138 }
3139
3140 /// The deinterlace setting of the clip on screen at `frame`, as it applies to
3141 /// the file `source`'s picture is decoded from (the stand-in when there is one):
3142 /// `Frame` for anything but interlaced H.264, which ignores the setting.
3143 fn deint_at(&self, source: usize, frame: u32) -> crate::project::Deinterlace {
3144 let mode = self.project.composite_clip_at(frame).map_or(crate::project::Deinterlace::Frame, |(lane, idx)| {
3145 self.project.deinterlace_of(lane, idx)
3146 });
3147 let path = &self.project.sources()[source].path;
3148 let file = self.proxies.then(|| crate::proxy::cached(path)).flatten().unwrap_or_else(|| path.clone());
3149 crate::deinterlace::effective(mode, &file)
3150 }
3151
3152 /// Opens B's own decoder for the current span's dissolve, the first time
3153 /// [`try_frame`](Self::try_frame) sees the playhead inside the window --
3154 /// a no-op once it is already open, or if this span has no dissolve at
3155 /// all. Everything [`start_span`](Self::start_span) works out for A's own
3156 /// decoder, worked out again for B: the stand-in switch
3157 /// ([`Self::picture_path`]), the file's own frame numbering
3158 /// ([`Self::rates`]), and B's *own* grade and fit, asked at B's own start
3159 /// on the timeline rather than at the position the blend writes to
3160 /// (still inside A's span) -- the same asymmetry
3161 /// [`crate::export`]'s own `Dissolve` is built with.
3162 fn open_dissolve_b(&mut self) {
3163 let (canvas_w, canvas_h) = self.view_size();
3164 let Some(d) = &self.dissolve else { return };
3165 if d.b.is_some() {
3166 return;
3167 }
3168 let (source, in_frame, window, b_start) = (d.b_source, d.b_in_frame, d.window, d.b_start);
3169 let path = self.picture_path(source);
3170 // B takes one picture per timeline frame: `Field` is its `Frame`; a clip with its
3171 // pulldown removed counts film frames.
3172 let b_deint = match self.deint_at(source, b_start) {
3173 crate::project::Deinterlace::Off => crate::project::Deinterlace::Off,
3174 crate::project::Deinterlace::Ivtc => crate::project::Deinterlace::Ivtc,
3175 _ => crate::project::Deinterlace::Frame,
3176 };
3177 let rate = crate::deinterlace::counted_rate(b_deint, self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME));
3178 let start_frame = rate.source_at(in_frame);
3179 let end_frame = rate.source_at(in_frame + window);
3180 let color = self
3181 .project
3182 .composite_color_at(b_start)
3183 .copied()
3184 .unwrap_or_default();
3185 let transform = self
3186 .project
3187 .composite_transform_at(b_start)
3188 .copied()
3189 .unwrap_or_default();
3190 let canvas = Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(b_start));
3191 let tone = self.project.tone();
3192 let stream = DecodeSession::open_worker_deferred_with(
3193 &path,
3194 start_frame,
3195 end_frame,
3196 color,
3197 transform,
3198 canvas,
3199 tone,
3200 Speed::NORMAL,
3201 b_deint,
3202 );
3203 if let Some(d) = self.dissolve.as_mut() {
3204 d.b = Some(DissolveB {
3205 frames: stream.frames,
3206 worker: stream.worker,
3207 held: None,
3208 });
3209 }
3210 }
3211
3212 /// Length of the edited timeline in seconds -- what a ruler shows, and it
3213 /// shrinks with every delete.
3214 pub fn timeline_duration(&self) -> f64 {
3215 f64::from(self.project.timeline_frames()) / self.meta.frame_rate
3216 }
3217
3218 /// Whether no lane holds anything: the emptied timeline, which plays black
3219 /// and silent and is zero seconds long. A state, not a failure -- but the
3220 /// one a caller with nothing to render (an export) has to refuse by name
3221 /// rather than write a file of no frames.
3222 pub fn is_empty(&self) -> bool {
3223 self.project.timeline_frames() == 0
3224 }
3225
3226 /// `(start, len)` per clip in timeline seconds, in order: what a clips lane
3227 /// needs to lay itself out. Selection is the caller's business.
3228 pub fn clip_spans(&self) -> Vec<(f64, f64)> {
3229 let fps = self.meta.frame_rate;
3230 self.project
3231 .clip_spans()
3232 .iter()
3233 .map(|&(start, len)| (f64::from(start) / fps, f64::from(len) / fps))
3234 .collect()
3235 }
3236
3237 /// [`clip_spans`](Self::clip_spans) plus the index into
3238 /// [`Project::sources`] each clip plays from -- what a lane needs to colour
3239 /// an imported clip differently from the file the session was opened with.
3240 pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> {
3241 self.lane_spans_by_source(Lane::V1)
3242 }
3243
3244 /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane,
3245 /// with each clip's group id -- what a two-lane front-end draws. The holes
3246 /// between consecutive entries are the gaps.
3247 pub fn lane_spans_by_source(&self, lane: Lane) -> Vec<(f64, f64, usize)> {
3248 let fps = self.meta.frame_rate;
3249 self.project
3250 .lane(lane)
3251 .iter()
3252 .map(|c| (f64::from(c.start) / fps, f64::from(c.len()) / fps, c.source))
3253 .collect()
3254 }
3255
3256 /// Every placement of one lane, in timeline order. What a two-lane
3257 /// front-end draws and nothing
3258 /// [`lane_spans_by_source`](Self::lane_spans_by_source) can answer: a clip
3259 /// carries its group id (which halves a click marks together) and its
3260 /// source range (where a waveform reads its peaks from) as well as its
3261 /// span. The holes between consecutive clips are the gaps.
3262 pub fn lane_clips(&self, lane: Lane) -> &[Clip] {
3263 self.project.lane(lane)
3264 }
3265
3266 /// The empty stretch of `lane` covering `frame`, or `None` when `frame`
3267 /// is inside a clip/caption placement or past the last one
3268 /// ([`Project::gap_at`]). What a right-click on empty bench space asks
3269 /// before offering to close it.
3270 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
3271 self.project.gap_at(lane, frame)
3272 }
3273
3274 /// The gap a Close gap verb closes on `lane` at `frame`: [`gap_at`](Self::gap_at), but
3275 /// only a gap that starts after frame 0. A lead-in before a lane's first clip is empty
3276 /// time, not a gap a hand made, so it is never closed.
3277 pub fn closable_gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
3278 self.gap_at(lane, frame).filter(|&(start, _)| start > 0)
3279 }
3280
3281 /// Closes the gap `(start, frames)` on `lane` and, when it borders a take, on the take's
3282 /// other lane too: the scope [`gap_take_scope`](Self::gap_take_scope) names, cut out by
3283 /// [`cut_regions`](Self::cut_regions). Returns that scope, so a caller can say what moved.
3284 /// The `Err` names what is in the way and nothing changes.
3285 pub fn close_gap_at(&mut self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
3286 let scope = self.gap_take_scope(lane, start, frames)?;
3287 self.cut_regions(&[(start, frames)], &scope)?;
3288 Ok(scope)
3289 }
3290
3291 /// How many bounded gaps that same right-click lane holds. The tail after
3292 /// the last placement is not counted, because nothing would ripple there.
3293 pub fn gap_count(&self, lane: Lane) -> usize {
3294 self.project.gap_count(lane)
3295 }
3296
3297 /// Every lane's handle, in display order -- what a front-end lays out top to
3298 /// bottom, and the list [`add_lane`](Self::add_lane) grows.
3299 pub fn lanes(&self) -> Vec<Lane> {
3300 self.project.lanes()
3301 }
3302
3303 /// The offline sources an export of `span` reads, as `(index, path)`, each source once and
3304 /// in the order the timeline meets them. `span` is the marked range, `None` for the whole
3305 /// timeline. A clip wholly outside the span does not count, so a file only such clips use
3306 /// does not stop the export.
3307 pub fn offline_in_span(&self, span: Option<(u32, u32)>) -> Vec<(usize, PathBuf)> {
3308 let offline = self.offline_sources();
3309 let mut out: Vec<(usize, PathBuf)> = Vec::new();
3310 if offline.is_empty() {
3311 return out;
3312 }
3313 for lane in self.lanes() {
3314 for clip in self.lane_clips(lane) {
3315 let (start, end) = (clip.start, clip.start.saturating_add(clip.frames()));
3316 if let Some((from, to)) = span
3317 && (end <= from || start >= to)
3318 {
3319 continue;
3320 }
3321 if let Some((i, path)) = offline.iter().find(|(i, _)| *i == clip.source)
3322 && !out.iter().any(|(_, p)| p == path)
3323 {
3324 out.push((*i, path.clone()));
3325 }
3326 }
3327 }
3328 out
3329 }
3330
3331 /// The sources whose files are not on disk, as `(index, saved path)`. Their
3332 /// clips stay on the timeline; a frame or an export that reads one is
3333 /// refused naming it.
3334 pub fn offline_sources(&self) -> Vec<(usize, PathBuf)> {
3335 self.project
3336 .sources()
3337 .iter()
3338 .enumerate()
3339 .filter(|(_, s)| !crate::source_present(&s.path))
3340 .map(|(i, s)| (i, s.path.clone()))
3341 .collect()
3342 }
3343
3344 /// Points source `index` at `path`, which must be the same material: the
3345 /// same kind (picture, sound or still), and a picture or sound at least as
3346 /// long as the furthest frame a clip reaches into the source (within a
3347 /// frame). Returns warnings: a length that differs by more than a frame from
3348 /// the file it replaces. The playhead is reopened on it. One undo step
3349 /// ([`Project::relink_source`]): undo points the source back at the old file
3350 /// and reads its length again. Nothing changes on a refusal.
3351 pub fn relink_source(&mut self, index: usize, path: &Path) -> crate::Result<Vec<String>> {
3352 let Some(old) = self.project.sources().get(index).cloned() else {
3353 return Err(format!("there is no source {index}").into());
3354 };
3355 if !path.is_file() {
3356 return Err(format!("{} is not a file", path.display()).into());
3357 }
3358 let kind = |p: &Path| {
3359 if crate::is_image(p) {
3360 "a still"
3361 } else if crate::is_audio(p) {
3362 "a sound file"
3363 } else {
3364 "a picture"
3365 }
3366 };
3367 if kind(&old.path) != kind(path) {
3368 return Err(format!(
3369 "source {index} is {} but {} is {}",
3370 kind(&old.path),
3371 path.display(),
3372 kind(path)
3373 )
3374 .into());
3375 }
3376 let candidate = Source::new(path, old.audio_stream);
3377 let (have, rate) = self.measure_source(&candidate)?;
3378 let expected = self.counts[index];
3379 // What the clips actually read: the furthest out-point any clip on any
3380 // lane takes from this source. A clip reading part of a source needs only
3381 // that part, so refusal is against the reach, not the whole length. Both
3382 // are in timeline-rate frames, the unit `have` is counted in.
3383 let reach = self
3384 .lanes()
3385 .into_iter()
3386 .flat_map(|lane| {
3387 self.lane_clips(lane)
3388 .iter()
3389 .filter(|c| c.source == index)
3390 .map(|c| c.out_frame)
3391 .collect::<Vec<_>>()
3392 })
3393 .max()
3394 .unwrap_or(0);
3395 if have + 1 < reach {
3396 return Err(format!(
3397 "{} has {have} frames but the clips on source {index} reach frame {reach}",
3398 path.display()
3399 )
3400 .into());
3401 }
3402 let mut warnings = Vec::new();
3403 if crate::source_present(&old.path) && have.abs_diff(expected) > 1 {
3404 warnings.push(format!(
3405 "{} has {have} frames; the file it replaces had {expected}",
3406 path.display()
3407 ));
3408 }
3409 self.project.relink_source(index, path)?;
3410 self.counts[index] = have;
3411 self.rates[index] = rate;
3412 let at = self.now();
3413 self.seek(at);
3414 Ok(warnings)
3415 }
3416
3417 /// Points several sources at copies of the same files ([`crate::collect`]) as one undo
3418 /// step. The copies are not measured against the clips: they are the same bytes. Their
3419 /// lengths are read again as an undo reads them, and the playhead is reopened. Returns how
3420 /// many sources moved.
3421 pub fn relink_all(&mut self, pairs: &[(usize, PathBuf)]) -> usize {
3422 let before = self.project.sources().to_vec();
3423 let moved = self.project.relink_sources(pairs);
3424 if moved > 0 {
3425 self.reread_sources(&before);
3426 self.invalidate(Dirty::Both);
3427 }
3428 moved
3429 }
3430
3431 /// Appends an empty lane and hands back its handle. One undo step
3432 /// ([`Project::add_lane`]), and no reseek: an empty lane changes nothing
3433 /// that plays until something is placed on it.
3434 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
3435 self.project.add_lane(kind)
3436 }
3437
3438 /// Drops that empty lane again, in [`Project::remove_lane`]'s words when it
3439 /// refuses. One undo step, and no reseek for the same reason the add needs
3440 /// none: an empty lane was playing nothing.
3441 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
3442 self.project.remove_lane(lane)
3443 }
3444
3445 /// Moves a whole track to display position `to`, clips and all
3446 /// ([`Project::move_lane`]), and hands back the handle it answers to
3447 /// afterwards -- `None` when nothing moved. One undo step.
3448 ///
3449 /// A *video* track that moves rebuilds the picture where the playhead
3450 /// stands, because display order is the stack and the frame on screen may
3451 /// be another lane's from here on; the sound plays on through it, untouched
3452 /// -- a mix is a sum, and a lane's gain travelled with it.
3453 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
3454 let moved = self.project.move_lane(lane, to)?;
3455 if lane.kind == LaneKind::Video {
3456 self.invalidate(Dirty::Picture);
3457 }
3458 Some(moved)
3459 }
3460
3461 /// The subtitle lanes in display order -- `S1..Sn`, the rows a front-end
3462 /// lays out beside the picture and sound ones
3463 /// ([`Project::subtitle_lanes`]). Empty until something adds one, which is
3464 /// [`add_lane`](Self::add_lane) with [`LaneKind::Subtitle`], and they come
3465 /// off, move and reorder through the very same doors every other lane does.
3466 pub fn subtitle_lanes(&self) -> Vec<Lane> {
3467 self.project.subtitle_lanes()
3468 }
3469
3470 /// What is placed on one subtitle lane, in timeline order: what a front-end
3471 /// draws as clips, each naming the palette row it plays
3472 /// ([`Self::subtitles`]) and the window of it it keeps
3473 /// ([`Project::sub_lane`]).
3474 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
3475 self.project.sub_lane(lane)
3476 }
3477
3478 /// Places a stretch of a subtitle track on `lane` at timeline frame `at`
3479 /// ([`Project::place_sub`], whose words a refusal is shown in). One undo
3480 /// step.
3481 ///
3482 /// No reseek and no invalidation, which is what the whole wrapper layer is
3483 /// here for: cues are drawn from [`sub_lane_cues`](Self::sub_lane_cues)
3484 /// over whatever picture is on screen, so nothing already decoded stops
3485 /// being right.
3486 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
3487 self.project.place_sub(lane, at, sub)
3488 }
3489
3490 /// Drags a placement to another subtitle lane or another frame
3491 /// ([`Project::move_sub`]). One undo step, and `Ok` with none for a drop
3492 /// that changed nothing. A caption in a group drags the group's clips with
3493 /// it -- a mapping change -- so this reseeks like a clip's drag does; a
3494 /// caption in no group moves nothing that plays and disturbs nothing.
3495 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
3496 let grouped = self.caption_grouped_with_clips(from, idx);
3497 let moved = self.project.move_sub(from, idx, to, start);
3498 if moved.is_ok() && grouped {
3499 self.invalidate(Dirty::Both);
3500 }
3501 moved
3502 }
3503
3504 /// Drags one edge of a placement to timeline frame `to`
3505 /// ([`Project::trim_sub`]), **at this timeline's own frame rate** -- a
3506 /// placement's position is in frames while its words are in microseconds,
3507 /// and the rate that joins them is the one thing a [`Project`] does not
3508 /// know. That is why a front-end trims through this door and never converts
3509 /// a cue's microseconds itself. One undo step. A caption in a group trims
3510 /// the group's clips with it, and that half reseeked; a lone caption's trim
3511 /// changes only the words, which are drawn over whatever is decoded.
3512 pub fn trim_sub(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> crate::Result<()> {
3513 let grouped = self.caption_grouped_with_clips(lane, idx);
3514 let trimmed = self
3515 .project
3516 .trim_sub(lane, idx, edge, to, self.meta.frame_rate);
3517 if trimmed.is_ok() && grouped {
3518 self.invalidate(Dirty::Both);
3519 }
3520 trimmed
3521 }
3522
3523 /// How far that edge may travel, `(first, last)` timeline frame inclusive
3524 /// ([`Project::trim_sub_room`]) -- what a front-end drawing the box during
3525 /// a drag asks, at this timeline's rate.
3526 pub fn trim_sub_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
3527 self.project
3528 .trim_sub_room(lane, idx, edge, self.meta.frame_rate)
3529 }
3530
3531 /// Takes one placement off a subtitle lane, leaving a gap
3532 /// ([`Project::lift_sub`]). One undo step; the palette row it played stays
3533 /// on this timeline's list.
3534 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
3535 self.project.lift_sub(lane, idx)
3536 }
3537
3538 /// What that subtitle lane shows on *this* timeline, in start order
3539 /// ([`Project::sub_lane_cues`] at this timeline's rate) -- the placed-clip
3540 /// counterpart of [`timeline_cues`](Self::timeline_cues), which carries a
3541 /// whole palette track through the spans that play its media. Pure, so a
3542 /// front-end may ask it per repaint.
3543 pub fn sub_lane_cues(&self, lane: Lane) -> Vec<crate::subtitle::Cue> {
3544 self.project.sub_lane_cues(lane, self.meta.frame_rate)
3545 }
3546
3547 /// Every cue on the subtitle lanes, in start order: the captions that File > Export
3548 /// captions and `export_captions` write as SRT or WebVTT ([`crate::subtitle::write_srt`]).
3549 pub fn caption_cues(&self) -> Vec<crate::subtitle::Cue> {
3550 let mut cues: Vec<crate::subtitle::Cue> = self.subtitle_lanes().into_iter().flat_map(|l| self.sub_lane_cues(l)).collect();
3551 cues.sort_by_key(|c| c.start_us);
3552 cues
3553 }
3554
3555 /// [`sub_lane_cues`](Self::sub_lane_cues) with the cue each one is, as
3556 /// `(start_us, end_us, track, cue)` in the same order ([`Project::sub_lane_cue_refs`]):
3557 /// what a front-end hit-tests a drawn cue against to find the words to edit.
3558 pub fn sub_lane_cue_refs(&self, lane: Lane) -> Vec<(i64, i64, usize, usize)> {
3559 self.project.sub_lane_cue_refs(lane, self.meta.frame_rate)
3560 }
3561
3562 /// [`sub_lane_cue_refs`](Self::sub_lane_cue_refs) with the part of each cue's own clock that
3563 /// is shown ([`Project::sub_lane_cue_spans`]), which its word times are moved by.
3564 pub fn sub_lane_cue_spans(&self, lane: Lane) -> Vec<crate::project::CueSpan> {
3565 self.project.sub_lane_cue_spans(lane, self.meta.frame_rate)
3566 }
3567
3568 /// Retypes one cue's words ([`Project::set_cue_text`]). One undo step, and
3569 /// `false` with none for a cue that is not there or already reads this.
3570 /// No invalidation: the picture's captions are drawn per repaint from the
3571 /// palette ([`sub_lane_cues`](Self::sub_lane_cues)), so the new words are on
3572 /// the next frame without a reseek.
3573 pub fn set_cue_text(&mut self, track: usize, cue: usize, text: &str) -> bool {
3574 self.project.set_cue_text(track, cue, text)
3575 }
3576
3577 /// Removes one cue from its track ([`Project::delete_cue`]): gone from every
3578 /// placement of the track, nothing moves. One undo step, and `false` with
3579 /// none for a cue that is not there.
3580 pub fn delete_cue(&mut self, track: usize, cue: usize) -> bool {
3581 self.project.delete_cue(track, cue)
3582 }
3583
3584 /// The room a cue has on the track's own clock ([`Project::cue_room`]).
3585 pub fn cue_room(&self, track: usize, cue: usize) -> Option<(i64, i64)> {
3586 self.project.cue_room(track, cue)
3587 }
3588
3589 /// Where timeline time `tl_us` is on the track's clock, through the placement on `lane`
3590 /// that shows the cue ([`Project::cue_track_us_at`]).
3591 pub fn cue_track_us_at(&self, lane: Lane, track: usize, cue: usize, tl_us: i64) -> Option<i64> {
3592 self.project.cue_track_us_at(lane, track, cue, tl_us, self.meta.frame_rate)
3593 }
3594
3595 /// Moves or trims one cue ([`Project::set_cue_times`]). One undo step.
3596 pub fn set_cue_times(&mut self, track: usize, cue: usize, start_us: i64, end_us: i64) -> crate::Result<bool> {
3597 self.project.set_cue_times(track, cue, start_us, end_us)
3598 }
3599
3600 /// Joins a cue with the one after it ([`Project::merge_cue_next`]). One undo step.
3601 pub fn merge_cue_next(&mut self, track: usize, cue: usize) -> crate::Result<()> {
3602 self.project.merge_cue_next(track, cue)
3603 }
3604
3605 /// Divides the cue straddling `t_us` on the track's clock ([`Project::split_cues_at`]). One undo step.
3606 pub fn split_cues_at(&mut self, track: usize, t_us: i64) -> bool {
3607 self.project.split_cues_at(track, t_us)
3608 }
3609
3610 /// Adds a cue to a track on the track's own clock ([`Project::add_cue`]): kept
3611 /// in the project and saved with it. One undo step; the index it lands at, or
3612 /// the refusal, which changes nothing.
3613 pub fn add_cue(&mut self, track: usize, start_us: i64, end_us: i64, text: &str, overwrite: bool) -> crate::Result<usize> {
3614 self.project.add_cue(track, start_us, end_us, text, overwrite)
3615 }
3616
3617 /// The title cards and text overlays, in draw order ([`Project::titles`]).
3618 pub fn titles(&self) -> &[crate::project::Title] {
3619 self.project.titles()
3620 }
3621
3622 /// The chapter markers, sorted by frame, at most one per frame
3623 /// ([`Project::chapters`]).
3624 pub fn chapters(&self) -> &[crate::project::Chapter] {
3625 self.project.chapters()
3626 }
3627
3628 /// The chapters as a YouTube description listing, `00:00 Intro` a line each, and the
3629 /// warnings its rules call for ([`chapter_listing`]). The whole timeline, never a range.
3630 pub fn youtube_chapters(&self) -> (String, Vec<String>) {
3631 let fps = self.meta.frame_rate;
3632 let end = (self.timeline_duration() * fps).round() as u32;
3633 let chapters: Vec<(u32, String)> = self.chapters().iter().map(|c| (c.frame, c.title.clone())).collect();
3634 chapter_listing(&chapters, fps, end)
3635 }
3636
3637 /// Adds a chapter at `frame` named `title`, and returns its index in
3638 /// [`chapters`](Self::chapters). One undo step; refused, with nothing changed,
3639 /// for a name the project refuses or a frame that already has a chapter.
3640 pub fn add_chapter(&mut self, frame: u32, title: &str) -> crate::Result<usize> {
3641 self.project.add_chapter(crate::project::Chapter { frame, title: title.to_string() })
3642 }
3643
3644 /// Takes the chapter at `idx` off the list. One undo step; `false`, with
3645 /// nothing changed, for an index that is not there.
3646 pub fn remove_chapter(&mut self, idx: usize) -> bool {
3647 self.project.remove_chapter(idx)
3648 }
3649
3650 /// Renames the chapter at `idx`. One undo step; `false` for an index that
3651 /// is not there, a name the project refuses, or the name it already has.
3652 pub fn set_chapter_title(&mut self, idx: usize, title: &str) -> bool {
3653 self.project.set_chapter_title(idx, title)
3654 }
3655
3656 /// Moves the chapter at `idx` to `frame`, and returns its new index. One undo
3657 /// step; refused for a frame another chapter already holds.
3658 pub fn move_chapter(&mut self, idx: usize, frame: u32) -> crate::Result<usize> {
3659 self.project.move_chapter(idx, frame)
3660 }
3661
3662 /// Maps every chapter's frame through `map` as one undo step, for an edit that
3663 /// moves time (see [`Project::remap_chapters`]). Returns how many chapters a
3664 /// landing on another's frame dropped.
3665 pub fn remap_chapters(&mut self, map: impl Fn(u32) -> u32) -> usize {
3666 self.project.remap_chapters(map)
3667 }
3668
3669 /// How burned captions animate ([`crate::captionanim`]).
3670 pub fn caption_style(&self) -> crate::captionanim::CaptionStyle {
3671 self.project.caption_style()
3672 }
3673
3674 /// Gives a caption track's cues the word times they were written from
3675 /// ([`Project::attach_cue_words`]); `auto_captions` calls it right after the import.
3676 pub fn attach_cue_words(&mut self, track: usize, timed: &[crate::subtitle::Cue]) {
3677 self.project.attach_cue_words(track, timed);
3678 }
3679
3680 /// Sets how burned captions animate; one undo step, `false` when it is already so.
3681 pub fn set_caption_style(&mut self, style: crate::captionanim::CaptionStyle) -> bool {
3682 self.project.set_caption_style(style)
3683 }
3684
3685 /// The comment markers, sorted by frame ([`Project::markers`]).
3686 pub fn markers(&self) -> &[crate::project::Marker] {
3687 self.project.markers()
3688 }
3689
3690 /// Adds a marker and returns its index in [`markers`](Self::markers). One undo step;
3691 /// refused, with nothing changed, for a marker the project refuses.
3692 pub fn add_marker(&mut self, marker: crate::project::Marker) -> crate::Result<usize> {
3693 self.project.add_marker(marker)
3694 }
3695
3696 /// Takes the marker at `idx` off. One undo step; `false` for an index that is not there.
3697 pub fn remove_marker(&mut self, idx: usize) -> bool {
3698 self.project.remove_marker(idx)
3699 }
3700
3701 /// Replaces the marker at `idx` and returns its new index. One undo step; refused for
3702 /// a marker the project refuses or one that changes nothing.
3703 pub fn set_marker(&mut self, idx: usize, marker: crate::project::Marker) -> crate::Result<usize> {
3704 self.project.set_marker(idx, marker)
3705 }
3706
3707 /// Maps every marker's start and end through `map` as one undo step, for an edit that
3708 /// moves time (see [`Project::remap_markers`]). `false` when nothing moved.
3709 pub fn remap_markers(&mut self, map: impl Fn(u32) -> u32) -> bool {
3710 self.project.remap_markers(map)
3711 }
3712
3713 /// The markers as a chapter list for an export of `range`, as [`chapter_list_ns`](Self::chapter_list_ns)
3714 /// lists chapters: `(start_ns, name)` pairs in frame order, the first marker on a frame
3715 /// winning when several share one (a chapter list holds one per instant).
3716 pub fn marker_list_ns(&self, range: Option<(u32, u32)>) -> Vec<(u64, String)> {
3717 let (from, to) = range.unwrap_or((0, u32::MAX));
3718 let fps = self.meta.frame_rate;
3719 let mut out: Vec<(u64, String)> = Vec::new();
3720 for m in self.project.markers().iter().filter(|m| m.frame >= from && m.frame < to) {
3721 let ns = (f64::from(m.frame - from) / fps * 1e9).round() as u64;
3722 if out.last().is_none_or(|(last, _)| *last != ns) {
3723 out.push((ns, m.name.clone()));
3724 }
3725 }
3726 out
3727 }
3728
3729 /// The chapter list an export of `range` (frames, as [`ExportSettings::range`]
3730 /// names it) writes: `(start_ns, name)` pairs in frame order. A chapter's time
3731 /// is measured from the start of the range, so an export that starts at frame
3732 /// 100 writes a chapter at frame 100 as the first one, at 0 ns. Chapters before
3733 /// the range or at or past its end are left out; with no range every chapter
3734 /// is listed from the start of the timeline.
3735 ///
3736 /// Ready for an export's chapter list: the codecs writers take the pairs as
3737 /// they are.
3738 pub fn chapter_list_ns(&self, range: Option<(u32, u32)>) -> Vec<(u64, String)> {
3739 let (from, to) = range.unwrap_or((0, u32::MAX));
3740 let fps = self.meta.frame_rate;
3741 self.project
3742 .chapters()
3743 .iter()
3744 .filter(|c| c.frame >= from && c.frame < to)
3745 .map(|c| {
3746 let ns = f64::from(c.frame - from) / fps * 1e9;
3747 (ns.round() as u64, c.title.clone())
3748 })
3749 .collect()
3750 }
3751
3752 /// Adds a title card or text overlay and recomposes the picture at the
3753 /// playhead. The index it lands at, or the refusal of [`Project::add_title`],
3754 /// which changes nothing.
3755 pub fn add_title(&mut self, title: crate::project::Title) -> crate::Result<usize> {
3756 let idx = self.project.add_title(title)?;
3757 self.invalidate(Dirty::Picture);
3758 Ok(idx)
3759 }
3760
3761 /// Replaces the title at `idx` -- see [`Project::set_title`]. One undo step
3762 /// and a recomposed picture.
3763 pub fn set_title(&mut self, idx: usize, title: crate::project::Title) -> bool {
3764 self.edit(Dirty::Picture, |p| p.set_title(idx, title))
3765 }
3766
3767 /// Takes the title at `idx` off -- see [`Project::remove_title`]. One undo
3768 /// step and a recomposed picture.
3769 pub fn remove_title(&mut self, idx: usize) -> bool {
3770 self.edit(Dirty::Picture, |p| p.remove_title(idx))
3771 }
3772
3773 /// Splits every lane at `timeline_secs`, so the two sides become two
3774 /// groups. Metadata only: a split never changes the timeline->source
3775 /// mapping, so the running decoder stays correct and playback does not
3776 /// blink. `false` at a clip start, in a gap and past the end, where there
3777 /// would be nothing to split off.
3778 pub fn cut_at(&mut self, timeline_secs: f64) -> bool {
3779 self.project
3780 .split(secs_to_frame(timeline_secs, self.meta.frame_rate))
3781 }
3782
3783 /// The frame nearest `frame` within `reach` frames at which [`cut_at`](Self::cut_at)
3784 /// lands cleanly on every lane ([`Project::cut_frame_near`]); `None` when none is that near.
3785 pub fn cut_frame_near(&self, frame: u32, reach: u32) -> Option<u32> {
3786 self.project.cut_frame_near(frame, reach)
3787 }
3788
3789 /// [`cut_at`](Self::cut_at) on the lanes in `lanes` only; the others keep
3790 /// their clips whole across the cut. Metadata only, like `cut_at`.
3791 pub fn cut_at_lanes(&mut self, timeline_secs: f64, lanes: &[Lane]) -> bool {
3792 self.project
3793 .split_on(secs_to_frame(timeline_secs, self.meta.frame_rate), lanes)
3794 }
3795
3796 /// The inverse of [`cut_at`](Self::cut_at): rejoins the clips that meet at
3797 /// `timeline_secs` in every lane and puts them back in one group. `false`
3798 /// unless a split could have produced what is there. Metadata only, like the
3799 /// split -- no reseek.
3800 pub fn regroup_at(&mut self, timeline_secs: f64) -> bool {
3801 self.project
3802 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))
3803 }
3804
3805 /// Takes that clip out of its group, so its picture and its sound are edited
3806 /// apart from here on. Metadata only like a cut -- no reseek -- and one undo
3807 /// step. `false` for a bad index and for a clip that is not grouped with
3808 /// anything, which is already detached.
3809 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
3810 self.project.ungroup(lane, idx)
3811 }
3812
3813 /// Puts two clips covering the same frames back into one group: the regroup
3814 /// of what [`ungroup`](Self::ungroup) took apart. Metadata only, one undo
3815 /// step, and the error says why when it refuses.
3816 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
3817 self.project.group(a, a_idx, b, b_idx)
3818 }
3819
3820 /// Puts every placement the picks name into one group
3821 /// ([`Project::group_all`]) -- the ctrl-click selection's own door, which
3822 /// may name clips and captions alike. Metadata only like the pair above:
3823 /// no reseek, one undo step, and the error says why when it refuses.
3824 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
3825 self.project.group_all(picks)
3826 }
3827
3828 /// [`delete_clip`](Self::delete_clip) for the caption the pick named: a
3829 /// caption in no group lifts exactly as [`lift_sub`](Self::lift_sub) lifts
3830 /// it -- no reseek, because nothing that plays has changed -- and a caption
3831 /// in a group takes the group with it, which ripples every member's own
3832 /// lane and reseeks like a delete. `false` for a bad index.
3833 pub fn delete_sub(&mut self, lane: Lane, idx: usize) -> bool {
3834 // Which of the two, asked before anything moves: the reseek a grouped
3835 // delete owes is the whole difference between the paths. A group of
3836 // captions alone (no clip on another lane) still ripples every
3837 // member's *own* sub lane closed (`Project::delete_sub_in`, since
3838 // cdc53a6), and a sub lane counts toward `timeline_frames` exactly
3839 // like a clip lane does -- so the timeline can shrink out from under
3840 // the playhead from a caption-only group too, not only a media one.
3841 // `caption_grouped_with_clips` answers a narrower question than the
3842 // one this dispatch needs; a caption carries a link at all only once
3843 // grouped (`place_sub` always starts one at `None`), so that alone is
3844 // "this delete ripples more than its own lane".
3845 match self
3846 .sub_lane(lane)
3847 .get(idx)
3848 .is_some_and(|s| s.link.is_some())
3849 {
3850 true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)),
3851 // A caption in no group is the plain lift that touches nothing
3852 // else: no reseek owed.
3853 false => self.project.delete_sub_in(lane, idx),
3854 }
3855 }
3856
3857 /// Whether the caption at `idx` of `lane` is grouped with clips on other
3858 /// lanes: the one question every caption edit that can move media has to
3859 /// ask first, because the answer is whether the edit owes a reseek -- and
3860 /// the front-end owes the same answer, asked before the edit moves the
3861 /// indices, so its flag reset matches the engine's reseek exactly.
3862 pub fn caption_grouped_with_clips(&self, lane: Lane, idx: usize) -> bool {
3863 self.project
3864 .sub_lane(lane)
3865 .get(idx)
3866 .and_then(|s| s.link)
3867 .is_some_and(|id| {
3868 self.project
3869 .lanes()
3870 .into_iter()
3871 .any(|l| l != lane && self.project.lane(l).iter().any(|c| c.link == Some(id)))
3872 })
3873 }
3874
3875 /// What the clip at `idx` of `lane` is equalized with, or `None` for one
3876 /// that plays flat -- what a card shows before it lets anyone drag a band.
3877 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
3878 self.project.eq_of(lane, idx)
3879 }
3880
3881 /// Gives that clip an equalizer, or takes it off with `None`. One undo step,
3882 /// like every other edit -- and it rebuilds the **sound** where the playhead
3883 /// is, so a band changed during playback is heard from the next chunk on
3884 /// rather than at the next play. The picture is not touched: the video
3885 /// worker keeps decoding through it ([`Dirty`]). `false` for a bad index or
3886 /// a non-finite band, and nothing changes.
3887 ///
3888 /// corner-cut: the audio rebuild is what makes it live, so the cost of a
3889 /// change is a decoder restart -- inaudible at a drag's end, but too much to
3890 /// call once per pointer sample (a caller commits one change per gesture).
3891 /// Upgrade path is the per-segment twin of [`crate::audio::MixControls`],
3892 /// which the lane worker would poll per chunk the way the mixer polls the
3893 /// gains.
3894 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
3895 self.edit(Dirty::Sound, |p| p.set_eq(lane, idx, params))
3896 }
3897
3898 /// The clip's own gain in dB at `idx` of `lane`, or `None` for an index
3899 /// that is not there ([`Project::clip_gain`]).
3900 pub fn clip_gain_of(&self, lane: Lane, idx: usize) -> Option<f32> {
3901 self.project.clip_gain(lane, idx)
3902 }
3903
3904 /// Sets that clip's gain in dB, clamped to the clip-gain range. One undo
3905 /// step, and the sound is rebuilt where the playhead is, as for
3906 /// [`set_eq`](Self::set_eq). `false` for a video lane, a bad index, a
3907 /// non-finite value, or a value already set.
3908 pub fn set_clip_gain(&mut self, lane: Lane, idx: usize, db: f32) -> bool {
3909 self.edit(Dirty::Sound, |p| p.set_clip_gain(lane, idx, db))
3910 }
3911
3912 /// Plays the timeline's sound at `at` (timeline seconds) for [`SCRUB_SECS`]: the audible
3913 /// half of a ruler scrub while paused. The decode happens on the scrub thread and nothing
3914 /// here waits for it, so a drag never stalls on the file; a request that arrives while an
3915 /// earlier one is still being read replaces it. Silent, and a no-op, past the end of the
3916 /// timeline or where nothing plays.
3917 pub fn scrub_audio(&mut self, at: f64) {
3918 if !(at.is_finite() && at >= 0.) {
3919 return;
3920 }
3921 let fps = self.meta.frame_rate;
3922 let target = (at * fps) as u32;
3923 let view = self.project.render_view();
3924 let segs = view.audio_segments_from(target, fps);
3925 if segs.is_empty() {
3926 return;
3927 }
3928 let eqs = view.audio_eqs_from(target, fps);
3929 let speeds = view.audio_speeds_from(target, fps);
3930 let fades = view.audio_fades_from(target, fps);
3931 let sources = self.project.audio_sources();
3932 let gains = self.mix_gains();
3933 let ducks = view.audio_ducks();
3934 let voices = view.audio_voices();
3935 let limiter = self.project.limiter();
3936 let sample_rate = self.sample_rate;
3937 let work: ScrubWork = Box::new(move || {
3938 let (meta, rx) = AudioSession::open_mixed_streams_live_fade(
3939 &sources,
3940 &segs,
3941 &eqs,
3942 &speeds,
3943 &fades,
3944 fps,
3945 &gains,
3946 &ducks,
3947 &voices,
3948 limiter,
3949 None,
3950 sample_rate,
3951 )
3952 .ok()??;
3953 let channels = usize::from(meta.channels).max(1);
3954 let want = (SCRUB_SECS * f64::from(meta.sample_rate)) as usize * channels;
3955 let mut buf = Vec::with_capacity(want);
3956 while buf.len() < want {
3957 match rx.recv_timeout(std::time::Duration::from_millis(500)) {
3958 Ok(chunk) => buf.extend_from_slice(&chunk.samples),
3959 Err(_) => break,
3960 }
3961 }
3962 buf.truncate(want);
3963 if buf.is_empty() {
3964 return None;
3965 }
3966 let fade = (SCRUB_FADE_SECS * f64::from(meta.sample_rate)) as usize;
3967 let samples = scrub_snippet(&buf, channels, fade);
3968 Some((meta.sample_rate, u32::from(meta.channels), samples))
3969 });
3970 let tx = self.scrub.tx.get_or_insert_with(|| {
3971 let (tx, rx) = std::sync::mpsc::channel();
3972 let _ = std::thread::Builder::new()
3973 .name("audio-scrub".into())
3974 .spawn(move || scrub_thread(rx));
3975 tx
3976 });
3977 let _ = tx.send(work);
3978 self.scrub.requests += 1;
3979 }
3980
3981 /// How many scrub snippets have been asked for on this session: the count a test reads to see
3982 /// that a drag did, or did not, play sound ([`PlaybackSession::scrub_audio`]).
3983 pub fn scrub_requests(&self) -> u64 {
3984 self.scrub.requests
3985 }
3986
3987 /// The clip's pitch shift in semitones at `idx` of `lane` ([`Project::clip_pitch`]).
3988 pub fn clip_pitch_of(&self, lane: Lane, idx: usize) -> Option<i8> {
3989 self.project.clip_pitch(lane, idx)
3990 }
3991
3992 /// Sets that clip's pitch in semitones, clamped to `-12..=12`. One undo step; the
3993 /// sound is rebuilt where the playhead is, as for [`set_clip_gain`](Self::set_clip_gain).
3994 /// `false` for a video lane, a bad index, or a value already set.
3995 pub fn set_clip_pitch(&mut self, lane: Lane, idx: usize, semitones: i32) -> bool {
3996 self.edit(Dirty::Sound, |p| p.set_clip_pitch(lane, idx, semitones))
3997 }
3998
3999 /// The clip's pan at `idx` of `lane`, `-1.0..=1.0` ([`Project::clip_pan`]).
4000 pub fn clip_pan_of(&self, lane: Lane, idx: usize) -> Option<f32> {
4001 self.project.clip_pan(lane, idx)
4002 }
4003
4004 /// Sets that clip's pan. One undo step; the sound is rebuilt where the playhead is, as for
4005 /// [`set_clip_gain`](Self::set_clip_gain). `false` for a video lane, a bad index, a
4006 /// non-finite value, or a value already set.
4007 pub fn set_clip_pan(&mut self, lane: Lane, idx: usize, pan: f32) -> bool {
4008 self.edit(Dirty::Sound, |p| p.set_clip_pan(lane, idx, pan))
4009 }
4010
4011 /// An audio lane's pan, `-1.0..=1.0` ([`Project::lane_pan`]).
4012 pub fn lane_pan(&self, lane: Lane) -> f32 {
4013 self.project.lane_pan(lane)
4014 }
4015
4016 /// Sets it. One undo step; the pan rides in each clip's envelope, so the sound is rebuilt
4017 /// where the playhead is (a caller commits one change per gesture).
4018 pub fn set_lane_pan(&mut self, lane: Lane, pan: f32) -> bool {
4019 self.edit(Dirty::Sound, |p| p.set_lane_pan(lane, pan))
4020 }
4021
4022 /// How loud that lane plays, in dB -- everything on it, every frequency of
4023 /// it. See [`Project::lane_gain_db`] for what it is *not*.
4024 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
4025 self.project.lane_gain_db(lane)
4026 }
4027
4028 /// Sets it. One undo step -- and **nothing is rebuilt**: a lane's volume
4029 /// lives at the sum, so the running mixer is handed the new number and
4030 /// picks it up at its next block ([`crate::audio::MixControls`]). A fader
4031 /// held down under an arrow key therefore moves the level and nothing else:
4032 /// no flush, no decoder restart, no hole in the sound and no blink in the
4033 /// picture.
4034 ///
4035 /// The one exception is the timeline that is not mixed at all -- a single
4036 /// audio lane at unity with the limiter off, which plays through the
4037 /// bit-exact single-stream path and has no mixer to talk to. Moving *that*
4038 /// off unity opens one, once; every move after it is live.
4039 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
4040 if !self.project.set_lane_gain_db(lane, db) {
4041 return false;
4042 }
4043 self.push_mix();
4044 true
4045 }
4046
4047 /// Sets or clears the auto-duck on an audio lane -- see
4048 /// [`Project::set_lane_duck`]. Live exactly as a volume is: the running
4049 /// mixer is handed the new duck and picks it up at its next block, and
4050 /// nothing is rebuilt.
4051 pub fn set_lane_duck(&mut self, lane: Lane, duck: Option<crate::duck::Duck>) -> bool {
4052 if !self.project.set_lane_duck(lane, duck) {
4053 return false;
4054 }
4055 self.push_mix();
4056 true
4057 }
4058
4059 /// The duck on `lane`, if it has one -- see [`Project::lane_duck`].
4060 pub fn lane_duck(&self, lane: Lane) -> Option<crate::duck::Duck> {
4061 self.project.lane_duck(lane)
4062 }
4063
4064 /// Every duck on `lane`, one per key -- see [`Project::lane_duck_list`].
4065 pub fn lane_duck_list(&self, lane: Lane) -> Vec<crate::duck::Duck> {
4066 self.project.lane_duck_list(lane)
4067 }
4068
4069 /// Removes the duck `lane` has under the key `under` (the key's
4070 /// [`Lane::ord`]) and keeps its others -- see [`Project::clear_lane_duck`].
4071 /// Live like [`set_lane_duck`](Self::set_lane_duck).
4072 pub fn clear_lane_duck(&mut self, lane: Lane, under: usize) -> bool {
4073 if !self.project.clear_lane_duck(lane, under) {
4074 return false;
4075 }
4076 self.push_mix();
4077 true
4078 }
4079
4080 /// The voice processors on `lane` -- see [`Project::lane_voice`].
4081 pub fn lane_voice(&self, lane: Lane) -> crate::voice::VoiceFx {
4082 self.project.lane_voice(lane)
4083 }
4084
4085 /// Sets the voice processors of an audio lane -- see [`Project::set_lane_voice`].
4086 /// One undo step. Not live: the processors run on the lane's own stream, so the
4087 /// sound is rebuilt where the playhead is, as for [`set_eq`](Self::set_eq).
4088 pub fn set_lane_voice(&mut self, lane: Lane, voice: crate::voice::VoiceFx) -> bool {
4089 self.edit(Dirty::Sound, |p| p.set_lane_voice(lane, voice))
4090 }
4091
4092 /// Learns a noise profile from `lane` -- the quietest half second of it, or the
4093 /// `range` (lane seconds) -- see [`crate::voice::learn_noise`]. Reads the lane as it
4094 /// plays and changes nothing.
4095 pub fn learn_noise(
4096 &self,
4097 lane: Lane,
4098 range: Option<(f64, f64)>,
4099 ) -> crate::Result<crate::voice::Learned> {
4100 crate::voice::learn_noise(&self.project, lane, self.meta.frame_rate, self.sample_rate, range)
4101 }
4102
4103 /// Whether the lane is hidden -- see [`Project::lane_hidden`].
4104 pub fn lane_hidden(&self, lane: Lane) -> bool {
4105 self.project.lane_hidden(lane)
4106 }
4107
4108 /// Whether the lane is muted -- see [`Project::lane_muted`].
4109 pub fn lane_muted(&self, lane: Lane) -> bool {
4110 self.project.lane_muted(lane)
4111 }
4112
4113 /// Whether the lane is locked -- see [`Project::lane_locked`]. Nothing here
4114 /// refuses an edit on it; the front-end does.
4115 pub fn lane_locked(&self, lane: Lane) -> bool {
4116 self.project.lane_locked(lane)
4117 }
4118
4119 /// Hides or shows a lane, live. A video lane's picture is recomposed at the
4120 /// playhead, the one rebuild this costs ([`Dirty::Picture`]); the sound keeps
4121 /// playing. A subtitle lane is drawn from the project at every repaint, so
4122 /// nothing is rebuilt for it at all.
4123 pub fn set_lane_hidden(&mut self, lane: Lane, hidden: bool) -> bool {
4124 if !self.project.set_lane_hidden(lane, hidden) {
4125 return false;
4126 }
4127 if lane.kind == LaneKind::Video {
4128 self.invalidate(Dirty::Picture);
4129 }
4130 true
4131 }
4132
4133 /// Mutes or unmutes an audio lane, live: the mix is handed its new gain at
4134 /// the next block exactly as a fader is ([`push_mix`](Self::push_mix)).
4135 pub fn set_lane_muted(&mut self, lane: Lane, muted: bool) -> bool {
4136 if !self.project.set_lane_muted(lane, muted) {
4137 return false;
4138 }
4139 self.push_mix();
4140 true
4141 }
4142
4143 /// Locks or unlocks a lane. Nothing plays differently, so nothing is
4144 /// touched -- it is in the lane list, so it is one undo step like the rest.
4145 pub fn set_lane_locked(&mut self, lane: Lane, locked: bool) -> bool {
4146 self.project.set_lane_locked(lane, locked)
4147 }
4148
4149 /// Names a lane ([`Project::set_lane_name`]). A label only: nothing is rebuilt.
4150 pub fn set_lane_name(&mut self, lane: Lane, name: &str) -> Result<bool, String> {
4151 self.project.set_lane_name(lane, name)
4152 }
4153
4154 /// The name given to a lane, `None` for none ([`Project::lane_name`]).
4155 pub fn lane_name(&self, lane: Lane) -> Option<&str> {
4156 self.project.lane_name(lane)
4157 }
4158
4159 /// What a lane header shows: the name, else the address ([`Project::lane_title`]).
4160 pub fn lane_title(&self, lane: Lane) -> String {
4161 self.project.lane_title(lane)
4162 }
4163
4164 /// Solos audio lanes for listening: while any is soloed, every other audio
4165 /// lane is silent in what this session plays. Monitoring only -- it is not
4166 /// project state, is not saved, and an export never reads it. Lanes that
4167 /// are not audio lanes are ignored, and an empty list clears the solo.
4168 /// `false` when nothing changes. A [`Lane`] is a handle into the lane list,
4169 /// so solo again after a lane is removed or moved.
4170 pub fn set_solo(&mut self, lanes: &[Lane]) -> bool {
4171 let solo: Vec<Lane> = self
4172 .project
4173 .audio_lanes()
4174 .into_iter()
4175 .filter(|lane| lanes.contains(lane))
4176 .collect();
4177 if solo == self.solo {
4178 return false;
4179 }
4180 self.solo = solo;
4181 self.push_mix();
4182 true
4183 }
4184
4185 /// The audio lanes soloed for listening, as [`set_solo`](Self::set_solo) took them.
4186 pub fn soloed(&self) -> &[Lane] {
4187 &self.solo
4188 }
4189
4190 /// The gains the sound plays: the project's own, with the audio lanes
4191 /// outside a solo silenced. A solo that names no audio lane any more is no
4192 /// solo, so a stale handle cannot silence everything. The export reads
4193 /// [`Project::audio_gains`] directly and never comes through here.
4194 fn mix_gains(&self) -> Vec<f32> {
4195 soloed_gains(
4196 self.project.render_view().audio_gains(),
4197 &self.project.render_view().audio_lanes(),
4198 &self.solo,
4199 )
4200 }
4201
4202 /// The level meters, as the sound has reached them since the last call, and
4203 /// starts them over: the highest level each audio lane reached after its own
4204 /// gain (mute and solo read as silence) and the master peak after the
4205 /// limiter, before the device's volume. The flat single-lane path has no
4206 /// mixer, and its one lane is the master. Cheap: atomics and one short lock,
4207 /// nothing on the device's callback.
4208 pub fn levels(&self) -> Levels {
4209 let master = self.audio.as_ref().map_or(0.0, |audio| {
4210 f32::from_bits(audio.peak.swap(0, Ordering::Relaxed))
4211 });
4212 let master_lr = self.master_peaks_lr();
4213 let mut lanes = match self.mix.as_ref() {
4214 Some(mix) => mix.take_lane_peaks(),
4215 None => vec![master],
4216 };
4217 lanes.resize(self.project.audio_lanes().len(), 0.0);
4218 Levels { lanes, master, master_lr }
4219 }
4220
4221 /// The master's left and right peaks since the last read (of this or of [`levels`](Self::levels)),
4222 /// and starts them over: the stereo transport meter's own door, which leaves the lane peaks and
4223 /// the mono master the mix card reads alone.
4224 pub fn master_peaks_lr(&self) -> [f32; 2] {
4225 self.audio.as_ref().map_or([0.0; 2], |audio| {
4226 [0, 1].map(|i| f32::from_bits(audio.peak_lr[i].swap(0, Ordering::Relaxed)))
4227 })
4228 }
4229
4230 /// Hands the mix the running mixer is reading its new settings -- the whole
4231 /// of what a fader and a ceiling cost. With no mixer listening (the
4232 /// single-lane flat path, and a session with no sound at all) the sound is
4233 /// rebuilt instead, which is what opens one.
4234 fn push_mix(&mut self) {
4235 let gains = self.mix_gains();
4236 let ducks = self.project.render_view().audio_ducks();
4237 let limiter = self.project.limiter();
4238 // A mixer reading these, or an open on its way to being one: either way
4239 // the number is heard without a rebuild, and *that* is what a handle
4240 // left over from an open that found nothing cannot do
4241 // ([`crate::audio::MixControls::is_reachable`]).
4242 if let Some(mix) = self.mix.as_ref().filter(|mix| mix.is_reachable()) {
4243 mix.set(gains, ducks, limiter);
4244 return;
4245 }
4246 // Nothing to hand it to. Only a setting that *needs* a mixer is worth
4247 // the flush and the re-open: a ceiling dragged with the limiter off, or
4248 // a fader put back to unity, changes not one sample of the flat
4249 // single-stream path the timeline is already playing
4250 // ([`AudioSession::is_mixed`]), and reseeking per nudge was a hole in
4251 // the sound for a change nobody could hear.
4252 if crate::audio::AudioSession::is_mixed(gains.len(), &gains, limiter, &self.project.render_view().audio_voices()) {
4253 self.reseek_audio();
4254 }
4255 }
4256
4257 /// The master limiter the whole mix is summed through.
4258 pub fn limiter(&self) -> crate::limiter::Limiter {
4259 self.project.limiter()
4260 }
4261
4262 /// Sets it, live like a lane volume and for the same reason -- the ceiling
4263 /// a person is dragging has to be the ceiling they are hearing. Nothing is
4264 /// rebuilt: the running limiter is *retuned* between two blocks
4265 /// ([`crate::limiter::LimiterState::retune`]), so its delay line keeps
4266 /// running and the sample count the master clock is made of does not move.
4267 ///
4268 /// corner-cut: not an undo step, and deliberately -- [`Project::undo`]
4269 /// restores the lane list, and the limiter is not in it, so snapshotting
4270 /// here would push a step whose undo changes nothing a person can see or
4271 /// hear (the twin [`set_lane_gain_db`](Self::set_lane_gain_db) *is*
4272 /// undoable only because a lane volume lives in that list). The project
4273 /// resolution is outside undo for the same reason and says so. Upgrade path
4274 /// is a history that carries the mix beside the lanes, which every existing
4275 /// snapshot site would then have to fill in.
4276 pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool {
4277 if !self.project.set_limiter(limiter) {
4278 return false;
4279 }
4280 self.push_mix();
4281 true
4282 }
4283
4284 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
4285 /// silence on the audio one, and nothing else moves. Reseeks, because what
4286 /// the playhead sits on has changed. `false` for a bad index -- the lift of
4287 /// the last placement there is empties the timeline, which is a state
4288 /// ([`is_empty`](Self::is_empty)) and one undo away.
4289 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {
4290 self.edit(Dirty::Both, |p| p.lift(lane, idx))
4291 }
4292
4293 /// [`swap_clips`](Self::swap_clips) without the ripple: each clip takes the
4294 /// other's head and nothing between them moves ([`Project::swap_in_place`]).
4295 /// The `Err` names the clip the longer one would overlap, and nothing changes.
4296 pub fn swap_clips_in_place(&mut self, lane: Lane, a: usize, b: usize) -> crate::Result<()> {
4297 self.project.swap_in_place(lane, a, b)?;
4298 self.invalidate(Dirty::Both);
4299 Ok(())
4300 }
4301
4302 /// Swaps two placements of one lane ([`Project::swap`]): `b` takes `a`'s
4303 /// start and the ones between them ripple by the difference. One undo step.
4304 pub fn swap_clips(&mut self, lane: Lane, a: usize, b: usize) -> bool {
4305 self.edit(Dirty::Both, |p| p.swap(lane, a, b))
4306 }
4307
4308 /// Moves that clip onto lane `to` with its head at timeline frame `start` --
4309 /// the drag that carries a take along its track or onto another one, and its
4310 /// whole group with it. See [`Project::move_clip`] for the walls `start` is
4311 /// clamped to and the ways a drop is refused. One undo step, and it reseeks
4312 /// like every other edit: which lane a clip sits on is what the compositor's
4313 /// topmost-lane-wins rule reads, and where it starts is what the playhead
4314 /// reads, so the frame on screen is recomposed at once.
4315 ///
4316 /// A *frame*, where the rest of this type takes seconds, for
4317 /// [`trim_clip`](Self::trim_clip)'s reason: the drag has already put the
4318 /// pointer on a frame, and converting it back through seconds would be a
4319 /// rounding step between the box let go of and the box committed.
4320 ///
4321 /// Across kinds (a picture onto an audio lane or back) the clip must fit
4322 /// the new lane's wall ([`held_to_lane`](Self::held_to_lane)): a clip past
4323 /// it is refused rather than cut, since a move is not an edit of its length.
4324 pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
4325 if from.kind != to.kind {
4326 let Some(clip) = self.lane_clips(from).get(idx).cloned() else {
4327 return false;
4328 };
4329 if self.held_to_lane(to, clip.clone()).out_frame != clip.out_frame {
4330 return false;
4331 }
4332 }
4333 self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start))
4334 }
4335
4336 /// [`move_clip_to`](Self::move_clip_to)'s general form: every one of
4337 /// `picks` travels the same frame delta as the dragged clip at `idx` of
4338 /// `from`, all-or-nothing, one undo step for the lot -- what a hand drags
4339 /// on a selection rather than a lone clip. See
4340 /// [`Project::move_selection`] for the clamp that makes it all-or-nothing.
4341 pub fn move_selection_to(
4342 &mut self,
4343 picks: &[(Lane, usize)],
4344 from: Lane,
4345 idx: usize,
4346 to: Lane,
4347 start: u32,
4348 ) -> bool {
4349 self.edit(Dirty::Both, |p| {
4350 p.move_selection(picks, from, idx, to, start)
4351 })
4352 }
4353
4354 /// [`trim_clip`](Self::trim_clip) as a ripple trim ([`Project::ripple_trim`]): the hole the
4355 /// edge leaves closes, or opens, and what follows moves with it. One undo step.
4356 pub fn ripple_trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
4357 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4358 if !self.project.ripple_trim_with_walls(lane, idx, edge, to, SourceWalls { picture: &picture, sound: &sound }) {
4359 return false;
4360 }
4361 let now = self.now();
4362 self.seek(now);
4363 true
4364 }
4365
4366 /// Drags one end of that clip to timeline frame `to`, changing how much of
4367 /// its source it plays and nothing else on the lane -- see [`Project::trim`]
4368 /// for the walls it is clamped by, which this fills the source lengths in
4369 /// for. One undo step per call, so a front-end calls it once, at the release
4370 /// of the drag. Reseeks like every other edit, which is what makes the
4371 /// picture (and the sound) follow a new in-point straight away. `false` for
4372 /// a bad index and for an edge already where it was asked to go.
4373 ///
4374 /// A *frame*, where the rest of this type takes seconds: a drag has already
4375 /// asked [`trim_room`](Self::trim_room) where the edge may land, and that
4376 /// answer is in frames -- converting it back through seconds would be a
4377 /// rounding step between the width drawn and the width committed.
4378 pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
4379 // Spelled out rather than through `edit`, whose closure cannot hold a
4380 // second borrow of the session while it has the project.
4381 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4382 if !self.project.trim_with_walls(lane, idx, edge, to, SourceWalls { picture: &picture, sound: &sound }) {
4383 return false;
4384 }
4385 let now = self.now();
4386 self.seek(now);
4387 true
4388 }
4389
4390 /// **Roll**: moves the cut at the end of the clip at `idx` of `lane` to timeline
4391 /// frame `to` ([`Project::roll`]): the out-point of that clip and the in-point of
4392 /// the one behind it move together. Returns where the cut is now; `None` for a
4393 /// clip with nothing abutting behind it. Reseeks, one undo step.
4394 pub fn roll_clip(&mut self, lane: Lane, idx: usize, to: u32) -> Option<u32> {
4395 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4396 let at = self.project.roll(lane, idx, to, SourceWalls { picture: &picture, sound: &sound })?;
4397 let now = self.now();
4398 self.seek(now);
4399 Some(at)
4400 }
4401
4402 /// Where that cut may travel, `(first, last)` frame inclusive ([`Project::roll_room`]).
4403 pub fn roll_room(&self, lane: Lane, idx: usize) -> Option<(u32, u32)> {
4404 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4405 self.project.roll_room(lane, idx, SourceWalls { picture: &picture, sound: &sound })
4406 }
4407
4408 /// **Slide**: starts that clip at timeline frame `to` between its neighbours
4409 /// ([`Project::slide`]). Returns where it starts now; `None` for a clip
4410 /// without a neighbour on both sides. Reseeks, one undo step.
4411 pub fn slide_clip(&mut self, lane: Lane, idx: usize, to: u32) -> Option<u32> {
4412 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4413 let at = self.project.slide(lane, idx, to, SourceWalls { picture: &picture, sound: &sound })?;
4414 let now = self.now();
4415 self.seek(now);
4416 Some(at)
4417 }
4418
4419 /// Where that clip may start when slid, `(first, last)` frame inclusive ([`Project::slide_room`]).
4420 pub fn slide_room(&self, lane: Lane, idx: usize) -> Option<(u32, u32)> {
4421 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4422 self.project.slide_room(lane, idx, SourceWalls { picture: &picture, sound: &sound })
4423 }
4424
4425 /// **Slip**: shifts that clip's source window by `by` source frames
4426 /// ([`Project::slip`]; [`slip_source_delta`](Self::slip_source_delta) turns timeline
4427 /// frames into them). Returns the frames it moved; `None` for a bad index or a
4428 /// still. Reseeks, one undo step.
4429 pub fn slip_clip(&mut self, lane: Lane, idx: usize, by: i64) -> Option<i64> {
4430 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4431 let moved = self.project.slip(lane, idx, by, SourceWalls { picture: &picture, sound: &sound })?;
4432 if moved != 0 {
4433 let now = self.now();
4434 self.seek(now);
4435 }
4436 Some(moved)
4437 }
4438
4439 /// How far that clip may slip, `(back, forward)` source frames ([`Project::slip_room`]).
4440 pub fn slip_room(&self, lane: Lane, idx: usize) -> Option<(i64, i64)> {
4441 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4442 self.project.slip_room(lane, idx, SourceWalls { picture: &picture, sound: &sound })
4443 }
4444
4445 /// The source frames `by` timeline frames are worth for that clip ([`Project::slip_source_delta`]).
4446 pub fn slip_source_delta(&self, lane: Lane, idx: usize, by: i64) -> Option<i64> {
4447 self.project.slip_source_delta(lane, idx, by)
4448 }
4449
4450 /// How fast the clip at `idx` of `lane` plays -- what a card shows before
4451 /// anyone drags it.
4452 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
4453 self.project.speed_of(lane, idx)
4454 }
4455
4456 /// Sets it, for that clip and its whole group ([`Project::set_speed`]): one
4457 /// undo step for the lot. Reseeks like every other edit, so the picture runs
4458 /// -- and the sound is resampled -- from the next frame on rather than at the
4459 /// next play. The `Err` names the clip in the way when slowing one down
4460 /// would run it into its neighbour, and nothing changes.
4461 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
4462 // Spelled out rather than through `edit`, whose closure hands back a
4463 // bool and would drop the refusal's own words. The playhead moves
4464 let at = self.project.speeded_playhead(
4465 lane,
4466 idx,
4467 speed,
4468 secs_to_frame(self.now(), self.meta.frame_rate),
4469 );
4470 self.project.set_speed(lane, idx, speed)?;
4471 let now = at.map_or_else(
4472 || self.now(),
4473 |frame| f64::from(frame) / self.meta.frame_rate,
4474 );
4475 self.seek(now);
4476 Ok(())
4477 }
4478
4479 /// Whether the clip at `idx` of `lane` plays backwards ([`Project::reversed_of`]).
4480 pub fn reversed_of(&self, lane: Lane, idx: usize) -> bool {
4481 self.project.reversed_of(lane, idx)
4482 }
4483
4484 /// Plays the clip and its whole group backwards, or forwards again
4485 /// ([`Project::set_reverse`]): one undo step, and a reseek at the playhead so
4486 /// the picture and the sound run the new way from the next frame on.
4487 pub fn set_reverse(&mut self, lane: Lane, idx: usize, on: bool) -> crate::Result<()> {
4488 self.project.set_reverse(lane, idx, on)?;
4489 let now = self.now();
4490 self.seek(now);
4491 Ok(())
4492 }
4493
4494 /// Gives the clip at `idx` of `lane` (and its group) a speed ramp, or clears it
4495 /// with empty `keys` ([`Project::set_speed_ramp`]). Reseeks like
4496 /// [`set_speed`](Self::set_speed), and the playhead holds where it stood.
4497 pub fn set_speed_ramp(
4498 &mut self,
4499 lane: Lane,
4500 idx: usize,
4501 keys: &[crate::project::SpeedKey],
4502 ) -> crate::Result<()> {
4503 self.project.set_speed_ramp(lane, idx, keys)?;
4504 let now = self.now();
4505 self.seek(now);
4506 Ok(())
4507 }
4508
4509 /// [`set_speed`](Self::set_speed) without the undo step -- the samples inside
4510 /// one drag ([`Project::set_speed_live`]). Reseeks like the committing one,
4511 /// which is what makes the bar move the picture under the hand.
4512 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
4513 // The mapping on every sample, not just at the commit: the bar moves
4514 // the rate live, and the scene has to stay put across the whole
4515 // gesture or the last picture before the release is not the one the
4516 // commit lands on.
4517 let at = self.project.speeded_playhead(
4518 lane,
4519 idx,
4520 speed,
4521 secs_to_frame(self.now(), self.meta.frame_rate),
4522 );
4523 self.project.set_speed_live(lane, idx, speed)?;
4524 let now = at.map_or_else(
4525 || self.now(),
4526 |frame| f64::from(frame) / self.meta.frame_rate,
4527 );
4528 self.seek(now);
4529 Ok(())
4530 }
4531
4532 /// The picture's source frame at `timeline_secs`: which source, and which
4533 /// frame of it -- the composite a viewer is looking at, through the same
4534 /// span math the decoder walks. What a test asks to prove a reseek kept
4535 /// the scene, and nothing in the editor itself reads.
4536 pub fn video_source_frame_at(&self, timeline_secs: f64) -> Option<(usize, u32)> {
4537 crate::export::stack_span_at(&self.project.render_view(), secs_to_frame(timeline_secs, self.meta.frame_rate))
4538 .and_then(|s| s.from)
4539 }
4540
4541 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
4542 /// together to keep every media take crossing it in sync
4543 /// ([`Project::gap_take_scope`]) -- what a right-click on empty bench
4544 /// space asks before offering to close it. Subtitle gaps stay on their own
4545 /// lane because captions are not A/V take halves.
4546 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
4547 self.project.gap_take_scope(lane, start, frames)
4548 }
4549
4550 /// Closes every bounded gap on one lane. Media lanes keep linked takes
4551 /// whole when the other half has the matching empty stretch and report the
4552 /// gaps that were not safe to close; subtitle lanes ripple captions only.
4553 pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> {
4554 let report = self.project.close_all_gaps_on_lane(lane)?;
4555 if report.closed > 0 {
4556 let now = self.now();
4557 self.seek(now);
4558 }
4559 Ok(report)
4560 }
4561
4562 /// Cuts every one of `regions` -- `(start, len)` in timeline frames -- out
4563 /// of the lanes in `scope` and closes each hole, as **one** edit
4564 /// ([`Project::cut_regions`]): the jumpcut a silence scan
4565 /// ([`crate::silence`]) asks for, one undo press however many silences it
4566 /// found. A lane outside `scope` does not move. Reseeks like every other
4567 /// edit, so what plays is the cut timeline from the playhead on. The `Err`
4568 /// names what is in the way and nothing changes.
4569 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
4570 // Spelled out rather than through `edit`, whose closure hands back a
4571 // bool and would drop the refusal's own words.
4572 self.project.cut_regions(regions, scope)?;
4573 let now = self.now();
4574 self.seek(now);
4575 Ok(())
4576 }
4577
4578 /// Plays every one of those regions at `speed` instead of cutting them,
4579 /// closing the room each one no longer needs ([`Project::speed_regions`]) --
4580 /// one edit, one undo press, and the same scope rule. The `Err` names the
4581 /// lane and frame in the way and nothing changes.
4582 pub fn speed_regions(
4583 &mut self,
4584 regions: &[(u32, u32)],
4585 speed: Speed,
4586 scope: &[Lane],
4587 ) -> crate::Result<()> {
4588 self.project.speed_regions(regions, speed, scope)?;
4589 let now = self.now();
4590 self.seek(now);
4591 Ok(())
4592 }
4593
4594 // The length of each source on a picture lane and on an audio lane
4595 // ([`wall_table`]): a linked take drags both edges together, so a trim
4596 // measures each lane's members against that lane's own length.
4597
4598 /// Where that edge may land, `(first, last)` timeline frame inclusive: what
4599 /// a drag clamps the pointer to so the box it draws is the box
4600 /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
4601 pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
4602 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4603 self.project.trim_room_with_walls(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound })
4604 }
4605
4606 /// [`trim_room`](Self::trim_room) with the walls named: which of the two is
4607 /// the source's media limit, so a drag that stops there can say so. `None`
4608 /// for a bad index.
4609 pub fn trim_walls(&self, lane: Lane, idx: usize, edge: Edge) -> Option<TrimWalls> {
4610 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4611 self.project.trim_walls_with_walls(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound })
4612 }
4613
4614 /// [`trim_walls`](Self::trim_walls) with each wall's bound named
4615 /// ([`Project::trim_bounds`]): the source, a neighbour at a frame, the
4616 /// timeline's first frame, a clip's minimum length or a still's cap. Asked
4617 /// before a trim, so the names are for the walls the trim is measured to.
4618 /// `None` for a bad index.
4619 pub fn trim_bounds(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(WallBound, WallBound)> {
4620 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4621 self.project
4622 .trim_bounds(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound })
4623 }
4624
4625 /// Records how long a source is and what rate it was shot at, for a source
4626 /// index that may be one `Project::import` just made or one it handed back.
4627 /// See [`Self::counts`] and [`Self::rates`], which are one table in two
4628 /// vectors and grow together.
4629 fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) {
4630 if source == self.counts.len() {
4631 self.counts.push(frames);
4632 self.rates.push(rate);
4633 }
4634 debug_assert_eq!(self.counts.len(), self.project.sources().len());
4635 debug_assert_eq!(self.rates.len(), self.counts.len());
4636 // A source just joined, which is the one moment the session's audio
4637 // device may need arming ([`Self::arm_audio`]).
4638 self.arm_audio();
4639 }
4640
4641 /// Opens the audio device for the first source in the library that has a
4642 /// track, when this session has none.
4643 ///
4644 /// A session opened silent -- its first file carried no sound, so
4645 /// [`Self::open_library`]/[`Self::open`] had no track to open a device on
4646 /// -- must not stay silent once a source *with* sound joins it: every later
4647 /// clip's audio would go unheard for the rest of the session. That is
4648 /// exactly what the walk [`Self::open_project`] makes at open prevents for
4649 /// a loaded project (c581d41); this is the same walk at the add door, and
4650 /// [`Self::note_frames`] is the one place a source joins.
4651 ///
4652 /// A no-op once a device is open, so it costs a scan of `is_some` on every
4653 /// later import. The clock stays on wall time until the next seek
4654 /// ([`Self::seek`]'s own `switch_to_audio`), which is the seek a front-end
4655 /// makes as it places the file it just imported.
4656 fn arm_audio(&mut self) {
4657 // A device that is there but *dead* is not a device: the walk below
4658 // opens another one, which is also what clears the notice a death put up
4659 // ([`Self::tick`]).
4660 let carried = self
4661 .audio
4662 .as_ref()
4663 .map(|audio| audio.gain.load(Ordering::Acquire));
4664 if let Some(audio) = &self.audio
4665 && !audio.died.load(Ordering::Acquire)
4666 {
4667 return;
4668 }
4669 for source in self
4670 .project
4671 .sources()
4672 .iter()
4673 .filter(|s| !crate::is_image(&s.path))
4674 {
4675 let (audio, disabled) = open_audio(&source.path, source.audio_stream);
4676 if let Some(audio) = audio {
4677 // The device is being replaced under a session that may already
4678 // be running at a level the user chose, so that level comes
4679 // across with it ([`Audio::gain`]) rather than the fresh
4680 // stream's 1.0.
4681 if let Some(bits) = carried {
4682 audio.gain.store(bits, Ordering::Release);
4683 audio.ao.lock().unwrap().set_volume(f32::from_bits(bits));
4684 }
4685 self.audio = Some(audio);
4686 self.audio_disabled = disabled;
4687 return;
4688 }
4689 }
4690 }
4691
4692 /// Opens the output again for a stream that died, at the rate and channel
4693 /// count it carried, and clears the flag that stopped the session feeding.
4694 ///
4695 /// An output that goes away -- a PipeWire daemon restarting, a sink node
4696 /// removed and put back -- leaves every stream that was open on it dead for
4697 /// good: its position is frozen, so the clock can only fall to wall time, and
4698 /// a session that never opens another device is silent for the rest of its
4699 /// life, through every seek and every pause/play, with nothing said about it.
4700 ///
4701 /// The device *only*, never the file: the feeder is [`Self::start_audio`]'s,
4702 /// at the seek that follows. That is what lets [`Self::tick`] call this too,
4703 /// once a frame -- a tick is not a seek and must not reseek the timeline. The
4704 /// clock is on wall time by then and stays there until a seek comes, which is
4705 /// the seek whose feeder opens in step with the picture.
4706 ///
4707 /// `if_idle_for` is the cooldown: a tick passes [`AUDIO_REARM_AFTER`], because
4708 /// sixty opens a second against a device that is gone for good is a spin; a
4709 /// seek passes zero, because that one is a person asking.
4710 ///
4711 /// `false` when there is nothing to open, nothing came back, or the cooldown
4712 /// has not passed -- and the flag stays standing for the next attempt.
4713 fn rearm_audio(&mut self, if_idle_for: Duration) -> bool {
4714 let Some(audio) = &self.audio else {
4715 return false;
4716 };
4717 if !audio.died.load(Ordering::Acquire) {
4718 return true;
4719 }
4720 {
4721 let mut at = audio.rearm_at.lock().unwrap();
4722 if at.is_some_and(|at| at.elapsed() < if_idle_for) {
4723 return false;
4724 }
4725 *at = Some(Instant::now());
4726 }
4727 let Some(ao) = AoSession::open(audio.sample_rate, audio.channels as u32) else {
4728 return false;
4729 };
4730 // A stream comes up streaming and a session starts paused: the fresh one
4731 // is silenced until the seek that feeds it says otherwise, which is the
4732 // same two steps [`open_audio`] takes on the way in.
4733 ao.set_active(false);
4734 // A fresh stream comes up at full volume, so the level this session was
4735 // already running at is put back onto it before it is installed: a
4736 // muted session that lost its device to a daemon restart would
4737 // otherwise come back loud while the window still reads "muted".
4738 ao.set_volume(f32::from_bits(audio.gain.load(Ordering::Acquire)));
4739 // Replacing the session is what closes the dead stream, so it is done
4740 // under the device lock the feeder writes through.
4741 *audio.ao.lock().unwrap() = ao;
4742 // The clock anchor and the played-out arithmetic both belong to the
4743 // stream that died: the new one stamps its own first sample
4744 // ([`Audio::content_at`]), and `start_audio` re-bases the count from the
4745 // device's own position.
4746 audio.content_at.store(-1, Ordering::Release);
4747 audio.died.store(false, Ordering::Release);
4748 if self.audio_disabled.as_deref() == Some(AUDIO_LOST) {
4749 self.audio_disabled = None;
4750 }
4751 true
4752 }
4753
4754 /// The rate noted for whichever source plays `path`, by
4755 /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however
4756 /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session
4757 /// has never taken in.
4758 fn file_rate(&self, path: &Path) -> Rate {
4759 self.source_of(path)
4760 .map_or(Rate::REAL_TIME, |i| self.rates[i])
4761 }
4762
4763 /// Which file this source's **picture** is decoded from: its stand-in when
4764 /// the project is cut on stand-ins and one has been made for it, and the
4765 /// film itself in every other case ([`crate::proxy`]).
4766 ///
4767 /// One `stat` per span open, against a decoder open that costs milliseconds
4768 /// -- so a proxy that appeared (or was deleted) since the last seek is
4769 /// picked up at this one, and no table of attachments exists to disagree
4770 /// with the cache.
4771 ///
4772 /// The sound never comes through here: [`open_audio`] is given the
4773 /// project's own source path, so a mix is the film's however this answers.
4774 pub fn picture_path(&self, source: usize) -> PathBuf {
4775 let path = &self.project.sources()[source].path;
4776 let Some(proxy) = self.proxies.then(|| crate::proxy::cached(path)).flatten() else {
4777 return path.clone();
4778 };
4779 // Said out loud, once per span opened, because "the picture came off
4780 // the stand-in and the delivery did not" is a claim somebody has to be
4781 // able to check: `export` prints the file *it* reads by the same rule.
4782 eprintln!("picture: proxy {}", proxy.display());
4783 proxy
4784 }
4785
4786 /// Whether the picture comes off the stand-ins ([`Self::set_proxies`]).
4787 pub fn proxies(&self) -> bool {
4788 self.proxies
4789 }
4790
4791 /// Cut on the stand-ins, or on the films themselves. Reseeks, so the very
4792 /// next picture comes from the other file -- which is what makes this a
4793 /// switch a person can flip while watching.
4794 ///
4795 /// Says nothing about *which* films have one: a source with no stand-in
4796 /// keeps playing its own pictures either way, and one made while this is on
4797 /// is picked up at the next seek.
4798 ///
4799 /// One undo step ([`Project::push_settings_step`]), and the seek below is
4800 /// what makes the undo of it land on the picture: it reopens the span
4801 /// through [`picture_path`](Self::picture_path), which reads this switch.
4802 pub fn set_proxies(&mut self, on: bool) {
4803 if self.proxies == on {
4804 return;
4805 }
4806 let from = self.settings_value();
4807 self.proxies = on;
4808 self.step_settings(from);
4809 let now = self.now();
4810 self.seek(now);
4811 }
4812
4813 /// Which encoder an export of this project would open its picture on
4814 /// ([`crate::export::EncoderSeat`]). What a front-end puts into the
4815 /// [`ExportSettings`](crate::export::ExportSettings) it starts an export
4816 /// with -- and what the export card shows -- so the pick, the prediction
4817 /// and the file are one answer.
4818 pub fn encoder_seat(&self) -> crate::export::EncoderSeat {
4819 self.encoder_seat
4820 }
4821
4822 /// Gives a loaded project the window's seat when it carries none of its own: nobody
4823 /// picked it, so it is no undo step. Its own copy of the settings is kept in step with
4824 /// the session, as [`Self::set_encoder_seat`] keeps it, and nothing else moves.
4825 pub fn default_encoder_seat(&mut self, seat: crate::export::EncoderSeat) {
4826 if self.encoder_seat == seat {
4827 return;
4828 }
4829 self.encoder_seat = seat;
4830 self.project.mirror_settings(self.settings_value());
4831 }
4832
4833 /// Pick the seat. Nothing to reseek and nothing to re-probe here: this
4834 /// decides what an *export* opens, never what plays. One undo step, like
4835 /// every other pick on the project.
4836 pub fn set_encoder_seat(&mut self, seat: crate::export::EncoderSeat) {
4837 if self.encoder_seat == seat {
4838 return;
4839 }
4840 let from = self.settings_value();
4841 self.encoder_seat = seat;
4842 self.step_settings(from);
4843 }
4844
4845 /// The rate this project's mix was picked to run at
4846 /// ([`Self::set_sample_rate`]), or `None` for the rate the first audio
4847 /// source derives it to.
4848 pub fn sample_rate(&self) -> Option<u32> {
4849 self.sample_rate
4850 }
4851
4852 /// Pick the mix's own rate, overriding the derived one. Nothing to reseek
4853 /// here: it takes effect at the next audio rebuild (a seek, an edit, a
4854 /// reopen), not on the device already playing. One undo step, like every
4855 /// other pick on the project.
4856 pub fn set_sample_rate(&mut self, rate: Option<u32>) {
4857 if self.sample_rate == rate {
4858 return;
4859 }
4860 let from = self.settings_value();
4861 self.sample_rate = rate;
4862 self.step_settings(from);
4863 }
4864
4865 /// Whether an imported film that wants a stand-in gets one made for it
4866 /// there and then ([`Self::set_auto_proxies`]).
4867 pub fn auto_proxies(&self) -> bool {
4868 self.auto_proxies
4869 }
4870
4871 /// Make the stand-ins on import, or make none until asked. Nothing to
4872 /// reseek: this decides what is *started*, never what is decoded -- a proxy
4873 /// already in the cache is still cut on while [`Self::proxies`] is on.
4874 ///
4875 /// One undo step, like every other switch on the project.
4876 pub fn set_auto_proxies(&mut self, on: bool) {
4877 if self.auto_proxies == on {
4878 return;
4879 }
4880 let from = self.settings_value();
4881 self.auto_proxies = on;
4882 self.step_settings(from);
4883 }
4884
4885 /// Which source `path` is, canonicalising only if it has to: a source's own
4886 /// path is canonical ([`Source::new`]), so a caller handing one back from
4887 /// [`sources`](Self::sources) -- which is every library row -- hits on the
4888 /// first walk and never pays for the `canonicalize` syscall the second one
4889 /// makes. One rule, so a path that names a length names a rate too.
4890 fn source_of(&self, path: &Path) -> Option<usize> {
4891 let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted);
4892 at(path).or_else(|| at(&Source::new(path, 0).path))
4893 }
4894
4895 /// How long the whole of `path` is, in timeline frames: the length noted
4896 /// when it became a source, so a file sitting in the library with no clip
4897 /// anywhere still knows how much of itself there is to place. `0` for a
4898 /// file this session has never taken in.
4899 ///
4900 /// By path and not by stream, because a file is one length however many
4901 /// audio tracks it carries -- the picture's frame count for an mp4, the
4902 /// playing time for a song.
4903 pub fn file_frames(&self, path: &Path) -> u32 {
4904 self.source_of(path).map_or(0, |i| self.counts[i])
4905 }
4906
4907 /// What rate the file at `path` was *shot* at, in frames per second -- which
4908 /// is the timeline's own rate for every source that shares it, and is not
4909 /// for one placed at another ([`Rate`]). By path like
4910 /// [`file_frames`](Self::file_frames), and the timeline's rate for a file
4911 /// this session has never taken in (and for a still and a song, which were
4912 /// shot at no rate at all).
4913 ///
4914 /// What a library row names the file with: the timeline's rate there would
4915 /// be a lie about a 23.976 fps file the moment one can join.
4916 pub fn file_fps(&self, path: &Path) -> f64 {
4917 self.file_rate(path).as_f64() * self.meta.frame_rate
4918 }
4919
4920 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
4921 /// on and its index there, by the same topmost-lane-wins rule the decoder
4922 /// follows. `None` over a gap and past the end. What a card that grades
4923 /// "this clip" opens on when nothing has been clicked.
4924 pub fn video_clip_at(&self, timeline_secs: f64) -> Option<(Lane, usize)> {
4925 self.project
4926 .composite_clip_at(secs_to_frame(timeline_secs, self.meta.frame_rate))
4927 }
4928
4929 /// Which clip of `lane` sits at `timeline_secs`, by the same rule
4930 /// [`video_clip_at`](Self::video_clip_at) picks the picture's with -- per
4931 /// lane, so a keyboard walking the lanes for something to select asks the
4932 /// engine rather than re-deriving where a clip ends.
4933 pub fn lane_clip_at(&self, lane: Lane, timeline_secs: f64) -> Option<usize> {
4934 self.project
4935 .lane_clip_at(lane, secs_to_frame(timeline_secs, self.meta.frame_rate))
4936 }
4937
4938 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
4939 /// as it was shot -- what a colour card reads when it opens.
4940 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
4941 self.project.color_of(lane, idx)
4942 }
4943
4944 /// Grades that clip, or takes the grade off with `None`. One undo step like
4945 /// every other edit, and it reseeks like one too -- which is what puts the
4946 /// new grade on the frame that is already on screen, paused or playing,
4947 /// without the caller having to nudge the playhead itself. `false` for an
4948 /// index that is not there and for a value that is not finite.
4949 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
4950 self.edit(Dirty::Picture, |p| p.set_color(lane, idx, params))
4951 }
4952
4953 /// The same grade and the same reseek without the undo step
4954 /// ([`Project::set_color_live`]): what the samples inside one slider drag go
4955 /// through, so the frame regrades under the hand and the whole gesture is
4956 /// still a single `z`.
4957 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
4958 self.edit(Dirty::Picture, |p| p.set_color_live(lane, idx, params))
4959 }
4960
4961 /// [`Project::lut_problems`]: the `.cube` files clips name that cannot be used, and why.
4962 pub fn lut_problems(&self) -> Vec<(PathBuf, String)> {
4963 self.project.lut_problems()
4964 }
4965
4966 /// [`Project::luts`]: every `.cube` file a clip's grade names.
4967 pub fn luts(&self) -> Vec<crate::cube::LutRef> {
4968 self.project.luts()
4969 }
4970
4971 /// [`Project::relink_lut`], with the reseek every picture edit makes.
4972 pub fn relink_lut(&mut self, from: &std::path::Path, to: &std::path::Path) -> usize {
4973 let mut n = 0;
4974 self.edit(Dirty::Picture, |p| {
4975 n = p.relink_lut(from, to);
4976 n > 0
4977 });
4978 n
4979 }
4980
4981 /// Where the clip at `idx` of `lane` is placed -- [`color_of`](Self::color_of)'s
4982 /// twin for geometry instead of grade.
4983 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
4984 self.project.transform_of(lane, idx)
4985 }
4986
4987 /// Moves/scales/rotates/crops that clip, or takes the placement off with
4988 /// `None` -- [`set_color`](Self::set_color)'s twin, one undo step and one
4989 /// reseek.
4990 pub fn set_transform(
4991 &mut self,
4992 lane: Lane,
4993 idx: usize,
4994 params: Option<TransformParams>,
4995 ) -> bool {
4996 self.edit(Dirty::Picture, |p| p.set_transform(lane, idx, params))
4997 }
4998
4999 /// The placement animation of the clip at `idx` of `lane`, in source order
5000 /// ([`Project::transform_keys_of`]).
5001 pub fn transform_keys_of(&self, lane: Lane, idx: usize) -> &[crate::transform::TransformKey] {
5002 self.project.transform_keys_of(lane, idx)
5003 }
5004
5005 /// Replaces the clip's placement animation, or clears it with an empty list
5006 /// ([`Project::set_transform_keys`]). One undo step and one reseek.
5007 pub fn set_transform_keys(
5008 &mut self,
5009 lane: Lane,
5010 idx: usize,
5011 keys: Vec<crate::transform::TransformKey>,
5012 ) -> bool {
5013 self.edit(Dirty::Picture, |p| p.set_transform_keys(lane, idx, keys))
5014 }
5015
5016 /// The opacity animation of the clip at `idx` of `lane`, in source order
5017 /// ([`Project::opacity_keys_of`]).
5018 pub fn opacity_keys_of(&self, lane: Lane, idx: usize) -> &[crate::transform::OpacityKey] {
5019 self.project.opacity_keys_of(lane, idx)
5020 }
5021
5022 /// Replaces the clip's opacity animation, or clears it with an empty list
5023 /// ([`Project::set_opacity_keys`]). One undo step and one reseek.
5024 pub fn set_opacity_keys(
5025 &mut self,
5026 lane: Lane,
5027 idx: usize,
5028 keys: Vec<crate::transform::OpacityKey>,
5029 ) -> bool {
5030 self.edit(Dirty::Picture, |p| p.set_opacity_keys(lane, idx, keys))
5031 }
5032
5033 /// The colour animation of the clip at `idx` of `lane`, in source order
5034 /// ([`Project::color_keys_of`]).
5035 pub fn color_keys_of(&self, lane: Lane, idx: usize) -> &[crate::color::ColorKey] {
5036 self.project.color_keys_of(lane, idx)
5037 }
5038
5039 /// Replaces the clip's colour animation, or clears it with an empty list
5040 /// ([`Project::set_color_keys`]). One undo step and one reseek.
5041 pub fn set_color_keys(
5042 &mut self,
5043 lane: Lane,
5044 idx: usize,
5045 keys: Vec<crate::color::ColorKey>,
5046 ) -> bool {
5047 self.edit(Dirty::Picture, |p| p.set_color_keys(lane, idx, keys))
5048 }
5049
5050 /// The effects stack of the clip at `idx` of `lane` ([`Project::effects_of`]).
5051 pub fn effects_of(&self, lane: Lane, idx: usize) -> &[crate::effects::Effect] {
5052 self.project.effects_of(lane, idx)
5053 }
5054
5055 /// The keys of the effect at stack position `slot` ([`Project::effect_keys_of`]).
5056 pub fn effect_keys_of(&self, lane: Lane, idx: usize, slot: usize) -> &[crate::effects::EffectKey] {
5057 self.project.effect_keys_of(lane, idx, slot)
5058 }
5059
5060 /// Replaces the keys of the effect at stack position `slot`, or clears them with an
5061 /// empty list ([`Project::set_effect_keys`]). One undo step and one reseek.
5062 pub fn set_effect_keys(&mut self, lane: Lane, idx: usize, slot: usize, keys: Vec<crate::effects::EffectKey>) -> bool {
5063 self.edit(Dirty::Picture, |p| p.set_effect_keys(lane, idx, slot, keys))
5064 }
5065
5066 /// Replaces the clip's effects stack ([`Project::set_effects`]). One undo
5067 /// step and one reseek.
5068 pub fn set_effects(&mut self, lane: Lane, idx: usize, effects: Vec<crate::effects::Effect>) -> bool {
5069 self.edit(Dirty::Picture, |p| p.set_effects(lane, idx, effects))
5070 }
5071
5072 /// [`Project::key_source_frame`].
5073 pub fn key_source_frame(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<u32> {
5074 self.project.key_source_frame(lane, idx, timeline_frame)
5075 }
5076
5077 /// [`Project::is_keyed`].
5078 pub fn is_keyed(&self, lane: Lane, idx: usize, kind: crate::project::KeyKind) -> bool {
5079 self.project.is_keyed(lane, idx, kind)
5080 }
5081
5082 /// [`Project::key_ease_at`].
5083 pub fn key_ease_at(
5084 &self,
5085 lane: Lane,
5086 idx: usize,
5087 kind: crate::project::KeyKind,
5088 timeline_frame: u32,
5089 ) -> Option<crate::transform::KeyEase> {
5090 self.project.key_ease_at(lane, idx, kind, timeline_frame)
5091 }
5092
5093 /// The stopwatch ([`Project::toggle_key`]). One undo step and one reseek.
5094 pub fn toggle_key(
5095 &mut self,
5096 lane: Lane,
5097 idx: usize,
5098 kind: crate::project::KeyKind,
5099 timeline_frame: u32,
5100 ) -> Option<bool> {
5101 let mut out = None;
5102 self.edit(Dirty::Picture, |p| {
5103 out = p.toggle_key(lane, idx, kind, timeline_frame);
5104 out.is_some()
5105 });
5106 out
5107 }
5108
5109 /// [`Project::set_key_ease_at`]. One undo step and one reseek.
5110 pub fn set_key_ease_at(
5111 &mut self,
5112 lane: Lane,
5113 idx: usize,
5114 kind: crate::project::KeyKind,
5115 timeline_frame: u32,
5116 ease: crate::transform::KeyEase,
5117 ) -> bool {
5118 self.edit(Dirty::Picture, |p| p.set_key_ease_at(lane, idx, kind, timeline_frame, ease))
5119 }
5120
5121 /// [`Project::put_transform_key_at`]; `snapshot` false is the live write of a drag.
5122 pub fn put_transform_key_at(
5123 &mut self,
5124 lane: Lane,
5125 idx: usize,
5126 timeline_frame: u32,
5127 params: TransformParams,
5128 snapshot: bool,
5129 ) -> bool {
5130 self.edit(Dirty::Picture, |p| p.put_transform_key_at(lane, idx, timeline_frame, params, snapshot))
5131 }
5132
5133 /// [`Project::put_opacity_key_at`]; `snapshot` false is the live write of a drag.
5134 pub fn put_opacity_key_at(
5135 &mut self,
5136 lane: Lane,
5137 idx: usize,
5138 timeline_frame: u32,
5139 opacity: f32,
5140 snapshot: bool,
5141 ) -> bool {
5142 self.edit(Dirty::Picture, |p| p.put_opacity_key_at(lane, idx, timeline_frame, opacity, snapshot))
5143 }
5144
5145 /// [`Project::put_color_key_at`]; `snapshot` false is the live write of a drag.
5146 pub fn put_color_key_at(
5147 &mut self,
5148 lane: Lane,
5149 idx: usize,
5150 timeline_frame: u32,
5151 params: ColorParams,
5152 snapshot: bool,
5153 ) -> bool {
5154 self.edit(Dirty::Picture, |p| p.put_color_key_at(lane, idx, timeline_frame, params, snapshot))
5155 }
5156
5157 /// The placement the clip shows at timeline `timeline_frame`, keys evaluated
5158 /// ([`Project::transform_at`]).
5159 pub fn transform_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<TransformParams> {
5160 self.project.transform_at(lane, idx, timeline_frame)
5161 }
5162
5163 /// The grade the clip shows at `timeline_frame`, keys evaluated ([`Project::color_at`]).
5164 pub fn color_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<ColorParams> {
5165 self.project.color_at(lane, idx, timeline_frame)
5166 }
5167
5168 /// The opacity the clip shows at `timeline_frame`, keys evaluated, fades not
5169 /// counted ([`Project::opacity_at`]).
5170 pub fn opacity_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> f32 {
5171 self.project.opacity_at(lane, idx, timeline_frame)
5172 }
5173
5174 /// The same placement and the same reseek without the undo step
5175 /// ([`Project::set_transform_live`]) -- [`set_color_live`](Self::set_color_live)'s
5176 /// twin for a slider drag.
5177 pub fn set_transform_live(
5178 &mut self,
5179 lane: Lane,
5180 idx: usize,
5181 params: Option<TransformParams>,
5182 ) -> bool {
5183 self.edit(Dirty::Picture, |p| p.set_transform_live(lane, idx, params))
5184 }
5185
5186 /// The project's resolution: what every clip is composed onto, what the
5187 /// window is sized to and what an export writes -- *not* any one file's.
5188 /// It starts as source 0's picture, which is what a project meant before it
5189 /// could have a resolution of its own.
5190 pub fn resolution(&self) -> (u32, u32) {
5191 (self.meta.width, self.meta.height)
5192 }
5193
5194 /// Source 0's own picture size -- what the project resolution started as,
5195 /// and the one size a caller offering a list of them must not leave out.
5196 pub fn native_resolution(&self) -> (u32, u32) {
5197 self.native
5198 }
5199
5200 /// Sets it. Rebuilds the **picture** where the playhead is, so the frame on
5201 /// screen is recomposed at the new size at once, paused or playing -- and
5202 /// the sound is not touched at all: the size of the canvas is not something
5203 /// a sample can carry, so resizing a 4K film mid-play costs neither a hole
5204 /// in the audio nor an offset against it ([`Dirty`]). `false` for a size
5205 /// that is not a picture -- zero either way, or past 8K, which is where the
5206 /// per-frame buffers stop being a sane thing to allocate from a keystroke.
5207 ///
5208 /// One undo step: the resolution is the project's own, so it rides in the
5209 /// entry beside the lanes and a `z` takes the canvas back to the size it
5210 /// was ([`Project::push_settings_step`]).
5211 pub fn set_resolution(&mut self, width: u32, height: u32) -> bool {
5212 if !crate::is_resolution(width, height) {
5213 return false;
5214 }
5215 if (width, height) == (self.meta.width, self.meta.height) {
5216 return false;
5217 }
5218 let from = self.settings_value();
5219 self.meta.width = width;
5220 self.meta.height = height;
5221 self.step_settings(from);
5222 self.invalidate(Dirty::Picture);
5223 true
5224 }
5225
5226 /// Which HDR-to-SDR rendition this project is watched and exported in
5227 /// ([`crate::tonemap::Preset`]) -- the reference one until somebody picks
5228 /// another, and a setting on the project rather than on any clip.
5229 pub fn tone(&self) -> crate::tonemap::Preset {
5230 self.project.tone()
5231 }
5232
5233 /// The project's notes ([`Project::notes`]).
5234 pub fn notes(&self) -> &str {
5235 self.project.notes()
5236 }
5237
5238 /// Sets the project's notes ([`Project::set_notes`]): one undo step, `false` for the text
5239 /// already in force.
5240 pub fn set_notes(&mut self, notes: &str) -> bool {
5241 self.project.set_notes(notes)
5242 }
5243
5244 /// How long a still is placed for, in seconds ([`Project::still_secs`]).
5245 pub fn still_secs(&self) -> f64 {
5246 self.project.still_secs()
5247 }
5248
5249 /// Sets the still length ([`Project::set_still_secs`]): one undo step, `false` for the length
5250 /// already in force. Stills placed after this take it; clips already on the timeline keep theirs.
5251 pub fn set_still_secs(&mut self, secs: f64) -> bool {
5252 self.project.set_still_secs(secs)
5253 }
5254
5255 /// The speech model the project names, or `None` for the one picked ([`Project::speech_model`]).
5256 pub fn speech_model(&self) -> Option<&str> {
5257 self.project.speech_model()
5258 }
5259
5260 /// Sets it ([`Project::set_speech_model`]).
5261 pub fn set_speech_model(&mut self, model: Option<&str>) -> bool {
5262 self.project.set_speech_model(model)
5263 }
5264
5265 /// The device the speech model runs on ([`Project::speech_device`]).
5266 pub fn speech_device(&self) -> crate::speech::DeviceChoice {
5267 self.project.speech_device()
5268 }
5269
5270 /// Sets it ([`Project::set_speech_device`]).
5271 pub fn set_speech_device(&mut self, device: crate::speech::DeviceChoice) -> bool {
5272 self.project.set_speech_device(device)
5273 }
5274
5275 /// What source 0's own file declared about how bright it gets
5276 /// ([`ContentLight`]): a property of the film, read once at open, and
5277 /// entirely absent (every field `None`) for an SDR file, a song or a
5278 /// still. Read-only -- the number a file carries, never a project setting
5279 /// a user can override, since nothing in [`Project`] holds one to persist.
5280 pub fn content_light(&self) -> ContentLight {
5281 self.content_light
5282 }
5283
5284 /// Picks one. Rebuilds the **picture** where the playhead is, exactly as
5285 /// [`set_resolution`](Self::set_resolution) does -- the frame on screen is
5286 /// remapped at once, paused or playing, and the sound is not touched: a
5287 /// rendition is not something a sample can carry. `false` for the rendition
5288 /// already in force.
5289 ///
5290 /// An SDR project is unmoved by this by construction: no clip of it builds a
5291 /// tone map at all ([`crate::tonemap`]), so the reseek recomposes the very
5292 /// same bytes.
5293 ///
5294 /// corner-cut: not an undo step, for the reason the resolution is not
5295 /// ([`Project::set_tone`]).
5296 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
5297 if !self.project.set_tone(preset) {
5298 return false;
5299 }
5300 self.invalidate(Dirty::Picture);
5301 true
5302 }
5303
5304 /// The scaffolding source's own frame rate -- what the project rate started
5305 /// as, and the one rate a caller offering a list of them must not leave out
5306 /// ([`native_resolution`](Self::native_resolution)'s reason).
5307 pub fn native_frame_rate(&self) -> f64 {
5308 self.native_fps
5309 }
5310
5311 /// Cuts this timeline at `fps` from here on: every clip is *conformed* to
5312 /// the new rate ([`Project::retime`]), every source is read through a
5313 /// [`Rate`] against it, and an export written from this session comes out at
5314 /// it. The edit survives as the same seconds of the same footage on a finer
5315 /// or coarser grid -- a 30 fps take on a timeline moved to 24 keeps its
5316 /// length and its sync, it is simply counted in 24ths now.
5317 ///
5318 /// Reseeks like [`set_resolution`](Self::set_resolution), so the picture and
5319 /// the sound under the playhead are already the new rate's when this
5320 /// returns. `false` -- changing nothing -- for a rate that is not a rate, for
5321 /// the one already in force, and for one no timescale can name
5322 /// ([`crate::mux::frame_timing`], the same wall a file of an unnameable rate
5323 /// is refused at).
5324 ///
5325 /// One undo step, and the entry it takes is the whole of the change: the
5326 /// lanes as they were in the *old* rate's numbering, with that rate beside
5327 /// them, so a `z` restores the two together ([`Project::retime`]). The
5328 /// step is taken before the retime rather than after, since this is the one
5329 /// settings door that moves the lanes the step holds. Picking the old rate
5330 /// back is still within a frame of where it started rather than on it: the
5331 /// *lanes* come home exactly out of the entry, and the per-source lengths
5332 /// are the half that goes through the map twice
5333 /// ([`PlaybackSession::adopt_settings`]).
5334 pub fn set_frame_rate(&mut self, fps: f64) -> bool {
5335 if !fps.is_finite() || fps <= 0.0 || fps == self.meta.frame_rate || self.project.rate_locked() {
5336 return false;
5337 }
5338 // Old timeline frames per new one, exactly -- the one map every frame
5339 // number on every lane goes through. Built before anything is touched,
5340 // since a rate no timescale can name is a refusal and not a half-retimed
5341 // project.
5342 let Ok(k) = Rate::from_fps(self.meta.frame_rate, fps) else {
5343 return false;
5344 };
5345 let from = self.settings_value();
5346 self.project.push_settings_step(from.clone(), from);
5347 // Lengths first: the retime holds every clip inside its source's *new*
5348 // length, so a clip that played to the last frame of its file still
5349 // does rather than naming one past the end.
5350 for count in &mut self.counts {
5351 *count = k.timeline_nearest(*count).max(1);
5352 }
5353 self.project.retime(k, &self.counts);
5354 // A file's own rate has not changed; what it is *against* has.
5355 for rate in &mut self.rates {
5356 *rate = rate.then(k);
5357 }
5358 self.meta.frame_rate = fps;
5359 self.meta.frame_count = k.timeline_nearest(self.meta.frame_count).max(1);
5360 // The copy the project keeps, now that the change has landed: what the
5361 // next lane edit's entry carries.
5362 self.project.mirror_settings(self.settings_value());
5363 let now = self.now();
5364 self.seek(now);
5365 true
5366 }
5367
5368 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
5369 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
5370 self.project.fit_of(lane, idx)
5371 }
5372
5373 /// Sets that clip's fit policy. One undo step and a reseek, exactly like a
5374 /// grade: the picture on screen is recomposed through the new policy without
5375 /// the caller nudging the playhead. `false` for an index that is not there.
5376 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
5377 self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit))
5378 }
5379
5380 /// [`Project::set_stabilise`]. Reseeks like a grade. The analysis it needs is
5381 /// started in the background ([`Self::stabilise_start`]); until it is done the
5382 /// clip plays as it is.
5383 pub fn set_stabilise(&mut self, lane: Lane, idx: usize, st: Option<crate::stabilise::Stabilise>) -> bool {
5384 let done = self.edit(Dirty::Picture, |p| p.set_stabilise(lane, idx, st));
5385 if done && st.is_some() {
5386 self.stabilise_start(lane, idx);
5387 }
5388 done
5389 }
5390
5391 /// The generator of kind `name` ([`crate::generate::KINDS`]) at its defaults, drawn for this
5392 /// timeline's canvas and rate.
5393 pub fn generator_named(&self, name: &str) -> Option<crate::generate::Gen> {
5394 crate::generate::Gen::named(name, self.meta.width, self.meta.height, self.meta.frame_rate)
5395 }
5396
5397 /// Places a generated clip ([`crate::generate`]) `secs` long on the video lane `onto` (`V1`
5398 /// when none), at `timeline_secs`, like a still. A countdown with no length asked for runs
5399 /// its own count. Overwrites what the stretch lands on, as a still does. `false` when the
5400 /// lane or the place is refused.
5401 pub fn place_generated(&mut self, spec: crate::generate::Gen, timeline_secs: f64, secs: Option<f64>, onto: Option<Lane>) -> crate::Result<bool> {
5402 let fps = self.meta.frame_rate;
5403 let source = self.generator_source(spec);
5404 let secs = secs.unwrap_or(match spec.kind {
5405 crate::generate::Kind::Countdown { from, .. } => f64::from(from),
5406 _ => self.project.still_secs(),
5407 });
5408 let wall = self.counts[source];
5409 let out = ((secs * fps).round() as u32).clamp(1, wall.max(1));
5410 let lane = match onto {
5411 Some(lane) if lane.kind == LaneKind::Video => lane,
5412 Some(_) => return Err("a generated clip goes on a video lane".into()),
5413 None => Lane::V1,
5414 };
5415 if self.project.lane(lane).is_empty() && !self.project.lanes().contains(&lane) {
5416 return Err(format!("{lane:?} is not a lane of this timeline").into());
5417 }
5418 Ok(self.place_at(lane, timeline_secs, Clip::source_range(source, 0, out)))
5419 }
5420
5421 /// Places a test tone ([`crate::generate::Tone`]) `secs` long on the audio lane `onto` (`A1`
5422 /// when none), at `timeline_secs`, as a sound file's stream is placed. The tone's file is made
5423 /// in `dir` the first time (the project's folder for a saved project, else the data folder).
5424 /// `false` when the place is refused.
5425 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> {
5426 let path = tone.write(dir, secs)?;
5427 let lane = match onto {
5428 Some(lane) if lane.kind == LaneKind::Audio => lane,
5429 Some(_) => return Err("a tone goes on an audio lane".into()),
5430 None => Lane::A1,
5431 };
5432 // A tone is a standalone audio file: taken into the library the first time it is
5433 // placed (as a song is), so the placement below finds it.
5434 if self.file_frames(&path) == 0 {
5435 self.import(&path)?;
5436 }
5437 self.place_stream_at(timeline_secs, &path, 0, Some(lane))
5438 }
5439
5440 /// The source index of `spec`, taken into the library the first time it is used.
5441 fn generator_source(&mut self, spec: crate::generate::Gen) -> usize {
5442 let source = self.project.import(spec.path(), 0);
5443 self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME);
5444 source
5445 }
5446
5447 /// Changes the generator the clip at `idx` of `lane` is, keeping its place and length.
5448 /// One undo step; `false` for a clip that is not there or no change.
5449 pub fn set_generator(&mut self, lane: Lane, idx: usize, spec: crate::generate::Gen) -> bool {
5450 let source = self.generator_source(spec);
5451 self.edit(Dirty::Picture, |p| p.set_clip_source(lane, idx, source))
5452 }
5453
5454 /// The generator the clip at `idx` of `lane` is, `None` for a clip made from a file.
5455 pub fn generator_of(&self, lane: Lane, idx: usize) -> Option<crate::generate::Gen> {
5456 let src = self.project.sources().get(self.project.lane(lane).get(idx)?.source)?;
5457 crate::generate::Gen::parse(&src.path)
5458 }
5459
5460 /// [`Project::set_label`].
5461 pub fn set_label(&mut self, lane: Lane, idx: usize, label: u8) -> bool {
5462 self.project.set_label(lane, idx, label)
5463 }
5464
5465 /// [`Project::set_enabled`]: a switched-off clip is skipped by picture and sound.
5466 pub fn set_enabled(&mut self, lane: Lane, idx: usize, enabled: bool) -> bool {
5467 self.edit(Dirty::Both, |p| p.set_enabled(lane, idx, enabled))
5468 }
5469
5470 /// [`Project::mark_of`].
5471 pub fn mark_of(&self, lane: Lane, idx: usize) -> crate::project::ClipMark {
5472 self.project.mark_of(lane, idx)
5473 }
5474
5475 /// [`Project::set_deinterlace`]. Stored only; the render reads it once the engine acts on it.
5476 pub fn set_deinterlace(&mut self, lane: Lane, idx: usize, mode: crate::project::Deinterlace) -> bool {
5477 self.project.set_deinterlace(lane, idx, mode)
5478 }
5479
5480 /// [`Project::deinterlace_of`].
5481 pub fn deinterlace_of(&self, lane: Lane, idx: usize) -> crate::project::Deinterlace {
5482 self.project.deinterlace_of(lane, idx)
5483 }
5484
5485 /// [`Project::stabilise_of`].
5486 pub fn stabilise_of(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Stabilise> {
5487 self.project.stabilise_of(lane, idx)
5488 }
5489
5490 /// The source and file-frame range the clip at `idx` of `lane` is analysed
5491 /// over, `None` for no clip or one that is not footage (a still, a song).
5492 pub fn stabilise_range(&self, lane: Lane, idx: usize) -> Option<(std::path::PathBuf, u32, u32)> {
5493 let c = self.project.lane(lane).get(idx)?;
5494 let path = &self.project.sources().get(c.source)?.path;
5495 if crate::is_image(path) || crate::is_audio(path) {
5496 return None;
5497 }
5498 let (lo, hi) = crate::stabilise::clip_range(path, c, self.meta.frame_rate);
5499 Some((path.clone(), lo, hi))
5500 }
5501
5502 /// Where the clip's stabilisation analysis stands ([`crate::stabilise::status`]).
5503 pub fn stabilise_status(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Status> {
5504 let (path, lo, hi) = self.stabilise_range(lane, idx)?;
5505 Some(crate::stabilise::status(&path, lo, hi))
5506 }
5507
5508 /// Starts the clip's stabilisation analysis in the background unless it is
5509 /// cached or running ([`crate::stabilise::start`]).
5510 pub fn stabilise_start(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Status> {
5511 let (path, lo, hi) = self.stabilise_range(lane, idx)?;
5512 Some(crate::stabilise::start(&path, lo, hi))
5513 }
5514
5515 /// Stops the clip's running analysis. `false` when none runs.
5516 pub fn stabilise_cancel(&self, lane: Lane, idx: usize) -> bool {
5517 self.stabilise_range(lane, idx).is_some_and(|(path, lo, hi)| crate::stabilise::cancel(&path, lo, hi))
5518 }
5519
5520 /// What auto reframe needs of the clip at `idx` of `lane`: its file range and the
5521 /// geometry its keys are made for ([`crate::reframe`]). `None` for no clip, a
5522 /// still or a song.
5523 pub fn reframe_job(&self, lane: Lane, idx: usize) -> Option<crate::reframe::ReframeJob> {
5524 let (path, lo, hi) = self.stabilise_range(lane, idx)?;
5525 let c = self.project.lane(lane).get(idx)?;
5526 let shown = crate::demux::Demuxer::open(&path).ok()?.0;
5527 let target = crate::reframe::Target {
5528 src_w: shown.width,
5529 src_h: shown.height,
5530 canvas_w: self.meta.width,
5531 canvas_h: self.meta.height,
5532 base: self.project.transform_of(lane, idx).copied().unwrap_or_default(),
5533 in_frame: c.in_frame,
5534 out_frame: c.out_frame,
5535 };
5536 Some(crate::reframe::ReframeJob { path, lo, hi, target })
5537 }
5538
5539 /// Writes reframe `keys` on the clip, and puts it on [`FitPolicy::Fit`] -- the
5540 /// placement they are made for. One undo step; `false` when the keys are refused.
5541 pub fn apply_reframe(&mut self, lane: Lane, idx: usize, keys: Vec<crate::transform::TransformKey>) -> bool {
5542 self.begin_batch();
5543 self.set_fit(lane, idx, FitPolicy::Fit);
5544 let done = self.set_transform_keys(lane, idx, keys);
5545 self.end_batch();
5546 done
5547 }
5548
5549 /// Redraws the picture once an analysis finished, so a stabilised clip shows
5550 /// its correction without an edit.
5551 pub fn stabilise_refresh(&mut self) {
5552 self.invalidate(Dirty::Picture);
5553 }
5554
5555 /// Starts following the rect or ellipse mask at stack position `slot` of the clip at
5556 /// `idx` of `lane` ([`crate::track`]) from source frame `from` to `to`, either order.
5557 /// The mask's centre at `from` is where the feature is; [`Self::track_mask_apply`]
5558 /// writes the path back once the track has finished.
5559 pub fn track_mask_start(&self, lane: Lane, idx: usize, slot: usize, from: u32, to: u32) -> Result<TrackJob, String> {
5560 use crate::effects::EffectKind;
5561 let c = self.project.lane(lane).get(idx).ok_or("there is no clip there")?;
5562 let e = c.effects.get(slot).ok_or("there is no effect in that stack position")?;
5563 if !matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask) {
5564 return Err("only a rect or ellipse mask can be tracked".into());
5565 }
5566 let (path, lo, hi) = self.stabilise_range(lane, idx).ok_or("a still or a song has no picture to track")?;
5567 let (from, to) = (from.clamp(lo, hi - 1), to.clamp(lo, hi - 1));
5568 if from == to {
5569 return Err("a track needs two frames: from and to are the same frame".into());
5570 }
5571 let forward = to > from;
5572 let range = if forward { (from, to + 1) } else { (to, from + 1) };
5573 let at = e.posed(f64::from(from));
5574 let (x, y) = (at.values[0], at.values[1]);
5575 let region = crate::track::Region { x, y, w: at.values[2], h: at.values[3] };
5576 // The placement the renderer gives the clip, so the track's points land on the canvas
5577 // where the mask is drawn: the base transform and its keys, on this canvas.
5578 let pose = crate::track::Pose {
5579 base: self.transform_of(lane, idx).copied().unwrap_or_default(),
5580 keys: self.transform_keys_of(lane, idx).to_vec(),
5581 canvas: self.resolution(),
5582 fit: crate::scale::FitPolicy::default(),
5583 };
5584 let id = crate::track::start(&path, range, from, forward, region, pose);
5585 Ok(TrackJob { lane, idx, slot, id, from, anchor: (x, y) })
5586 }
5587
5588 /// Writes every finished track in `jobs` onto its mask ([`Self::track_mask_apply`]) and
5589 /// takes it out of `jobs`; running ones stay. Each landing is one undo step. Returns one
5590 /// entry per track that ended.
5591 pub fn track_settle(&mut self, jobs: &mut Vec<TrackJob>) -> Vec<TrackDone> {
5592 let mut done = Vec::new();
5593 let mut running = Vec::new();
5594 for job in std::mem::take(jobs) {
5595 let result = match crate::track::status(job.id) {
5596 crate::track::Status::Running(_) => {
5597 running.push(job);
5598 continue;
5599 }
5600 crate::track::Status::Gone => continue,
5601 crate::track::Status::Finished => match crate::track::take(job.id) {
5602 None => continue,
5603 Some(Err(e)) => Err(e),
5604 Some(Ok(t)) => self.track_mask_apply(&job, &t).map(|keys| {
5605 let frames = t.points.iter().map(|p| p.0);
5606 TrackOutcome {
5607 keys,
5608 from: frames.clone().min().unwrap_or(job.from),
5609 to: frames.max().unwrap_or(job.from),
5610 lost_at: t.lost_at,
5611 }
5612 }),
5613 },
5614 };
5615 done.push(TrackDone { lane: job.lane, idx: job.idx, slot: job.slot, result });
5616 }
5617 *jobs = running;
5618 done
5619 }
5620
5621 /// Writes a finished track onto its mask: the mask's centre moves by the feature's
5622 /// displacement from where it was at the start, and its size and soft edge keep the
5623 /// values they have at each frame. Keys inside the tracked frames are replaced and
5624 /// keys outside them stay. Returns how many keys were written. One undo step.
5625 pub fn track_mask_apply(&mut self, job: &TrackJob, track: &crate::track::Track) -> Result<usize, String> {
5626 use crate::effects::EffectKey;
5627 use crate::track::{KEY_TOLERANCE, simplify};
5628 use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS};
5629 let Some(&(_, x0, y0)) = track.points.first() else {
5630 return Err("the track has no points".into());
5631 };
5632 let mut pts: Vec<(u32, f32, f32)> = track
5633 .points
5634 .iter()
5635 .map(|&(f, x, y)| (f, job.anchor.0 + x - x0, job.anchor.1 + y - y0))
5636 .collect();
5637 pts.sort_by_key(|p| p.0);
5638 let (first, last) = (pts[0].0, pts[pts.len() - 1].0);
5639 let outside: Vec<EffectKey> =
5640 self.effect_keys_of(job.lane, job.idx, job.slot).iter().filter(|k| k.at < first || k.at > last).copied().collect();
5641 let room = MAX_TRANSFORM_KEYS.saturating_sub(outside.len()).max(2);
5642 let mut tolerance = KEY_TOLERANCE;
5643 let mut kept = simplify(&pts, tolerance);
5644 while kept.len() > room {
5645 tolerance *= 2.0;
5646 kept = simplify(&pts, tolerance);
5647 }
5648 let mut keys = {
5649 let e = self
5650 .project
5651 .lane(job.lane)
5652 .get(job.idx)
5653 .and_then(|c| c.effects.get(job.slot))
5654 .ok_or("the mask is gone")?;
5655 kept.iter()
5656 .map(|&i| {
5657 let (f, x, y) = pts[i];
5658 let mut values = e.posed(f64::from(f)).values;
5659 values[0] = x;
5660 values[1] = y;
5661 EffectKey { at: f, values, ease: KeyEase::Linear }
5662 })
5663 .collect::<Vec<_>>()
5664 };
5665 keys.extend(outside);
5666 keys.sort_by_key(|k| k.at);
5667 let count = keys.len();
5668 if !self.set_effect_keys(job.lane, job.idx, job.slot, keys) {
5669 return Err("the engine refused the keys (is the mask still there?)".into());
5670 }
5671 Ok(count)
5672 }
5673
5674 /// Waveform flags on a visualizer clip. Reseeks like a grade: the
5675 /// painter reads them on the next picture.
5676 pub fn set_visualizer(&mut self, lane: Lane, idx: usize, flags: u8) -> bool {
5677 self.edit(Dirty::Picture, |p| p.set_visualizer(lane, idx, flags))
5678 }
5679
5680 pub fn set_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
5681 self.edit(Dirty::Picture, |p| p.set_viz_paint(lane, idx, paint))
5682 }
5683
5684 /// The same look and the same repaint without the undo step
5685 /// ([`Project::set_viz_paint_live`]): what the samples inside one drag
5686 /// across the colour wheel go through, so the picture follows the hand and
5687 /// the whole gesture is still a single `z`.
5688 pub fn set_viz_paint_live(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
5689 self.edit(Dirty::Picture, |p| p.set_viz_paint_live(lane, idx, paint))
5690 }
5691
5692 /// Timeline frames of ramp-up from silence at the start of the clip at
5693 /// `idx` of `lane`. `0` for an index that is not there.
5694 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
5695 self.project.fade_in_of(lane, idx)
5696 }
5697
5698 /// The volume envelope of the clip at `idx` of `lane`
5699 /// ([`Project::gain_keys_of`]).
5700 pub fn gain_keys_of(&self, lane: Lane, idx: usize) -> &[GainKey] {
5701 self.project.gain_keys_of(lane, idx)
5702 }
5703
5704 /// Replaces the clip's whole volume envelope ([`Project::set_gain_keys`]).
5705 /// A sound-only edit: no reseek of the picture.
5706 pub fn set_gain_keys(&mut self, lane: Lane, idx: usize, keys: Vec<GainKey>) -> bool {
5707 self.edit(Dirty::Sound, |p| p.set_gain_keys(lane, idx, keys))
5708 }
5709
5710 /// Puts one point into the clip's volume envelope ([`Project::add_gain_key`]).
5711 pub fn add_gain_key(&mut self, lane: Lane, idx: usize, key: GainKey) -> bool {
5712 self.edit(Dirty::Sound, |p| p.add_gain_key(lane, idx, key))
5713 }
5714
5715 /// Takes the point at source frame `at` out of the clip's volume envelope
5716 /// ([`Project::remove_gain_key`]).
5717 pub fn remove_gain_key(&mut self, lane: Lane, idx: usize, at: u32) -> bool {
5718 self.edit(Dirty::Sound, |p| p.remove_gain_key(lane, idx, at))
5719 }
5720
5721 /// The effective envelope dB at a timeline frame, keys and clip gain but not
5722 /// the fades ([`Project::gain_db_at`]).
5723 pub fn gain_db_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<f32> {
5724 self.project.gain_db_at(lane, idx, timeline_frame)
5725 }
5726
5727 /// Sets that clip's fade-in, clamped to its own length. A sound-only
5728 /// edit, same as an equalizer or a fader: no reseek needed.
5729 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5730 self.edit(Dirty::Sound, |p| p.set_fade_in(lane, idx, frames))
5731 }
5732
5733 /// Timeline frames of ramp-down to silence at the end of the clip at
5734 /// `idx` of `lane`. `0` for an index that is not there.
5735 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
5736 self.project.fade_out_of(lane, idx)
5737 }
5738
5739 /// Sets that clip's fade-out. Same promises as [`Self::set_fade_in`].
5740 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5741 self.edit(Dirty::Sound, |p| p.set_fade_out(lane, idx, frames))
5742 }
5743
5744 /// Crossfades the audio clip at `idx` of `lane` into its neighbour, over
5745 /// `frames`. Same promises as [`Project::crossfade`].
5746 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5747 self.edit(Dirty::Sound, |p| p.crossfade(lane, idx, frames))
5748 }
5749
5750 /// Timeline frames of dissolve at the end of the clip at `idx` of `lane`,
5751 /// into its neighbour. `0` for an index that is not there.
5752 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
5753 self.project.transition_out_of(lane, idx)
5754 }
5755
5756 /// The kind of the transition that clip plays into its neighbour.
5757 pub fn transition_kind_of(&self, lane: Lane, idx: usize) -> crate::transitions::TransitionKind {
5758 self.project.transition_kind_of(lane, idx)
5759 }
5760
5761 /// Sets that clip's transition into its neighbour, kind and length in one
5762 /// undo step. A picture edit, like [`Self::set_transition_out`].
5763 pub fn set_transition(
5764 &mut self,
5765 lane: Lane,
5766 idx: usize,
5767 kind: crate::transitions::TransitionKind,
5768 frames: u32,
5769 ) -> bool {
5770 self.edit(Dirty::Picture, |p| p.set_transition(lane, idx, kind, frames))
5771 }
5772
5773 /// Sets that clip's dissolve into its neighbour, clamped to its own
5774 /// length. A picture edit -- same as a grade or fit policy.
5775 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5776 self.edit(Dirty::Picture, |p| p.set_transition_out(lane, idx, frames))
5777 }
5778
5779 /// The clip at `idx` -- what a caller copies. It is a pair of source frame
5780 /// numbers and nothing else, so a copy stays valid after the clip it came
5781 /// from is deleted. `None` past the end.
5782 pub fn clip_at(&self, idx: usize) -> Option<Clip> {
5783 self.project.clips().get(idx).cloned()
5784 }
5785
5786 /// Inserts `clip` at the playhead, splitting the clip under it. Like a
5787 /// delete this moves every following frame, so the session reseeks; past
5788 /// the end of the timeline the clip is appended. One undo step.
5789 pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool {
5790 // The clipboard's own rule, and only the clipboard's: a paste past the
5791 // end is an append, never a clip with black in front of it. The frame
5792 // itself is honoured in [`Project::paste`], because a *drop* names a
5793 // place on the bed and means it.
5794 let at =
5795 secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames());
5796 let clip = self.held_to_take(clip);
5797 self.edit(Dirty::Both, |p| p.paste(at, clip))
5798 }
5799
5800 /// [`paste_at`](Self::paste_at)'s general form: [`Project::paste_set`]'s
5801 /// door, clamped to the timeline's own end the same way -- a set let go
5802 /// past the last frame lands there rather than carrying black in front of
5803 /// it, exactly as a lone clip's paste does.
5804 pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool {
5805 let at =
5806 secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames());
5807 // Each item is held to its own lane's wall, as a lone placement is.
5808 let items: Vec<(Lane, Clip)> = items
5809 .iter()
5810 .map(|(lane, clip)| (*lane, self.held_to_lane(*lane, clip.clone())))
5811 .collect();
5812 self.edit(Dirty::Both, |p| p.paste_set(at, &items))
5813 }
5814
5815 /// Places the whole of `path` played on its audio `stream` at
5816 /// `timeline_secs`, the way [`paste_at`](Self::paste_at) places a copy --
5817 /// the door a library row goes through, and the only way a stream other
5818 /// than the one an import brought in reaches the timeline. The `(file,
5819 /// stream)` pair becomes a source if it is not one already.
5820 ///
5821 /// Refused, changing nothing, unless that stream can join *this* timeline:
5822 /// same audio parameters as the first source, in the same words
5823 /// [`import`](Self::import) refuses a file with. One output device and one
5824 /// copied AAC track mean one *layout* for the whole timeline, so a mono
5825 /// track cannot join a stereo one. Its sample rate may be its own: the
5826 /// segment's resampler conforms it at the decoder's door.
5827 /// A front-end greys such a row out; this is the backstop that keeps a
5828 /// stale one from making the whole timeline silent.
5829 ///
5830 /// Which lane it lands on is decided here, from the file and from `onto` --
5831 /// the lane it was let go over, if it was let go over one at all: a file
5832 /// with a picture asked for by no lane, or for one of the first pair, is
5833 /// pasted across `V1` and `A1` as a grouped take; asked for by a further
5834 /// *video* lane it is *placed* there with its sound on that lane's own audio
5835 /// row (`V2` -> `A2`, added if it is not there yet), overwriting what the two
5836 /// halves land on and rippling nothing; asked for by a further audio lane it
5837 /// is that file's sound alone. A file with no picture ([`crate::is_audio`]) is placed
5838 /// on the audio lane it was asked for, or on `A1`, and never on a video
5839 /// lane. A still image ([`crate::is_image`]) is its mirror: the video lane
5840 /// it was asked for or `V1`, never an audio one, and it goes down
5841 /// the project's still length ([`Project::still_secs`]) long rather than at the length it is
5842 /// *allowed* to be trimmed out to. A caller never has to ask.
5843 pub fn place_stream_at(
5844 &mut self,
5845 timeline_secs: f64,
5846 path: &Path,
5847 stream: usize,
5848 onto: Option<Lane>,
5849 ) -> crate::Result<bool> {
5850 self.place_stream_mode(timeline_secs, path, stream, onto, None)
5851 }
5852
5853 /// [`place_stream_at`](Self::place_stream_at) as an **overwrite**: what the file lands on
5854 /// is replaced for its length and nothing is pushed along ([`SourceEdit::Overwrite`]). The
5855 /// lanes it lands on are chosen exactly as `place_stream_at` chooses them, and a refusal
5856 /// comes back with the engine's own words.
5857 pub fn place_stream_overwrite_at(
5858 &mut self,
5859 timeline_secs: f64,
5860 path: &Path,
5861 stream: usize,
5862 onto: Option<Lane>,
5863 ) -> crate::Result<bool> {
5864 self.place_stream_mode(timeline_secs, path, stream, onto, Some(crate::SourceEdit::Overwrite))
5865 }
5866
5867 /// The one placement behind both doors: `overwrite` of `None` is the insert-and-paste
5868 /// `place_stream_at` has always made; `Some` replaces what is there through
5869 /// [`edit_from_source_at`](Self::edit_from_source_at).
5870 fn place_stream_mode(
5871 &mut self,
5872 timeline_secs: f64,
5873 path: &Path,
5874 stream: usize,
5875 onto: Option<Lane>,
5876 overwrite: Option<crate::SourceEdit>,
5877 ) -> crate::Result<bool> {
5878 let wanted = Source::new(path, stream);
5879 // Another stream of a file this session has taken in: that is what a
5880 // library row is, and it is why nothing here has to check dimensions or
5881 // frame rate -- the file passed that at import. Its length is the one
5882 // the import noted, so a source that has never been placed is as
5883 // placeable as one that is already on a lane.
5884 let frames = self.file_frames(&wanted.path);
5885 if frames == 0 {
5886 return Err(format!("{} is not on this timeline", path.display()).into());
5887 }
5888 // A still has no sound to hold to the timeline's -- and no length
5889 // either, so it goes down at the project's still length rather than at the
5890 // ten minutes it is *allowed* to be dragged out to.
5891 let image = crate::is_image(path);
5892 if !image {
5893 let first = self.first_audio()?;
5894 self.audio_matches_cached(&wanted, &first)?;
5895 }
5896 let rate = self.file_rate(&wanted.path);
5897 let source = self.project.import(path, stream);
5898 self.note_frames(source, frames, rate);
5899 let clip = Clip {
5900 speed_keys: Vec::new(),
5901 reversed: false,
5902 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5903 angle: Default::default(),
5904 fade_in: 0,
5905 fade_out: 0,
5906 transition_out: 0,
5907 transition_kind: Default::default(),
5908 visualizer: 0,
5909 viz_paint: 0,
5910 gain_db: 0.0,
5911 gain_keys: Vec::new(),
5912 pan: 0,
5913 transform_keys: Vec::new(),
5914 opacity_keys: Vec::new(),
5915 color_keys: Vec::new(),
5916 effects: Vec::new(),
5917 start: 0,
5918 in_frame: 0,
5919 out_frame: match image {
5920 true => place_frames(frames, self.meta.frame_rate, self.project.still_secs()),
5921 false => sound_held_frames(path, stream, frames, self.meta.frame_rate),
5922 },
5923 source,
5924 link: None,
5925 eq: None,
5926 color: None,
5927 transform: None,
5928 fit: FitPolicy::default(),
5929 speed: Speed::NORMAL,
5930 pitch: 0,
5931 };
5932 // Which lane a source may land on is decided here and only here, so a
5933 // front-end never has to make the same call twice: a file with no
5934 // picture goes on an audio lane alone, overwriting and rippling
5935 // nothing, because there is nothing on the video lane to move along
5936 // with it. A lane of the source's own kind takes it as it is dropped;
5937 // only `V1` means the grouped take, since that is the pair the paste
5938 // spans and a second video lane is a layer of its own.
5939 // ...and a still is the mirror of a song: a picture and no sound, so a
5940 // video lane and nothing else -- never the grouped take, which would
5941 // put a clip on `A1` for a source the audio worker cannot open.
5942 if image {
5943 let lane = match onto {
5944 Some(lane) if lane.kind == LaneKind::Video => lane,
5945 _ => Lane::V1,
5946 };
5947 if let Some(edit) = overwrite {
5948 self.edit_from_source_at(edit, timeline_secs, &[(lane, clip)])?;
5949 return Ok(true);
5950 }
5951 return Ok(self.place_at(lane, timeline_secs, clip));
5952 }
5953 let onto = match (sound_only(path), onto) {
5954 // No picture: an audio lane and nothing else, whichever one was
5955 // asked for -- `A1` when none was.
5956 (true, Some(lane)) if lane.kind == LaneKind::Audio => Some(lane),
5957 (true, _) => Some(Lane::A1),
5958 // A picture: the lane it was let go over, unless that is one of the
5959 // first pair. Those two are the grouped take a paste spans, and a
5960 // further lane is a layer of its own -- its picture on `V2`, its
5961 // sound on `A2` (below).
5962 (false, Some(lane)) if lane.ord > 0 => Some(lane),
5963 (false, _) => None,
5964 };
5965 // An overwrite lays the same lanes down as an insert would, replacing what is under
5966 // them: a picture and its sound as one take (a link on both halves), a sound alone
5967 // on its audio lane.
5968 if let Some(edit) = overwrite {
5969 let items: Vec<(Lane, Clip)> = match onto {
5970 Some(lane) if lane.kind == LaneKind::Audio => vec![(lane, clip)],
5971 Some(lane) if lane.kind == LaneKind::Video => vec![
5972 (lane, clip.clone()),
5973 (Lane::new(LaneKind::Audio, lane.ord), clip),
5974 ],
5975 _ => vec![(Lane::V1, clip.clone()), (Lane::A1, clip)],
5976 };
5977 self.edit_from_source_at(edit, timeline_secs, &items)?;
5978 return Ok(true);
5979 }
5980 Ok(match onto {
5981 // A picture let go over a further *video* track lands there with the
5982 // sound it came with -- `V2`'s picture, `A2`'s sound, one take and
5983 // one undo step ([`Project::place_take`]). Dropped on a further
5984 // audio lane it is the sound alone, which is what asking an audio
5985 // row for an mp4 means.
5986 Some(lane) if lane.kind == LaneKind::Video => {
5987 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
5988 let clip = self.held_to_take(clip);
5989 self.edit(Dirty::Both, |p| p.place_take(lane, at, clip))
5990 }
5991 Some(lane) => self.place_at(lane, timeline_secs, clip),
5992 // The grouped take, at the frame it was let go on -- past the last
5993 // clip included, where the bed is black and the ghost was drawn.
5994 // Not [`Self::paste_at`]: that door clamps to the end for the
5995 // clipboard, and a drop that named a place is not a paste.
5996 None => {
5997 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
5998 let clip = self.held_to_take(clip);
5999 self.edit(Dirty::Both, |p| p.paste(at, clip))
6000 }
6001 })
6002 }
6003
6004 /// Takes `path` played on `stream` out of the library -- the door a library
6005 /// row's own remove goes through, naming the row exactly as
6006 /// [`place_stream_at`](Self::place_stream_at) does. Refused in
6007 /// [`Project::remove_source`]'s words while a clip still plays from it, and
6008 /// for a row this timeline does not have.
6009 ///
6010 /// Reseeks like an edit even though nothing playable changed: the clip
6011 /// indexes into the source list have just moved, and the running workers
6012 /// were opened against the old numbering.
6013 ///
6014 /// The index that went, because everything past it moved down: a caller
6015 /// holding a source index of its own (a clipboard) has to fix it up or drop
6016 /// it, or it names a different file afterwards. The **last** row goes like
6017 /// any other and leaves a session with an empty library -- silent, empty of
6018 /// clips, and unsaveable ([`save_project`](Self::save_project)); a
6019 /// front-end showing one is showing an empty window.
6020 /// [`remove_source`](Self::remove_source) for the one source that may go
6021 /// without clearing undo: the **last** entry, when no clip and no undo or
6022 /// redo step names it ([`Project::remove_unused_source`]). Nothing playable
6023 /// changes, so there is no reseek and the timeline and its history stay as
6024 /// they were. Used to roll back a batch that imported a source and then
6025 /// failed, where clearing history would also wipe the user's undo.
6026 pub fn remove_unused_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> {
6027 let wanted = Source::new(path, stream);
6028 let idx = self
6029 .project
6030 .sources()
6031 .iter()
6032 .position(|s| *s == wanted)
6033 .ok_or_else(|| format!("{} is not on this timeline", path.display()))?;
6034 self.project.remove_unused_source(idx)?;
6035 if idx < self.counts.len() {
6036 self.counts.remove(idx);
6037 self.rates.remove(idx);
6038 }
6039 Ok(idx)
6040 }
6041
6042 pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> {
6043 let wanted = Source::new(path, stream);
6044 let idx = self
6045 .project
6046 .sources()
6047 .iter()
6048 .position(|s| *s == wanted)
6049 .ok_or_else(|| format!("{} is not on this timeline", path.display()))?;
6050 self.project.remove_source(idx)?;
6051 // The one thing that shortens the source list, so the one place
6052 // [`Self::counts`] shortens with it: left behind, the gone file's length
6053 // would become the wall a *surviving* source is trimmed against
6054 // ([`trim_room`](Self::trim_room)) and the next import would land its
6055 // count one index late.
6056 if idx < self.counts.len() {
6057 self.counts.remove(idx);
6058 self.rates.remove(idx);
6059 }
6060 let now = self.now();
6061 self.seek(now);
6062 Ok(idx)
6063 }
6064
6065 /// What the timeline's audio *is*: the chosen stream of the first source
6066 /// that could have any ([`audio_source_of`]), probed. Every other source is
6067 /// held to it.
6068 ///
6069 /// Through the session's own memo ([`probes`](Self::probes)), because this
6070 /// is asked on the render thread: the free [`first_audio_of`] is the one a
6071 /// worker with no session to reach for calls.
6072 fn first_audio(&mut self) -> crate::Result<Option<crate::AudioProbe>> {
6073 match audio_source_of(self.project.sources()) {
6074 Some(first) => {
6075 let (path, stream) = (first.path.clone(), first.audio_stream);
6076 self.probe_cached(&path, stream)
6077 }
6078 None => Ok(None),
6079 }
6080 }
6081
6082 /// One audio header, read at most once per session per `(path, stream)`.
6083 fn probe_cached(
6084 &mut self,
6085 path: &Path,
6086 stream: usize,
6087 ) -> crate::Result<Option<crate::AudioProbe>> {
6088 let key = (path.to_path_buf(), stream);
6089 if let Some(probe) = self.probes.get(&key) {
6090 return Ok(*probe);
6091 }
6092 let probe = AudioSession::probe(path, stream)?;
6093 self.probes.insert(key, probe);
6094 Ok(probe)
6095 }
6096
6097 /// [`audio_matches`] with this session's memo behind the new file's own
6098 /// header too -- the second of the two opens a place or an import pays.
6099 fn audio_matches_cached(
6100 &mut self,
6101 source: &Source,
6102 first: &Option<crate::AudioProbe>,
6103 ) -> crate::Result<()> {
6104 let probe = self.probe_cached(&source.path, source.audio_stream)?;
6105 audio_matches_probed(probe, first)
6106 }
6107
6108 /// Places `clip` on `lane` alone at the playhead, overwriting what it lands
6109 /// on and rippling nothing -- the one-lane insert a source with no picture
6110 /// makes, and the only way an audio-only file reaches the timeline. The
6111 /// placement belongs to no group (see [`Project::place`]). One undo step,
6112 /// and it reseeks like every other edit.
6113 ///
6114 /// The clip is held to `lane`'s own wall first ([`held_to_lane`](Self::held_to_lane)):
6115 /// a caller's `out_frame` past the source's length on that lane is cut back
6116 /// to it, so no door places a clip the save would refuse.
6117 pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool {
6118 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6119 let clip = self.held_to_lane(lane, clip);
6120 self.edit(Dirty::Both, |p| p.place(lane, at, clip))
6121 }
6122
6123 /// [`Project::edit_from_source`]'s door: an insert or an overwrite of the
6124 /// halves in `items` at `timeline_secs`. Each half is held to its own lane's
6125 /// wall -- and a take of a picture and its sound to the shorter of the two,
6126 /// so the halves run the same length and stay one link. One undo step; it
6127 /// reseeks like every other edit. The error says why it refused.
6128 pub fn edit_from_source_at(
6129 &mut self,
6130 kind: crate::SourceEdit,
6131 timeline_secs: f64,
6132 items: &[(Lane, Clip)],
6133 ) -> crate::Result<()> {
6134 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6135 let both = items.iter().any(|(l, _)| l.kind == LaneKind::Video)
6136 && items.iter().any(|(l, _)| l.kind == LaneKind::Audio);
6137 let items: Vec<(Lane, Clip)> = items
6138 .iter()
6139 .map(|(lane, clip)| {
6140 let held = if both {
6141 self.held_to_take(clip.clone())
6142 } else {
6143 self.held_to_lane(*lane, clip.clone())
6144 };
6145 (*lane, held)
6146 })
6147 .collect();
6148 let mut result = Ok(());
6149 let done = self.edit(Dirty::Both, |p| match p.edit_from_source(kind, at, &items) {
6150 Ok(()) => true,
6151 Err(e) => {
6152 result = Err(e);
6153 false
6154 }
6155 });
6156 match (done, result) {
6157 (_, Err(e)) => Err(e),
6158 (false, Ok(())) => Err("the edit changed nothing".into()),
6159 (true, Ok(())) => Ok(()),
6160 }
6161 }
6162
6163 /// The longest `clip` may run on `lane`: its source's length on that lane's
6164 /// kind -- the picture's on a video lane, the sound's on an audio lane
6165 /// ([`lane_walls`]), the two tables [`save_project`](Self::save_project)
6166 /// checks each lane against. `out_frame` is held to that wall; a clip the
6167 /// wall leaves no frame of is one [`Project::place`] refuses.
6168 fn held_to_lane(&self, lane: Lane, mut clip: Clip) -> Clip {
6169 let (picture, sound) =
6170 lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
6171 let table = match lane.kind {
6172 LaneKind::Audio => sound,
6173 _ => picture,
6174 };
6175 if let Some(&wall) = table.get(clip.source) {
6176 clip.out_frame = clip.out_frame.min(wall);
6177 }
6178 clip
6179 }
6180
6181 /// [`held_to_lane`](Self::held_to_lane) for a clip placed as one take: a
6182 /// picture on a video lane and its sound on an audio lane, so it is held to
6183 /// the shorter of the source's two walls. Both halves of a take share the
6184 /// one clip, so neither may run past its own lane.
6185 fn held_to_take(&self, mut clip: Clip) -> Clip {
6186 let (picture, sound) =
6187 lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
6188 let wall = [picture.get(clip.source), sound.get(clip.source)]
6189 .into_iter()
6190 .flatten()
6191 .min();
6192 if let Some(&wall) = wall {
6193 clip.out_frame = clip.out_frame.min(wall);
6194 }
6195 clip
6196 }
6197
6198 /// Places a waveform-visualizer clip of `path`'s audio on a video lane.
6199 /// The picture is painted from the sound ([`DecodeSession::open_visualizer`]);
6200 /// this does not also put a copy on an audio lane.
6201 pub fn place_visualizer(
6202 &mut self,
6203 start: u32,
6204 path: &Path,
6205 stream: usize,
6206 in_frame: u32,
6207 out_frame: u32,
6208 onto: Option<Lane>,
6209 ) -> crate::Result<bool> {
6210 if out_frame <= in_frame {
6211 return Err("visualizer clip is empty".into());
6212 }
6213 let wanted = Source::new(path, stream);
6214 let first = self.first_audio()?;
6215 self.audio_matches_cached(&wanted, &first)?;
6216 let frames = match self.file_frames(&wanted.path) {
6217 0 => {
6218 let n = audio_frames(path, self.meta.frame_rate)?;
6219 let source = self.project.import(path, stream);
6220 self.note_frames(source, n, Rate::REAL_TIME);
6221 n
6222 }
6223 n => n,
6224 };
6225 let out_frame = out_frame.min(frames);
6226 if out_frame <= in_frame {
6227 return Err("visualizer clip is empty".into());
6228 }
6229 let source = self.project.import(path, stream);
6230 let clip = Clip {
6231 speed_keys: Vec::new(),
6232 reversed: false,
6233 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
6234 angle: Default::default(),
6235 fade_in: 0,
6236 fade_out: 0,
6237 transition_out: 0,
6238 transition_kind: Default::default(),
6239 visualizer: 1,
6240 viz_paint: 0,
6241 gain_db: 0.0,
6242 gain_keys: Vec::new(),
6243 pan: 0,
6244 transform_keys: Vec::new(),
6245 opacity_keys: Vec::new(),
6246 color_keys: Vec::new(),
6247 effects: Vec::new(),
6248 start: 0,
6249 in_frame,
6250 out_frame,
6251 source,
6252 link: None,
6253 eq: None,
6254 color: None,
6255 transform: None,
6256 fit: FitPolicy::default(),
6257 speed: Speed::NORMAL,
6258 pitch: 0,
6259 };
6260 let end = start + clip.frames();
6261 let overlaps = |lane: Lane| {
6262 self.project
6263 .lane(lane)
6264 .iter()
6265 .any(|c| c.start < end && start < c.end())
6266 };
6267 let lane = match onto {
6268 Some(lane) if lane.kind == LaneKind::Video && !overlaps(lane) => lane,
6269 _ => self
6270 .project
6271 .lanes()
6272 .into_iter()
6273 .filter(|l| l.kind == LaneKind::Video)
6274 .find(|&l| !overlaps(l))
6275 .unwrap_or_else(|| self.add_lane(LaneKind::Video)),
6276 };
6277 let clip = self.held_to_lane(lane, clip);
6278 Ok(self.edit(Dirty::Both, |p| p.place(lane, start, clip)))
6279 }
6280
6281 /// Removes `lane`'s clip at `idx` and everything under it, closing the gap
6282 /// on every lane. Unlike a split this *does* move every following frame, so
6283 /// the session reseeks to wherever the playhead now points.
6284 /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead.
6285 /// `false` for a bad index; the last remaining clip goes like any other and
6286 /// leaves the timeline empty ([`is_empty`](Self::is_empty)).
6287 ///
6288 /// The lane travels because the index is a lane's own: `V2`'s third clip is
6289 /// not `V1`'s, and a front-end that could only say "the third clip" would
6290 /// delete the wrong one the moment a second lane exists.
6291 pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool {
6292 self.edit(Dirty::Both, |p| p.delete_in(lane, idx))
6293 }
6294
6295 /// Undoes the last successful edit, and reseeks like a delete. A step on
6296 /// the project's own settings comes back the same way: the canvas, the
6297 /// rate and the switches are put back on the session here
6298 /// ([`Self::adopt_settings`]), so a `z` after a resolution pick, an
6299 /// encoder pick or a proxy switch lands exactly as one after a cut does.
6300 pub fn undo(&mut self) -> bool {
6301 self.restored_step(Project::undo)
6302 }
6303
6304 /// Redoes the last edit [`undo`](Self::undo) took back, and reseeks like
6305 /// a delete -- settings included, exactly as `undo` takes them back.
6306 pub fn redo(&mut self) -> bool {
6307 self.restored_step(Project::redo)
6308 }
6309
6310 /// Every sequence in tab order ([`Project::sequences`]).
6311 pub fn sequences(&self) -> Vec<crate::project::SequenceInfo> {
6312 self.project.sequences()
6313 }
6314
6315 /// The active sequence's id.
6316 pub fn active_sequence(&self) -> u32 {
6317 self.project.active_sequence()
6318 }
6319
6320 /// The name of sequence `id`.
6321 pub fn sequence_name(&self, id: u32) -> Option<String> {
6322 self.project.sequence_name(id).map(str::to_string)
6323 }
6324
6325 /// The sequence called `name`.
6326 pub fn sequence_named(&self, name: &str) -> Option<u32> {
6327 self.project.sequence_named(name)
6328 }
6329
6330 /// See [`Project::source_uses_parked`].
6331 pub fn source_uses_parked(&self, source: usize) -> Vec<(u32, usize)> {
6332 self.project.source_uses_parked(source)
6333 }
6334
6335 /// See [`Project::compound_pieces`].
6336 pub fn compound_pieces(&self, kind: LaneKind, clip: &Clip) -> Vec<Clip> {
6337 self.project.compound_pieces(kind, clip)
6338 }
6339
6340 /// The sequence the compound clip at `lane`/`idx` plays.
6341 pub fn compound_at(&self, lane: Lane, idx: usize) -> Option<u32> {
6342 self.project.compound_at(lane, idx)
6343 }
6344
6345 /// The angle names of sequence `id` when it is a multicam source ([`Project::angle_names`]).
6346 pub fn angle_names(&self, id: u32) -> Option<Vec<String>> {
6347 self.project.angle_names(id).map(<[String]>::to_vec)
6348 }
6349
6350 /// The multicam source the clip at `lane`/`idx` plays and its angle names, when it is a
6351 /// multicam clip.
6352 pub fn multicam_at(&self, lane: Lane, idx: usize) -> Option<(u32, Vec<String>)> {
6353 let c = self.project.lane(lane).get(idx)?;
6354 self.project.multicam_of(c).map(|(id, n)| (id, n.to_vec()))
6355 }
6356
6357 /// Whether the rate and other time-scaled settings are fixed because the
6358 /// project holds more than one sequence.
6359 pub fn rate_locked(&self) -> bool {
6360 self.project.rate_locked()
6361 }
6362
6363 /// An edit that can be refused with a reason: the picture and the sound are
6364 /// rebuilt when it was made.
6365 fn edit_try<T>(&mut self, f: impl FnOnce(&mut Project) -> crate::Result<T>) -> crate::Result<T> {
6366 let made = f(&mut self.project)?;
6367 self.invalidate(Dirty::Both);
6368 Ok(made)
6369 }
6370
6371 /// Adds an empty sequence; see [`Project::new_sequence`]. Not switched to.
6372 pub fn new_sequence(&mut self, name: Option<&str>) -> crate::Result<u32> {
6373 self.edit_try(|p| p.new_sequence(name))
6374 }
6375
6376 /// Makes an editor timeline a new sequence and switches to it ([`crate::interchange::build`]).
6377 /// Each file it names is taken in as a library file is; one that is gone is offline, as a
6378 /// missing file is in a saved project. One undo step.
6379 pub fn import_timeline(&mut self, t: &crate::interchange::Timeline) -> crate::Result<u32> {
6380 let mut reach: Vec<(PathBuf, u32)> = Vec::new();
6381 for item in t.tracks.iter().flat_map(|tr| &tr.items) {
6382 if let crate::interchange::Item::Clip(c) = item {
6383 match reach.iter_mut().find(|(p, _)| *p == c.path) {
6384 Some((_, r)) => *r = (*r).max(c.out_frame),
6385 None => reach.push((c.path.clone(), c.out_frame)),
6386 }
6387 }
6388 }
6389 for (path, furthest) in &reach {
6390 if self.source_of(path).is_some() {
6391 continue;
6392 }
6393 if crate::source_present(path) {
6394 self.import(path)?;
6395 } else {
6396 let source = self.project.import(path, 0);
6397 self.note_frames(source, *furthest, Rate::REAL_TIME);
6398 }
6399 }
6400 self.begin_batch();
6401 let made = self.edit_try(|p| crate::interchange::build(p, t));
6402 self.end_batch();
6403 made
6404 }
6405
6406 /// See [`Project::rename_sequence`].
6407 pub fn rename_sequence(&mut self, id: u32, name: &str) -> crate::Result<()> {
6408 self.edit_try(|p| p.rename_sequence(id, name))
6409 }
6410
6411 /// See [`Project::duplicate_sequence`].
6412 pub fn duplicate_sequence(&mut self, id: u32) -> crate::Result<u32> {
6413 self.edit_try(|p| p.duplicate_sequence(id))
6414 }
6415
6416 /// See [`Project::delete_sequence`]. The picture and sound follow the
6417 /// sequence that is active afterwards.
6418 pub fn delete_sequence(&mut self, id: u32) -> crate::Result<u32> {
6419 self.edit_try(|p| p.delete_sequence(id))
6420 }
6421
6422 /// Makes `id` the sequence on the timeline and in the picture and sound. Not an undo step.
6423 pub fn switch_sequence(&mut self, id: u32) -> crate::Result<()> {
6424 if id == self.project.active_sequence() {
6425 return Ok(());
6426 }
6427 self.edit_try(|p| p.switch_sequence(id))
6428 }
6429
6430 /// See [`Project::nest`].
6431 pub fn nest(&mut self, picks: &[(Lane, usize)], name: Option<&str>) -> crate::Result<crate::project::Nested> {
6432 self.edit_try(|p| p.nest(picks, name))
6433 }
6434
6435 /// See [`Project::break_apart`].
6436 pub fn break_apart(&mut self, picks: &[(Lane, usize)]) -> crate::Result<Vec<(Lane, usize)>> {
6437 self.edit_try(|p| p.break_apart(picks))
6438 }
6439
6440 /// Syncs the sources `picks` and makes a multicam clip of them at `timeline_secs` on `lane`
6441 /// ([`Project::make_multicam`]). With [`MulticamSync::Audio`] every camera is lined up with
6442 /// the first one that has sound by the loudness curve of its track
6443 /// ([`crate::multisync`]); a camera that cannot be matched (no sound, or too weak a match)
6444 /// starts with the others and the report says so. One undo step.
6445 pub fn make_multicam_at(
6446 &mut self,
6447 picks: &[usize],
6448 sync: MulticamSync,
6449 name: Option<&str>,
6450 lane: Lane,
6451 timeline_secs: f64,
6452 ) -> crate::Result<MulticamReport> {
6453 let job = self.multicam_job(picks, sync)?;
6454 let plan = job.run(&std::sync::atomic::AtomicU32::new(0), &std::sync::atomic::AtomicBool::new(false))?;
6455 self.apply_multicam(&plan, name, lane, timeline_secs)
6456 }
6457
6458 /// The part of [`make_multicam_at`](Self::make_multicam_at) that only reads the sources, as a
6459 /// value that can be run on a thread of its own ([`MulticamJob::run`]) while the window stays
6460 /// live; [`apply_multicam`](Self::apply_multicam) then makes the clip, one undo step.
6461 pub fn multicam_job(&self, picks: &[usize], sync: MulticamSync) -> crate::Result<MulticamJob> {
6462 let mut seen = Vec::new();
6463 let mut sources = Vec::new();
6464 for &p in picks {
6465 let Some(src) = self.project.sources().get(p) else {
6466 return Err(format!("source {p} is not in the project").into());
6467 };
6468 if seen.contains(&p) {
6469 return Err(format!("source {p} is picked twice: an angle is one camera").into());
6470 }
6471 seen.push(p);
6472 sources.push(MulticamJobSource {
6473 index: p,
6474 path: src.path.clone(),
6475 audio_stream: src.audio_stream,
6476 frames: self.counts.get(p).copied().unwrap_or(0).max(1),
6477 });
6478 }
6479 Ok(MulticamJob { sources, sync, fps: self.meta.frame_rate })
6480 }
6481
6482 /// The library's bins ([`Project::bins`]).
6483 pub fn bins(&self) -> &[crate::project::Bin] {
6484 self.project.bins()
6485 }
6486
6487 /// Makes a bin; see [`Project::create_bin`]. A label only: nothing is rebuilt.
6488 pub fn create_bin(&mut self, name: &str, parent: u32) -> Result<u32, String> {
6489 self.project.create_bin(name, parent)
6490 }
6491
6492 /// See [`Project::rename_bin`].
6493 pub fn rename_bin(&mut self, id: u32, name: &str) -> Result<bool, String> {
6494 self.project.rename_bin(id, name)
6495 }
6496
6497 /// See [`Project::remove_bin`].
6498 pub fn remove_bin(&mut self, id: u32) -> Result<usize, String> {
6499 self.project.remove_bin(id)
6500 }
6501
6502 /// See [`Project::move_to_bin`].
6503 pub fn move_to_bin(&mut self, srcs: &[usize], bin: u32) -> Result<usize, String> {
6504 self.project.move_to_bin(srcs, bin)
6505 }
6506
6507 /// See [`Project::set_favourite`].
6508 pub fn set_favourite(&mut self, srcs: &[usize], on: bool) -> Result<usize, String> {
6509 self.project.set_favourite(srcs, on)
6510 }
6511
6512 /// Makes the multicam clip a [`MulticamJob::run`] measured, at `timeline_secs` on `lane`. One
6513 /// undo step. Refused when the project's sources are no longer the ones that were measured.
6514 pub fn apply_multicam(&mut self, plan: &MulticamPlan, name: Option<&str>, lane: Lane, timeline_secs: f64) -> crate::Result<MulticamReport> {
6515 for a in &plan.sources {
6516 if self.project.sources().get(a.index).map(|s| &s.path) != Some(&a.path) {
6517 return Err("the media list changed while the angles were being synced".into());
6518 }
6519 }
6520 let fps = self.meta.frame_rate;
6521 let at = secs_to_frame(timeline_secs, fps);
6522 let made = self.edit_try(|p| p.make_multicam(name, &plan.angles, lane, at))?;
6523 Ok(MulticamReport { made, how: plan.how.clone(), offsets_secs: plan.offsets.clone(), starts: plan.angles.iter().map(|a| a.start).collect() })
6524 }
6525
6526 /// See [`Project::switch_angle`], at `timeline_secs`.
6527 pub fn switch_angle_at(
6528 &mut self,
6529 lane: Option<Lane>,
6530 timeline_secs: f64,
6531 video: Option<u8>,
6532 audio: Option<Option<u8>>,
6533 ) -> crate::Result<Vec<(Lane, u32)>> {
6534 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6535 self.edit_try(|p| p.switch_angle(lane, at, video, audio))
6536 }
6537
6538 /// The multicam clip under timeline `frame`, if any ([`Project::multicam_under`]).
6539 pub fn multicam_under(&self, frame: u32) -> Option<crate::project::MulticamUnder> {
6540 self.project.multicam_under(frame)
6541 }
6542
6543 /// One flattened project per angle of the multicam clip under `frame` and the timeline meta
6544 /// to compose them with ([`crate::export::compose_at`]): the angle monitor's tiles, composed
6545 /// off the window's thread.
6546 pub fn angle_views(&self, frame: u32) -> Option<(crate::project::MulticamUnder, Vec<crate::project::Project>, VideoMeta)> {
6547 self.project.angle_views(frame).map(|(u, v)| (u, v, self.meta))
6548 }
6549
6550 /// See [`Project::flatten_multicam`].
6551 pub fn flatten_multicam(&mut self, lane: Lane, idx: usize) -> crate::Result<Vec<(Lane, usize)>> {
6552 self.edit_try(|p| p.flatten_multicam(lane, idx))
6553 }
6554
6555 /// See [`Project::place_sequence`], at `timeline_secs`.
6556 pub fn place_sequence_at(&mut self, seq: u32, lane: Lane, timeline_secs: f64) -> crate::Result<()> {
6557 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6558 self.edit_try(|p| p.place_sequence(seq, lane, at))
6559 }
6560
6561 /// The project as an edit sees it, compound clips and all, with the undo history left out
6562 /// (what a "did this batch change anything" comparison reads; [`export_snapshot`](Self::export_snapshot)
6563 /// is the expanded one a render reads).
6564 pub fn raw_snapshot(&self) -> (crate::project::Project, VideoMeta) {
6565 (self.project.raw_snapshot(), self.meta)
6566 }
6567
6568 /// [`export_snapshot`](Self::export_snapshot) of sequence `seq` (the active one for `None`).
6569 pub fn export_snapshot_of(&self, seq: Option<u32>) -> crate::Result<(crate::project::Project, VideoMeta)> {
6570 Ok((self.project.render_snapshot(seq)?, self.meta))
6571 }
6572
6573 /// Starts a batch: the edits until [`end_batch`](Self::end_batch) are one
6574 /// undo step, taken before the first of them. Only the caller that opens a
6575 /// batch sees the difference; the GUI never calls this, so its steps stay one per edit.
6576 pub fn begin_batch(&mut self) {
6577 self.project.begin_batch();
6578 }
6579
6580 /// Ends the batch [`begin_batch`](Self::begin_batch) opened.
6581 pub fn end_batch(&mut self) {
6582 self.project.end_batch();
6583 }
6584
6585 /// The mark an action takes before it edits, for [`Self::name_step`].
6586 pub fn step_mark(&mut self) -> u64 {
6587 self.project.step_mark()
6588 }
6589
6590 /// Names the step the action that took `mark` pushed, so Undo and Redo can say what
6591 /// they take back. An action that pushed nothing names nothing.
6592 pub fn name_step(&mut self, mark: u64, label: &str) {
6593 self.project.name_step(mark, label);
6594 }
6595
6596 /// What [`undo`](Self::undo) takes back, when the step was named.
6597 pub fn undo_label(&self) -> Option<&str> {
6598 self.project.undo_label()
6599 }
6600
6601 /// What [`redo`](Self::redo) walks forward to, when the step was named.
6602 pub fn redo_label(&self) -> Option<&str> {
6603 self.project.redo_label()
6604 }
6605
6606 /// The names of the steps [`undo`](Self::undo) can take back, oldest first
6607 /// ([`Project::undo_labels`]).
6608 pub fn undo_labels(&self) -> Vec<Option<String>> {
6609 self.project.undo_labels()
6610 }
6611
6612 /// The names of the steps [`redo`](Self::redo) can walk forward to, the next one last
6613 /// ([`Project::redo_labels`]).
6614 pub fn redo_labels(&self) -> Vec<Option<String>> {
6615 self.project.redo_labels()
6616 }
6617
6618 /// Moves through the undo history by `index` steps from where it stands: negative undoes that
6619 /// many, positive redoes. Each step goes through [`undo`](Self::undo) or [`redo`](Self::redo),
6620 /// so it reseeks like them. Returns how many steps were taken; it stops early at either end.
6621 pub fn jump_to(&mut self, index: isize) -> usize {
6622 let mut taken = 0;
6623 for _ in 0..index.unsigned_abs() {
6624 let moved = match index < 0 {
6625 true => self.undo(),
6626 false => self.redo(),
6627 };
6628 if !moved {
6629 break;
6630 }
6631 taken += 1;
6632 }
6633 taken
6634 }
6635
6636 /// How many steps [`undo`](Self::undo) can still take.
6637 pub fn undo_depth(&self) -> usize {
6638 self.project.history_len()
6639 }
6640
6641 /// How many steps [`redo`](Self::redo) can still take.
6642 pub fn redo_depth(&self) -> usize {
6643 self.project.redo_len()
6644 }
6645
6646 /// Which state the timeline is in ([`Project::revision`]): equal before and
6647 /// after an undo means the undo walked back to the same timeline, so a save
6648 /// taken at one can tell whether the timeline has since moved off it.
6649 pub fn revision(&self) -> u64 {
6650 self.project.revision()
6651 }
6652
6653 /// Every undo snapshot the session has pushed, including those the
6654 /// [`HISTORY_CAP`](crate::project) has since dropped. Unlike
6655 /// [`undo_depth`](Self::undo_depth) it keeps rising at the cap, so a caller
6656 /// counts a batch's steps as the difference of two reads of it.
6657 pub fn history_pushes(&self) -> u64 {
6658 self.project.history_pushes()
6659 }
6660
6661 /// Drops the redo stack with no step taken. For a caller that rolled its own
6662 /// trial edits back: the undone states they left are not a branch to redo.
6663 pub fn clear_redo(&mut self) {
6664 self.project.clear_redo();
6665 }
6666
6667 /// Moves the redo stack out ([`RedoCheckpoint`]) with no step taken, for a
6668 /// caller whose trial edits may be rolled back. The trial's own edits clear
6669 /// it and its rollback fills it, so [`restore_redo`](Self::restore_redo)
6670 /// puts back exactly what was there before the trial.
6671 pub fn take_redo(&mut self) -> RedoCheckpoint {
6672 self.project.take_redo()
6673 }
6674
6675 /// Puts back the redo stack [`take_redo`](Self::take_redo) took out.
6676 pub fn restore_redo(&mut self, cp: RedoCheckpoint) {
6677 self.project.restore_redo(cp);
6678 }
6679
6680 /// Opens (`true`) or closes (`false`) a trial batch's hold on the undo cap:
6681 /// while held, its steps evict nothing, so a rolled-back trial leaves the
6682 /// history exactly as it found it. Closing trims back to the cap.
6683 pub fn hold_history(&mut self, hold: bool) {
6684 self.project.hold_history(hold);
6685 }
6686
6687 /// Takes `path` into the **library**: it becomes a source of this session,
6688 /// with its length noted ([`file_frames`](Self::file_frames)), and nothing
6689 /// is placed on any lane. What reaches the timeline is decided afterwards,
6690 /// by dragging the row onto a lane
6691 /// ([`place_stream_at`](Self::place_stream_at)) -- importing a file is not
6692 /// a decision about where it plays.
6693 ///
6694 /// The source index, new or the one this file already had: importing twice
6695 /// registers once. *Not* an undo step -- a source entry alone changes
6696 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take
6697 /// back, and nothing reseeks.
6698 ///
6699 /// Refused unless it can join the timeline -- a decoder this machine can
6700 /// open, and audio parameters that agree or none at all; the `Err` names
6701 /// the property that disagrees,
6702 /// for a caller to show. Nothing is changed by a refusal. A *resolution* of
6703 /// its own is not a refusal: the clip is placed on the project canvas by its
6704 /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame
6705 /// rate* of its own: the file is placed for the seconds it lasts and read at
6706 /// [`Rate`] against the timeline's rate, so it plays at the speed it was
6707 /// shot at.
6708 /// [`import`](Self::import), with what the import cannot do for the file
6709 /// said back as warnings rather than left on stderr. A file whose sound is in
6710 /// a codec this build does not decode (DTS, say) imports with its picture and
6711 /// plays silent: the one warning is that sentence, naming the track. Empty
6712 /// for a file with nothing to warn about.
6713 pub fn import_with_warnings(&mut self, path: &Path) -> crate::Result<(usize, Vec<String>)> {
6714 let source = self.import(path)?;
6715 let warnings = AudioSession::unsupported(path)
6716 .ok()
6717 .flatten()
6718 .map(|why| format!("{}: {why}; its sound will be silent", path.display()))
6719 .into_iter()
6720 .collect();
6721 Ok((source, warnings))
6722 }
6723
6724 pub fn import(&mut self, path: &Path) -> crate::Result<usize> {
6725 if crate::is_audio(path) {
6726 return self.import_audio(path);
6727 }
6728 // One frame of a numbered run is the whole run: a clip of its frames, asked nothing.
6729 if let Some(run) = crate::sequence::Run::parse(path).or_else(|| crate::sequence::Run::detect(path)) {
6730 return self.import_run(&run);
6731 }
6732 if crate::is_image(path) {
6733 return self.import_image(path);
6734 }
6735 // Both halves on this thread, which is what a caller with nothing else
6736 // to do wants; a front-end splits them across a worker instead
6737 // ([`probe_import`](Self::probe_import)).
6738 // A container with sound but no picture is a song wearing a video
6739 // extension -- the same fallback `open_stream` and the project
6740 // scaffold make, so every door in agrees on what the file is.
6741 match Self::probe_import(self.import_gate(), path) {
6742 Ok(probe) => Ok(self.take_probe(path, probe)),
6743 Err(e) if crate::demux::NoVideoTrack::is_it(&e) => self.import_audio(path),
6744 Err(e) => Err(e),
6745 }
6746 }
6747
6748 /// Everything an import is *checked against*, taken off this timeline in
6749 /// one owned piece: the sources its audio must agree with and the meta its
6750 /// rate is read against. Costs two clones and touches no disk, so the
6751 /// thread holding the session can hand it to a worker and go on painting.
6752 pub fn import_gate(&self) -> ImportGate {
6753 ImportGate {
6754 sources: self.project.sources().to_vec(),
6755 timeline: self.meta,
6756 }
6757 }
6758
6759 /// The reading half of [`import`](Self::import), with no session in it: the
6760 /// container's header, the decoder this machine would open it with, and the
6761 /// audio check against the gate -- every read an import pays.
6762 ///
6763 /// This is the half that costs. Measured on a 24 GB 4K HEVC remux: 21.4 s of
6764 /// header with the pages cold, 429 ms warm, plus 1-4 s of probing the
6765 /// timeline's own first source. So a front-end runs *this* on its background
6766 /// executor and hands what comes back to
6767 /// [`import_probed`](Self::import_probed), which costs a push -- the same
6768 /// split [`parse_subtitles`](Self::parse_subtitles) makes, for the same
6769 /// reason.
6770 ///
6771 /// The container fork only: a song and a still fork before the demuxer
6772 /// ([`import`](Self::import)) and pay a header read of their own.
6773 ///
6774 /// The `Err` is the refusal [`import`](Self::import) would have given, in
6775 /// the same words -- nothing is refused twice and nothing is worded twice.
6776 pub fn probe_import(gate: ImportGate, path: &Path) -> crate::Result<ImportProbe> {
6777 let (meta, _) = Demuxer::open(path)?;
6778 let first = first_audio_of(&gate.sources)?;
6779 // Stream 0: an import brings a file in on its first audio track, and
6780 // [`place_stream_at`](Self::place_stream_at) is how any other one of
6781 // its streams reaches the timeline afterwards.
6782 // ...and the rate it will be read at comes back from the check that
6783 // accepted it, so the number the refusal was decided on is the number
6784 // the file is played by.
6785 let rate = matches_timeline(&Source::new(path, 0), &meta, &gate.timeline, &first)?;
6786 Ok(ImportProbe { gate, meta, rate })
6787 }
6788
6789 /// Registers a file already read by [`probe_import`](Self::probe_import).
6790 /// The whole of what an import costs the thread that calls it: a source
6791 /// entry and its length, no open, no seek, no decode -- which is why the
6792 /// probe is a separate door.
6793 ///
6794 /// The timeline may have moved while the worker read: a source removed or a
6795 /// file opened is a different set of things the probe was checked against,
6796 /// so the probe is re-read here ([`ImportGate`]) and a stale one is simply
6797 /// imported the slow way rather than trusted. Same answer either way, so no
6798 /// caller has to know which arm it took.
6799 pub fn import_probed(&mut self, path: &Path, probe: ImportProbe) -> crate::Result<usize> {
6800 match probe.gate.sources == self.project.sources() && probe.gate.timeline == self.meta {
6801 true => Ok(self.take_probe(path, probe)),
6802 false => self.import(path),
6803 }
6804 }
6805
6806 /// The push both import doors end at.
6807 fn take_probe(&mut self, path: &Path, probe: ImportProbe) -> usize {
6808 let source = self.project.import(path, 0);
6809 // Its length *on this timeline*: a file shot slower than the timeline
6810 // runs covers more frames than it holds, which is the whole of what
6811 // placing it at another rate means ([`Rate`]).
6812 self.note_frames(
6813 source,
6814 probe.rate.timeline_at(probe.meta.frame_count),
6815 probe.rate,
6816 );
6817 source
6818 }
6819
6820 /// The same registration for a standalone audio file: a song has no
6821 /// picture, so the length noted for it is its playing time rounded up to
6822 /// whole frames, which is the only frame count such a source has.
6823 ///
6824 /// Refused in the same words as any other import when its layout disagrees
6825 /// with the timeline's track -- one output device, one layout. A silent
6826 /// timeline has no track to disagree with, so a song joins it and *is* its
6827 /// sound ([`Self::arm_audio`]). Nothing is changed by a refusal.
6828 fn import_audio(&mut self, path: &Path) -> crate::Result<usize> {
6829 let first = self.first_audio()?;
6830 // Stream 0, and there is no other: a standalone audio file carries one
6831 // track (`AudioSession::probe_streams`), so nothing here has a stream
6832 // to pick the way `place_stream_at` does for an mp4.
6833 self.audio_matches_cached(&Source::new(path, 0), &first)?;
6834 let frames = audio_frames(path, self.meta.frame_rate)?;
6835 let source = self.project.import(path, 0);
6836 self.note_frames(source, frames, Rate::REAL_TIME);
6837 Ok(source)
6838 }
6839
6840 /// The registration of a numbered run ([`crate::sequence`]): one source named for the whole
6841 /// run, held to as many frames as the run holds, at the timeline's rate. The first frame is
6842 /// what a refusal is decided on -- a run of pictures this engine cannot compose is refused in
6843 /// the words a single still would be.
6844 fn import_run(&mut self, run: &crate::sequence::Run) -> crate::Result<usize> {
6845 let (width, height) = crate::decode::image_size(&run.frame(0))?;
6846 if !crate::is_resolution(width, height) {
6847 return Err(format!(
6848 "{} is {width}x{height}, which is not a picture this engine composes",
6849 run.frame(0).display()
6850 )
6851 .into());
6852 }
6853 let source = self.project.import(run.spelled(), 0);
6854 self.note_frames(source, run.count, Rate::REAL_TIME);
6855 Ok(source)
6856 }
6857
6858 /// The same registration for a still image, and the shortest of the three:
6859 /// a picture has nothing to agree with. No frame rate (it is one picture),
6860 /// no audio (it is silent), and a resolution of its own is what every
6861 /// import is allowed -- the clip is placed on the project canvas by its fit
6862 /// policy. The one refusal left is a file that is not a picture at all, or
6863 /// one too big to compose ([`crate::is_resolution`]), and the header alone
6864 /// answers both.
6865 ///
6866 /// The length noted is the wall a trim is held to, not a duration the file
6867 /// has: see [`image_frames`].
6868 fn import_image(&mut self, path: &Path) -> crate::Result<usize> {
6869 let (width, height) = crate::decode::image_size(path)?;
6870 if !crate::is_resolution(width, height) {
6871 return Err(format!(
6872 "{} is {width}x{height}, which is not a picture this engine composes",
6873 path.display()
6874 )
6875 .into());
6876 }
6877 let source = self.project.import(path, 0);
6878 self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME);
6879 Ok(source)
6880 }
6881
6882 /// Applies an edit and, if it took, rebuilds **what it dirtied** and nothing
6883 /// else ([`Dirty`]). A structural edit reseeks: `seek` clamps to the new
6884 /// duration and keeps playing playing, so a delete that shortens the
6885 /// timeline past the playhead lands on the last frame. A grade or a fit
6886 /// policy rebuilds the picture where it stands, with the sound running
6887 /// through it untouched -- no flush, no re-open, no hole -- and an
6888 /// equalizer the other way round.
6889 /// The project's own settings as this session has them now
6890 /// ([`ProjectSettings`]): the canvas and the rate are `meta`'s, the
6891 /// switches are this session's own fields, and the rendition and the
6892 /// limiter are the project's -- two halves of one header, which is what
6893 /// every history entry carries beside the lanes ([`Project::snapshot`]).
6894 fn settings_value(&self) -> ProjectSettings {
6895 ProjectSettings {
6896 resolution: (self.meta.width, self.meta.height),
6897 frame_rate: self.meta.frame_rate,
6898 encoder_seat: self.encoder_seat,
6899 sample_rate: self.sample_rate,
6900 proxies: self.proxies,
6901 auto_proxies: self.auto_proxies,
6902 tone: self.project.tone(),
6903 limiter: self.project.limiter(),
6904 caption_style: self.project.caption_style(),
6905 notes: self.project.notes().to_string(),
6906 still_secs: self.project.still_secs(),
6907 speech_model: self.project.speech_model().map(str::to_string),
6908 speech_device: self.project.speech_device(),
6909 }
6910 }
6911
6912 /// One undo step for a change to the project's own settings, taken after
6913 /// the change: `from` is the state the door found, and what the project
6914 /// does with the two values is [`Project::push_settings_step`]'s.
6915 fn step_settings(&mut self, from: ProjectSettings) {
6916 let now = self.settings_value();
6917 self.project.push_settings_step(from, now);
6918 }
6919
6920 /// Puts the project's settings back on this session -- what a step that
6921 /// restored them leaves for the player to take up. The canvas, the rate and
6922 /// the switches live here, and the rendition and the limiter are the
6923 /// project's own, already back in place by the time this runs. Every lane
6924 /// edit's entry comes through here too and moves nothing, which is the
6925 /// common case; the *rate* is the one that needs more than the fields,
6926 /// because every source's frame count is held against it and the conform
6927 /// that scaled them is not in the entry.
6928 fn adopt_settings(&mut self) {
6929 let s = self.project.settings_now();
6930 // A project nobody has handed a canvas to: a fresh [`Project`] carries
6931 // the placeholder ([`ProjectSettings::placeholder`]) and no session is
6932 // on one -- the entries pushed before the first settings door hold lane
6933 // edits and that placeholder, and adopting it would zero the canvas.
6934 if s.frame_rate <= 0.0 {
6935 return;
6936 }
6937 let was = self.meta.frame_rate;
6938 self.meta.width = s.resolution.0;
6939 self.meta.height = s.resolution.1;
6940 self.meta.frame_rate = s.frame_rate;
6941 self.encoder_seat = s.encoder_seat;
6942 self.sample_rate = s.sample_rate;
6943 self.proxies = s.proxies;
6944 self.auto_proxies = s.auto_proxies;
6945 if s.frame_rate != was {
6946 // Within a frame, like the way out ([`Self::set_frame_rate`]'s own
6947 // caveat): the lane frame numbers came home exactly, out of the
6948 // entry, and only the per-source lengths are re-derived through the
6949 // map back.
6950 let Ok(k) = Rate::from_fps(was, s.frame_rate) else {
6951 return;
6952 };
6953 for count in &mut self.counts {
6954 *count = k.timeline_nearest(*count).max(1);
6955 }
6956 for rate in &mut self.rates {
6957 *rate = rate.then(k);
6958 }
6959 self.meta.frame_count = k.timeline_nearest(self.meta.frame_count).max(1);
6960 }
6961 }
6962
6963 /// [`Self::undo`] and [`Self::redo`] themselves: the project's own step,
6964 /// and then whatever it restored for the session to take up
6965 /// ([`Self::adopt_settings`]). Reseeks both halves, so a canvas that moved
6966 /// is repainted and a proxy switch that flipped reopens the file.
6967 fn restored_step(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool {
6968 let before = self.project.sources().to_vec();
6969 if !f(&mut self.project) {
6970 return false;
6971 }
6972 // Adopted *before* the reseek below, never after it: everything the
6973 // reseek reads is one of the settings the entry just put back --
6974 // `landing` the rate and the frame count, `picture_path` the switches,
6975 // the sound the sample rate -- so a landing computed from the values
6976 // the step *undid* lands on the wrong frame of the right project (and
6977 // reopens the file through the switch that just went back).
6978 self.adopt_settings();
6979 // A step that put a relinked file's old path back is read again here,
6980 // before the reseek opens it.
6981 self.reread_sources(&before);
6982 self.invalidate(Dirty::Both);
6983 true
6984 }
6985
6986 /// Takes `other`'s timeline over as one undo step ([`Project::adopt_as_step`]),
6987 /// the way a recovery puts an autosave's edits on the saved project it opened.
6988 /// The settings are adopted and the sources read again exactly as an undo
6989 /// does it. `false`, with nothing changed, when the project refuses it.
6990 pub fn adopt_as_step(&mut self, other: &PlaybackSession) -> bool {
6991 let before = self.project.sources().to_vec();
6992 if !self.project.adopt_as_step(&other.project) {
6993 return false;
6994 }
6995 self.adopt_settings();
6996 self.reread_sources(&before);
6997 self.invalidate(Dirty::Both);
6998 true
6999 }
7000
7001 /// Measures the sources a step moved or added, against the timeline as it
7002 /// stands. `before` is the list the step started from: a source whose path
7003 /// or stream differs from it (a relink undone or redone, an entry adopted
7004 /// from another project) has its length and rate read again, and so does
7005 /// one past the end of the counts. A file that can no longer be read keeps
7006 /// the length it had, or a whole picture's for an entry it never had.
7007 fn reread_sources(&mut self, before: &[Source]) {
7008 let now = self.project.sources().to_vec();
7009 self.counts.truncate(now.len());
7010 self.rates.truncate(now.len());
7011 for (i, source) in now.iter().enumerate() {
7012 if i < self.counts.len() && before.get(i) == Some(source) {
7013 continue;
7014 }
7015 let (count, rate) = match self.measure_source(source) {
7016 Ok(measured) => measured,
7017 Err(_) => (
7018 self.counts.get(i).copied().unwrap_or(self.meta.frame_count),
7019 self.rates.get(i).copied().unwrap_or(Rate::REAL_TIME),
7020 ),
7021 };
7022 if i < self.counts.len() {
7023 self.counts[i] = count;
7024 self.rates[i] = rate;
7025 } else {
7026 self.counts.push(count);
7027 self.rates.push(rate);
7028 }
7029 }
7030 }
7031
7032 /// The frame count and the rate `source`'s file has on this timeline: what a
7033 /// relink measures a new file by, and what an undo measures the file it puts
7034 /// back by. The file must be the kind and the material the timeline holds,
7035 /// as [`Self::relink_source`] checks it.
7036 fn measure_source(&mut self, source: &Source) -> crate::Result<(u32, Rate)> {
7037 let path = source.path.as_path();
7038 let first = self.first_audio()?;
7039 if crate::is_image(path) {
7040 crate::decode::image_size(path)?;
7041 Ok((image_frames(self.meta.frame_rate), Rate::REAL_TIME))
7042 } else if crate::is_audio(path) {
7043 audio_matches(source, &first)?;
7044 Ok((audio_frames(path, self.meta.frame_rate)?, Rate::REAL_TIME))
7045 } else {
7046 let (other, _) = Demuxer::open(path)?;
7047 let rate = matches_timeline(source, &other, &self.meta, &first)?;
7048 Ok((rate.timeline_at(other.frame_count), rate))
7049 }
7050 }
7051
7052 fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool {
7053 let done = f(&mut self.project);
7054 self.project.settle();
7055 if !done {
7056 return false;
7057 }
7058 self.invalidate(dirty);
7059 true
7060 }
7061
7062 /// Where an edit rebuilds from: the clock, except at the end of a played-out
7063 /// timeline, where the clock has kept running on wall time and the edit
7064 /// resumes at the end the viewer saw (so a paste there plays the pasted clip).
7065 fn playhead(&self) -> f64 {
7066 match self.eos {
7067 true => self.now().min(self.eos_end),
7068 false => self.now(),
7069 }
7070 }
7071
7072 /// Rebuilds the dirtied half (or both) at the playhead.
7073 fn invalidate(&mut self, dirty: Dirty) {
7074 match dirty {
7075 Dirty::Picture => {
7076 let (_, target) = self.landing(self.playhead());
7077 self.start_picture(target);
7078 }
7079 Dirty::Sound => self.reseek_audio(),
7080 Dirty::Both => {
7081 let now = self.playhead();
7082 self.seek(now);
7083 }
7084 }
7085 }
7086
7087 /// Says how big the picture is on screen, in device pixels -- what a
7088 /// front-end showing this session pushes once it knows where the picture
7089 /// actually lands. Rendering a 1080p project's visualizer for a 600 px
7090 /// preview costs nine times the pixels for nothing the eye can see; a
7091 /// window that is fullscreen gets the project's own size back by pushing
7092 /// it. `true` when the size moved enough to be worth a new picture: under
7093 /// 8 px on both axes is a resize nobody can see, and a window being
7094 /// dragged would otherwise restart the picture every tick.
7095 pub fn set_view_size(&mut self, width: u32, height: u32) -> bool {
7096 let want = self.view_want(width, height);
7097 match self.view {
7098 Some(now) if now.0.abs_diff(want.0) < 8 && now.1.abs_diff(want.1) < 8 => false,
7099 _ => {
7100 self.view = Some(want);
7101 true
7102 }
7103 }
7104 }
7105
7106 /// [`Self::set_view_size`] with no deadband: what asks for the *exact*
7107 /// size rather than one within 8 px of it. A still saved at the project's
7108 /// own pixels is a file whose dimensions are read back, so "close enough
7109 /// to be invisible" is not close enough to be right. `true` when the view
7110 /// moved, `false` when it was already there -- which is also the answer
7111 /// that lets a caller skip waiting for a frame it already has.
7112 pub fn set_view_size_exact(&mut self, width: u32, height: u32) -> bool {
7113 let want = self.view_want(width, height);
7114 match self.view {
7115 Some(now) if now == want => false,
7116 _ => {
7117 self.view = Some(want);
7118 true
7119 }
7120 }
7121 }
7122
7123 /// The size a push of `(width, height)` settles on: even on both axes
7124 /// (YUV 4:2:0 has no odd chroma) and never past the project's own.
7125 fn view_want(&self, width: u32, height: u32) -> (u32, u32) {
7126 let fit = |n: u32, cap: u32| (n & !1).clamp(2, cap.max(2));
7127 (fit(width, self.meta.width), fit(height, self.meta.height))
7128 }
7129
7130 /// The canvas a span's pictures are painted at: [`Self::set_view_size`]'s
7131 /// size once one has been pushed, the project's own otherwise.
7132 pub fn view_size(&self) -> (u32, u32) {
7133 self.view.unwrap_or((self.meta.width, self.meta.height))
7134 }
7135
7136 /// Current timeline position in seconds.
7137 pub fn now(&self) -> f64 {
7138 self.clock.now()
7139 }
7140
7141 pub fn is_playing(&self) -> bool {
7142 self.clock.is_playing()
7143 }
7144
7145 pub fn play(&mut self) {
7146 if self.clock.is_playing() {
7147 return;
7148 }
7149 // Invariant: the clock is positioned *before* audio restarts. Audio
7150 // reports are relative to the first one after that, so a seek would go
7151 // here too -- `clock.seek_to(t)` and then `set_active(true)`.
7152 self.clock.play();
7153 // Above or below 1x the sound stays off: `set_rate(1.0)` brings it back.
7154 if let Some(audio) = self.audio.as_ref().filter(|_| self.clock.rate() == 1.0) {
7155 audio.set_playing(true);
7156 }
7157 }
7158
7159 /// Sets the playback speed: 1.0 is real time, 2/4/8 forward, -1/-2 backward.
7160 ///
7161 /// Anything but 1x runs the clock on wall time at that rate and keeps the
7162 /// sound silent -- audio cannot play backward or fast without a stretch the
7163 /// engine does not do here. Going back to 1x reopens the sound at the
7164 /// current position, as a seek does. Drawing the picture backward is not
7165 /// done for the sound; the picture is, from the playhead down ([`Back`]), and
7166 /// turning the clock round restarts it there.
7167 pub fn set_rate(&mut self, rate: f64) {
7168 if !rate.is_finite() || rate == 0.0 || rate == self.clock.rate() {
7169 return;
7170 }
7171 let was_backward = self.backward();
7172 if rate != 1.0 {
7173 if let Some(audio) = &self.audio {
7174 audio.set_playing(false);
7175 }
7176 self.clock.set_rate(rate);
7177 } else {
7178 self.clock.set_rate(1.0);
7179 if self.audio.is_some() {
7180 self.reseek_audio();
7181 }
7182 }
7183 if was_backward != self.backward() {
7184 let (_, target) = self.landing(self.now());
7185 self.start_picture(target);
7186 }
7187 }
7188
7189 pub fn pause(&mut self) {
7190 if !self.clock.is_playing() {
7191 return;
7192 }
7193 if let Some(audio) = &self.audio {
7194 audio.set_playing(false);
7195 }
7196 self.clock.pause();
7197 }
7198
7199 pub fn toggle(&mut self) {
7200 if self.clock.is_playing() {
7201 self.pause()
7202 } else {
7203 self.play()
7204 }
7205 }
7206
7207 /// Stops the transport where the timeline stops: the clock is paused and put
7208 /// on the out point.
7209 ///
7210 /// Playing past the last frame is wall time counting on past the end of the
7211 /// media -- there is no picture left to pace it -- so a session left at EOF
7212 /// reports a `now()` that walks off the end of the timeline in real time,
7213 /// and a caller that reads the playhead (a cut, a paste, an insert) then
7214 /// acts at a position no clip is at. How far off depends only on how long
7215 /// the window was left open, so no clamp in a caller is worth writing.
7216 ///
7217 /// End of stream is deliberately left set: the picture is still the last
7218 /// frame and this is still the end. That is what makes it safe to call on
7219 /// the crossing into it -- the state the transport shows does not change,
7220 /// only the running clock stops.
7221 /// Carries the clock on past the last frame, on wall time from where it stands, for a
7222 /// take that runs longer than the timeline. The audio is stopped with it: nothing is
7223 /// left to play. A no-op unless the clock runs on the audio device.
7224 pub fn run_past_end(&mut self) {
7225 if self.clock.source() != ClockSource::Audio {
7226 return;
7227 }
7228 if let Some(audio) = &self.audio {
7229 audio.set_playing(false);
7230 }
7231 self.clock.switch_to_wall();
7232 }
7233
7234 pub fn halt_at_end(&mut self) {
7235 self.pause();
7236 // Played backward the end it ran into is the start, and the rate goes back
7237 // to real time there: the next press plays on from the top.
7238 if self.backward() {
7239 self.set_rate(1.0);
7240 self.clock.seek_to(0.0);
7241 // The picture restart above cleared it; this is still the end.
7242 self.eos = true;
7243 return;
7244 }
7245 self.clock.seek_to(self.timeline_duration());
7246 }
7247
7248 /// The gain this session's device is running at, read back from the device
7249 /// rather than remembered here: `None` with no audio output, or a plugin
7250 /// too old to answer -- the two cases where a remembered answer would be a
7251 /// claim nothing can check.
7252 pub fn gain(&self) -> Option<f32> {
7253 self.audio.as_ref()?.ao.lock().unwrap().gain()
7254 }
7255
7256 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
7257 /// one knob, because muting and turning it down are the same thing to the
7258 /// device, and *which* the user meant is a question only the UI can answer
7259 /// -- it keeps the level to come back to.
7260 ///
7261 /// The level is remembered for as long as this session lives
7262 /// ([`Audio::gain`]) and only so that a device which is *replaced* under
7263 /// the session -- re-armed after a death, armed by a late import -- comes
7264 /// back at the level the session was already running at. It is still not
7265 /// project state: a fresh session starts at 1.0, so a caller still pushes
7266 /// it once per session, and an export -- which renders the file rather
7267 /// than what the speakers are doing -- can never pick it up. Silent with
7268 /// no audio device, which is also the only honest answer there.
7269 ///
7270 /// Mute is not pause: the samples are still consumed and the device clock
7271 /// still runs, so the picture keeps playing against it.
7272 pub fn set_gain(&self, gain: f32) -> bool {
7273 match &self.audio {
7274 // The device is the owner and is told first: a remembered level
7275 // that says something the device does not agree with is worse
7276 // than no memory at all, because the next replacement would
7277 // restore the wrong number.
7278 Some(audio) if audio.ao.lock().unwrap().set_volume(gain) => {
7279 audio.gain.store(gain.to_bits(), Ordering::Release);
7280 true
7281 }
7282 _ => false,
7283 }
7284 }
7285
7286 /// A copy of the most recent mono samples the device was handed, and the
7287 /// rate they play at: the signal *after* every clip's equalizer, speed and
7288 /// the mix, which is what an analyser drawn behind an EQ curve has to show.
7289 /// `None` with no audio output at all, and empty until the feeder has
7290 /// written once (right after a seek, for instance).
7291 ///
7292 /// Never blocks anything that matters: the feeder holds this lock for one
7293 /// memcpy and the device's own callback lives in the plugin, on the far
7294 /// side of a ring buffer, where it cannot see this at all.
7295 pub fn audio_tap(&self) -> Option<(Vec<f32>, u32)> {
7296 let audio = self.audio.as_ref()?;
7297 let tap = audio.tap.lock().unwrap().clone();
7298 Some((tap, audio.sample_rate))
7299 }
7300
7301 /// Says that this session is being **watched in real time**, so a picture
7302 /// whose moment has passed is worth nothing and the decode worker may drop
7303 /// it where it is cheap to drop -- before the conversion (a full BGRA pass
7304 /// over 8 MB at 1080p) and before the queue.
7305 ///
7306 /// Off by default, and that is the contract every *pull* consumer relies on:
7307 /// an export, the file-level [`DecodeSession`] API and a test draining as
7308 /// fast as it can all ask for a range of frames and must be given every one
7309 /// of them, in order. Only a viewer has a moment for a picture to be past.
7310 ///
7311 /// A front-end that turns this on was dropping those very frames itself, one
7312 /// repaint later (`Player::pump` takes everything due and shows the last):
7313 /// what changes is where the work stops, and therefore how quickly a decoder
7314 /// that fell behind catches up.
7315 ///
7316 /// It does not replace [`resync_picture`](Self::resync_picture): both
7317 /// mechanisms are live and this one is the first line. It catches up without
7318 /// restarting anything, which is why the front-end's resync -- a picture
7319 /// restart, once per `RESYNC_GAP` -- now fires only where dropping was not
7320 /// enough (a decoder so far behind that even one picture in nine
7321 /// ([`crate::decode`]'s `LATE_RUN`) cannot close the gap).
7322 pub fn drop_late_pictures(&mut self, on: bool) {
7323 self.drop_late = on;
7324 }
7325
7326 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
7327 /// workers are replaced rather than steered: a fresh channel cannot hold a
7328 /// stale frame, and it works just as well after EOF, where the old workers
7329 /// have already exited.
7330 ///
7331 /// Playing stays playing and paused stays paused -- but a paused seek still
7332 /// decodes, so the caller can show the frame it landed on.
7333 pub fn seek(&mut self, secs: f64) {
7334 let (t, target) = self.landing(secs);
7335 let was_playing = self.clock.is_playing();
7336 self.stop_audio();
7337 self.start_picture(target);
7338 if self.clock.rate() != 1.0 {
7339 // Sound stays silent off-speed; `set_rate(1.0)` reopens it here.
7340 self.clock.seek_to(t);
7341 return;
7342 }
7343 let audio_running = self.start_audio(target);
7344 // Same invariant as `play`: position the clock before audio restarts.
7345 if audio_running && self.clock.source() != ClockSource::Audio {
7346 self.clock.switch_to_audio();
7347 }
7348 self.clock.seek_to(t);
7349 self.resume(was_playing);
7350 }
7351
7352 /// Abandons whatever the picture worker still owes and restarts it at the
7353 /// clock. The sound and the clock are untouched -- this is the *video*
7354 /// catching up to its master, not a seek -- so nothing the ear is following
7355 /// moves, and a caller that is behind by more than it can watch calls this
7356 /// instead of waiting for a decoder that only falls further back
7357 /// (`Player::pump`).
7358 pub fn resync_picture(&mut self) {
7359 self.invalidate(Dirty::Picture);
7360 }
7361
7362 /// Where a seek to `secs` lands: the clamped timeline position and the
7363 /// timeline frame it means. The one place the clamp lives, so every
7364 /// invalidation below lands on the same frame a seek would.
7365 fn landing(&self, secs: f64) -> (f64, u32) {
7366 let fps = self.meta.frame_rate;
7367 let total = self.project.timeline_frames();
7368 let t = secs.clamp(0.0, f64::from(total) / fps);
7369 (t, secs_to_frame(t, fps).min(total.saturating_sub(1)))
7370 }
7371
7372 /// Rebuilds the **picture** at `target` and touches nothing else: the sound
7373 /// keeps playing out of the same stream, the clock keeps running, and a
7374 /// grade dragged during playback is therefore silent.
7375 fn start_picture(&mut self, target: u32) {
7376 // Abandon first, drop second: the old worker may be parked in `send` on
7377 // the bounded channel, where only the disconnect wakes it -- and it
7378 // then finds the span already superseded. The *thread* is kept, and
7379 // with it the open file and the open decoder, so a seek onto the same
7380 // source costs a demuxer seek and a decoder flush rather than the
7381 // VA-API init (98 ms) a new worker would pay; a worker that cannot take
7382 // the new span is retired by [`retire`](Self::retire) instead, and
7383 // nothing on this thread joins either way.
7384 self.worker.abandon();
7385 // The span runs from `target` to the end of whatever it landed in -- a
7386 // clip, or a gap, which starts a black-frame worker instead. `None` is
7387 // the emptied timeline, black too, and `start_span` says so.
7388 let span = match self.backward() {
7389 true => back_span_at(&self.project.render_view(), target),
7390 false => crate::export::stack_span_at(&self.project.render_view(), target),
7391 };
7392 self.start_span(span);
7393 self.eos = false;
7394 }
7395
7396 /// Silences the device and supersedes whatever is feeding it: the first half
7397 /// of every audio restart, and the only thing that ever discards queued
7398 /// sound.
7399 fn stop_audio(&mut self) {
7400 self.mix = None;
7401 if let Some(audio) = &self.audio {
7402 let ao = audio.ao.lock().unwrap();
7403 ao.set_active(false);
7404 // Bumped and flushed while holding the device lock, because the
7405 // feeder re-checks the epoch inside that same lock: whatever it is
7406 // carrying can no longer reach the ring after this point.
7407 audio.epoch.fetch_add(1, Ordering::Release);
7408 // Nothing of the new stream has been played yet, by definition.
7409 audio.content_at.store(-1, Ordering::Release);
7410 ao.flush();
7411 // The flushed samples are not being played any more, so nothing may
7412 // still be drawn from them.
7413 audio.tap.lock().unwrap().clear();
7414 }
7415 }
7416
7417 /// Puts the device back where it was: playing if it was playing, and with
7418 /// the clock held until the new stream is really audible (see
7419 /// [`Audio::content_at`]).
7420 ///
7421 /// Only the *intent* is set here: the open runs on the feeder
7422 /// ([`start_audio`](Self::start_audio)), so the device is started by that
7423 /// stream's first real sample instead ([`Audio::wants_active`]). A device
7424 /// made active over an empty ring plays its own silence and counts one
7425 /// underrun per starved quantum -- a scripted cold play-seek-scrub session
7426 /// used to go from 5 to 1721 of them -- while the ear hears the same silence
7427 /// either way, so nothing is gained for the count that is lost.
7428 fn resume(&mut self, was_playing: bool) {
7429 self.priming = true;
7430 if let Some(audio) = &self.audio {
7431 audio.set_playing(was_playing);
7432 }
7433 }
7434
7435 /// Rebuilds the **sound** from `target` -- the second half of a restart --
7436 /// and says whether a feeder took the job. Not whether it will find
7437 /// anything to play: the stream is opened on that feeder
7438 /// ([`Audio::spawn_feeder_deferred`]), so a silent timeline is heard of
7439 /// there, not here. Nothing on this thread reads the file.
7440 ///
7441 /// The clock is unaffected by the wait, which is the reason it may be a
7442 /// long one: it holds where the seek put it until the *first real sample*
7443 /// is queued ([`Audio::content_at`], [`tick`](Self::tick)), whether that is
7444 /// ten milliseconds later or ten seconds.
7445 ///
7446 /// `true` is therefore *optimistic*, and the callers' `switch_to_audio` with
7447 /// it: a timeline that turns out to have nothing to play ends its feeder at
7448 /// once, which sets `fed_all` and hands the clock back to wall time at the
7449 /// next tick, from where it stood ([`PlaybackClock::switch_to_wall`] is
7450 /// continuous, so nothing jumps).
7451 fn start_audio(&mut self, target: u32) -> bool {
7452 let fps = self.meta.frame_rate;
7453 let mut audio_running = false;
7454 let mut live = None;
7455 // A dead output gets an attempt here without waiting out the cooldown: a
7456 // seek is a person asking, and this is the one moment the sound can come
7457 // back into step with the picture, because the feeder opened below starts
7458 // at the target. If it does not come back the flag stands and the guard
7459 // under it leaves the clock on wall time.
7460 self.rearm_audio(Duration::ZERO);
7461 if let Some(audio) = &self.audio
7462 && !audio.died.load(Ordering::Acquire)
7463 {
7464 // The device position keeps counting across a flush, so re-basing
7465 // `fed` on it is what keeps `played_out` exact for the new stream.
7466 let played = audio.ao.lock().unwrap().position().unwrap_or(0).max(0) as u64;
7467 audio.fed.store(played * audio.channels, Ordering::Relaxed);
7468 audio.fed_all.store(false, Ordering::Release);
7469 // One worker for the whole rest of the timeline, so the joins
7470 // between clips are gapless: the video reopens at a boundary, the
7471 // ear never hears it -- and a join between two *files* is just
7472 // another segment, because every segment names its own source.
7473 // One play list per audio lane, summed by the mixer: what the ear
7474 // hears is every lane at once, and a lane's own gaps are silence in
7475 // it rather than a hole in the count the master clock keeps.
7476 let segs = self.project.render_view().audio_segments_from(target, fps);
7477 // The equalizers beside them, one per segment: the worker filters a
7478 // segment's own samples before the mix, so a clip's curve reaches
7479 // that clip and stops. Rebuilt on every seek, which is what makes an
7480 // EQ edit audible at once -- `edit` reseeks, so the drag that
7481 // changed a band restarts the workers with the new curve already in
7482 // them, and no live channel has to reach into a running one.
7483 let eqs = self.project.render_view().audio_eqs_from(target, fps);
7484 // ...and the rates, the same way again: a speeded segment is
7485 // resampled inside its own worker, before the mix, so what the ear
7486 // hears is what the timeline shows. Empty for a project nobody has
7487 // speeded, which is the path that decodes the same samples it always
7488 // did.
7489 let speeds = self.project.render_view().audio_speeds_from(target, fps);
7490 // ...and the fades, the same way again: a clip's own envelope runs
7491 // inside its worker, after the rate and the equalizer, so a fade
7492 // edit is audible at once exactly as an EQ edit is.
7493 let fades = self.project.render_view().audio_fades_from(target, fps);
7494 // Each source on the stream it was placed with: what plays is what
7495 // the library row said, and what an export copies (`export::run`).
7496 let sources = self.project.audio_sources();
7497 // ...and the mix settings over the lot: each lane's own volume on
7498 // its way into the sum and the master limiter over the sum. These
7499 // two are handed over *live* as well as at the open: they sit at
7500 // the sum, where nothing is decoded, so a fader moved later is a
7501 // number the running mixer picks up rather than a stream rebuilt
7502 // under the ear ([`crate::audio::MixControls`]).
7503 let gains = self.mix_gains();
7504 let ducks = self.project.render_view().audio_ducks();
7505 // ...and the voice processors, which are not live: an edit to one
7506 // rebuilds the sound like an equalizer edit does.
7507 let voices = self.project.render_view().audio_voices();
7508 let limiter = self.project.limiter();
7509 let controls = crate::audio::MixControls::new(gains.clone(), ducks.clone(), limiter);
7510 // Only a mixed timeline has a mixer to talk to; the single-lane
7511 // flat path is the bit-exact one and has none. Decided here from
7512 // the very lists the open is about to be handed
7513 // ([`AudioSession::is_mixed`]) rather than read off the handle
7514 // afterwards, because there *is* no afterwards on this thread any
7515 // more -- the open runs on the feeder.
7516 let mixed = crate::audio::AudioSession::is_mixed(segs.len(), &gains, limiter, &voices);
7517 let worker_controls = Arc::clone(&controls);
7518 // ...and the rate the mix runs at, if the project picked one: the
7519 // same override [`crate::edith::save`] writes and [`Self::open_project`]
7520 // reads back.
7521 let sample_rate = self.sample_rate;
7522 // ...and the open itself -- every track a segment names, its packet
7523 // table, its priming -- happens there too. That is the whole point:
7524 // one `pread` on a cold 25 GB film is seconds, and this is called
7525 // from a ruler drag ([`Audio::spawn_feeder_deferred`]).
7526 audio_running = audio.spawn_feeder_deferred(move || {
7527 match AudioSession::open_mixed_streams_live_fade(
7528 &sources,
7529 &segs,
7530 &eqs,
7531 &speeds,
7532 &fades,
7533 fps,
7534 &gains,
7535 &ducks,
7536 &voices,
7537 limiter,
7538 Some(&worker_controls),
7539 sample_rate,
7540 ) {
7541 Ok(Some((_, rx))) => Some(rx),
7542 // A silent timeline, and a source that will not open: both
7543 // feed nothing, which the feeder itself reports by ending.
7544 // The mix goes with them -- no mixer was started, so a fader
7545 // moved later must rebuild the sound rather than hand its
7546 // number to a thread that does not exist
7547 // ([`crate::audio::MixControls::detach`]).
7548 Ok(None) => {
7549 worker_controls.detach();
7550 None
7551 }
7552 Err(e) => {
7553 worker_controls.detach();
7554 // A read this session abandoned on purpose -- the seek
7555 // after it, or the session going away -- is not a file
7556 // that would not open, and says nothing.
7557 if !crate::demux::is_cancelled(&e) && std::env::var_os("EDITH_DEBUG").is_some() {
7558 eprintln!("timeline audio open failed: {e}");
7559 }
7560 None
7561 }
7562 }
7563 });
7564 live = (audio_running && mixed).then_some(controls);
7565 if !audio_running {
7566 // Nothing will ever be fed again; let `tick` fall to wall time
7567 // instead of waiting on a device that has no more work coming.
7568 audio.fed_all.store(true, Ordering::Release);
7569 }
7570 }
7571 self.mix = live;
7572 audio_running
7573 }
7574
7575 /// Rebuilds the sound alone, from where the playhead is: what a change that
7576 /// no picture can show goes through. The video worker is left decoding, so
7577 /// the picture does not blink -- and the clock, held still by
7578 /// [`resume`](Self::resume) until the new stream is audible, puts the sound
7579 /// back exactly where the picture already is.
7580 ///
7581 /// End of stream is deliberately left alone -- no picture worker is started
7582 /// here, so a timeline that was played out still is; see
7583 /// [`is_eos`](Self::is_eos).
7584 fn reseek_audio(&mut self) {
7585 if self.clock.rate() != 1.0 {
7586 // Off-speed the sound is silent and `set_rate(1.0)` rebuilds it, so a
7587 // change to it now has nothing to rebuild.
7588 return;
7589 }
7590 let (t, target) = self.landing(self.now());
7591 let was_playing = self.clock.is_playing();
7592 self.stop_audio();
7593 let audio_running = self.start_audio(target);
7594 if audio_running && self.clock.source() != ClockSource::Audio {
7595 self.clock.switch_to_audio();
7596 }
7597 self.clock.seek_to(t);
7598 self.resume(was_playing);
7599 }
7600
7601 /// Renders the edited timeline to `out` on a worker thread. The session is
7602 /// untouched -- the export decodes the source file for itself -- but a
7603 /// caller should still [`pause`](PlaybackSession::pause) first, because
7604 /// playback and export otherwise fight over the same decoder hardware.
7605 ///
7606 /// Later edits do not reach a running export: it works from a snapshot of
7607 /// the edit list taken here.
7608 ///
7609 /// corner-cut: this defaults the settings; the app still calls it that way,
7610 /// and the export options card replaces the call with
7611 /// [`export_to_with`](PlaybackSession::export_to_with).
7612 pub fn export_to(&self, out: &Path) -> crate::ExportHandle {
7613 self.export_to_with(out, &crate::export::ExportSettings::default())
7614 }
7615
7616 /// [`export_to`](PlaybackSession::export_to) with the output settings spelled
7617 /// out rather than defaulted.
7618 pub fn export_to_with(
7619 &self,
7620 out: &Path,
7621 settings: &crate::export::ExportSettings,
7622 ) -> crate::ExportHandle {
7623 // The chapter marks, measured from the export's own start (the range's
7624 // `from`, the same clock `chapter_list_ns` uses). A caller's list wins.
7625 let mut settings = settings.clone();
7626 if settings.chapters.is_empty() {
7627 settings.chapters = self.chapter_list_ns(settings.range);
7628 }
7629 let mut snapshot = self.project.export_snapshot();
7630 // A range that never reads a missing file is written without opening it.
7631 if let Some(range) = settings.range {
7632 snapshot.drop_offline_outside(range, crate::source_present);
7633 }
7634 crate::export::start(snapshot, self.meta, out, &settings, self.sample_rate)
7635 }
7636
7637 /// Moves the clock forward; the caller runs this once per rendered frame.
7638 /// Costs an atomic load, and once per session a mode switch.
7639 pub fn tick(&mut self) {
7640 // Before every early return below: where the playhead stands is what the
7641 // decode worker drops its stale pictures against, and a front-end that
7642 // repaints without draining (a slow frame, a busy render thread) must
7643 // still be moving it -- otherwise the queue fills with pictures whose
7644 // moment passed while nobody was taking them.
7645 self.publish_playhead();
7646 // Before the clock-source guard below, and not after it: a dead output is
7647 // what *puts* the clock on wall time, so this branch has to keep running
7648 // while it is there -- the one attempt that can bring the sound back is
7649 // in it.
7650 if self
7651 .audio
7652 .as_ref()
7653 .is_some_and(|audio| audio.died.load(Ordering::Acquire))
7654 {
7655 // Output died mid-stream: its position will never reach `fed`, so the
7656 // EOF comparison below is unreachable. Wall time takes over from
7657 // wherever the clock last stood, and the session says so rather than
7658 // going silent for good without a word: a front-end already has a
7659 // line for a silent session ([`Self::audio_disabled_reason`]).
7660 if self.audio_disabled.is_none() {
7661 self.audio_disabled = Some(AUDIO_LOST.to_string());
7662 }
7663 self.clock.switch_to_wall();
7664 // ...and the output is offered another open, once a second: a
7665 // restarting daemon takes a moment, and this runs once a frame. A
7666 // re-arm that takes is what clears the notice, and the next seek
7667 // feeds it.
7668 self.rearm_audio(AUDIO_REARM_AFTER);
7669 return;
7670 }
7671 let Some(audio) = &self.audio else {
7672 return; // wall time from the start, nothing to poll
7673 };
7674 if self.clock.source() != ClockSource::Audio {
7675 return;
7676 }
7677 // `None` until the device's first callback: the clock holds at its
7678 // anchor rather than guessing, which is why playback starts on time
7679 // instead of a quantum early.
7680 let Some(position) = audio.ao.lock().unwrap().position() else {
7681 return;
7682 };
7683 if audio.played_out(position) {
7684 // Audio EOF. Wall time carries the same timeline on from here, with
7685 // no jump, and this branch cannot be reached again.
7686 //
7687 // The device is stopped with it: nothing will ever be queued for
7688 // this stream again, so every quantum it would go on playing is
7689 // silence counted as a decoder that fell behind -- the tail of a
7690 // stream, where [`crate::ao`]'s own `primed` covers the head of
7691 // one. A seek from here starts it again like any other
7692 // ([`resume`](Self::resume)), which is why the stamp goes with it:
7693 // there is no sample of *this* stream left to start on.
7694 audio.set_playing(false);
7695 audio.content_at.store(-1, Ordering::Release);
7696 self.clock.switch_to_wall();
7697 return;
7698 }
7699 if self.priming {
7700 // A stream that has been started and has not been heard yet: the
7701 // device is playing the silence of its own restart, and none of it
7702 // is timeline time ([`Audio::content_at`]). The clock holds where
7703 // the seek left it -- so the picture holds too, on the frame it
7704 // landed on, rather than sliding ahead of a sound that has not
7705 // started.
7706 let started = audio.content_at.load(Ordering::Acquire);
7707 if started < 0 {
7708 return;
7709 }
7710 // ...and then the *first sample of the stream* becomes the
7711 // reference, not whatever position this poll happened to catch: the
7712 // clock's own anchor is its first report ([`PlaybackClock`]), and
7713 // anchoring it here is what makes a mid-play edit cost no offset.
7714 //
7715 // corner-cut: `started` is the position when the sample was queued,
7716 // and it is heard at the next callback -- up to one quantum (5-21
7717 // ms) later, so that much of the restart is still counted. Upgrade
7718 // path is the position at the first *pop* of real audio, which only
7719 // the plugin's RT thread can see.
7720 self.clock
7721 .set_audio_position(started as u64, audio.sample_rate);
7722 self.priming = false;
7723 }
7724 self.clock
7725 .set_audio_position(position as u64, audio.sample_rate);
7726 }
7727}
7728
7729impl Drop for PlaybackSession {
7730 /// The video workers -- the running one and every cancelled one still in
7731 /// [`retired`](PlaybackSession::retired) -- cancel and join themselves when
7732 /// those fields drop right after this, the running one behind its receiver
7733 /// so a `send` cannot hold the join. *That* is what a session must not exit
7734 /// without: no decode worker outlives it, so none can be inside libva when
7735 /// Mesa's `atexit` handlers free the state under it.
7736 ///
7737 /// This is the audio half: bumping the epoch retires the feeder at its next write,
7738 /// which drops the decode receiver with it. Neither is waited for -- no
7739 /// driver state is torn down on the audio side.
7740 fn drop(&mut self) {
7741 if let Some(audio) = &self.audio {
7742 audio.epoch.fetch_add(1, Ordering::Release);
7743 }
7744 }
7745}
7746
7747/// Whether `path`, already demuxed to `meta`, may join a timeline whose
7748/// parameters are `timeline` and whose audio probes as `first`: a decoder this
7749/// machine can open, audio parameters that agree (or no audio at all), and a
7750/// frame rate that can be named
7751/// against the timeline's. The [`Rate`] it will be read at comes back with the
7752/// answer, so the number the check was decided on is the number it plays by.
7753///
7754/// *Not* the same size any more. A project has its own resolution
7755/// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its
7756/// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
7757/// letterboxed clip rather than a refusal, and so is a frame rate of its own:
7758/// the timeline keeps its own rate and the file is read at [`Rate`] against it
7759/// ([`PlaybackSession::import`] notes how long it is *here*). Nor the same
7760/// codec: every clip opens its own decoder, so a mixed-codec timeline is a
7761/// decoder each rather than a refusal.
7762///
7763/// The `Err` names the property that disagrees, and those strings are what a
7764/// front-end shows verbatim; [`PlaybackSession::import`] and
7765/// [`PlaybackSession::open_project`] share them so a file refused at import is
7766/// refused in the same words at load.
7767fn matches_timeline(
7768 source: &Source,
7769 meta: &VideoMeta,
7770 timeline: &VideoMeta,
7771 first: &Option<crate::AudioProbe>,
7772) -> crate::Result<Rate> {
7773 // The codec is *not* held to the timeline's -- every clip opens its own
7774 // decoder, so an H.264 take and an HEVC one play on one timeline. What the
7775 // codec gate was really protecting against stays, in the one place that
7776 // can actually answer it: on a machine without the VA-API plugin an HEVC
7777 // or VP8 clip would be black frames with the refusal on stderr alone,
7778 // so the file is asked for a decoder *here*, at the door, where the `Err`
7779 // is still something a front-end can show. A zero-length range probes and
7780 // starts no
7781 // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`]
7782 // only enters VA-API off that path.
7783 DecodeSession::open_worker(
7784 &source.path,
7785 0,
7786 0,
7787 ColorParams::default(),
7788 TransformParams::default(),
7789 Composer::passthrough(),
7790 // A zero-length range decodes nothing, so no table is built and the
7791 // rendition cannot matter here.
7792 crate::tonemap::Preset::default(),
7793 )?;
7794 // The frame rate is *not* a refusal any more: a file shot at another rate is
7795 // placed for the seconds it lasts and read through [`Rate`] at the
7796 // decoder's door, so it plays at the speed it was shot at on a timeline
7797 // that counts frames faster or slower.
7798 //
7799 // A rate that cannot be *named* still is, and this is the one place it is
7800 // caught: `Rate::from_fps` builds itself out of the muxer's own timescales,
7801 // and a file whose rate has none of those (a container that says nothing and
7802 // holds one block, so the demuxer measures 0 fps) would otherwise be read
7803 // 1:1 in silence -- the old rate gate refused those too, by arithmetic
7804 // accident. The `Err` is `mux::frame_timing`'s own words.
7805 let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?;
7806 audio_matches(source, first)?;
7807 Ok(rate)
7808}
7809
7810/// Whether a candidate's audio may join a timeline whose first source probes as
7811/// `first`: same layout -- or no audio of its own at all, which is silence over
7812/// the clip's span and agrees with everything. One output device and one
7813/// exported track is all there is, so one width; the *rate* is conformed rather
7814/// than matched ([`crate::audio::Resample`]), which is why it is not asked
7815/// about here.
7816///
7817/// The audio half of [`matches_timeline`], which a stream placed on its own
7818/// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
7819/// comes with is already on the timeline.
7820///
7821/// The format itself is deliberately *not* part of this: an mp3 that agrees on
7822/// layout plays alongside a timeline of mp4s perfectly well. What it
7823/// cannot do is be copied into an export, which is a refusal of its own, at
7824/// export time (`AudioSession::copy_multi_streams`).
7825/// What a timeline's audio is held to: the probe of the first source that could
7826/// have any track.
7827///
7828/// The probe of the first source that really **has a track**, walking forward
7829/// past a still (no track by definition) and past a source whose file carries
7830/// none (a screen recording with no sound). A silent leading source must not
7831/// pin the timeline's layout: pinned to it, a later file with sound could never
7832/// be admitted, and the layout a *following* file is held to would be the
7833/// silent source's `None`. This is the same walk
7834/// [`PlaybackSession::open_project`] makes when it opens the device -- the two
7835/// have to agree, so probing and opening can never name different sources.
7836///
7837/// `Ok(None)` for a timeline with no track anywhere: nothing but stills, with
7838/// no file at all, or every non-still source silent. That is a silent timeline,
7839/// and a file with sound is admitted onto it -- it *becomes* the timeline's
7840/// sound ([`PlaybackSession::arm_audio`] opens the device for it), exactly the
7841/// c581d41 rule ("a later source with real audio must be heard") at the add
7842/// door.
7843fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
7844 for source in sources
7845 .iter()
7846 .filter(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
7847 {
7848 if let Some(probe) = AudioSession::probe(&source.path, source.audio_stream)? {
7849 return Ok(Some(probe));
7850 }
7851 }
7852 Ok(None)
7853}
7854
7855/// Whether a file is sound and no picture, which decides the lane it goes on.
7856/// The extension answers for a song; an mp4 or Matroska file is asked of its
7857/// header the way [`PlaybackSession::import`] asks it, so an audio-only mp4
7858/// lands on an audio lane exactly as it imports and reopens.
7859fn sound_only(path: &Path) -> bool {
7860 if crate::is_audio(path) {
7861 return true;
7862 }
7863 if crate::is_image(path) {
7864 return false;
7865 }
7866 matches!(Demuxer::open(path), Err(ref e) if NoVideoTrack::is_it(e))
7867}
7868
7869/// *Which* source that is: the first one that is not a still. The single answer
7870/// to "what does this timeline's sound come from", so that probing it
7871/// ([`first_audio_of`]) and opening the device on it
7872/// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only
7873/// the scaffolding file until a save renumbers it or a library removal takes it
7874/// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the
7875/// device is a timeline that plays silent although every clip on it has sound.
7876///
7877/// `None` for a library of nothing but stills, and for one with no file at all:
7878/// both are silent timelines.
7879fn audio_source_of(sources: &[Source]) -> Option<&Source> {
7880 sources
7881 .iter()
7882 .find(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
7883}
7884
7885fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
7886 let probe = AudioSession::probe(&source.path, source.audio_stream)?;
7887 audio_matches_probed(probe, first)
7888}
7889
7890/// The verdict alone, once the file's own header is in hand: the half a session
7891/// with a memo behind it ([`PlaybackSession::audio_matches_cached`]) does not
7892/// have to open the file for.
7893fn audio_matches_probed(
7894 probe: Option<crate::AudioProbe>,
7895 first: &Option<crate::AudioProbe>,
7896) -> crate::Result<()> {
7897 // The layout, which the audio worker holds every source to anyway -- and not
7898 // the rate any more: a file written at another one is resampled to the
7899 // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as
7900 // a file shot at another frame rate is read through [`Rate`]. Both silent is
7901 // a match.
7902 if probe.map(|p| p.channels) == first.map(|p| p.channels) {
7903 return Ok(());
7904 }
7905 // A mono file joins a wider timeline: [`crate::audio::widen`] duplicates
7906 // its one channel into every channel the timeline carries, the inverse of
7907 // the [`crate::audio::downmix`] a wider file already folds through. A
7908 // wider file onto a mono timeline -- beyond a stereo pair -- stays refused
7909 // below; the stereo pair is narrowed by [`crate::audio::widen`] (below).
7910 if let (Some(p), Some(b)) = (probe, first)
7911 && p.channels == 1
7912 && b.channels > 1
7913 {
7914 return Ok(());
7915 }
7916 // ...and a stereo file joins a mono timeline: [`crate::audio::widen`]
7917 // averages its pair into the one channel the timeline carries. Import and
7918 // open both come through here, so a project this accepts always reopens.
7919 if let (Some(p), Some(b)) = (probe, first)
7920 && p.channels == 2
7921 && b.channels == 1
7922 {
7923 return Ok(());
7924 }
7925 // ...and a *silent* file joins whatever the timeline is: it contributes
7926 // silence over its span, which is the very thing both audio paths already
7927 // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays
7928 // it, `AudioSession::copy_multi_streams` writes it). There is no rate and
7929 // no layout to disagree about, so there is nothing left to refuse.
7930 let Some(probe) = probe else {
7931 return Ok(());
7932 };
7933 // The timeline has no track anywhere (nothing but stills, or every
7934 // non-image source silent): there is no layout to disagree with, and the
7935 // arriving file with sound *becomes* the timeline's sound --
7936 // [`PlaybackSession::arm_audio`] opens the device for it, exactly the walk
7937 // [`PlaybackSession::open_project`] makes. Refusing here ("the file has
7938 // audio, the timeline is silent") pinned the timeline to its silent first
7939 // source for good: remove that file and add another, and the second file's
7940 // sound could never be heard.
7941 let Some(b) = first else {
7942 return Ok(());
7943 };
7944 Err(format!(
7945 "audio {} ch does not match the timeline's {} ch",
7946 probe.channels, b.channels
7947 )
7948 .into())
7949}
7950
7951/// How many timeline frames a still image is *held to*: [`IMAGE_MAX_SECS`] of
7952/// them, since an image has no length of its own. The number a source's own
7953/// entry in [`PlaybackSession::counts`] gets, so a trim may drag an image out
7954/// to ten minutes and no further -- and so a saved project reloads, because
7955/// [`PlaybackSession::open_project`] recomputes exactly this and refuses a clip
7956/// that ends past it.
7957fn image_frames(fps: f64) -> u32 {
7958 ((IMAGE_MAX_SECS * fps)
7959 .ceil()
7960 .clamp(1.0, f64::from(u32::MAX))) as u32
7961}
7962
7963/// How long a still is placed for: `secs` (the project's still length), never past the length
7964/// it is held to and never zero (a clip is never empty).
7965fn place_frames(count: u32, fps: f64, secs: f64) -> u32 {
7966 ((secs * fps)
7967 .ceil()
7968 .clamp(1.0, f64::from(count.max(1)))) as u32
7969}
7970
7971/// The project one document of a file describes, on the canvas and rate `meta` gives it.
7972fn project_of(doc: crate::edith::Document, meta: &VideoMeta) -> crate::Result<Project> {
7973 let subtitles = crate::subtitle::open_all(&doc.subtitles);
7974 Ok(
7975Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)?
7976 .with_mix(&doc.gains, doc.limiter)
7977 .with_ducks(&doc.ducks)
7978 .with_voices(&doc.voices)
7979 .with_lane_names(&doc.names)
7980 .with_bins(doc.bins)
7981 .with_lane_flags(&doc.flags)
7982 .with_tone(doc.tone)
7983 .with_notes(doc.notes)
7984 .with_still_secs(doc.still_secs)
7985 .with_speech(doc.speech_model, doc.speech_device)
7986 // The palette before what is placed on it: a caption names a row of
7987 // it, and [`Project::with_subs`] refuses one naming a row that is
7988 // not there.
7989 .with_subtitles(subtitles)
7990 .with_sub_langs(&doc.sub_langs)
7991 // The cue overrides, over the words the files gave: a retyped
7992 // cue comes back as it was typed.
7993 .with_cue_edits(&doc.cue_edits)
7994 // ...and the cues added to a track, after the file's own, each at
7995 // its start (see [`crate::edith`]'s `cueadd` lines).
7996 .with_cue_adds(&doc.cue_adds)
7997 // The title cards and text overlays, in the order the file has them.
7998 .with_titles(doc.titles)
7999 // The chapter markers, in frame order (see [`crate::edith`]'s `chapter` lines).
8000 .with_chapters(doc.chapters)
8001 // The comment markers, in frame order (`marker` lines).
8002 .with_markers(doc.markers)
8003 .with_cue_words(&doc.cue_words)
8004 .with_caption_style(doc.caption_style)
8005 .with_subs(doc.subs)?
8006 // The header a load puts back: the canvas and rate above, which a
8007 // save's own `resolution`/`fps` lines may have moved off the
8008 // scaffold's, and the switches the literal below carries -- handed
8009 // in here because they are the project's own and a door that moved
8010 // one after this would snapshot whatever copy it holds, which until
8011 // this line is the placeholder's. No undo step for
8012 // [`Project::with_mix`]'s reason: a project that arrived one `z`
8013 // from a state it was never in is a project whose first undo is a
8014 // surprise.
8015 .with_canvas(meta.width, meta.height, meta.frame_rate)
8016 .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate)
8017 )
8018}
8019
8020/// The two tables a trim measures by, `(picture, sound)`: [`wall_table`] for a
8021/// video lane and for an audio one, so a linked take's members each meet their
8022/// own lane's length. Borrows `counts` only, so the caller may hold them across
8023/// a `&mut` to the project.
8024fn lane_walls<'a>(
8025 sources: &[Source],
8026 counts: &'a [u32],
8027 fps: f64,
8028) -> (Cow<'a, [u32]>, Cow<'a, [u32]>) {
8029 (
8030 wall_table(sources, counts, fps, Lane::V1),
8031 wall_table(sources, counts, fps, Lane::A1),
8032 )
8033}
8034
8035/// The length each source's clips are walled by on `lane`, in timeline frames.
8036/// A clip on an audio lane takes the sound, so a video source's own audio stream
8037/// sets its length there (the picture's frame count is the length everywhere
8038/// else, and `counts` is that table). Stills and audio files already are their
8039/// sound's length in `counts`, and a source with no audio stream keeps its
8040/// `counts` entry. Mirrors the length `place` gives an audio-lane placement in
8041/// the MCP (`source_frames`).
8042fn wall_table<'a>(sources: &[Source], counts: &'a [u32], fps: f64, lane: Lane) -> Cow<'a, [u32]> {
8043 if lane.kind != LaneKind::Audio {
8044 return Cow::Borrowed(counts);
8045 }
8046 Cow::Owned(
8047 sources
8048 .iter()
8049 .zip(counts)
8050 .map(|(source, &frames)| {
8051 if crate::is_image(&source.path) || crate::is_audio(&source.path) {
8052 return frames;
8053 }
8054 match audio_stream_secs(&source.path, source.audio_stream) {
8055 Some(secs) if secs > 0.0 => (secs * fps).ceil().clamp(1.0, f64::from(u32::MAX)) as u32,
8056 _ => frames,
8057 }
8058 })
8059 .collect(),
8060 )
8061}
8062
8063/// How long a placed file's clip is: its picture's frame count, held to the length
8064/// its sound is walled by ([`wall_table`]) when it has one. A grouped take puts the
8065/// same clip on the picture lane and the sound lane, so a 2.002 s picture beside a
8066/// 2.000 s sound is 60 frames, not 61 -- the sound's own wall is what the load and
8067/// save checks hold the audio lane to, and one clip must satisfy both lanes.
8068fn sound_held_frames(path: &Path, stream: usize, frames: u32, fps: f64) -> u32 {
8069 if crate::is_image(path) || crate::is_audio(path) {
8070 return frames.max(1);
8071 }
8072 match audio_stream_secs(path, stream) {
8073 Some(secs) if secs > 0.0 => {
8074 let held = (secs * fps).ceil().clamp(1.0, f64::from(u32::MAX)) as u32;
8075 frames.min(held).max(1)
8076 }
8077 _ => frames.max(1),
8078 }
8079}
8080
8081/// [`AudioSession::stream_duration_secs`] for one stream, remembered per file:
8082/// a trim asks for it on every drag step. Only a found length is kept; a file
8083/// that cannot be read now may be back in a moment.
8084fn audio_stream_secs(path: &Path, stream: usize) -> Option<f64> {
8085 static SECS: std::sync::OnceLock<Mutex<std::collections::HashMap<(PathBuf, usize), f64>>> =
8086 std::sync::OnceLock::new();
8087 let cache = SECS.get_or_init(Default::default);
8088 let key = (path.to_path_buf(), stream);
8089 if let Some(&secs) = cache.lock().ok()?.get(&key) {
8090 return Some(secs);
8091 }
8092 let secs = AudioSession::stream_duration_secs(path, stream).ok()??;
8093 cache.lock().ok()?.insert(key, secs);
8094 Some(secs)
8095}
8096
8097/// How many timeline frames a standalone audio file occupies: its playing time
8098/// rounded *up*, so the last partial frame is still covered rather than cut off,
8099/// and never zero (a clip is never empty).
8100fn audio_frames(path: &Path, fps: f64) -> crate::Result<u32> {
8101 let secs = AudioSession::duration_secs(path)?
8102 .ok_or_else(|| format!("{} has no audio track", path.display()))?;
8103 let frames = (secs * fps).ceil();
8104 if !frames.is_finite() || frames < 0.0 || frames > f64::from(u32::MAX) {
8105 return Err(format!(
8106 "{} is {secs} s long, which is not a timeline",
8107 path.display()
8108 )
8109 .into());
8110 }
8111 Ok((frames as u32).max(1))
8112}
8113
8114/// `None` for a silent session -- no audio track, no plugin, no daemon, or a
8115/// track the decoder refuses. Dropping the receiver on the way out stops the
8116/// audio decode worker, so a failure here leaves nothing running.
8117///
8118/// The second half is why, for the cases the *file* is to blame for: those are
8119/// a surprise worth showing (see
8120/// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a
8121/// file with no audio at all and a machine with no output device are not.
8122fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
8123 let sources = [(path.to_path_buf(), stream)];
8124 let (meta, rx) =
8125 match AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) {
8126 Ok(Some(opened)) => opened,
8127 // No AAC track: silent by nature, or sound in a codec we do not
8128 // have -- and only the second of those is worth a word.
8129 Ok(None) => {
8130 let reason = AudioSession::unsupported(path).ok().flatten();
8131 if let Some(reason) = &reason {
8132 crate::audio::debug_once(format!("audio disabled: {reason}"));
8133 }
8134 return (None, reason);
8135 }
8136 Err(e) => {
8137 crate::audio::debug_once(format!("audio disabled: {e}"));
8138 return (None, Some(e.to_string()));
8139 }
8140 };
8141 let Some(ao) = AoSession::open(meta.sample_rate, u32::from(meta.channels)) else {
8142 return (None, None); // no device: the machine's business, not the file's
8143 };
8144 // The stream comes up streaming; a session starts paused, so silence the
8145 // device until `play`. The feeder still fills the ring in the meantime.
8146 ao.set_active(false);
8147
8148 let audio = Audio {
8149 ao: Arc::new(Mutex::new(ao)),
8150 sample_rate: meta.sample_rate,
8151 channels: u64::from(meta.channels),
8152 fed: Arc::new(AtomicU64::new(0)),
8153 fed_all: Arc::new(AtomicBool::new(false)),
8154 died: Arc::new(AtomicBool::new(false)),
8155 epoch: Arc::new(AtomicU64::new(0)),
8156 content_at: Arc::new(AtomicI64::new(-1)),
8157 gain: Arc::new(AtomicU32::new(1.0f32.to_bits())),
8158 wants_active: Arc::new(AtomicBool::new(false)),
8159 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),
8160 peak: Arc::new(AtomicU32::new(0)),
8161 peak_lr: Arc::new([AtomicU32::new(0), AtomicU32::new(0)]),
8162 feeders: Arc::new(AtomicUsize::new(0)),
8163 rearm_at: Arc::new(Mutex::new(None)),
8164 };
8165 (audio.spawn_feeder(rx).then_some(audio), None)
8166}
8167
8168/// Pours decoded chunks into the device, keeping whatever the ring would not
8169/// take. Ends when the decoder is done, the output dies, or a seek supersedes
8170/// this feeder.
8171fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
8172 let mut pending: Vec<f32> = Vec::new();
8173 loop {
8174 if pending.is_empty() {
8175 match rx.recv() {
8176 Ok(chunk) => pending = chunk.samples,
8177 Err(_) => {
8178 // Decoder finished or went away. What is in the ring still
8179 // plays out; what comes after it is the end of the timeline
8180 // and not a decoder that fell behind, so the device is told
8181 // to stop counting it. Under the lock and past the epoch,
8182 // like every other word this thread has with the device: a
8183 // superseded feeder must not say this about the stream that
8184 // replaced it.
8185 let ao = audio.ao.lock().unwrap();
8186 if audio.epoch.load(Ordering::Acquire) == epoch {
8187 ao.stream_ended();
8188 }
8189 return;
8190 }
8191 }
8192 }
8193 let accepted = {
8194 let mut ao = audio.ao.lock().unwrap();
8195 // Under the lock, immediately before the write: `seek` bumps the
8196 // epoch and flushes the ring holding this very lock, so past this
8197 // check no stale sample can be queued behind the flush.
8198 if audio.epoch.load(Ordering::Acquire) != epoch {
8199 return;
8200 }
8201 let accepted = match ao.write(&pending) {
8202 Some(n) => n,
8203 None => {
8204 // Output died; flag it so `tick` moves the clock to wall time.
8205 audio.died.store(true, Ordering::Release);
8206 return;
8207 }
8208 };
8209 // The first sample of this stream to reach the ring, stamped with
8210 // what the device had played by then: everything before it was the
8211 // silence of the restart, and [`PlaybackSession::tick`] anchors the
8212 // clock here so that silence is never timeline time. Under the
8213 // device lock, with the epoch already checked, so the stamp and the
8214 // sample belong to the same stream.
8215 if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 {
8216 let at = ao.position().unwrap_or(0).max(0);
8217 audio.content_at.store(at, Ordering::Release);
8218 // ...and the device position this stream's samples are counted
8219 // from ([`Audio::played_out`]). Rebased *here* rather than at
8220 // the seek, because the open runs on this thread now: every
8221 // millisecond it took is device time nobody fed, and counting
8222 // it would make the stream read as played out that long before
8223 // it really is -- an early hand-off to wall time at the end of
8224 // the timeline. The seek's own rebase still stands for the
8225 // stream that never queues a sample at all.
8226 audio
8227 .fed
8228 .store(at as u64 * audio.channels, Ordering::Relaxed);
8229 // ...and *this* is where a playing timeline's device starts: on
8230 // the first sample there is to play, under the same lock and
8231 // past the same epoch check as the stamp, so the silence of the
8232 // open was never played and never counted
8233 // ([`Audio::wants_active`]).
8234 if audio.wants_active.load(Ordering::Acquire) {
8235 ao.set_active(true);
8236 }
8237 } else if accepted == 0 && audio.content_at.load(Ordering::Acquire) < 0 {
8238 // Nothing taken with nothing yet queued is the *flush* of the
8239 // restart still standing: the ring refuses a write until a
8240 // callback has consumed the flag (`engine_audio::accept`), and
8241 // only a running device has callbacks. So the device is started
8242 // here too -- there is a sample in hand, which is what the wait
8243 // was for -- and the quantum or two of that handshake is the
8244 // silence `Shared::primed` does not count.
8245 if audio.wants_active.load(Ordering::Acquire) {
8246 ao.set_active(true);
8247 }
8248 }
8249 accepted
8250 };
8251 audio.fed.fetch_add(accepted as u64, Ordering::Relaxed);
8252 audio.note_tap(&pending[..accepted]);
8253 pending.drain(..accepted);
8254 if !pending.is_empty() {
8255 // Ring full: nothing to do but let the device drain it. Except when
8256 // *nothing* was taken, which after a flush means the ring is still
8257 // waiting for the device to consume the flush flag rather than
8258 // being full: that is the head of a restart, and every millisecond
8259 // spent parked there is a millisecond of silence.
8260 match accepted {
8261 0 => thread::sleep(FLUSH_WAIT),
8262 _ => thread::sleep(RING_FULL_WAIT),
8263 }
8264 }
8265 }
8266}
8267
8268/// The stretch of the timeline that ends at `frame` (inclusive) and starts where
8269/// whatever is shown there starts: [`crate::export::stack_span_at`] at that
8270/// start, cut short at `frame`. What a backward play draws, from `frame` down.
8271fn back_span_at(project: &Project, frame: u32) -> Option<crate::project::Span> {
8272 let mut lo = 0;
8273 let visible = project
8274 .lanes()
8275 .into_iter()
8276 .filter(|lane| lane.kind == LaneKind::Video && !project.lane_hidden(*lane));
8277 for lane in visible {
8278 let clips = project.lane(lane);
8279 let from = match project.lane_clip_at(lane, frame) {
8280 Some(idx) => clips[idx].start,
8281 None => clips.iter().rfind(|c| c.end() <= frame).map_or(0, |c| c.end()),
8282 };
8283 lo = lo.max(from);
8284 }
8285 let mut span = crate::export::stack_span_at(project, lo)?;
8286 span.len = span.len.min(frame + 1 - lo);
8287 Some(span)
8288}
8289
8290/// Timeline seconds to a 0-based frame index, floor semantics: position `t`
8291/// shows the frame whose interval contains it. The epsilon absorbs float error
8292/// at exact frame boundaries -- `123.0/30.0 * 30.0` is `122.999...`, and a
8293/// bare truncation would land one frame early (S6 finding: 4 of every 300
8294/// frames round-trip wrong through `clip_spans()` seconds without this).
8295fn secs_to_frame(secs: f64, fps: f64) -> u32 {
8296 (secs * fps + 1e-6).floor().max(0.0) as u32
8297}
8298
8299/// Per-byte lerp of two same-sized BGRA8 frames -- [`crate::scale::blend_i420`]'s
8300/// interleaved-buffer twin. By the time a picture reaches [`try_frame`]
8301/// (`PlaybackSession::try_frame`) it is already colour-converted for the
8302/// screen, so there are no separate Y/U/V planes left to blend, only the one
8303/// buffer; straight alpha survives the lerp untouched (255 against 255 is
8304/// still 255). `t` is B's weight, [`crate::export::dissolve_weight`]'s own
8305/// convention.
8306fn blend_bgra(a: &[u8], b: &[u8], t: f32) -> Vec<u8> {
8307 let t = t.clamp(0.0, 1.0);
8308 assert_eq!(a.len(), b.len(), "blend_bgra: mismatched frame sizes");
8309 a.iter()
8310 .zip(b)
8311 .map(|(&av, &bv)| (av as f32 + (bv as f32 - av as f32) * t).round() as u8)
8312 .collect()
8313}
8314
8315/// A chapter time as YouTube writes one in a description: `MM:SS`, or `H:MM:SS` from an hour on.
8316/// The frame is floored to whole seconds.
8317pub fn youtube_time(frame: u32, fps: f64) -> String {
8318 let secs = (f64::from(frame) / fps).floor() as u64;
8319 let (h, m, sec) = (secs / 3600, (secs % 3600) / 60, secs % 60);
8320 if h > 0 {
8321 format!("{h}:{m:02}:{sec:02}")
8322 } else {
8323 format!("{m:02}:{sec:02}")
8324 }
8325}
8326
8327/// The YouTube description listing for `chapters` (frame, name, sorted by frame) and the warnings
8328/// its rules call for: the first chapter at 00:00, each chapter at least 10 seconds long (the last
8329/// runs to `end`), and at least 3 chapters. Empty when there are none.
8330pub fn chapter_listing(chapters: &[(u32, String)], fps: f64, end: u32) -> (String, Vec<String>) {
8331 if chapters.is_empty() {
8332 return (String::new(), Vec::new());
8333 }
8334 let listing = chapters
8335 .iter()
8336 .map(|(f, t)| format!("{} {t}", youtube_time(*f, fps)))
8337 .collect::<Vec<_>>()
8338 .join("\n");
8339 let mut warnings = Vec::new();
8340 if chapters[0].0 != 0 {
8341 warnings.push(format!(
8342 "the first chapter starts at {}, not 00:00: YouTube needs one at 00:00",
8343 youtube_time(chapters[0].0, fps)
8344 ));
8345 }
8346 for (i, (frame, title)) in chapters.iter().enumerate() {
8347 let next = chapters.get(i + 1).map_or(end, |c| c.0);
8348 let secs = f64::from(next.saturating_sub(*frame)) / fps;
8349 if secs < 10.0 {
8350 warnings.push(format!("chapter \"{title}\" at {} lasts {secs:.1} s: YouTube wants 10 s or more", youtube_time(*frame, fps)));
8351 }
8352 }
8353 if chapters.len() < 3 {
8354 warnings.push(format!("YouTube needs at least 3 chapters; this timeline has {}", chapters.len()));
8355 }
8356 (listing, warnings)
8357}
8358
8359#[cfg(test)]
8360mod tests {
8361 use super::{
8362 SCRUB_SECS, scrub_snippet, AUDIO_LOST, Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of,
8363 blend_bgra, secs_to_frame,
8364 };
8365 use std::path::PathBuf;
8366 use std::sync::atomic::Ordering;
8367
8368 fn asset(name: &str) -> PathBuf {
8369 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8370 .join("../../assets")
8371 .join(name)
8372 }
8373
8374 /// A scrub snippet is the window it was cut from, as long as [`SCRUB_SECS`], and it rises
8375 /// from silence and falls to it again over its fades, so no edge of it can click.
8376 #[test]
8377 fn a_scrub_snippet_is_the_window_long_and_faded_at_both_ends() {
8378 let rate = 48_000u32;
8379 let frames = (SCRUB_SECS * f64::from(rate)) as usize;
8380 assert_eq!(frames, 3360, "70 ms at 48 kHz");
8381 let fade = (0.01 * f64::from(rate)) as usize;
8382 let src = vec![1.0f32; frames * 2];
8383 let out = scrub_snippet(&src, 2, fade);
8384 assert_eq!(out.len(), frames * 2, "the window's length, both channels");
8385 assert!(out[0].abs() < 0.01 && out[1].abs() < 0.01, "starts at silence: {:?}", &out[..2]);
8386 let last = out.len() - 2;
8387 assert!(out[last].abs() < 0.01 && out[last + 1].abs() < 0.01, "ends at silence");
8388 let mid = frames / 2 * 2;
8389 assert_eq!((out[mid], out[mid + 1]), (1.0, 1.0), "the middle is untouched");
8390 for f in 1..fade {
8391 assert!(out[2 * f] >= out[2 * (f - 1)], "the fade in rises at frame {f}");
8392 let tail = out.len() - 2 * (f + 1);
8393 assert!(out[tail] >= out[tail + 2], "the fade out falls toward the end at frame {f}");
8394 }
8395 // A window shorter than twice the fade has its fade held to half of it.
8396 let short = scrub_snippet(&[1.0; 8], 1, 100);
8397 assert_eq!(short.len(), 8);
8398 assert!(short[0].abs() < 0.5 && short[7].abs() < 0.5, "{short:?}");
8399 assert!(scrub_snippet(&[1.0; 8], 0, 2).len() == 8, "a zero width is read as mono");
8400 }
8401
8402 /// The crash path: a saved project with several sequences (one of them a compound clip
8403 /// over another, plus a marker) is written as an autosave and read back, and the autosave
8404 /// on top of the saved file recovers to the same sequences, compound clips and markers.
8405 #[test]
8406 fn autosave_round_trips_every_sequence_compound_and_marker() {
8407 let dir = crate::scratch::Scratch::dir("ve_sidecar_round_trip");
8408 let media = dir.join("film.mp4");
8409 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture");
8410 let path = dir.join("proj.edith");
8411 let s = PlaybackSession::open(&media).expect("open the fixture");
8412 s.set_gain(0.0);
8413 s.save_project_noted(&path).expect("save the base");
8414 let mut s = PlaybackSession::open_project(&path).expect("reopen the base");
8415 let b = s.new_sequence(Some("Cut B")).expect("a second sequence");
8416 s.switch_sequence(b).expect("switch to it");
8417 assert!(s.place_stream_at(0.0, &media, 0, None).expect("placeable"));
8418 let copy = s.duplicate_sequence(b).expect("duplicate it");
8419 s.switch_sequence(copy).expect("switch to the copy");
8420 s.nest(&[(Lane::V1, 0)], Some("Inner")).expect("nest a clip");
8421 assert_eq!(s.project.sequences().len(), 4, "the base, B, its copy and the nested one");
8422 s.add_marker(crate::project::Marker {
8423 frame: 3,
8424 length: 0,
8425 name: "beat".into(),
8426 note: String::new(),
8427 color: crate::project::MarkerColor::Red,
8428 })
8429 .expect("a marker");
8430 assert_eq!(s.project.markers().len(), 1, "the marker is on the sequence being edited");
8431 let sidecar = dir.join("proj.autosave.edith");
8432 s.save_autosave(&sidecar).expect("the autosave");
8433 let back = PlaybackSession::open_project(&sidecar).expect("the autosave opens");
8434 assert_eq!(back.project.sequences(), s.project.sequences(), "the same sequences, in order");
8435 assert_eq!(back.project.active_sequence(), s.project.active_sequence());
8436 assert_eq!(back.project.markers().len(), 1, "the marker comes back");
8437 assert_eq!(back.project.markers()[0].name, "beat");
8438 // The recovery path: the saved file, with the autosave on top of it.
8439 let mut saved = PlaybackSession::open_project(&path).expect("the saved file");
8440 assert!(saved.adopt_as_step(&back), "the autosave lands on the saved file");
8441 assert_eq!(saved.project.sequences(), s.project.sequences(), "recovery holds every sequence");
8442 assert_eq!(saved.project.markers().len(), 1, "and the marker");
8443 }
8444
8445 /// A clip past its source's end in a parked sequence is shortened on save, just as in the
8446 /// active one, and the save says which sequence it was in. It is never refused.
8447 #[test]
8448 fn save_shortens_the_parked_sequences_over_wall_clips() {
8449 let dir = crate::scratch::Scratch::dir("ve_save_parked_walls");
8450 let media = dir.join("film.mp4");
8451 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture");
8452 let mut s = PlaybackSession::open(&media).expect("open the fixture");
8453 s.set_gain(0.0);
8454 let copy = s.duplicate_sequence(s.project.active_sequence()).expect("duplicate");
8455 let copy_name = s.project.sequence_name(copy).expect("the copy is named").to_string();
8456 let path = dir.join("proj.edith");
8457 assert!(s.save_project_noted(&path).expect("whole walls save").is_empty());
8458 s.counts[0] = 1;
8459 let notes = s.save_project_noted(&path).expect("the save never refuses");
8460 assert!(notes.iter().any(|n| n.contains(&format!("in sequence \"{copy_name}\""))), "{notes:?}");
8461 assert!(notes.iter().all(|n| !n.contains("frame")), "no frame numbers in a note: {notes:?}");
8462 PlaybackSession::open_project(&path).expect("the saved file opens");
8463 }
8464
8465 /// A video file whose sound is shorter than its picture (a 22.96 s picture under 20.67 s of
8466 /// sound): the timeline it opens to holds the grouped take to the sound's length, so an
8467 /// edit chain that splits, ripple-deletes and dissolves saves without a refusal and leaves
8468 /// no audio clip past the sound's end.
8469 #[test]
8470 fn a_picture_longer_than_its_sound_saves_after_edits() {
8471 let dir = crate::scratch::Scratch::dir("ve_short_sound_edits");
8472 let media = dir.join("speech.mp4");
8473 let made = std::process::Command::new("ffmpeg")
8474 .args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=160x120:rate=25:duration=22.96",
8475 "-f", "lavfi", "-i", "sine=frequency=440:duration=20.67", "-c:v", "mpeg4", "-c:a", "aac"])
8476 .arg(&media)
8477 .status()
8478 .map(|s| s.success() && media.exists())
8479 .unwrap_or(false);
8480 if !made {
8481 eprintln!("no ffmpeg: a picture longer than its sound cannot be generated, skipping");
8482 return;
8483 }
8484 let mut s = PlaybackSession::open(&media).expect("open the fixture");
8485 s.set_gain(0.0);
8486 let sound_frames = 517;
8487 assert_eq!(s.lane_clips(Lane::A1)[0].out_frame, sound_frames, "the opened take is the sound's length");
8488 assert_eq!(s.lane_clips(Lane::V1)[0].out_frame, sound_frames, "and so is its picture");
8489
8490 let path = dir.join("proj.edith");
8491 assert!(s.cut_at(5.0));
8492 assert!(s.cut_regions(&[(50, 100)], &[Lane::V1, Lane::A1]).is_ok());
8493 assert!(s.set_transition_out(Lane::V1, 0, 10));
8494 assert!(s.place_stream_at(0.0, &media, 0, None).expect("placeable"));
8495 let notes = s.save_project_noted(&path).expect("the edited take saves");
8496 assert!(notes.is_empty(), "nothing needed shortening: {notes:?}");
8497 for lane in [Lane::V1, Lane::A1] {
8498 for c in s.lane_clips(lane) {
8499 assert!(c.out_frame <= sound_frames, "{lane:?} clip ends at {} past the sound", c.out_frame);
8500 }
8501 }
8502 }
8503
8504 /// A relink is one undo step on the session too: undo points the source back at the old file,
8505 /// which reads again (no longer offline), and redo points it at the new one.
8506 #[test]
8507 fn undoing_a_relink_reads_the_old_file_again() {
8508 let dir = crate::scratch::Scratch::dir("ve_relink_undo_session");
8509 let media = dir.join("film.mp4");
8510 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture");
8511 let session = PlaybackSession::open(&media).expect("open the fixture");
8512 session.set_gain(0.0);
8513 let path = dir.join("proj.edith");
8514 session.save_project(&path).expect("save");
8515 let moved = dir.join("moved.mp4");
8516 std::fs::rename(&media, &moved).expect("move the media");
8517
8518 let mut s = PlaybackSession::open_project(&path).expect("opens offline");
8519 assert_eq!(s.offline_sources().len(), 1);
8520 s.relink_source(0, &moved).expect("relinks");
8521 assert!(s.offline_sources().is_empty());
8522 std::fs::copy(&moved, &media).expect("the old file is back beside it");
8523 assert!(s.undo());
8524 assert_eq!(s.sources()[0].path, std::fs::canonicalize(&media).expect("canonical"));
8525 assert!(s.offline_sources().is_empty(), "the old file reads again");
8526 assert!(s.redo());
8527 assert_eq!(s.sources()[0].path, std::fs::canonicalize(&moved).expect("canonical"));
8528 }
8529
8530 /// A dead output is not the end of a session's sound.
8531 ///
8532 /// The stream is stopped the way a seek stops one and then flagged the way a
8533 /// failed write flags it ([`feed`]): nothing is feeding and nothing will. The
8534 /// session must say so -- a dead output used to hand the clock to wall time
8535 /// in silence, for the rest of the session's life, through every seek -- and
8536 /// the play (and the seek after it) must put the output back, which is read
8537 /// off the tap: the samples that actually reached the device. A session that
8538 /// only switched the clock leaves the tap empty.
8539 ///
8540 /// The tick below runs with the cooldown already spent (an attempt stamped
8541 /// just now), which is what makes the notice observable at all *and* what
8542 /// proves the one thing a frame-rate poll must not do: open a device that is
8543 /// gone for good sixty times a second.
8544 #[test]
8545 fn a_dead_output_is_rearmed_and_the_sound_comes_back() {
8546 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8547 assert!(
8548 session.audio_tap().is_some(),
8549 "test_av.mp4 carries an audio track, which is what this drives"
8550 );
8551
8552 session.stop_audio();
8553 let audio = session.audio.as_ref().expect("audio");
8554 audio.died.store(true, Ordering::Release);
8555 *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now());
8556
8557 session.tick();
8558 assert_eq!(
8559 session.audio_disabled_reason(),
8560 Some(AUDIO_LOST),
8561 "a dead output went to wall time without a word"
8562 );
8563 assert!(
8564 session
8565 .audio
8566 .as_ref()
8567 .expect("audio")
8568 .died
8569 .load(Ordering::Acquire),
8570 "a tick opened the output again inside the cooldown"
8571 );
8572 assert!(
8573 session.audio_tap().expect("audio").0.is_empty(),
8574 "something was still feeding the device"
8575 );
8576
8577 // Playing is the ask that is not throttled: the output is opened again,
8578 // the flag clears and a feeder fills the device -- asynchronously, so the
8579 // tap is waited on.
8580 session.play();
8581 session.seek(1.0);
8582 let mut fed = Vec::new();
8583 for _ in 0..200 {
8584 fed = session.audio_tap().expect("audio").0;
8585 if !fed.is_empty() {
8586 break;
8587 }
8588 std::thread::sleep(std::time::Duration::from_millis(5));
8589 }
8590 assert!(
8591 !fed.is_empty(),
8592 "playing after a dead output fed nothing: the session cannot come back"
8593 );
8594 assert!(
8595 !session
8596 .audio
8597 .as_ref()
8598 .expect("audio")
8599 .died
8600 .load(Ordering::Acquire),
8601 "the death flag stood after the output was replaced"
8602 );
8603 assert_eq!(
8604 session.audio_disabled_reason(),
8605 None,
8606 "the notice was left standing over a session that is playing again"
8607 );
8608 }
8609
8610 /// A monitoring level is state, and a device replaced under the session is
8611 /// a new object that knows nothing about it: the re-armed stream came up
8612 /// at full volume, so a session playing muted while PipeWire restarted
8613 /// came back loud with the toolbar still reading "muted". The gain is
8614 /// therefore read back *from the device* ([`PlaybackSession::gain`]) and
8615 /// put back onto the replacement.
8616 ///
8617 /// The silent sink is what makes this a state round-trip rather than a
8618 /// claim about ears: it keeps the gain it was given, so the level after a
8619 /// re-arm is a number this process can read, and a plain open with no gain
8620 /// ever pushed is the control that says 1.0 is a real default rather than
8621 /// a leftover.
8622 #[test]
8623 fn a_rearmed_output_comes_back_at_the_level_the_session_was_running() {
8624 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8625 // The control: a session nobody has pushed a level at is at full
8626 // volume, which is what a *fresh* device is expected to be.
8627 assert_eq!(
8628 session.gain(),
8629 Some(1.0),
8630 "a session that never had a gain pushed is not at full volume"
8631 );
8632 assert!(
8633 session.set_gain(0.0),
8634 "a muted push was refused by the silent sink"
8635 );
8636 assert_eq!(
8637 session.gain(),
8638 Some(0.0),
8639 "the push did not reach the device"
8640 );
8641
8642 // The device goes away the way a daemon restart takes it: the stream is
8643 // stopped and flagged dead, with the cooldown already spent. The
8644 // replacement is opened by the door the sibling re-arm witness drives
8645 // -- a play and the seek that follows, which is `start_audio`'s
8646 // unthrottled attempt -- and the death flag clearing is what says a new
8647 // device really was installed, rather than the read below passing over
8648 // the old one.
8649 session.stop_audio();
8650 let audio = session.audio.as_ref().expect("audio");
8651 audio.died.store(true, Ordering::Release);
8652 *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now());
8653 session.play();
8654 session.seek(1.0);
8655 assert!(
8656 !session
8657 .audio
8658 .as_ref()
8659 .expect("audio")
8660 .died
8661 .load(Ordering::Acquire),
8662 "the device was never replaced, so the level below says nothing about \
8663 a re-armed stream"
8664 );
8665
8666 assert_eq!(
8667 session.gain(),
8668 Some(0.0),
8669 "the replacement device came up at full volume: a muted session \
8670 that lost its output came back loud while the window still said muted"
8671 );
8672 }
8673
8674 /// The seat declares the canvas's own size; the painter masks the planes it
8675 /// returns to even dimensions, and a canvas the two disagree about used to
8676 /// take the picture down between them. On the revision before the seat masked
8677 /// what it declares, a 1920x1 canvas died *in the painter* -- `decode.rs`
8678 /// clamped the zero line of an h of 0: `max = -1`, `min > max` -- and a
8679 /// 321x181 one died in the conversion on the *canvas's* chroma plane, one row
8680 /// past the masked source's: `index out of bounds: the len is 14400 but the
8681 /// index is 14400`, a full plane and not an empty one.
8682 ///
8683 /// This drives the same path a front-end does (`set_resolution`, then frames
8684 /// out of the session). It is a guard against the shape coming back rather
8685 /// than a reproduction: a frame does still arrive on the parent revision
8686 /// (which is why the masking, not this test, is the fix).
8687 #[test]
8688 fn a_visualizer_seat_paints_a_canvas_it_cannot_evenly_divide() {
8689 for (w, h) in [(1920, 1), (1921, 1081), (320, 1), (321, 181)] {
8690 let mut session =
8691 PlaybackSession::open(asset("test_tone.mp3")).expect("open the audio fixture");
8692 assert!(
8693 session.set_resolution(w, h),
8694 "{w}x{h} should be a resolution this session takes"
8695 );
8696 let mut frame = None;
8697 for _ in 0..400 {
8698 if let Some(f) = session.try_frame() {
8699 frame = Some(f);
8700 break;
8701 }
8702 std::thread::sleep(std::time::Duration::from_millis(5));
8703 }
8704 let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas"));
8705 assert_eq!(
8706 (frame.width, frame.height),
8707 (w, h),
8708 "a frame at the canvas's own size"
8709 );
8710 }
8711 }
8712
8713 /// `blend_bgra` at the two ends and the midpoint of its weight -- `t=0` is
8714 /// pure A, `t=1` is pure B, `t=0.5` rounds each byte to its own midpoint.
8715 /// Straight alpha (255 in both) survives every weight, which is the one
8716 /// channel a wrong blend would otherwise fog.
8717 #[test]
8718 fn blend_bgra_interpolates_every_byte_including_alpha() {
8719 let a = [10u8, 20, 30, 255];
8720 let b = [110u8, 120, 130, 255];
8721 assert_eq!(blend_bgra(&a, &b, 0.0), a);
8722 assert_eq!(blend_bgra(&a, &b, 1.0), b);
8723 assert_eq!(blend_bgra(&a, &b, 0.5), [60, 70, 80, 255]);
8724 }
8725
8726 /// A still wants the project's own pixels, not a view near them.
8727 /// [`PlaybackSession::set_view_size`] calls under 8 px no change at all (a
8728 /// window being dragged must not restart the picture every tick), so a
8729 /// caller that means "paint at the project's size" has to say it through
8730 /// [`PlaybackSession::set_view_size_exact`] -- and read its `false` as "the
8731 /// view is already there, the frame in hand is the one wanted", which is
8732 /// what stops it waiting for a picture nothing will reseek into existence.
8733 #[test]
8734 fn a_still_gets_the_exact_view_size_where_a_push_settles_for_near() {
8735 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8736 assert!(session.set_resolution(1920, 1080));
8737 let (w, h) = session.resolution();
8738 assert_eq!((w, h), (1920, 1080));
8739 // A preview-sized push, then the ask a still makes: two pixels short on
8740 // each axis, which the deadbanded push calls no change at all.
8741 assert!(session.set_view_size(1918, 1078));
8742 assert!(
8743 std::ops::Not::not(session.set_view_size(w, h)),
8744 "the push's deadband is exactly what a still cannot use"
8745 );
8746 assert_eq!(
8747 session.view_size(),
8748 (1918, 1078),
8749 "the push left the view near, not at, full -- so a still written now would be short"
8750 );
8751 assert!(
8752 session.set_view_size_exact(w, h),
8753 "the exact setter must move a view the push called close enough"
8754 );
8755 assert_eq!(session.view_size(), (w, h));
8756 // ...and at the size already it says so rather than repainting: that
8757 // `false` is the caller's "write the frame you have".
8758 assert!(std::ops::Not::not(session.set_view_size_exact(w, h)));
8759 }
8760
8761 /// The dissolve window's own edges, in the units [`PlaybackSession::start_span`]
8762 /// computes them in: a `tail_start` of `span.start + span.len - window`
8763 /// puts the very first output frame of the window at `idx_in_window == 0`
8764 /// and the very last at `window - 1`, clamped rather than overrun by a
8765 /// frame that lands exactly on the span's own end -- the same off-by-one
8766 /// a stray `%` or unclamped subtraction would have shown on screen as a
8767 /// blend that never quite reached full B.
8768 #[test]
8769 fn dissolve_window_edges_index_zero_to_window_minus_one() {
8770 let (span_start, span_len, window) = (100u32, 30u32, 10u32);
8771 let tail_start = span_start + span_len - window;
8772 assert_eq!(tail_start, 120);
8773 let idx_in_window = |frame: u32| (frame - tail_start).min(window - 1);
8774 assert_eq!(idx_in_window(120), 0, "first frame of the window");
8775 assert_eq!(idx_in_window(129), 9, "last frame of the window");
8776 assert_eq!(
8777 idx_in_window(130),
8778 9,
8779 "one past the span's own end clamps rather than panics"
8780 );
8781 }
8782
8783 /// A picked project rate overrides the derived one, and its absence leaves
8784 /// the source's own -- the seam every explicit-sample-rate caller
8785 /// (playback rebuild, both export encoders) goes through
8786 /// ([`crate::AudioSession::open_multi_streams_speed_at`]). The per-segment
8787 /// conform chain resamples to whatever `meta` names, so the meta *is* the
8788 /// behaviour.
8789 #[test]
8790 fn a_picked_sample_rate_overrides_the_derived_one() {
8791 let file = asset("test_av.mp4");
8792 let sources = [(file, 0)];
8793 let segs = [(Some(0), 0., 1.)];
8794 let derived =
8795 crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], None)
8796 .expect("open the fixture")
8797 .expect("the fixture has sound")
8798 .0
8799 .sample_rate;
8800 let picked = crate::AudioSession::open_multi_streams_speed_at(
8801 &sources,
8802 &segs,
8803 &[],
8804 &[],
8805 Some(32000),
8806 )
8807 .expect("open the fixture")
8808 .expect("the fixture has sound")
8809 .0
8810 .sample_rate;
8811 assert_ne!(
8812 derived, 32000,
8813 "a fixture at the picked rate proves nothing"
8814 );
8815 assert_eq!(picked, 32000);
8816 }
8817
8818 /// Which source the timeline's sound is opened on -- the one rule
8819 /// [`open_project`](PlaybackSession::open_project), the probe every import
8820 /// is held to and the audio worker all read through. A still at index 0 is
8821 /// a picture, not a silent timeline: opening the device on it is a project
8822 /// that plays silent although every clip on it has sound.
8823 #[test]
8824 fn the_audio_reference_is_never_a_still() {
8825 let (video, still) = (asset("test_av.mp4"), asset("test_still.png"));
8826 let sources = [Source::new(&still, 0), Source::new(&video, 3)];
8827 assert_eq!(
8828 audio_source_of(&sources).map(|s| (&s.path, s.audio_stream)),
8829 Some((&sources[1].path, 3)),
8830 "the first source that could have a track, with its own stream"
8831 );
8832 assert!(
8833 audio_source_of(&sources[..1]).is_none(),
8834 "nothing but stills"
8835 );
8836 assert!(audio_source_of(&[]).is_none(), "and no file at all");
8837 }
8838
8839 /// What a front end's "resolution/rate picked before any file is open"
8840 /// setting costs the engine: nothing new. `open` then `set_resolution`/
8841 /// `set_frame_rate` right after construction -- the app's technique for
8842 /// applying a pre-import pick to the session it just made, mirroring
8843 /// [`PlaybackSession::open_project`]'s own `doc.resolution`/`doc.fps`
8844 /// override -- lands exactly where either setter lands it whenever it is
8845 /// called, and a later `import` of another file leaves both untouched: an
8846 /// import registers a source and its length, and never writes `meta.width`,
8847 /// `meta.height` or `meta.frame_rate`.
8848 #[test]
8849 fn a_pre_import_setting_survives_construction_and_a_later_import() {
8850 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8851 let native = session.native_resolution();
8852 let native_fps = session.native_frame_rate();
8853 // The explicit picks a pre-import setting would apply, distinct from
8854 // the fixture's own so a no-op would be caught.
8855 let (picked_w, picked_h) = (1920, 1080);
8856 assert_ne!((picked_w, picked_h), native, "the test needs a real change");
8857 let picked_fps = 24.0;
8858 assert_ne!(picked_fps, native_fps, "the test needs a real change");
8859 assert!(session.set_resolution(picked_w, picked_h));
8860 assert!(session.set_frame_rate(picked_fps));
8861 assert_eq!(session.resolution(), (picked_w, picked_h));
8862 assert_eq!(session.meta().frame_rate, picked_fps);
8863
8864 // A second file joining the timeline is exactly the case the front end
8865 // worried a later import could silently override the explicit pick --
8866 // it cannot, because `import` never touches the canvas.
8867 session
8868 .import(&asset("test_av2.mp4"))
8869 .expect("av2 matches the timeline it was set to");
8870 assert_eq!(
8871 session.resolution(),
8872 (picked_w, picked_h),
8873 "an import must not move the project's own canvas size"
8874 );
8875 assert_eq!(
8876 session.meta().frame_rate,
8877 picked_fps,
8878 "an import must not move the project's own rate"
8879 );
8880 }
8881
8882 #[test]
8883 fn an_audio_lane_walls_a_video_by_its_sound_and_a_video_lane_by_its_picture() {
8884 // A 2 s picture under 60 s of sound: the A1 half of a placed take can be
8885 // trimmed out to the sound's end, the V1 half only to the picture's.
8886 let path = asset("test_short_video_long_audio.mp4");
8887 let mut session = PlaybackSession::open(&path).expect("open the fixture");
8888 session.set_gain(0.0);
8889 let fps = session.meta().frame_rate;
8890 // Placed at the end, so nothing sits in front of it and the walls are the
8891 // source's own, not a neighbour's.
8892 let end = session.timeline_duration();
8893 assert!(
8894 session
8895 .place_stream_at(end, &path, 0, Some(Lane::A1))
8896 .expect("a file on this timeline is placeable")
8897 );
8898 let a1 = session.lane_clips(Lane::A1).len() - 1;
8899 let v1 = session.lane_clips(Lane::V1).len() - 1;
8900
8901 let audio = session.trim_walls(Lane::A1, a1, Edge::End).expect("A1 clip");
8902 let picture = session.trim_walls(Lane::V1, v1, Edge::End).expect("V1 clip");
8903 let placed = (end * fps).round();
8904 assert!(
8905 audio.hi as f64 >= placed + 59.0 * fps,
8906 "the sound is 60 s: the A1 end may reach {} frames at {fps} fps",
8907 audio.hi
8908 );
8909 assert!(
8910 (picture.hi as f64) < placed + 3.0 * fps,
8911 "the picture is 2 s: the V1 end stops at {} frames",
8912 picture.hi
8913 );
8914 assert!(
8915 session.trim_clip(Lane::A1, a1, Edge::End, (placed + 40.0 * fps) as u32),
8916 "the A1 clip trims to 40 s"
8917 );
8918 assert_eq!(session.lane_clips(Lane::A1)[a1].len(), (40.0 * fps) as u32);
8919 }
8920
8921 /// The seam between the two lists a source index reaches: dropping a file
8922 /// from the library shortens `sources`, and `counts` -- the frame length
8923 /// per source, which is what a trim is walled by -- has to lose the same
8924 /// entry. Left behind, the dead file's length would wall the survivor.
8925 #[test]
8926 fn removing_a_source_takes_its_frame_count_with_it() {
8927 // Source 0 is 5 s, source 1 is 4 s: two different walls, so a stale
8928 // count cannot pass for the right one.
8929 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8930 session.set_gain(0.0);
8931 // Imported, then dragged onto the end -- an import alone places nothing
8932 // ([`PlaybackSession::import`]), and this test needs both takes there.
8933 session.import(&asset("test_av2.mp4")).expect("av2 matches");
8934 let end = session.timeline_duration();
8935 assert!(
8936 session
8937 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
8938 .expect("a file just imported is on this timeline")
8939 );
8940 let (long, short) = (session.counts[0], session.counts[1]);
8941 assert!(long > short, "{long} vs {short}");
8942
8943 // Clear source 0's take, then take the file itself out: av2's clip is
8944 // the only one left and it is source 0 now.
8945 assert!(session.delete_clip(Lane::V1, 0));
8946 session
8947 .remove_source(&asset("test_av.mp4"), 0)
8948 .expect("nothing plays it any more");
8949 assert_eq!(session.counts, vec![short], "the dead length went with it");
8950 assert_eq!(session.sources().len(), session.counts.len());
8951
8952 // The wall is the surviving file's own length, not the gone one's: a
8953 // whole-file clip cannot be dragged out any further at all.
8954 let clip = session.lane_clips(Lane::V1)[0].clone();
8955 assert_eq!(clip.len(), short, "av2's take, whole");
8956 assert_eq!(
8957 session.trim_room(Lane::V1, 0, Edge::End),
8958 Some((clip.start + 1, clip.end()))
8959 );
8960 assert!(
8961 !session.trim_clip(Lane::V1, 0, Edge::End, clip.end() + 30),
8962 "past the file's last frame is refused, by ITS length"
8963 );
8964
8965 // ...and the next import still lines the two lists up, which is the
8966 // alignment `note_frames` asserts on.
8967 session
8968 .import(&asset("test_av.mp4"))
8969 .expect("it may come back");
8970 assert_eq!(session.counts, vec![short, long]);
8971 assert_eq!(session.sources().len(), session.counts.len());
8972 }
8973
8974 /// The two headers a place reads are read *once*: an mp4 dropped on a lane
8975 /// used to open its own container and the timeline's first source every
8976 /// time, both on the thread that draws, and a film whose pages have gone
8977 /// cold is 1.7 s of that.
8978 ///
8979 /// Proved by answering, not by timing: the memo is filled with a layout the
8980 /// file does not have, and the place is refused. Only a door that read the
8981 /// remembered header rather than the disk can refuse it.
8982 #[test]
8983 fn a_place_reads_each_audio_header_once() {
8984 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8985 session.set_gain(0.0);
8986 session.import(&asset("test_av2.mp4")).expect("av2 matches");
8987 let end = session.timeline_duration();
8988 assert!(
8989 session
8990 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
8991 .expect("a file just imported is on this timeline")
8992 );
8993 assert_eq!(
8994 session.probes.len(),
8995 2,
8996 "the timeline's first source and the file placed, once each"
8997 );
8998
8999 // Now say av2 is 5.1. Nothing on disk changed, so a door that opens the
9000 // file still matches; one that trusts the memo refuses by layout.
9001 // Keyed exactly as a [`Source`] names a file -- canonical, symlinks
9002 // resolved -- which is the key the doors look up.
9003 let av2 = Source::new(asset("test_av2.mp4"), 0).path;
9004 session.probes.insert(
9005 (av2, 0),
9006 Some(crate::AudioProbe {
9007 sample_rate: 48_000,
9008 channels: 6,
9009 }),
9010 );
9011 let refused = session
9012 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
9013 .expect_err("the remembered layout disagrees with the timeline's");
9014 assert!(
9015 refused.to_string().contains("6 ch"),
9016 "refused in the layout's own words: {refused}"
9017 );
9018 assert_eq!(session.probes.len(), 2, "and nothing was opened to say so");
9019 }
9020
9021 /// The door a library preview opens a chosen stream through: `test_multiaudio.mp4`
9022 /// has stream 0 stereo and stream 1 mono
9023 /// ([`crate::waveform::tests::each_stream_of_a_file_has_its_own_envelope`]
9024 /// names the same fixture), so a session that actually bound the stream it
9025 /// was asked for plays a different layout than one that did not -- and
9026 /// plain [`PlaybackSession::open`] still lands on stream 0, unchanged.
9027 #[test]
9028 fn open_with_audio_stream_binds_the_named_track() {
9029 let multi = asset("test_multiaudio.mp4");
9030 let zero = PlaybackSession::open_with_audio_stream(&multi, 0).expect("stream 0 opens");
9031 let one = PlaybackSession::open_with_audio_stream(&multi, 1).expect("stream 1 opens");
9032 let default = PlaybackSession::open(&multi).expect("default open");
9033 let (Some(a0), Some(a1), Some(ad)) = (
9034 zero.audio.as_ref(),
9035 one.audio.as_ref(),
9036 default.audio.as_ref(),
9037 ) else {
9038 // No audio device on this machine: nothing further to check --
9039 // the device is the machine's business, not this door's.
9040 return;
9041 };
9042 assert_eq!(a0.channels, 2, "stream 0 is the stereo pair");
9043 assert_eq!(a1.channels, 1, "stream 1 is the mono track");
9044 assert_ne!(a0.channels, a1.channels, "the two streams must differ");
9045 assert_eq!(
9046 ad.channels, a0.channels,
9047 "open() still defaults to stream 0"
9048 );
9049 }
9050
9051 /// The bug this regression pins: a preview paused (or scrubbed) to a
9052 /// frame inside a dissolve window used to show plain A forever, because
9053 /// B's decoder only opened on the tick that landed in the window and
9054 /// nothing polled `try_frame` again while the clock stood still
9055 /// (`Player::pump` only drains while playing or a seek is owed, and one
9056 /// delivered frame clears "owed"). Two clips of real fixtures, touching,
9057 /// with a dissolve set on the join -- seeking into the window and taking
9058 /// exactly one frame (no play, no second tick) must already show a blend:
9059 /// the same position with the dissolve turned off must differ from it.
9060 #[test]
9061 fn a_single_paused_tick_inside_the_dissolve_window_is_already_blended() {
9062 let window = 6u32;
9063 let build = |transition: u32| {
9064 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open a");
9065 s.set_gain(0.0);
9066 s.import(&asset("test_av2.mp4")).expect("av2 matches");
9067 let end = s.timeline_duration();
9068 assert!(
9069 s.place_stream_at(end, &asset("test_av2.mp4"), 0, None)
9070 .expect("av2, placed right after a")
9071 );
9072 if transition > 0 {
9073 assert!(s.set_transition_out(Lane::V1, 0, transition));
9074 }
9075 s
9076 };
9077 let mut on = build(window);
9078 let mut off = build(0);
9079
9080 let fps = on.meta().frame_rate;
9081 let clip0_len = on.lane_clips(Lane::V1)[0].len();
9082 assert!(
9083 clip0_len > window,
9084 "the fixture needs to outlast the window"
9085 );
9086 let mid_of_window = clip0_len - window / 2;
9087 let t = f64::from(mid_of_window) / fps;
9088
9089 // One seek, then one frame -- exactly what a paused preview's single
9090 // repaint asks the engine for. Polled rather than taken on the first
9091 // call because the seek itself just restarted the decoder
9092 // (`start_span`) and its first picture is not synchronous; once
9093 // *a* frame lands this is the one tick under test.
9094 let frame_at = |s: &mut PlaybackSession| -> crate::decode::Frame {
9095 s.seek(t);
9096 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
9097 loop {
9098 if let Some(f) = s.try_frame() {
9099 return f;
9100 }
9101 assert!(
9102 std::time::Instant::now() < deadline,
9103 "no frame within 120s of the seek"
9104 );
9105 std::thread::sleep(std::time::Duration::from_millis(10));
9106 }
9107 };
9108
9109 let off_frame = frame_at(&mut off);
9110 let on_frame = frame_at(&mut on);
9111 assert_eq!(on_frame.index, off_frame.index, "same timeline position");
9112 assert_ne!(
9113 on_frame.bgra, off_frame.bgra,
9114 "paused inside the window, the dissolve must already show B blended in"
9115 );
9116 }
9117
9118 #[test]
9119 fn boundary_seconds_round_trip_to_their_own_frame() {
9120 for f in 0u32..300 {
9121 let secs = f64::from(f) / 30.0;
9122 assert_eq!(secs_to_frame(secs, 30.0), f, "frame {f}");
9123 }
9124 // Mid-frame positions still floor, and negatives clamp.
9125 assert_eq!(secs_to_frame(10.5 / 30.0, 30.0), 10);
9126 assert_eq!(secs_to_frame(-0.2, 30.0), 0);
9127 }
9128
9129 /// A paused transform nudge -- `set_transform_live` at the position the
9130 /// picture already stands on -- never pays a full decoder restart: the
9131 /// worker is reused (`Worker::reseek`), never replaced
9132 /// (`PlaybackSession::retire`), so `restarts()` does not move. Guards the
9133 /// path a card's live edits go through against a future change routing
9134 /// them back through `seek`/a fresh worker, and a gap left between two
9135 /// edits (a person's think-time between nudges) longer than the *old*
9136 /// hardware-idle window still counts zero restarts -- a decoder worker
9137 /// outliving its span is not a "restart" this counter (or a caller) sees,
9138 /// whatever the hardware session inside it did.
9139 #[test]
9140 fn a_paused_transform_nudge_reuses_the_worker_not_a_restart() {
9141 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
9142 s.set_gain(0.0);
9143 let poll = |s: &mut PlaybackSession| -> crate::decode::Frame {
9144 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
9145 loop {
9146 if let Some(f) = s.try_frame() {
9147 return f;
9148 }
9149 assert!(std::time::Instant::now() < deadline, "no frame within 120s");
9150 std::thread::sleep(std::time::Duration::from_millis(10));
9151 }
9152 };
9153 let first = poll(&mut s);
9154 let before = s.restarts();
9155
9156 // A gap past the pre-fix 2s hardware-idle window: the whole point of
9157 // widening it is that a nudge landing here still reuses the worker.
9158 std::thread::sleep(std::time::Duration::from_millis(2500));
9159
9160 let clip = s.video_clip_at(s.now()).expect("a clip under the playhead");
9161 let params = TransformParams {
9162 scale: 1.2,
9163 ..Default::default()
9164 };
9165 assert!(
9166 s.set_transform_live(clip.0, clip.1, Some(params)),
9167 "the edit took"
9168 );
9169 let next = poll(&mut s);
9170
9171 assert_eq!(
9172 before,
9173 s.restarts(),
9174 "a live transform edit must reuse the worker"
9175 );
9176 assert_eq!(
9177 next.index, first.index,
9178 "paused: same timeline position before and after"
9179 );
9180 }
9181
9182 /// A rate undo lands the picture where the playhead is, in the rate that
9183 /// came *back*: the entry a pick takes carries the old numbering beside the
9184 /// old rate, so an undo restores both and the reseek has to be computed
9185 /// after the restore. Computed before it, the landing is the pre-undo
9186 /// rate's reading of the post-undo project -- `now` clamps to the pre-undo
9187 /// rate's idea of the timeline's end and the worker is handed the last
9188 /// frame of a five-second timeline for a playhead at three seconds.
9189 #[test]
9190 fn a_rate_undo_reseeks_at_the_rate_it_restored() {
9191 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
9192 s.set_gain(0.0);
9193 let poll = |s: &mut PlaybackSession| -> crate::decode::Frame {
9194 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
9195 loop {
9196 if let Some(f) = s.try_frame() {
9197 return f;
9198 }
9199 assert!(std::time::Instant::now() < deadline, "no frame within 120s");
9200 std::thread::sleep(std::time::Duration::from_millis(10));
9201 }
9202 };
9203 let native = s.native_frame_rate();
9204 s.seek(3.0);
9205 assert_eq!(s.now(), 3.0, "the fixture is five seconds long");
9206 assert!(s.set_frame_rate(native * 2.0), "the rate pick");
9207 assert!(s.undo(), "the pick is one step");
9208 assert_eq!(s.meta().frame_rate, native, "the rate came back");
9209 assert_eq!(
9210 s.now(),
9211 3.0,
9212 "the playhead is the seconds it was, read at the rate that came back"
9213 );
9214 // The worker's own landing, which is the half the clock alone cannot
9215 // show: a frame 149 of 150 is exactly the pre-undo rate's clamp.
9216 assert_eq!(
9217 s.span.expect("a span for the picture").start,
9218 secs_to_frame(3.0, native),
9219 "the picture was asked for the playhead's own frame"
9220 );
9221 let frame = poll(&mut s);
9222 assert_eq!(
9223 frame.index,
9224 secs_to_frame(3.0, native),
9225 "and that is the frame that arrived"
9226 );
9227 }
9228
9229 /// The session's live look samples leave its history exactly where the
9230 /// press left it -- the colour-wheel drag's twin for the packed look, and
9231 /// what lets the app drive one from a pointer: `z` after a drag lands
9232 /// before the press, not one sample back down the drag.
9233 #[test]
9234 fn a_live_look_drag_is_one_step_of_the_sessions_history() {
9235 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
9236 let (lane, idx) = s.video_clip_at(s.now()).expect("a clip under the playhead");
9237 let look = |hue: u8| crate::decode::with_viz_paint_hue(crate::decode::VIZ_PAINT_AZURE, hue);
9238 assert!(s.set_viz_paint(lane, idx, look(1)), "the press");
9239 for hue in 2..=6u8 {
9240 assert!(s.set_viz_paint_live(lane, idx, look(hue)), "a sample");
9241 }
9242 assert_eq!(s.project.lane(lane)[idx].viz_paint, look(6));
9243 assert!(s.undo(), "the drag's own step");
9244 assert_eq!(
9245 s.project.lane(lane)[idx].viz_paint,
9246 0,
9247 "one undo is the whole drag"
9248 );
9249 }
9250
9251 #[test]
9252 fn solo_keeps_only_the_soloed_audio_lanes_audible() {
9253 use super::soloed_gains;
9254 use crate::project::LaneKind;
9255 let a1 = Lane::new(LaneKind::Audio, 0);
9256 let a2 = Lane::new(LaneKind::Audio, 1);
9257 let a3 = Lane::new(LaneKind::Audio, 2);
9258 let v1 = Lane::new(LaneKind::Video, 0);
9259 let audio = [a1, a2, a3];
9260 let gains = vec![1.0, 0.5, 0.0];
9261 assert_eq!(
9262 soloed_gains(gains.clone(), &audio, &[a2]),
9263 vec![0.0, 0.5, 0.0],
9264 "the others go silent, the soloed one keeps its own gain"
9265 );
9266 assert_eq!(
9267 soloed_gains(gains.clone(), &audio, &[]),
9268 vec![1.0, 0.5, 0.0],
9269 "no solo changes nothing"
9270 );
9271 assert_eq!(
9272 soloed_gains(gains.clone(), &audio, &[v1]),
9273 vec![1.0, 0.5, 0.0],
9274 "a video lane is no audio solo"
9275 );
9276 assert_eq!(
9277 soloed_gains(gains.clone(), &[a1, a3], &[a2]),
9278 vec![1.0, 0.5, 0.0],
9279 "a solo naming no audio lane any more is no solo"
9280 );
9281 }
9282}