forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

playback.rs9207 lines, 433.5 KiBHistoryRawDownload
1//! One timeline over one or more files: the decode workers, the audio output
2//! and the master clock wired together so a front-end only has to render and
3//! call [`tick`].
4//!
5//! [`tick`]: PlaybackSession::tick
6//!
7//! Everything degrades to silent-but-correct: no audio track, no plugin, no
8//! PipeWire daemon and an unusable format all end up in [`ClockSource::Wall`],
9//! where the video is paced by real time instead of by the device.
10//!
11//! Drift policy stays with the caller -- this type answers "what time is it",
12//! the renderer decides which frame that means.
13
14use std::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/// How long one scrub snippet plays ([`PlaybackSession::scrub_audio`]): long enough to hear
823/// what a word or a beat is, short enough that a drag across a second of sound is a run of
824/// clicks rather than a smear.
825pub const SCRUB_SECS: f64 = 0.07;
826/// The fade at each end of a scrub snippet, in seconds ([`scrub_snippet`]).
827const SCRUB_FADE_SECS: f64 = 0.01;
828
829/// One scrub snippet's samples: the window `src` holds (interleaved, `channels` wide) with a
830/// raised-cosine fade of `fade` frames at each end, so the snippet starts and stops at silence
831/// and no edge of it can click. The fade is held to half the window, and the result is the
832/// window's length.
833pub fn scrub_snippet(src: &[f32], channels: usize, fade: usize) -> Vec<f32> {
834 let channels = channels.max(1);
835 let frames = src.len() / channels;
836 let mut out = src[..frames * channels].to_vec();
837 let fade = fade.min(frames / 2);
838 for f in 0..fade {
839 // Rising from just above silence to just below unity over `fade` frames.
840 let g = 0.5 - 0.5 * (std::f32::consts::PI * (f as f32 + 0.5) / fade as f32).cos();
841 for c in 0..channels {
842 out[f * channels + c] *= g;
843 out[(frames - 1 - f) * channels + c] *= g;
844 }
845 }
846 out
847}
848
849/// A piece of scrub work: opening and reading a snippet's audio, which happens off the caller's
850/// thread. It hands back the device's rate and width and the faded samples.
851type ScrubWork = Box<dyn FnOnce() -> Option<(u32, u32, Vec<f32>)> + Send>;
852
853/// The scrub thread's handle: `None` until the first snippet is asked for.
854#[derive(Default)]
855struct Scrub {
856 tx: Option<std::sync::mpsc::Sender<ScrubWork>>,
857 /// How many snippets have been asked for ([`PlaybackSession::scrub_requests`]).
858 requests: u64,
859}
860
861/// The scrub thread. It owns one output stream for as long as the rate and width hold, and
862/// plays only the newest request: a drag that outruns the decoder skips the ones it left behind.
863fn scrub_thread(rx: Receiver<ScrubWork>) {
864 let mut out: Option<(u32, u32, AoSession)> = None;
865 while let Ok(mut work) = rx.recv() {
866 while let Ok(newer) = rx.try_recv() {
867 work = newer;
868 }
869 let Some((rate, channels, samples)) = work() else {
870 continue;
871 };
872 if out.as_ref().is_none_or(|(r, c, _)| *r != rate || *c != channels) {
873 out = AoSession::open(rate, channels).map(|ao| (rate, channels, ao));
874 }
875 if let Some((_, _, ao)) = out.as_mut() {
876 // A snippet replaces the one still sounding, so the newest is heard at once.
877 ao.flush();
878 ao.set_active(true);
879 ao.write(&samples);
880 }
881 }
882}
883
884impl PlaybackSession {
885 /// Opens `path` and starts both decode workers. Only video failure is fatal:
886 /// a file we cannot hear is still a file we can watch.
887 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {
888 Self::open_stream(path, 0)
889 }
890
891 /// Opens `path` exactly as [`open`](Self::open) does, but binds `stream` --
892 /// the index a library row names ([`crate::probe`]'s own numbering of a
893 /// file's audio tracks) -- as the one that keeps the clock and plays,
894 /// rather than always the first. What a library preview asks for when the
895 /// row *is* a particular stream, so a remux with several audio tracks
896 /// previews the one that was clicked.
897 pub fn open_with_audio_stream(
898 path: impl AsRef<Path>,
899 audio_stream: usize,
900 ) -> crate::Result<Self> {
901 Self::open_stream(path, audio_stream)
902 }
903
904 fn open_stream(path: impl AsRef<Path>, audio_stream: usize) -> crate::Result<Self> {
905 // Canonical from the first byte: the project canonicalizes every
906 // source ([`Source::new`]), and [`Worker::reseek`] reuses a decoder
907 // only when the paths match textually -- a raw path here would make
908 // every later picture edit pay a full reopen instead of a seek.
909 let path = crate::project::canonical(path.as_ref());
910 // A timeline is normally scaffolded from source 0's picture -- its size,
911 // its frame rate, its clock. A song has none of that, so it scaffolds
912 // the *canvas* instead and its own sound keeps the clock: an audio-only
913 // project is a project like any other, it simply plays black.
914 if crate::is_audio(&path) {
915 return Self::open_audio_only(&path, audio_stream);
916 }
917 // A still is the other source with no timeline in it: it has a picture
918 // (which becomes the canvas) but no rate and no length, so it too
919 // scaffolds rather than describes.
920 // A numbered run opens as one clip of its frames, the same as an import of it.
921 if let Some(run) = crate::sequence::Run::parse(&path).or_else(|| crate::sequence::Run::detect(&path)) {
922 return Self::open_image_only(&run.spelled(), Some(run.count));
923 }
924 if crate::is_image(&path) {
925 return Self::open_image_only(&path, None);
926 }
927 // `open_worker` rather than `open` purely for the worker handle: the
928 // field has to exist from the start for the first seek to use it.
929 // Ungraded: a file just opened has one clip per lane and nothing has
930 // graded it yet. Every later span is opened by `start_span`, which asks
931 // the project.
932 // Passthrough: a freshly opened file *is* the project resolution, so
933 // there is nothing to place it on. Every later span goes through
934 // `start_span`, which builds the canvas from the project.
935 let opened = DecodeSession::open_worker(
936 &path,
937 0,
938 u32::MAX,
939 ColorParams::default(),
940 TransformParams::default(),
941 Composer::passthrough(),
942 // The default rendition: a file just opened is a project nobody has
943 // picked one for, exactly as it is a project nobody has graded.
944 crate::tonemap::Preset::default(),
945 );
946 // `is_audio` above is the extension's word, and an extension can lie: a
947 // song muxed into an `.mp4` reads as a film until the header is actually
948 // walked. The demuxer's own `NoVideoTrack` is that walk saying there was
949 // never a picture in it, and the fallback is the same audio-only door the
950 // extension check would have taken up front -- not a fault, a type.
951 let (meta, stream) = match opened {
952 Ok(opened) => opened,
953 Err(e) if NoVideoTrack::is_it(&e) => return Self::open_audio_only(&path, audio_stream),
954 Err(e) => return Err(e),
955 };
956 // A file is opened on its first audio stream by default, like
957 // `Project::single` names it -- unless a caller through
958 // `open_with_audio_stream` picked another.
959 let (audio, audio_disabled) = open_audio(&path, audio_stream);
960 let source = match audio {
961 Some(_) => ClockSource::Audio,
962 None => ClockSource::Wall,
963 };
964 // One clip per lane covering the file, so timeline == source until the
965 // first edit -- and the range opened above is exactly that clip's.
966 // The grouped pair runs one length: the sound's when the file's sound is shorter
967 // than its picture (the walls the save and the load check the audio lane to), so
968 // the take is sound_held_frames long from the start, not the picture's count.
969 let held = sound_held_frames(&path, 0, meta.frame_count, meta.frame_rate);
970 let project = Project::single(&path, held);
971 let span = crate::export::stack_span_at(&project, 0);
972 // A second, header-only open purely for the light level: `open_worker`
973 // above already read one to hand the decode thread its own, but never
974 // hands it back out. The same trade the audio header cache above this
975 // makes -- a second container open, paid once at open rather than never
976 // -- since nothing here decodes a single picture.
977 let content_light = Demuxer::open(&path)
978 .map(|(_, d)| d.light())
979 .unwrap_or_default();
980 Ok(Self {
981 scrub: Scrub::default(),
982 load_warnings: Vec::new(),
983 meta,
984 content_light,
985 native: (meta.width, meta.height),
986 native_fps: meta.frame_rate,
987 frames: stream.frames,
988 worker: stream.worker,
989 backend: stream.backend,
990 video_failure: stream.failure,
991 retired: Vec::new(),
992 restarts: 0,
993 clock: PlaybackClock::new(source),
994 audio,
995 audio_disabled,
996 project,
997 counts: vec![meta.frame_count],
998 probes: std::collections::HashMap::new(),
999 // Source 0 *is* the timeline's rate: it defined it.
1000 rates: vec![Rate::REAL_TIME],
1001 span_rate: Rate::REAL_TIME,
1002 span,
1003 span_priming: true,
1004 feed: Feed::Live,
1005 back: Back::Off,
1006 dissolve: None,
1007 view: None,
1008 eos: false,
1009 eos_end: 0.0,
1010 mix: None,
1011 solo: Vec::new(),
1012 priming: false,
1013 drop_late: false,
1014 // A file just opened is a project nobody has picked stand-ins for.
1015 proxies: false,
1016 auto_proxies: true,
1017 encoder_seat: crate::export::EncoderSeat::default(),
1018 sample_rate: None,
1019 })
1020 }
1021
1022 /// Opens `path` into the **library alone**: everything
1023 /// [`open`](Self::open) scaffolds from it -- the resolution, the frame
1024 /// rate, the clock, the source entry and its length -- over an *empty*
1025 /// timeline. What an import into a window that has no session yet makes,
1026 /// since an import registers a source and never places a clip
1027 /// ([`import`](Self::import)); the file reaches a lane when it is dragged
1028 /// there.
1029 ///
1030 /// Nothing to undo, like the import it stands in for: the lanes start
1031 /// empty rather than being emptied, so no snapshot is pushed.
1032 pub fn open_library(path: impl AsRef<Path>) -> crate::Result<Self> {
1033 let mut session = Self::open(path)?;
1034 // The pair of lanes an opened file comes up with (`Project::single`,
1035 // `open_audio_only`), emptied -- the source list and so the noted
1036 // counts are carried over untouched, which is what keeps a library row
1037 // placeable at its full length.
1038 session.project = Project::from_parts(
1039 session.project.sources().to_vec(),
1040 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())],
1041 Vec::new(),
1042 Vec::new(),
1043 Vec::new(),
1044 )?;
1045 // Onto the emptied mapping: black picture, silence, zero duration.
1046 session.seek(0.);
1047 Ok(session)
1048 }
1049
1050 /// A timeline with no file behind it: a `width` x `height` canvas at `fps`,
1051 /// no sources and no clips, for a project started from nothing. Its picture
1052 /// is the black of an uncovered canvas, its length is zero, and the first
1053 /// import sets the sources the way it does on any session.
1054 pub fn empty(width: u32, height: u32, fps: f64) -> crate::Result<Self> {
1055 if width == 0 || height == 0 || fps <= 0.0 {
1056 return Err(format!("empty timeline: {width}x{height} at {fps} fps").into());
1057 }
1058 let meta = VideoMeta {
1059 width,
1060 height,
1061 frame_rate: fps,
1062 frame_count: 0,
1063 codec: Codec::H264,
1064 color: ColorDescription::default(),
1065 matrix_assumed: false,
1066 rotation: Rotation::None,
1067 coded_width: width,
1068 coded_height: height,
1069 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1070 };
1071 let stream = DecodeSession::open_black(width, height, 0);
1072 Ok(Self {
1073 scrub: Scrub::default(),
1074 load_warnings: Vec::new(),
1075 meta,
1076 content_light: ContentLight::default(),
1077 native: (width, height),
1078 native_fps: fps,
1079 frames: stream.frames,
1080 worker: stream.worker,
1081 backend: stream.backend,
1082 video_failure: stream.failure,
1083 retired: Vec::new(),
1084 restarts: 0,
1085 clock: PlaybackClock::new(ClockSource::Wall),
1086 audio: None,
1087 audio_disabled: None,
1088 project: Project::from_parts(
1089 Vec::new(),
1090 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())],
1091 Vec::new(),
1092 Vec::new(),
1093 Vec::new(),
1094 )?,
1095 counts: Vec::new(),
1096 probes: std::collections::HashMap::new(),
1097 rates: Vec::new(),
1098 span_rate: Rate::REAL_TIME,
1099 span: None,
1100 span_priming: true,
1101 feed: Feed::Live,
1102 back: Back::Off,
1103 dissolve: None,
1104 view: None,
1105 eos: false,
1106 eos_end: 0.0,
1107 mix: None,
1108 solo: Vec::new(),
1109 priming: false,
1110 drop_late: false,
1111 proxies: false,
1112 auto_proxies: true,
1113 encoder_seat: crate::export::EncoderSeat::default(),
1114 sample_rate: None,
1115 })
1116 }
1117
1118 /// Opens a standalone audio file ([`crate::is_audio`]) as a timeline of its
1119 /// own: one clip on `A1`, nothing on the video lane, and a picture that is
1120 /// the black of an uncovered canvas ([`AUDIO_ONLY_CANVAS`]) for as long as
1121 /// the song runs. Its own sound keeps the clock, exactly as a video's does.
1122 ///
1123 /// Refused when the file has no sound to time it by: a source with neither a
1124 /// picture nor a playable length is not a timeline, and that is what
1125 /// [`audio_frames`] answers -- the *device* is a different question, and a
1126 /// machine without one opens this like any other session, silently.
1127 fn open_audio_only(path: &Path, stream: usize) -> crate::Result<Self> {
1128 let (width, height, frame_rate) = AUDIO_ONLY_CANVAS;
1129 let meta = VideoMeta {
1130 width,
1131 height,
1132 frame_rate,
1133 // Rounded up to whole frames, which is the only frame count a
1134 // source with no picture has -- the same length `import_audio`
1135 // gives a song joining a timeline of video. The demuxer's words are
1136 // named with the file, since this is the door a file that is not
1137 // really audio at all comes to.
1138 frame_count: audio_frames(path, frame_rate)
1139 .map_err(|e| format!("{}: {e}", path.display()))?,
1140 codec: Codec::H264,
1141 // A canvas this engine drew itself, not a stream that was read:
1142 // the default description is what it is drawn in.
1143 color: ColorDescription::default(),
1144 matrix_assumed: false,
1145 rotation: Rotation::None,
1146 // No container said anything about these: the canvas this engine drew
1147 // itself is square pixels at the size it was drawn at.
1148 coded_width: width,
1149 coded_height: height,
1150 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1151 };
1152 let (audio, audio_disabled) = open_audio(path, stream);
1153 // Through `from_parts` rather than `Project::single`, which is the
1154 // *video* open's pair of grouped clips: here there is no picture to
1155 // group the sound with, so the video lane starts empty.
1156 let clip = Clip {
1157 speed_keys: Vec::new(),
1158 reversed: false,
1159 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1160 angle: Default::default(),
1161 fade_in: 0,
1162 fade_out: 0,
1163 transition_out: 0,
1164 transition_kind: Default::default(),
1165 visualizer: 0,
1166 viz_paint: 0,
1167 gain_db: 0.0,
1168 gain_keys: Vec::new(),
1169 pan: 0,
1170 transform_keys: Vec::new(),
1171 opacity_keys: Vec::new(),
1172 color_keys: Vec::new(),
1173 effects: Vec::new(),
1174 start: 0,
1175 in_frame: 0,
1176 out_frame: meta.frame_count,
1177 source: 0,
1178 link: None,
1179 eq: None,
1180 color: None,
1181 transform: None,
1182 fit: FitPolicy::default(),
1183 speed: Speed::NORMAL,
1184 pitch: 0,
1185 };
1186 let project = Project::from_parts(
1187 vec![Source::new(path, 0)],
1188 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, vec![clip])],
1189 Vec::new(),
1190 Vec::new(),
1191 Vec::new(),
1192 )?;
1193 // Every frame of this timeline is a gap, since no video lane covers
1194 // anything: `composite_span_at` says so and the black worker
1195 // `start_span` would open is opened here instead, for the reason `open`
1196 // opens its decoder inline -- the field has to exist for the first seek.
1197 let span = crate::export::stack_span_at(&project, 0);
1198 let stream = DecodeSession::open_black(width, height, span.map_or(1, |s| s.len));
1199 Ok(Self {
1200 scrub: Scrub::default(),
1201 load_warnings: Vec::new(),
1202 meta,
1203 content_light: ContentLight::default(),
1204 native: (width, height),
1205 native_fps: frame_rate,
1206 frames: stream.frames,
1207 worker: stream.worker,
1208 backend: stream.backend,
1209 video_failure: stream.failure,
1210 retired: Vec::new(),
1211 restarts: 0,
1212 // The song keeps the clock, as a video's own sound does -- and wall
1213 // time keeps it on a machine with no device, where the picture
1214 // (black) still has to move at some rate.
1215 clock: PlaybackClock::new(match audio {
1216 Some(_) => ClockSource::Audio,
1217 None => ClockSource::Wall,
1218 }),
1219 audio,
1220 audio_disabled,
1221 project,
1222 counts: vec![meta.frame_count],
1223 probes: std::collections::HashMap::new(),
1224 // Source 0 *is* the timeline's rate: it defined it.
1225 rates: vec![Rate::REAL_TIME],
1226 span_rate: Rate::REAL_TIME,
1227 span,
1228 span_priming: true,
1229 feed: Feed::Live,
1230 back: Back::Off,
1231 dissolve: None,
1232 view: None,
1233 eos: false,
1234 eos_end: 0.0,
1235 mix: None,
1236 solo: Vec::new(),
1237 priming: false,
1238 drop_late: false,
1239 // A file just opened is a project nobody has picked stand-ins for.
1240 proxies: false,
1241 auto_proxies: true,
1242 encoder_seat: crate::export::EncoderSeat::default(),
1243 sample_rate: None,
1244 })
1245 }
1246
1247 /// Opens a still image ([`crate::is_image`]) as a timeline of its own: one
1248 /// clip on `V1`, [`STILL_DEFAULT_SECS`] long, over silence. The *canvas* is
1249 /// the image's own picture -- unlike a song, a still has one, and inventing
1250 /// a 1080p canvas around a 640x360 PNG would letterbox it against nothing.
1251 /// The frame rate is [`IMAGE_ONLY_RATE`], for the reason an audio-only
1252 /// timeline has one at all: nothing was shot on it.
1253 ///
1254 /// Wall time keeps the clock, as it does for any silent source.
1255 /// `frames` is the length of a numbered run (its spelling is `path`), or `None` for one picture,
1256 /// which is held and placed for [`image_frames`] and [`IMAGE_PLACE_SECS`].
1257 fn open_image_only(path: &Path, frames: Option<u32>) -> crate::Result<Self> {
1258 // Decoded here rather than probed: this is the door a `.png` that is
1259 // not one comes to, and the picture is wanted a line later anyway.
1260 let still = crate::decode::Still::open(path)?;
1261 let meta = VideoMeta {
1262 width: still.width,
1263 height: still.height,
1264 frame_rate: IMAGE_ONLY_RATE,
1265 // Its length is the wall a trim is held to, exactly as a song's
1266 // playing time is -- see [`image_frames`].
1267 frame_count: frames.unwrap_or_else(|| image_frames(IMAGE_ONLY_RATE)),
1268 codec: Codec::H264,
1269 color: ColorDescription::default(),
1270 matrix_assumed: false,
1271 // `Rotation::None` is honest, not a shrug: a still's own turn was
1272 // made in `Still::open`, before these planes were written, so the
1273 // pair below is already the displayed one and there is nothing left
1274 // for a consumer to make.
1275 rotation: Rotation::None,
1276 // No container said anything about these: the picture this engine
1277 // decoded itself is square pixels at the size it was decoded at.
1278 coded_width: still.width,
1279 coded_height: still.height,
1280 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1281 };
1282 let clip = Clip {
1283 speed_keys: Vec::new(),
1284 reversed: false,
1285 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1286 angle: Default::default(),
1287 fade_in: 0,
1288 fade_out: 0,
1289 transition_out: 0,
1290 transition_kind: Default::default(),
1291 visualizer: 0,
1292 viz_paint: 0,
1293 gain_db: 0.0,
1294 gain_keys: Vec::new(),
1295 pan: 0,
1296 transform_keys: Vec::new(),
1297 opacity_keys: Vec::new(),
1298 color_keys: Vec::new(),
1299 effects: Vec::new(),
1300 start: 0,
1301 in_frame: 0,
1302 out_frame: place_frames(meta.frame_count, IMAGE_ONLY_RATE, STILL_DEFAULT_SECS),
1303 source: 0,
1304 link: None,
1305 eq: None,
1306 color: None,
1307 transform: None,
1308 fit: FitPolicy::default(),
1309 speed: Speed::NORMAL,
1310 pitch: 0,
1311 };
1312 // No group and no audio clip: a still is silent, and a clip on `A1`
1313 // playing from a PNG is a source the audio worker cannot open.
1314 let project = Project::from_parts(
1315 vec![Source::new(path, 0)],
1316 vec![(LaneKind::Video, vec![clip]), (LaneKind::Audio, Vec::new())],
1317 Vec::new(),
1318 Vec::new(),
1319 Vec::new(),
1320 )?;
1321 let span = crate::export::stack_span_at(&project, 0);
1322 // The placeholder the first seek supersedes, opened here for `open`'s
1323 // reason: the field has to exist before anything can seek.
1324 let stream = DecodeSession::open_still(
1325 path,
1326 0,
1327 span.map_or(1, |s| s.len),
1328 ColorParams::default(),
1329 TransformParams::default(),
1330 Composer::passthrough(),
1331 )?;
1332 Ok(Self {
1333 scrub: Scrub::default(),
1334 load_warnings: Vec::new(),
1335 meta,
1336 content_light: ContentLight::default(),
1337 native: (meta.width, meta.height),
1338 native_fps: IMAGE_ONLY_RATE,
1339 frames: stream.frames,
1340 worker: stream.worker,
1341 backend: stream.backend,
1342 video_failure: stream.failure,
1343 retired: Vec::new(),
1344 restarts: 0,
1345 clock: PlaybackClock::new(ClockSource::Wall),
1346 audio: None,
1347 audio_disabled: None,
1348 project,
1349 counts: vec![meta.frame_count],
1350 probes: std::collections::HashMap::new(),
1351 // Source 0 *is* the timeline's rate: it defined it.
1352 rates: vec![Rate::REAL_TIME],
1353 span_rate: Rate::REAL_TIME,
1354 span,
1355 span_priming: true,
1356 feed: Feed::Live,
1357 back: Back::Off,
1358 dissolve: None,
1359 view: None,
1360 eos: false,
1361 eos_end: 0.0,
1362 mix: None,
1363 solo: Vec::new(),
1364 priming: false,
1365 drop_late: false,
1366 // A file just opened is a project nobody has picked stand-ins for.
1367 proxies: false,
1368 auto_proxies: true,
1369 encoder_seat: crate::export::EncoderSeat::default(),
1370 sample_rate: None,
1371 })
1372 }
1373
1374 /// Opens a project file written by [`save_project`](Self::save_project):
1375 /// the whole timeline, restored to where its playhead stood, paused like
1376 /// [`open`](Self::open).
1377 ///
1378 /// A *new* session rather than a reload of this one, so a load that fails
1379 /// leaves the caller's current session untouched -- atomic by
1380 /// construction. Every named file is opened and checked here: the
1381 /// *scaffolding* source -- the first that is not a still, since a picture
1382 /// carries no rate -- defines the timeline exactly as `open` does, every
1383 /// other source has to match it the way [`import`](Self::import) demands
1384 /// (a save renumbers, so which index that is says nothing), and every clip
1385 /// has to still be inside the file it plays from. A source that vanished or
1386 /// shrank since the save is a refusal naming it, not a silently shorter
1387 /// timeline -- the disappearing-file tolerance elsewhere in this type
1388 /// applies only *after* a project has loaded.
1389 ///
1390 /// The undo history is not saved: `undo` is `false` on a fresh load.
1391 pub fn open_project(path: &Path) -> crate::Result<Self> {
1392 Self::open_project_relinked(path, &[])
1393 }
1394
1395 /// What the last load changed to open the file, one line per clip it clamped
1396 /// (a clip that ran past its source). Empty for a project that opened as saved.
1397 pub fn load_warnings(&self) -> &[String] {
1398 &self.load_warnings
1399 }
1400
1401 /// [`open_project`](Self::open_project) with some saved paths replaced:
1402 /// each `(saved, found)` pair points the source the project saved at `saved`
1403 /// at `found` before anything is checked. A source whose file is still
1404 /// missing is **offline**: its clips stay on the timeline, nothing is read
1405 /// from it, and [`offline_sources`](Self::offline_sources) names it. Only a
1406 /// project with no present source at all is refused.
1407 /// A project none of whose sources is on disk: the timeline is the canvas and rate it was saved
1408 /// with, every clip stays, and every source is offline. Each source's length is the furthest
1409 /// frame a clip reaches into it, which is what a relink is checked against.
1410 fn open_all_offline(doc: crate::edith::Document) -> crate::Result<Self> {
1411 let (width, height) = doc.resolution.unwrap_or((1920, 1080));
1412 let fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0).unwrap_or(30.0);
1413 let counts: Vec<u32> = (0..doc.sources.len())
1414 .map(|i| {
1415 doc.lanes
1416 .iter()
1417 .flat_map(|(_, clips)| clips)
1418 .filter(|clip| clip.source == i)
1419 .map(|clip| clip.out_frame)
1420 .max()
1421 .unwrap_or(0)
1422 })
1423 .collect();
1424 let rates = vec![Rate::REAL_TIME; doc.sources.len()];
1425 let mut session = Self::empty(width, height, fps)?;
1426 session.project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)?
1427 .with_mix(&doc.gains, doc.limiter)
1428 .with_ducks(&doc.ducks)
1429 .with_voices(&doc.voices)
1430 .with_lane_names(&doc.names)
1431 .with_bins(doc.bins)
1432 .with_lane_flags(&doc.flags)
1433 .with_tone(doc.tone)
1434 .with_notes(doc.notes)
1435 .with_still_secs(doc.still_secs);
1436 session.counts = counts;
1437 session.rates = rates;
1438 Ok(session)
1439 }
1440
1441 pub fn open_project_relinked(path: &Path, relinks: &[(PathBuf, PathBuf)]) -> crate::Result<Self> {
1442 let mut doc = crate::edith::load(path)?;
1443 for source in doc.sources.iter_mut() {
1444 if let Some((_, found)) = relinks
1445 .iter()
1446 .find(|(saved, _)| crate::project::canonical(saved) == source.path)
1447 {
1448 *source = Source { fav: source.fav, bin: source.bin, ..Source::new(found, source.audio_stream) };
1449 }
1450 }
1451 if doc.sources.iter().all(|s| !crate::source_present(&s.path)) && !doc.sources.is_empty() {
1452 return Self::open_all_offline(doc);
1453 }
1454 // *Which* source scaffolds it: the first that is not a still, and index
1455 // 0 only when there is no other. A still defines no frame rate -- it is
1456 // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps
1457 // footage off a PNG that was imported first and so sits at index 0
1458 // (`Project::without_orphan_sources` keeps every source in session
1459 // order, so whatever was imported first is saved first) reads the
1460 // timeline as 30 fps and then refuses every file on it for not
1461 // matching. The rule this and
1462 // [`audio_source_of`] share: nothing may assume what source 0 *is*.
1463 //
1464 // A v9 file says what rate it was cut at, and that answer beats the
1465 // scaffold's *where the scaffold has none to give*: a still and a song
1466 // are both given a made-up rate (`IMAGE_ONLY_RATE`,
1467 // `AUDIO_ONLY_CANVAS`), so a timeline of nothing but those used to come
1468 // back at 30 fps however it was cut. A scaffold with a picture keeps
1469 // defining the timeline as it always did -- it is the file every clip
1470 // on the lane was conformed to, and the two agree by construction.
1471 let saved_fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0);
1472 // An offline source cannot scaffold: the first present non-still does,
1473 // then the first present anything.
1474 let scaffold = doc
1475 .sources
1476 .iter()
1477 .position(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
1478 .or_else(|| doc.sources.iter().position(|s| crate::source_present(&s.path)))
1479 .unwrap_or(0);
1480 // Owned: the sources move into the `Project` below, and the device is
1481 // opened after that (see the comment there).
1482 let first = doc
1483 .sources
1484 .get(scaffold)
1485 .cloned()
1486 .ok_or("the project names no sources")?;
1487 // The scaffolding source both defines the timeline and is what the
1488 // playhead's first picture comes from, so it is opened for playback
1489 // rather than merely probed.
1490 // One value, not two locals: everything below this line can refuse, and
1491 // locals drop in reverse declaration order -- a bare worker would join
1492 // its decode thread while the receiver next to it was still holding
1493 // that thread parked in `send`, which is a hang (see [`FrameStream`]).
1494 // Ungraded, and superseded before a frame of it is shown: the `seek` at
1495 // the end of this function reopens the playhead's span through
1496 // `start_span`, which is where a saved grade reaches the picture.
1497 // ...unless it has no picture to open: a project whose source 0 is a
1498 // song scaffolds the canvas the same way a fresh audio-only open does
1499 // ([`open_audio_only`](Self::open_audio_only)), and the placeholder
1500 // black stream is superseded by the `seek` at the end of this function
1501 // like every other worker opened here.
1502 // What source 0's own file declares about its light level, read the
1503 // same way [`open_stream`](Self::open_stream) reads it for a fresh
1504 // open: [`ContentLight::default()`] for a song or a still, neither of
1505 // which is graded.
1506 let content_light = if crate::is_audio(&first.path) || crate::is_image(&first.path) {
1507 ContentLight::default()
1508 } else {
1509 Demuxer::open(&first.path)
1510 .map(|(_, d)| d.light())
1511 .unwrap_or_default()
1512 };
1513 // The extension's word, corrected below the moment the header disagrees
1514 // with it (`NoVideoTrack`, the same fallback `open_stream` takes): every
1515 // later question in this function about source 0 asks *this*, not
1516 // `crate::is_audio` again, so a discovered song stays one for the rest
1517 // of the scaffold.
1518 let mut audio_only = crate::is_audio(&first.path);
1519 let (mut meta, stream) = match audio_only {
1520 true => {
1521 let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS;
1522 let frame_rate = saved_fps.unwrap_or(canvas_fps);
1523 let meta = VideoMeta {
1524 width,
1525 height,
1526 frame_rate,
1527 frame_count: audio_frames(&first.path, frame_rate)
1528 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
1529 codec: Codec::H264,
1530 color: ColorDescription::default(),
1531 matrix_assumed: false,
1532 rotation: Rotation::None,
1533 // No container said anything about these: the canvas this engine drew
1534 // itself is square pixels at the size it was drawn at.
1535 coded_width: width,
1536 coded_height: height,
1537 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1538 };
1539 (meta, DecodeSession::open_black(width, height, 1))
1540 }
1541 // ...and a still scaffolds its own picture as the canvas, exactly
1542 // as a fresh `open_image_only` does, with the same placeholder
1543 // stream the `seek` at the end supersedes.
1544 false if crate::is_image(&first.path) => {
1545 let still = crate::decode::Still::open(&first.path)
1546 .map_err(|e| format!("source {}: {e}", first.path.display()))?;
1547 let frame_rate = saved_fps.unwrap_or(IMAGE_ONLY_RATE);
1548 let meta = VideoMeta {
1549 width: still.width,
1550 height: still.height,
1551 frame_rate,
1552 frame_count: image_frames(frame_rate),
1553 codec: Codec::H264,
1554 color: ColorDescription::default(),
1555 matrix_assumed: false,
1556 // `Rotation::None` is honest, not a shrug: `Still::open`
1557 // made the file's own turn before these planes were
1558 // written, so the pair below is already the displayed one.
1559 rotation: Rotation::None,
1560 // No container said anything about these: the picture this
1561 // engine decoded itself is square pixels at its own size.
1562 coded_width: still.width,
1563 coded_height: still.height,
1564 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1565 };
1566 let stream = DecodeSession::open_still(
1567 &first.path,
1568 0,
1569 1,
1570 ColorParams::default(),
1571 TransformParams::default(),
1572 Composer::passthrough(),
1573 )?;
1574 (meta, stream)
1575 }
1576 false => match DecodeSession::open_worker(
1577 &first.path,
1578 0,
1579 u32::MAX,
1580 ColorParams::default(),
1581 TransformParams::default(),
1582 Composer::passthrough(),
1583 // The saved rendition, from the document rather than from the
1584 // project (which is built below): this placeholder is what the
1585 // window shows until the `seek` at the end reopens the span.
1586 doc.tone,
1587 ) {
1588 Ok(opened) => opened,
1589 // A saved source whose extension named a film but whose header
1590 // names no picture: the same door a fresh open falls to
1591 // (`open_stream`), so a project first cut around a song muxed
1592 // into an `.mp4` reloads instead of refusing on a track that was
1593 // never there to begin with.
1594 Err(e) if NoVideoTrack::is_it(&e) => {
1595 audio_only = true;
1596 let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS;
1597 let frame_rate = saved_fps.unwrap_or(canvas_fps);
1598 let meta = VideoMeta {
1599 width,
1600 height,
1601 frame_rate,
1602 frame_count: audio_frames(&first.path, frame_rate)
1603 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
1604 codec: Codec::H264,
1605 color: ColorDescription::default(),
1606 matrix_assumed: false,
1607 rotation: Rotation::None,
1608 // No container said anything about these: the canvas this engine drew
1609 // itself is square pixels at the size it was drawn at.
1610 coded_width: width,
1611 coded_height: height,
1612 pixel_aspect: crate::demux::PixelAspect::SQUARE,
1613 };
1614 (meta, DecodeSession::open_black(width, height, 1))
1615 }
1616 Err(e) => return Err(format!("source {}: {e}", first.path.display()).into()),
1617 },
1618 };
1619 // The project's own resolution, which is source 0's picture unless the
1620 // file says otherwise -- every dialect before v7 had no way to say it,
1621 // and that default is exactly what those projects meant.
1622 let native = (meta.width, meta.height);
1623 if let Some((width, height)) = doc.resolution {
1624 meta.width = width;
1625 meta.height = height;
1626 }
1627 // ...and the project's own *rate*, which is the scaffold's unless the
1628 // file says otherwise. The two made-up rates above already took the
1629 // saved one (their counts are computed from it); a scaffold with a
1630 // picture keeps its own here, so a project cut at a rate nobody picked
1631 // is the file it always was -- and one where a rate *was* picked
1632 // ([`set_frame_rate`](Self::set_frame_rate)) comes back at it rather
1633 // than at the media's, which would leave every clip number counted in
1634 // frames the timeline no longer has.
1635 let native_fps = match audio_only {
1636 true => AUDIO_ONLY_CANVAS.2,
1637 false if crate::is_image(&first.path) => IMAGE_ONLY_RATE,
1638 false => meta.frame_rate,
1639 };
1640 if let Some(fps) = saved_fps {
1641 meta.frame_rate = fps;
1642 }
1643 // A song and a still have no rate of their own to be conformed from:
1644 // their length above was counted in the timeline's frames already,
1645 // whatever those are. A file with pictures is read through [`Rate`] like
1646 // any other source when the project is cut at another rate.
1647 let made_up = audio_only || crate::is_image(&first.path);
1648 let scaffold_rate = match made_up || native_fps == meta.frame_rate {
1649 true => Rate::REAL_TIME,
1650 false => Rate::from_fps(native_fps, meta.frame_rate)
1651 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
1652 };
1653 let first_audio = first_audio_of(&doc.sources)?;
1654
1655 // In source order, with the scaffold's own count in its own slot: the
1656 // clip check below indexes this list by source, so it must line up with
1657 // `doc.sources` whichever entry the scaffolding came from.
1658 let mut counts = Vec::with_capacity(doc.sources.len());
1659 // Beside it, one entry per source, grown at every `push` below: the
1660 // scaffold defines the rate, so it is read frame for frame; every other
1661 // one is however long it is *in this timeline's frames*, which is the
1662 // length `import` noted for it and the wall the clip check below holds
1663 // it to.
1664 let mut rates = Vec::with_capacity(doc.sources.len());
1665 for (i, source) in doc.sources.iter().enumerate() {
1666 if i == scaffold {
1667 counts.push(scaffold_rate.timeline_at(meta.frame_count));
1668 rates.push(scaffold_rate);
1669 continue;
1670 }
1671 // Offline: nothing to check it against. Its length is the furthest
1672 // frame a clip reaches into it, so the clip check below holds.
1673 if !crate::source_present(&source.path) {
1674 let reach = doc
1675 .lanes
1676 .iter()
1677 .flat_map(|(_, clips)| clips)
1678 .filter(|clip| clip.source == i)
1679 .map(|clip| clip.out_frame)
1680 .max()
1681 .unwrap_or(0);
1682 counts.push(reach);
1683 rates.push(Rate::REAL_TIME);
1684 continue;
1685 }
1686 // A still has neither a rate to match nor a track to match with:
1687 // its length is the one it is held to, recomputed exactly as the
1688 // import that first noted it did ([`image_frames`]), which is what
1689 // makes the clip check below meaningful on a reload.
1690 if crate::is_image(&source.path) {
1691 crate::decode::image_size(&source.path)
1692 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1693 counts.push(image_frames(meta.frame_rate));
1694 rates.push(Rate::REAL_TIME);
1695 continue;
1696 }
1697 // A source with no picture is checked on what it does have, and
1698 // its length is its playing time -- the same two answers `import`
1699 // gave it when it first joined the timeline.
1700 if crate::is_audio(&source.path) {
1701 audio_matches(source, &first_audio)
1702 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1703 counts.push(audio_frames(&source.path, meta.frame_rate)?);
1704 rates.push(Rate::REAL_TIME);
1705 continue;
1706 }
1707 // A container with sound but no picture (an audio-only mp4 behind a
1708 // video extension) is held and counted exactly as `import_audio` holds
1709 // and counts it when it first joins the timeline -- the same door
1710 // `import` takes, so a file that imports always reopens.
1711 let (other, _) = match Demuxer::open(&source.path) {
1712 Ok(opened) => opened,
1713 Err(e) if NoVideoTrack::is_it(&e) => {
1714 audio_matches(source, &first_audio)
1715 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1716 counts.push(audio_frames(&source.path, meta.frame_rate)?);
1717 rates.push(Rate::REAL_TIME);
1718 continue;
1719 }
1720 Err(e) => return Err(format!("source {}: {e}", source.path.display()).into()),
1721 };
1722 let rate = matches_timeline(source, &other, &meta, &first_audio)
1723 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
1724 counts.push(rate.timeline_at(other.frame_count));
1725 rates.push(rate);
1726 }
1727 // A still is silent, so a clip playing one on an audio lane is a
1728 // segment the audio worker would open a PNG for. Refused by name
1729 // here, which is the one door it can arrive through
1730 // (`place_stream_at` never puts one there). An audio file on a
1731 // *video* lane used to be refused the same way; it plays as a
1732 // waveform visualizer now ([`DecodeSession::open_visualizer`]).
1733 for (kind, clip) in doc
1734 .lanes
1735 .iter()
1736 .chain(doc.sequences.iter().flat_map(|s| s.doc.lanes.iter()))
1737 .flat_map(|(kind, clips)| clips.iter().map(move |clip| (*kind, clip)))
1738 .filter(|(_, clip)| !crate::project::is_sequence_source(clip.source))
1739 {
1740 let path = &doc.sources[clip.source].path;
1741 if kind == LaneKind::Audio && crate::is_image(path) {
1742 return Err(format!(
1743 "{} is a still image: it can only play on a video lane",
1744 path.display()
1745 )
1746 .into());
1747 }
1748 }
1749 // Each lane is held to the length its own clips are walled by ([`wall_table`]).
1750 // A clip that runs past its source is clamped to the source's end and
1751 // reported in `warnings`, not refused: a project that was saved with one
1752 // (a placement or a trim that used the wrong length) must still open, and
1753 // the clamp is the one change that keeps every later edit's walls true.
1754 let audio_walls = wall_table(&doc.sources, &counts, meta.frame_rate, Lane::A1);
1755 let mut warnings = Vec::new();
1756 let mut i = 0;
1757 let sources = doc.sources.clone();
1758 for (kind, clips) in doc
1759 .lanes
1760 .iter_mut()
1761 .chain(doc.sequences.iter_mut().flat_map(|s| s.doc.lanes.iter_mut()))
1762 {
1763 let walls: &[u32] = if *kind == LaneKind::Audio { &audio_walls } else { &counts };
1764 for clip in clips.iter_mut() {
1765 let n = i;
1766 i += 1;
1767 if crate::project::is_sequence_source(clip.source) {
1768 continue;
1769 }
1770 let wall = walls[clip.source];
1771 if clip.out_frame > wall && wall > 0 {
1772 warnings.push(format!(
1773 "clip {n} ended at frame {} but {} has {wall} frames: clamped to {wall}",
1774 clip.out_frame,
1775 sources[clip.source].path.display(),
1776 ));
1777 clip.out_frame = wall;
1778 if clip.in_frame >= clip.out_frame {
1779 clip.in_frame = clip.out_frame - 1;
1780 }
1781 }
1782 }
1783 }
1784 // The subtitle files are read here rather than in the parser: a
1785 // `.edith` names them and holds no cues. One that has gone missing, or
1786 // whose track is a codec of pictures, comes back listed and refused by
1787 // name ([`crate::subtitle::open_all`]) -- a project does not stop
1788 // opening over a subtitle, and a re-save does not lose the row.
1789 //
1790 // All of them in one call, in saved order, because a file is walked
1791 // whole to reach one track: a film whose project names many of its
1792 // tracks is one walk here rather than one per row.
1793 let playhead = doc.playhead;
1794 let (proxy, auto_proxy, encoder, sample_rate) = (doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate);
1795 let seq_active = doc.seq_active.take();
1796 let seq_order = std::mem::take(&mut doc.seq_order);
1797 let seq_docs = std::mem::take(&mut doc.sequences);
1798 let mcams = std::mem::take(&mut doc.mcams);
1799 let mut project = project_of(doc, &meta)?;
1800 if let Some((active, name)) = seq_active {
1801 // The fresh project's placeholder sequence is not the file's: the file's
1802 // sequences (the active one by `set_sequence_meta`) are all there is.
1803 project.clear_sequences();
1804 for sd in seq_docs {
1805 let other = project_of(sd.doc, &meta)?;
1806 project.absorb_sequence(sd.id, &sd.name, other)?;
1807 }
1808 project.set_sequence_meta(active, &name, &seq_order);
1809 project.set_multicam(&mcams)?;
1810 project.check_sequences()?;
1811 }
1812 let span = crate::export::stack_span_at(&project.render_view(), 0);
1813 // Last, because it is the one thing here that cannot be taken back: the
1814 // feeder thread outlives the `Audio` value (it holds its own clones) and
1815 // only a session's `drop` retires it, so a refusal above this line would
1816 // leave a PipeWire stream and a thread behind for a project that never
1817 // opened. Nothing before it needs the device.
1818 //
1819 // On the source the timeline's *sound* is defined by, which is the
1820 // scaffold unless that one is a still ([`audio_source_of`]): opening a
1821 // PNG as the device is a session with no audio at all, however many
1822 // clips with sound are on its lanes.
1823 //
1824 // `audio_source_of` alone only rules out a still; it says nothing
1825 // about whether the file it lands on actually *has* a track. A device
1826 // pinned to the first candidate that opens silent (no track, or one
1827 // the decoder refuses) would leave every later clip's sound unheard
1828 // for the rest of the session, however many other sources on the
1829 // timeline have real audio -- so this walks forward past a silent
1830 // candidate to the first source that really opens a device, and keeps
1831 // only the last attempt's reason when none of them do (a later
1832 // source's silence is not worth reporting over an earlier one's).
1833 let (audio, audio_disabled) = {
1834 let mut opened = (None, None);
1835 for source in project
1836 .sources()
1837 .iter()
1838 .filter(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
1839 {
1840 opened = open_audio(&source.path, source.audio_stream);
1841 if opened.0.is_some() {
1842 break;
1843 }
1844 }
1845 opened
1846 };
1847 let mut session = Self {
1848 scrub: Scrub::default(),
1849 meta,
1850 load_warnings: warnings,
1851 content_light,
1852 native,
1853 native_fps,
1854 frames: stream.frames,
1855 worker: stream.worker,
1856 backend: stream.backend,
1857 video_failure: stream.failure,
1858 retired: Vec::new(),
1859 restarts: 0,
1860 clock: PlaybackClock::new(match audio {
1861 Some(_) => ClockSource::Audio,
1862 None => ClockSource::Wall,
1863 }),
1864 audio,
1865 audio_disabled,
1866 project,
1867 counts,
1868 probes: std::collections::HashMap::new(),
1869 rates,
1870 span_rate: Rate::REAL_TIME,
1871 span,
1872 span_priming: true,
1873 feed: Feed::Live,
1874 back: Back::Off,
1875 dissolve: None,
1876 view: None,
1877 eos: false,
1878 eos_end: 0.0,
1879 mix: None,
1880 solo: Vec::new(),
1881 priming: false,
1882 drop_late: false,
1883 // What the file says, and `false` for every dialect before v12:
1884 // a project cut on the films themselves opens on them.
1885 proxies: proxy,
1886 // ...and what it says about making them, which is "yes" for every
1887 // dialect before v13 and for one that leaves the line out.
1888 auto_proxies: auto_proxy,
1889 // ...and which encoder it exports with, which is the seat this
1890 // machine has for every dialect before v14.
1891 encoder_seat: encoder,
1892 sample_rate,
1893 };
1894 // The scaffolding above opened source 0 from its first frame and the
1895 // whole of its audio; this puts both onto the clip the playhead is
1896 // actually in -- a seek replaces the decoder and supersedes the audio
1897 // worker by epoch, exactly as it does after an edit. It also clamps,
1898 // so a playhead past a hand-shortened timeline lands on the last frame.
1899 session.seek(f64::from(playhead) / meta.frame_rate);
1900 Ok(session)
1901 }
1902
1903 pub fn meta(&self) -> &VideoMeta {
1904 &self.meta
1905 }
1906
1907 /// What the pictures now arriving are being decoded by: the clip under the
1908 /// playhead, since one video worker feeds the composite at a time. An
1909 /// atomic load -- a front-end may ask it every repaint -- and it is what
1910 /// *opened*, so a clip whose hardware session fell back to software reads
1911 /// [`Backend::Software`] from the frame that fallback happened.
1912 pub fn decode_backend(&self) -> Backend {
1913 self.backend.get()
1914 }
1915
1916 /// What an export of this timeline would encode the *sound* with, before
1917 /// one is started: the copy an mp4 normally makes, or the software encoder
1918 /// the format (or an equalized lane) forces. Pure -- no probe, no file
1919 /// opened -- so a card may ask it per repaint; the picture's half costs a
1920 /// plugin open and lives in [`crate::export::planned_video`].
1921 pub fn planned_audio(&self, format: crate::export::Format, ranged: bool) -> &'static str {
1922 crate::export::planned_audio(&self.project.render_view(), format, ranged)
1923 }
1924
1925 /// The timeline an export started right now would be run against, owned:
1926 /// what lets a front-end ask [`crate::export::planned_seats`] what that
1927 /// export would open *off* its render thread, which is the only way to ask
1928 /// a question that opens files. The very snapshot
1929 /// [`export_to_with`](Self::export_to_with) hands the worker, so the answer
1930 /// is about the export that would really start.
1931 pub fn export_snapshot(&self) -> (crate::project::Project, VideoMeta) {
1932 (self.project.export_snapshot(), self.meta)
1933 }
1934
1935 /// The timeline's frame rate: what an editor timeline is read at ([`crate::interchange::otio::read`]).
1936 pub fn timeline_frame_rate(&self) -> f64 {
1937 self.meta.frame_rate
1938 }
1939
1940 /// The active sequence as an editor timeline, for the interchange formats ([`crate::interchange`]).
1941 pub fn timeline_snapshot(&self) -> crate::interchange::Timeline {
1942 let (project, meta) = self.export_snapshot();
1943 crate::interchange::of_project(&project, meta.frame_rate, (meta.width, meta.height))
1944 }
1945
1946 /// The composed picture at timeline `frame`, headless and exact: what
1947 /// export writes for that frame, scaled to fit `width` x `height`. Does not
1948 /// touch the playback clock. See [`crate::export::compose_at`].
1949 pub fn compose_at(
1950 &self,
1951 frame: u32,
1952 width: u32,
1953 height: u32,
1954 ) -> crate::Result<crate::decode::Frame> {
1955 let (project, meta) = self.export_snapshot();
1956 crate::export::compose_at(&project, &meta, frame, width, height)
1957 }
1958
1959 /// What an export would do about the tracks at `picks` --
1960 /// [`crate::export::planned_subtitles`], asked of the project a front-end is
1961 /// holding, and pure for the same reason. `picks` is any run of rows of
1962 /// [`subtitles`](Self::subtitles): the whole
1963 /// [`ExportSettings::subtitles`](crate::export::ExportSettings::subtitles)
1964 /// list a card is about to send (`picks.iter().copied()`) as much as a
1965 /// single `Some(row)`.
1966 pub fn planned_subtitles(
1967 &self,
1968 format: crate::export::Format,
1969 picks: impl IntoIterator<Item = usize>,
1970 ) -> String {
1971 crate::export::planned_subtitles(&self.project.render_view(), format, picks)
1972 }
1973
1974 /// Where the cues of the track at `pick` land on *this* timeline --
1975 /// [`crate::export::timeline_cues`], the very map an export writes the file
1976 /// with, so a front-end that draws these draws what the file will say. On a
1977 /// rippled or cut timeline that is the whole point: an embedded track rides
1978 /// the spans that still play it, and a standalone `.srt` keeps the
1979 /// timeline's own clock, clipped to its length.
1980 ///
1981 /// Empty for a row that is not there and for a track that could not be read.
1982 /// Pure and file-free, so it may be asked per repaint; the cost is a walk of
1983 /// the spans and of the cues.
1984 pub fn timeline_cues(&self, pick: usize) -> Vec<crate::subtitle::Cue> {
1985 self.project
1986 .subtitles()
1987 .get(pick)
1988 .map_or_else(Vec::new, |t| {
1989 crate::export::timeline_cues(&self.project.render_view(), t, self.meta.frame_rate)
1990 })
1991 }
1992
1993 /// Why the sound's rate is not a choice for this timeline in this format --
1994 /// [`crate::export::audio_rate_refusal`], asked of the project a front-end
1995 /// is holding, and pure for the same reason.
1996 pub fn audio_rate_refusal(
1997 &self,
1998 format: crate::export::Format,
1999 ranged: bool,
2000 ) -> Option<&'static str> {
2001 crate::export::audio_rate_refusal(&self.project.render_view(), format, ranged)
2002 }
2003
2004 /// Why this session plays silent although the file has sound -- an audio
2005 /// track in a codec we cannot decode, or one the decoder refused. `None`
2006 /// when there is audio, and for a file that never had any. A front-end
2007 /// shows it once, at open: without it the whole thing is a stderr line.
2008 pub fn audio_disabled_reason(&self) -> Option<&str> {
2009 self.audio_disabled.as_deref()
2010 }
2011
2012 /// Why the picture stopped short of the end of its range, if it did -- the
2013 /// video twin of [`Self::audio_disabled_reason`], and the reason a corrupt
2014 /// file used to be indistinguishable from a finished one.
2015 ///
2016 /// A closed frame channel is not an answer: a span that ran to the end of
2017 /// the file and a span that gave up on a broken packet both drop the
2018 /// sender, and [`Self::try_frame`] returns `None` for either. The app read
2019 /// that as end-of-stream, so a file with a damaged middle froze on its last
2020 /// good picture and the transport said ENDED -- no notice, no banner, and
2021 /// nothing on the screen to say the film had stopped being the film.
2022 ///
2023 /// `None` for a span that played its whole range, which is the ordinary
2024 /// case and the one that must stay silent: a notice that fires on every
2025 /// film is a notice nobody reads. The reason is the engine's own words, for
2026 /// the same reason the sound one is.
2027 pub fn video_failure_reason(&self) -> Option<String> {
2028 self.video_failure.reason()
2029 }
2030
2031 /// The files this timeline plays from, index 0 first -- a caller needs it
2032 /// to name an export or a window after the media rather than the project.
2033 pub fn sources(&self) -> &[Source] {
2034 self.project.sources()
2035 }
2036
2037 /// The subtitle tracks on this timeline, in the order they were added: what
2038 /// a front-end lists and what [`save_project`](Self::save_project) writes.
2039 /// A track that could not be read is *in* this list, saying why
2040 /// ([`crate::subtitle::SubtitleTrack::refused`]) -- listed and skipped, not
2041 /// dropped.
2042 pub fn subtitles(&self) -> &[crate::subtitle::SubtitleTrack] {
2043 self.project.subtitles()
2044 }
2045
2046 /// Adds subtitles from `path`: every subtitle track of a Matroska file, or
2047 /// the one track a standalone `.srt`/`.vtt`/`.ass` is. Hands back how many
2048 /// were added -- 0 for a file whose tracks are all on the timeline already,
2049 /// since importing the same file twice is the same subtitles.
2050 ///
2051 /// An error only when the file cannot be read *at all*; a track this cannot
2052 /// parse is added refused by name, for the reason
2053 /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves:
2054 /// subtitles are not clips and land on no lane.
2055 pub fn import_subtitles(&mut self, path: &Path) -> crate::Result<usize> {
2056 let tracks = Self::parse_subtitles(path)?;
2057 // A file that was walked and carries none is refused as *that*, because
2058 // the alternative -- 0 added -- is the very sentence a file whose tracks
2059 // are already on this timeline gets, and the two are opposite answers a
2060 // person acts differently on. Said only after the walk actually looked
2061 // ([`crate::subtitle::of_media`]); a *file* that is not a container at
2062 // all never reaches here, [`parse_subtitles`](Self::parse_subtitles)
2063 // refuses it in its own words.
2064 if tracks.is_empty() {
2065 return Err(Self::no_subtitles_in(path));
2066 }
2067 Ok(self.add_subtitle_tracks(tracks))
2068 }
2069
2070 /// The reading half of [`import_subtitles`](Self::import_subtitles), with no
2071 /// session in it: every subtitle track of a Matroska file, or the one track
2072 /// a standalone `.srt`/`.vtt`/`.ass` is, cues and all. Same refusal rule.
2073 ///
2074 /// This is the half that costs -- a walk of the whole container, measured at
2075 /// 210 ms on a 25 GB 35-track file and 1.3 s on a 3 GB one whose pages were
2076 /// cold -- so a front-end runs *this* on its background executor and hands
2077 /// what comes back to [`add_subtitle_tracks`](Self::add_subtitle_tracks),
2078 /// which costs a push. Both doors are this one function, so the import
2079 /// button and the background one cannot drift apart.
2080 pub fn parse_subtitles(path: &Path) -> crate::Result<Vec<crate::subtitle::SubtitleTrack>> {
2081 // The containers that carry subtitle tracks *inside* them: every
2082 // Matroska one ([`crate::demux::is_matroska`], which is where `.mks` --
2083 // the subtitles alone -- comes in) and the mp4 family, whose `tx3g`
2084 // timed text is what an mp4 export of this project's own writes, so a
2085 // file edith wrote is a file edith imports back. A transport stream
2086 // carries Blu-ray/AVCHD PGS bitmaps the same way.
2087 let tracks = match crate::demux::is_matroska(path)
2088 || crate::demux::is_mpegts(path)
2089 || path.extension().is_some_and(|e| {
2090 matches!(
2091 e.to_string_lossy().to_ascii_lowercase().as_str(),
2092 "mp4" | "m4v" | "mov" | "3gp" | "3g2"
2093 )
2094 }) {
2095 true => crate::subtitle::of_media(path)?,
2096 false => vec![crate::subtitle::open(path, None)],
2097 };
2098 // A standalone file that could not be parsed is a refusal here rather
2099 // than a row nobody asked for: the import is the moment to say so, and
2100 // the load is the moment to keep it.
2101 if let [one] = &tracks[..]
2102 && one.track.is_none()
2103 && let Some(why) = &one.refused
2104 {
2105 return Err(why.clone().into());
2106 }
2107 Ok(tracks)
2108 }
2109
2110 /// What a file the walk found no subtitle track in is refused with,
2111 /// wherever the refusal is worded: the engine's own door
2112 /// ([`import_subtitles`](Self::import_subtitles)) and a front-end that
2113 /// splits the walk from the push ([`parse_subtitles`](Self::parse_subtitles)
2114 /// then [`add_subtitle_tracks`](Self::add_subtitle_tracks)) must not tell a
2115 /// person two different stories about the same file.
2116 pub fn no_subtitles_in(path: &Path) -> crate::Error {
2117 format!("no subtitle tracks in {}", path.display()).into()
2118 }
2119
2120 /// Puts tracks already read by [`parse_subtitles`](Self::parse_subtitles)
2121 /// on this timeline, in the order given. Hands back how many actually went
2122 /// on: [`Project::add_subtitles`] drops the ones already here -- same file,
2123 /// same track number -- so 0 is "this file's subtitles are on the timeline
2124 /// already", which is the sentence a front-end says.
2125 ///
2126 /// The whole of what an import costs the thread that calls it, which is why
2127 /// the parse is a separate door: nothing here opens, seeks or decodes.
2128 /// Subtitles are not clips and land on no lane, so nothing playable changes
2129 /// and no undo step is pushed ([`Project::remove_subtitles`] says why).
2130 /// [`import_subtitles`](Self::import_subtitles) with a language on its tracks: `lang` as a
2131 /// person typed it, on every track, or else a standalone file's own name
2132 /// ([`crate::subtitle::import_language`]). Returns the count added and the language with where
2133 /// it came from, `None` when none was set. One undo step, as the import is.
2134 pub fn import_subtitles_as(
2135 &mut self,
2136 path: &Path,
2137 lang: Option<&str>,
2138 ) -> crate::Result<(usize, Option<(String, &'static str)>)> {
2139 let mut tracks = Self::parse_subtitles(path)?;
2140 if tracks.is_empty() {
2141 return Err(Self::no_subtitles_in(path));
2142 }
2143 let standalone = tracks.iter().all(|t| t.track.is_none());
2144 let named = if lang.is_some() || standalone {
2145 crate::subtitle::import_language(path, lang)?
2146 } else {
2147 None
2148 };
2149 if let Some((code, _)) = &named {
2150 for t in &mut tracks {
2151 if lang.is_some() || t.track.is_none() {
2152 crate::subtitle::set_language(t, code);
2153 }
2154 }
2155 }
2156 let n = self.add_subtitle_tracks(tracks);
2157 Ok((n, named))
2158 }
2159
2160 /// Names the language of subtitle track `track` ([`Project::set_subtitle_language`]). One undo step.
2161 pub fn set_subtitle_language(&mut self, track: usize, code: &str) -> bool {
2162 self.project.set_subtitle_language(track, code)
2163 }
2164
2165 pub fn add_subtitle_tracks(&mut self, tracks: Vec<crate::subtitle::SubtitleTrack>) -> usize {
2166 // One undo step for the whole import (see [`Project::add_subtitles_all`]).
2167 self.project.add_subtitles_all(&tracks)
2168 }
2169
2170 /// Takes the track at `idx` off this timeline -- the door a subtitle row's
2171 /// own remove goes through, the way [`import_subtitles`](
2172 /// Self::import_subtitles) is the door that puts one on. Refused in
2173 /// [`Project::remove_subtitles`]'s words for a row this timeline does not
2174 /// have, and for one a caption on a subtitle lane still plays -- delete
2175 /// those placements first, or the words under them would change.
2176 ///
2177 /// Nothing playable changes and no worker was opened against a cue, so
2178 /// unlike [`remove_source`](Self::remove_source) this does not reseek. Rows
2179 /// past `idx` move down by one: a caller holding a picked row (the export's
2180 /// subtitle pick) has to fix it up or drop it; the placements on the lanes
2181 /// are walked down with it and need no fixing.
2182 ///
2183 /// One undo step, and the reindex with it ([`Project::remove_subtitles`]'s
2184 /// own entry): every step in the history names its tracks by index into the
2185 /// palette, so an entry carries the palette it was taken beside its lanes --
2186 /// which is what lets a `z` put this row back, and every placement that
2187 /// moved down with it. What that entry cannot bring back is the *pick*: it
2188 /// is the caller's, and a caller holding one fixes it up or drops it
2189 /// ([`crate::subs::sub_pick_after_restore`]).
2190 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
2191 self.project.remove_subtitles(idx)
2192 }
2193
2194 /// Writes the timeline to `path` as a `.edith`, atomically (see
2195 /// [`crate::edith`]). Sources no clip plays from are left out, and the
2196 /// playhead is saved with it so a reopened project resumes where it stood.
2197 ///
2198 /// Refused, writing nothing, for a session whose library is empty (every
2199 /// row removed, [`Project::remove_source`]): a file naming no source has no
2200 /// timeline in it and [`open_project`](Self::open_project) could only
2201 /// refuse it, so the refusal belongs here, where nothing has been
2202 /// overwritten yet.
2203 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
2204 if self.project.sources().is_empty() {
2205 return Err("this project names no file: there is nothing to save".into());
2206 }
2207 self.save_project_noted(path).map(|_| ())
2208 }
2209
2210 /// [`save_project`](Self::save_project) that also returns what it had to change
2211 /// to write the file, one plain sentence per clip, for the front-end to show. A
2212 /// clip that runs past its source's end (a placement or an edit that used the
2213 /// wrong length, or a project saved before the walls held) is shortened to the
2214 /// source's end on the way out, never refused: the user's work is saved, and the
2215 /// note says what was shortened.
2216 pub fn save_project_noted(&self, path: &Path) -> crate::Result<Vec<String>> {
2217 if self.project.sources().is_empty() {
2218 return Err("this project names no file: there is nothing to save".into());
2219 }
2220 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
2221 let mut notes = Vec::new();
2222 let mut main = self.project.clone();
2223 notes.extend(self.wall_notes(&main.clamp_to_walls(&picture, &sound), None));
2224 // The parked sequences are saved whole too, so they are held to the same walls.
2225 let mut parked = Vec::new();
2226 for (id, name, active) in self.project.sequence_rows() {
2227 if !active {
2228 let mut other = self.project.as_sequence(id)?;
2229 notes.extend(self.wall_notes(&other.clamp_to_walls(&picture, &sound), Some(&name)));
2230 parked.push((id, other));
2231 }
2232 }
2233 self.write_project(path, &main, &parked)?;
2234 Ok(notes)
2235 }
2236
2237 /// One plain sentence per clip [`Project::clamp_to_walls`] shortened, naming the
2238 /// clip by its file's name and its lane. `seq` names a parked sequence.
2239 fn wall_notes(&self, clamps: &[crate::project::WallClamp], seq: Option<&str>) -> Vec<String> {
2240 let of = seq.map_or_else(String::new, |n| format!(" in sequence \"{n}\""));
2241 clamps
2242 .iter()
2243 .map(|c| {
2244 let path = &self.project.sources()[c.source].path;
2245 let name = path.file_stem().map_or_else(
2246 || path.display().to_string(),
2247 |s| s.to_string_lossy().into_owned(),
2248 );
2249 let what = match c.lane.kind {
2250 LaneKind::Audio => "sound",
2251 _ => "picture",
2252 };
2253 format!(
2254 "The {what} of \"{name}\" on {} runs past the end of its file{of}. It was shortened to fit.",
2255 c.lane.label(),
2256 )
2257 })
2258 .collect()
2259 }
2260
2261 /// Writes the timeline to `path` for an autosave: exactly what
2262 /// [`save_project`](Self::save_project) writes, minus its wall check. A clip
2263 /// that runs past its source is written as it is, not refused, so an
2264 /// autosave can never fail on a session's state -- the one place a refusal
2265 /// would lose the edits it was meant to keep. [`open_project`](Self::open_project)
2266 /// already clamps such a clip to its source with a warning when the file is
2267 /// read back, so the file still opens.
2268 ///
2269 /// The one refusal kept is an empty library ([`save_project`](Self::save_project)):
2270 /// a file that names no source has no timeline in it to write.
2271 pub fn save_autosave(&self, path: &Path) -> crate::Result<()> {
2272 if self.project.sources().is_empty() {
2273 return Err("this project names no file: there is nothing to save".into());
2274 }
2275 let mut parked = Vec::new();
2276 for (id, _, active) in self.project.sequence_rows() {
2277 if !active {
2278 parked.push((id, self.project.as_sequence(id)?));
2279 }
2280 }
2281 self.write_project(path, &self.project, &parked)
2282 }
2283
2284 /// The write [`save_project`](Self::save_project) and
2285 /// [`save_autosave`](Self::save_autosave) share: the project as it stands,
2286 /// atomically, with its playhead and settings.
2287 /// `main` is the active sequence as it is to be written and `parked` the others,
2288 /// by id, already held to their walls.
2289 fn write_project(&self, path: &Path, main: &Project, parked: &[(u32, Project)]) -> crate::Result<()> {
2290 let dir = crate::edith::project_dir(path);
2291 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
2292 .min(main.timeline_frames().saturating_sub(1));
2293 let main_bytes = self.encode_sequence(&dir, main, playhead);
2294 let main_bytes = crate::edith::binned(main_bytes, self.project.sources(), self.project.bins());
2295 let main_bytes = crate::edith::noted(main_bytes, self.project.notes(), self.project.still_secs());
2296 if !self.project.uses_sequences() {
2297 return crate::edith::write_atomic(path, &main_bytes);
2298 }
2299 // Several sequences: the active one is the body, the others follow as blocks of
2300 // their own, each a whole document (v45).
2301 let mut blocks = Vec::new();
2302 for (id, name, active) in self.project.sequence_rows() {
2303 if active {
2304 continue;
2305 }
2306 let Some((_, other)) = parked.iter().find(|(p, _)| *p == id) else { continue };
2307 let at = playhead.min(other.timeline_frames().saturating_sub(1));
2308 blocks.push(crate::edith::SeqBlock { id, name, bytes: self.encode_sequence(&dir, other, at) });
2309 }
2310 let order: Vec<u32> = self.project.sequence_rows().iter().map(|r| r.0).collect();
2311 let active = self.project.active_sequence();
2312 let name = self.project.sequence_name(active).unwrap_or("Sequence").to_string();
2313 let bytes = crate::edith::sequenced(main_bytes, (active, &name), &order, &blocks, &self.project.multicam_rows());
2314 crate::edith::write_atomic(path, &bytes)
2315 }
2316
2317 /// One sequence as the bytes of a standalone project document: `project` has that
2318 /// sequence active.
2319 fn encode_sequence(&self, dir: &Path, project: &Project, playhead: u32) -> Vec<u8> {
2320 let (sources, lanes, eq, color, transform) = project.without_orphan_sources();
2321 crate::edith::encode_flagged(
2322 dir,
2323 &sources,
2324 &lanes,
2325 // The lane volumes and the limiter with them: a mix that vanished
2326 // on a reload would be a mix nobody could keep, and both are the
2327 // project's, not this machine's (the monitoring volume is not
2328 // written and never will be).
2329 &project.lane_gains(),
2330 // ...and what is placed on each lane, in the same order again: the
2331 // captions, which are the only thing a subtitle lane holds.
2332 &project.lane_subs(),
2333 // The subtitle tracks with them, by reference: which file the cues
2334 // are in, never the cues (see [`crate::edith`]).
2335 project.subtitles(),
2336 &eq,
2337 &color,
2338 &transform,
2339 (self.meta.width, self.meta.height),
2340 // ...and the rate it was cut at, which nothing else in the file
2341 // says: a timeline of stills and songs used to come back at
2342 // whatever its scaffold implied (`open_project`).
2343 Some(self.meta.frame_rate),
2344 // ...and which rendition its HDR media is watched in, for the same
2345 // reason: a picked look that vanished on a reload is a look nobody
2346 // could keep.
2347 project.tone(),
2348 // ...and whether it is cut on the stand-ins, for the same reason.
2349 // *Which* files have one is not saved: [`crate::proxy`] finds that
2350 // out from the film itself, so nothing here can go stale.
2351 self.proxies,
2352 // ...and whether it makes them by itself, which is a different
2353 // question from whether it cuts on them and the only one an import
2354 // asks ([`Self::auto_proxies`]).
2355 self.auto_proxies,
2356 // ...and which encoder an export of it opens, for the same reason:
2357 // a project delivered on the software encoder is delivered on it
2358 // again after a reload.
2359 self.encoder_seat,
2360 project.limiter(),
2361 // ...and the rate the mix was picked to run at, for the same
2362 // reason: a project delivered at a chosen rate is delivered at it
2363 // again after a reload.
2364 self.sample_rate,
2365 playhead,
2366 // ...and each lane's switches, hidden, muted or locked, which a
2367 // reload has to hand back as they were left.
2368 &project.lane_flags(),
2369 // ...and each audio lane's duck, by the key lane it names, in the
2370 // same order again: a ducked music bed that came back unducked
2371 // would be a mix nobody could keep.
2372 &project.lane_ducks(),
2373 // ...and the cues somebody retyped, which live in no file: the words
2374 // a reload has to hand back as they were typed.
2375 project.cue_edits(),
2376 // ...and the cues added to a track, which no file has.
2377 project.cue_adds(),
2378 // ...and the title cards and text overlays, which are the project's own.
2379 project.titles(),
2380 // ...and the chapter markers, which are the project's own too.
2381 project.chapters(),
2382 // ...and the comment markers.
2383 project.markers(),
2384 &project.caption_style(),
2385 // ...and each audio lane's voice processors, which a reload has to
2386 // hand back as they were left (the noise profile included: it is
2387 // learned from the sound, and re-learning it would not be the same).
2388 &project.lane_voices(),
2389 // ...and the names the user gave the lanes.
2390 &project.lane_names(),
2391 )
2392 }
2393
2394 /// The next decoded frame, its `index` rewritten from a source frame to a
2395 /// *timeline* frame -- the only frame space that leaves the engine, and the
2396 /// one [`PlaybackSession::now`] is in.
2397 ///
2398 /// `None` means "nothing right now": the decoder is behind, or a clip
2399 /// boundary is being reopened -- and *that* now happens entirely on the new
2400 /// worker ([`DecodeSession::open_worker_deferred`]), so it costs this
2401 /// thread a thread spawn and the caller simply keeps showing its last frame
2402 /// for however long the source takes to open (hundreds of milliseconds on a
2403 /// big film, seconds off a cold cache). End of stream is
2404 /// [`PlaybackSession::is_eos`].
2405 pub fn try_frame(&mut self) -> Option<Frame> {
2406 self.publish_playhead();
2407 loop {
2408 match self.frames.try_recv() {
2409 Ok(mut frame) => {
2410 // A gap's worker indexes from zero, a decoder's from its in
2411 // point, and the span itself knows which: [`Span::timeline_at`]
2412 // is the *stamp*, and it is the ceil half of the pair whose
2413 // floor half an export encodes with -- so the frame the pump
2414 // is holding at any timeline frame is the very frame the
2415 // export writes there, at every rate
2416 // (`speed_maps_both_ways`). An empty timeline has no span,
2417 // and its one black frame is frame 0. Real time is the
2418 // arithmetic this always did, frame for frame.
2419 // ...through the file's own rate first, which is the ceil
2420 // half of *that* pair: the picture at source frame `i` is
2421 // due at the first timeline-rate frame that shows it, and a
2422 // slower file's picture is therefore held for the frames in
2423 // between. Real time for a gap and for a single-rate
2424 // project, where this is the identity.
2425 frame.index = self.stamp(frame.index);
2426 // The first picture out of the span now decoding ends its
2427 // prime ([`Self::span_priming`]).
2428 self.span_priming = false;
2429 // Inside the dissolve window this span's tail owes its
2430 // successor, if any: B's own decoder, graded and placed
2431 // exactly as an export would place it, blended over A's
2432 // already-converted picture -- the one blend point every
2433 // path to the screen goes through, playing or scrubbed,
2434 // since both drain this same channel one frame at a time.
2435 if self
2436 .dissolve
2437 .as_ref()
2438 .is_some_and(|d| frame.index >= d.tail_start)
2439 {
2440 self.open_dissolve_b();
2441 }
2442 if let Some(d) = self.dissolve.as_mut()
2443 && frame.index >= d.tail_start
2444 && let Some(b) = d.b.as_mut()
2445 {
2446 while let Ok(bf) = b.frames.try_recv() {
2447 b.held = Some(bf);
2448 }
2449 // The window's first tick, with B's decoder not yet
2450 // caught up: a paused or scrubbed preview gets no
2451 // later tick to correct itself on (nothing is due
2452 // while the clock is frozen -- `Player::pump`), so
2453 // this is the one chance to blend rather than show A
2454 // alone. Bounded so a source B cannot decode never
2455 // freezes the preview -- eager-opened in
2456 // `start_span`, B is normally already warm here and
2457 // this waits on nothing at all.
2458 if b.held.is_none() {
2459 b.held = b.frames.recv_timeout(DISSOLVE_B_TIMEOUT).ok();
2460 }
2461 if let Some(bf) = &b.held {
2462 let idx_in_window = (frame.index - d.tail_start).min(d.window - 1);
2463 let t = crate::export::dissolve_weight(idx_in_window, d.window);
2464 frame.bgra = match d.kind {
2465 crate::transitions::TransitionKind::Dissolve => {
2466 blend_bgra(&frame.bgra, &bf.bgra, t)
2467 }
2468 kind => crate::transitions::blend_bgra(
2469 kind,
2470 &frame.bgra,
2471 &bf.bgra,
2472 t,
2473 frame.width as usize,
2474 frame.height as usize,
2475 ),
2476 };
2477 }
2478 }
2479 // A picture fade is drawn toward black, the way export draws
2480 // it ([`crate::export::picture_fade_at`]): black is zero in
2481 // every colour channel of BGRA, the alpha byte left alone.
2482 // A layered picture's fades were applied per clip by its worker.
2483 let fade = match self.span.is_some_and(|s| {
2484 crate::export::layered_at(&self.project.render_view(), s.start)
2485 }) {
2486 true => None,
2487 false => crate::export::picture_fade_at(&self.project.render_view(), frame.index),
2488 };
2489 if let Some(k) = fade {
2490 for px in frame.bgra.as_chunks_mut::<4>().0 {
2491 for c in &mut px[..3] {
2492 *c = (f32::from(*c) * k).round() as u8;
2493 }
2494 }
2495 }
2496 return Some(frame);
2497 }
2498 Err(TryRecvError::Empty) => return None,
2499 // The worker stopped: at the end of its range, or on a decode
2500 // error -- which is why this skips the rest of a broken clip
2501 // rather than stalling on it.
2502 Err(TryRecvError::Disconnected) => {
2503 if !self.next_clip() {
2504 self.eos = true;
2505 self.eos_end =
2506 f64::from(self.project.timeline_frames()) / self.meta.frame_rate;
2507 return None;
2508 }
2509 }
2510 }
2511 }
2512 }
2513
2514 /// Whether the timeline has been played out: the picture worker ran to the
2515 /// end and there was no next clip. It is exactly that and nothing more,
2516 /// which is what decides who clears it -- **starting a picture does**
2517 /// (`start_picture`), so a seek clears it and so does every edit that
2518 /// rebuilds the picture (`Dirty::Picture`, `Dirty::Both` -- a paste or a
2519 /// placement past the end revives the session, and it has a new picture to
2520 /// show for it).
2521 ///
2522 /// A **sound-only** edit does not (`Dirty::Sound`: an equalizer, a fader):
2523 /// it rebuilds the sound where the playhead stands and starts no picture
2524 /// worker, so the last frame is still the last frame and this is still the
2525 /// end. A front-end's `Ended` therefore survives an EQ tweak made after the
2526 /// timeline ran out -- the parameters are on the project either way, and the
2527 /// next press restarts from the top with them, which is what `Ended` means.
2528 pub fn is_eos(&self) -> bool {
2529 self.eos
2530 }
2531
2532 /// Tells the decode worker which frame of its *file* the clock has reached,
2533 /// so the pictures it is holding that are already behind the playhead are
2534 /// dropped where they are cheap to drop -- before the conversion and before
2535 /// the queue -- instead of being converted, queued and thrown away by the
2536 /// caller one repaint later. The whole of the late-frame policy: a decoder
2537 /// that has fallen behind catches up by not painting what nobody can see,
2538 /// rather than by being restarted every two seconds (`Player::pump`).
2539 ///
2540 /// The stamp is the exact inverse of the one [`try_frame`](Self::try_frame)
2541 /// puts on a decoded frame: timeline frame -> the clip's own frames
2542 /// ([`Span::speed`]) -> the file's ([`Rate`]). A gap and the emptied
2543 /// timeline have no file to be inside of, and publish nothing.
2544 fn publish_playhead(&self) {
2545 // Backward the worker is not walking toward the clock but away from where
2546 // it started, and a stale picture is dropped by the pump instead.
2547 if !self.drop_late || self.backward() {
2548 return;
2549 }
2550 let Some(span) = self.span else { return };
2551 let Some((_, in_frame)) = span.from else {
2552 return;
2553 };
2554 let now = secs_to_frame(self.clock.now(), self.meta.frame_rate);
2555 let offset = now.saturating_sub(span.start).min(span.len);
2556 self.worker.playhead(
2557 self.span_rate
2558 .source_at(in_frame + span.source_offset(offset)),
2559 );
2560 }
2561
2562 /// Whether the clock runs backward: the picture is then drawn from the
2563 /// playhead down ([`Back`]) and a pump presents what is *at or after* the
2564 /// clock instead of at or before it.
2565 pub fn backward(&self) -> bool {
2566 self.clock.rate() < 0.0
2567 }
2568
2569 /// The playback rate: 1.0 is real time, negative is backward.
2570 pub fn rate(&self) -> f64 {
2571 self.clock.rate()
2572 }
2573
2574 /// The timeline frame a decoded frame numbered `idx` is due at, in the numbering
2575 /// the current worker was opened with ([`Back`]). Forward it is the ceil half
2576 /// of the pair an export encodes with ([`Span::timeline_at`]) through the
2577 /// file's own rate; backward the same mapping read off the file frame the
2578 /// stream really holds, so the stamps fall as the stream goes on.
2579 fn stamp(&self, idx: u32) -> u32 {
2580 let Some(s) = self.span else { return idx };
2581 let rate = self.span_rate;
2582 match self.back {
2583 Back::Off => s.timeline_at(rate.timeline_at(idx)),
2584 Back::Mirror { top } => {
2585 s.timeline_at(rate.timeline_at((2 * top).saturating_sub(idx)))
2586 }
2587 Back::Forward => {
2588 let first = s.from.map_or(0, |(_, f)| f);
2589 s.timeline_at((2 * first).saturating_sub(rate.timeline_at(idx)))
2590 }
2591 Back::Gap => s.start + s.len.saturating_sub(1).saturating_sub(idx),
2592 }
2593 }
2594
2595 /// Installs `replacement` as the decode worker, parking the outgoing one in
2596 /// [`retired`](Self::retired) rather than joining it here, and reaping the
2597 /// parked ones that have already returned.
2598 ///
2599 /// The sweep is what bounds the list: every worker in it was cancelled
2600 /// before this ran, and a cancelled worker is out within an access unit
2601 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's
2602 /// worker on this seek and the list stays a handful long. Nothing waits.
2603 fn retire(&mut self, replacement: Worker) {
2604 // A *replacement*, which is now the narrow case: a seek onto the file
2605 // the worker already has open steers it instead ([`Worker::reseek`])
2606 // and never comes here, so this count is the picture restarts that
2607 // really cost a thread and a decoder open -- which is what makes it
2608 // worth counting.
2609 self.restarts += 1;
2610 let mut outgoing = std::mem::replace(&mut self.worker, replacement);
2611 // Terminal, unlike the [`Worker::abandon`] a seek does: this worker is
2612 // being replaced rather than steered, so its thread has to end -- and
2613 // the cancel is what drops its command channel, without which a worker
2614 // parked between spans would sit in `recv` forever, never reaped here
2615 // and never joined in any bounded time at exit.
2616 outgoing.cancel();
2617 self.retired.push(outgoing);
2618 self.retired.retain(|w| !w.is_finished());
2619 }
2620
2621 /// Picture restarts so far; see [`restarts`](Self::restarts). The one place
2622 /// a worker is ever replaced counts them, so a seek, a resync and a clip
2623 /// boundary all land here and a measurement need not guess which it saw.
2624 #[doc(hidden)]
2625 pub fn restarts(&self) -> u64 {
2626 self.restarts
2627 }
2628
2629 /// Whether the picture span now decoding has yet to hand over a frame:
2630 /// true from the moment a span is started -- a seek, a clip boundary, a
2631 /// picture restart -- until that span's first frame arrives. Whatever
2632 /// lateness that first frame carries is the span's own reopen, not a
2633 /// decoder falling behind, so a front-end gating its late-picture restart
2634 /// on this answers a prime with the decode already on its way rather than
2635 /// with another restart of it.
2636 pub fn picture_priming(&self) -> bool {
2637 self.span_priming
2638 }
2639
2640 /// Whether the picture now playing is read off a render-cache segment
2641 /// ([`crate::render_cache`]) rather than composed live.
2642 pub fn playing_from_cache(&self) -> bool {
2643 matches!(self.feed, Feed::Cached { .. })
2644 }
2645
2646 /// The part of `span` a render-cache segment can stand in for, with the
2647 /// segment it comes from: the span's first frame must be inside a segment
2648 /// that matches the timeline now, and the span must be a forward clip at
2649 /// 1x through no dissolve. The returned span keeps the span's own start and
2650 /// its length up to the segment's end, and reads from the segment's own
2651 /// first frame ([`Feed::Cached`]), at real time, so the stamp is the identity.
2652 fn cached_cut(
2653 &self,
2654 span: Option<Span>,
2655 backward: bool,
2656 ) -> Option<(Span, crate::render_cache::Segment)> {
2657 let span = span?;
2658 if backward
2659 || self.dissolve.is_some()
2660 || span.reverse
2661 || span.ramp.is_some()
2662 || span.speed != Speed::NORMAL
2663 {
2664 return None;
2665 }
2666 let (source, _) = span.from?;
2667 let segment = crate::render_cache::at(&self.project, &self.meta, span.start)?;
2668 let len = span.end().min(segment.to) - span.start;
2669 let cut = Span {
2670 len,
2671 from: Some((source, span.start - segment.from)),
2672 ..span
2673 };
2674 Some((cut, segment))
2675 }
2676
2677 /// Starved audio callbacks since the device opened, and how far into the
2678 /// device's own playback (seconds) the last of them was -- `None` for a
2679 /// session with no device at all. The counter the plugin prints on drop,
2680 /// readable while the session runs: read it either side of a seek and the
2681 /// difference is what that seek cost the ear.
2682 #[doc(hidden)]
2683 pub fn audio_underruns(&self) -> Option<(u64, Option<f64>)> {
2684 let audio = self.audio.as_ref()?;
2685 let (count, last) = audio.ao.lock().unwrap().underruns();
2686 Some((count, last.map(|p| p as f64 / f64::from(audio.sample_rate))))
2687 }
2688
2689 /// How many threads this session still has running of its own: the decode
2690 /// worker, every retired one that has not returned yet, and the audio
2691 /// feeders still in the air. One for a session playing along quietly.
2692 ///
2693 /// The oracle a seek storm is judged by. `/proc/self/status` counts the
2694 /// *process*, and a suite decoding twenty files at once moves that number
2695 /// under a test that never touched them -- this counts only what the
2696 /// session in hand owns, so it says the same thing alone and in a crowd.
2697 #[doc(hidden)]
2698 pub fn live_workers(&self) -> usize {
2699 usize::from(!self.worker.is_finished())
2700 + self.retired.iter().filter(|w| !w.is_finished()).count()
2701 + self.audio.as_ref().map_or(0, Audio::live_feeders)
2702 }
2703
2704 /// Starts feeding whatever follows the current span on the timeline --
2705 /// another clip, or a gap, which is black frames from a worker that opens no
2706 /// file. `false` past the end. The next timeline frame is derived rather
2707 /// than remembered as a clip index, because a `split` while playing cuts the
2708 /// clip under the running worker and only the mapping stays true.
2709 fn next_clip(&mut self) -> bool {
2710 // No span is the emptied timeline: it was played out the moment its one
2711 // black frame went by, and there is no "next" to walk to.
2712 let backward = self.backward();
2713 let span = match (self.span, backward) {
2714 (None, _) => return false,
2715 // Backward the next stretch to draw is the one that ends just before
2716 // this one starts, and the start of the timeline is where it ends.
2717 (Some(span), true) => match span.start.checked_sub(1) {
2718 Some(frame) => back_span_at(&self.project.render_view(), frame),
2719 None => return false,
2720 },
2721 (Some(span), false) => crate::export::stack_span_at(&self.project.render_view(), span.end()),
2722 };
2723 let Some(span) = span else { return false };
2724 // We only get here on a disconnect, so the old span is already done;
2725 // abandon anyway, so `start_span` treats every path alike -- and the
2726 // *worker* is kept, because the next clip is very often the same file
2727 // (a split cuts one clip in two) and it already has it open.
2728 self.worker.abandon();
2729 self.start_span(Some(span));
2730 true
2731 }
2732
2733 /// Points the video worker at `span`: a decoder over its source range, or a
2734 /// black-frame generator for a gap -- and for `None`, the emptied timeline,
2735 /// which is one frame of black so the viewer shows the nothing that is
2736 /// there rather than the last picture of the clip that was deleted. The old
2737 /// worker must already have been cancelled -- this is the half both `seek`
2738 /// and `next_clip` share.
2739 ///
2740 /// A source that will not open leaves the *span* installed anyway: the
2741 /// timeline still moves, there are simply no more pictures, and the
2742 /// disconnected receiver carries the session on to the next span. For a
2743 /// video that is now the worker's own doing -- it opens the file, so it is
2744 /// the one that finds out -- and nothing on this thread waits to hear it.
2745 fn start_span(&mut self, span: Option<Span>) {
2746 // The viewer's own size, once one has said it ([`Self::set_view_size`]):
2747 // every picture below is painted at *this*, and the project's
2748 // resolution otherwise.
2749 let (canvas_w, canvas_h) = self.view_size();
2750 // The outgoing span's own dissolve, if it ever opened B's decoder:
2751 // that decoder's pictures were for a window this span is leaving
2752 // (played through, paused before, or seeked away from), and never
2753 // for the one about to start -- parked in `retired` exactly like the
2754 // picture worker below, so joining it costs this thread nothing.
2755 if let Some(Dissolve { b: Some(b), .. }) = self.dissolve.take() {
2756 let mut worker = b.worker;
2757 worker.cancel();
2758 self.retired.push(worker);
2759 self.retired.retain(|w| !w.is_finished());
2760 }
2761 // What the *new* span's own tail owes its successor -- checked here,
2762 // once, rather than every tick: adjacency can only change on an edit,
2763 // and every edit that could touches this span starts it over
2764 // ([`crate::export::dissolve_window`] makes the identical check for
2765 // the same reason, on export).
2766 let backward = self.backward();
2767 self.back = Back::Off;
2768 self.dissolve = span.filter(|_| !backward).and_then(|s| {
2769 crate::export::dissolve_window(&self.project.render_view(), &s).map(
2770 |(b_source, b_in_frame, window, b_start)| Dissolve {
2771 tail_start: s.start + s.len - window,
2772 window,
2773 b_source,
2774 b_in_frame,
2775 b_start,
2776 kind: crate::transitions::kind_at(&self.project.render_view(), s.start),
2777 b: None,
2778 },
2779 )
2780 });
2781 // B's decoder opens now, at the start of the *span*, rather than
2782 // waiting for the playhead to reach the window: the window is about a
2783 // second, which is exactly the head start a decoder open (VA-API
2784 // init measured 98ms worst case) needs to have a first picture ready
2785 // by the time playback -- or a seek straight into the window -- asks
2786 // for one. Without this a paused seek into the window met a `held`
2787 // that was still `None` and nothing ever asked again
2788 // (`try_frame`'s bounded wait below is the last-resort backstop for a
2789 // seek that lands inside the window before this head start pays off).
2790 if self.dissolve.is_some() {
2791 self.open_dissolve_b();
2792 }
2793 // Which file's frames the worker about to be opened will number its
2794 // pictures in: the span's own source, and real time for a gap, whose
2795 // black worker counts timeline frames already. Set before the open,
2796 // because the open is the first thing that converts with it.
2797 // A layered span's worker numbers its frames on the timeline itself
2798 // ([`crate::export::layered_stream`]), so it is read at real time.
2799 let layered = span.is_some_and(|s| crate::export::layered_at(&self.project.render_view(), s.start));
2800 // A field-mode clip of an interlaced file is decoded as fields, two to a
2801 // frame: the decoder's frame numbers are field numbers, so the file's
2802 // rate against the timeline doubles ([`crate::deinterlace::fields_rate`]).
2803 let deint = match span.and_then(|s| s.from) {
2804 Some((source, _)) if !layered => self.deint_at(source, span.map_or(0, |s| s.start)),
2805 _ => crate::project::Deinterlace::Frame,
2806 };
2807 self.span_rate = match span.and_then(|s| s.from) {
2808 Some((source, _)) if !layered => {
2809 let rate = self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME);
2810 crate::deinterlace::counted_rate(deint, rate)
2811 }
2812 _ => Rate::REAL_TIME,
2813 };
2814 // The new span owes its first picture from the moment it is asked for:
2815 // every path below, the reused worker as much as a fresh one
2816 // ([`Self::span_priming`]).
2817 self.span_priming = true;
2818 // A render-cache segment over this span's first frame plays the render
2819 // instead of compositing it ([`Feed::Cached`]). Only forward at 1x and
2820 // never through a dissolve; every other span stays on the live path.
2821 self.feed = Feed::Live;
2822 if let Some((cut, segment)) = self.cached_cut(span, backward) {
2823 let source_frame = cut.from.map_or(0, |(_, f)| f);
2824 let end = source_frame + cut.len;
2825 self.span_rate = Rate::REAL_TIME;
2826 // The render already holds the grade, transform, fit, tone and
2827 // effects, so the decoder applies none of them.
2828 let stream = DecodeSession::open_worker_deferred_with(
2829 &segment.path,
2830 source_frame,
2831 end,
2832 ColorParams::default(),
2833 TransformParams::default(),
2834 Composer::new(canvas_w, canvas_h, FitPolicy::default()),
2835 self.project.tone(),
2836 Speed::NORMAL,
2837 crate::project::Deinterlace::Frame,
2838 );
2839 self.frames = stream.frames;
2840 self.backend = stream.backend;
2841 self.retire(stream.worker);
2842 self.span = Some(cut);
2843 self.feed = Feed::Cached { segment: segment.path };
2844 return;
2845 }
2846 let opened = match span {
2847 // Two or more clips cover the span: its composed pictures come from a
2848 // stream of their own, each clip drawn over the ones beneath it as an
2849 // export draws them, at the viewer's size.
2850 Some(span) if layered => {
2851 let mut view_meta = self.meta;
2852 view_meta.width = canvas_w;
2853 view_meta.height = canvas_h;
2854 // Each clip's picture comes off its stand-in when the project is
2855 // cut on stand-ins, the way a single clip's does ([`picture_path`]).
2856 let paths = self.proxies.then(|| {
2857 self.project
2858 .sources()
2859 .iter()
2860 .map(|s| crate::proxy::cached(&s.path).unwrap_or_else(|| s.path.clone()))
2861 .collect()
2862 });
2863 Ok(crate::export::layered_stream(
2864 self.project.export_snapshot(),
2865 view_meta,
2866 crate::colorspace::ColorDescription::output_sized(self.meta.width, self.meta.height),
2867 span,
2868 paths,
2869 ))
2870 }
2871 // The grade is the composite's at this frame -- the same clip the
2872 // span itself came from -- and it is constant across the span, so
2873 // the worker carries it and every frame it converts wears it.
2874 Some(Span {
2875 start,
2876 from: Some((source, in_frame)),
2877 ..
2878 }) if crate::is_image(&self.project.sources()[source].path) => {
2879 // A still: the same grade and the same canvas as any other
2880 // clip, over a picture decoded once and repeated for the span.
2881 // As many pictures as the span reads *source* frames, so a still
2882 // is numbered like a decoder's output and a speed reaches it
2883 // through the same rewrite (`try_frame`) as any other clip.
2884 DecodeSession::open_still(
2885 &self.project.sources()[source].path,
2886 in_frame,
2887 span.expect("matched above").source_len(),
2888 self.project
2889 .composite_color_at(start)
2890 .copied()
2891 .unwrap_or_default(),
2892 self.project
2893 .composite_transform_at(start)
2894 .copied()
2895 .unwrap_or_default(),
2896 Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(start)),
2897 )
2898 .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}"))
2899 }
2900 Some(Span {
2901 start,
2902 from: Some((source, in_frame)),
2903 ..
2904 }) if crate::is_audio(&self.project.sources()[source].path)
2905 || self.project.render_view().composite_visualizer_at(start) & 1 != 0 =>
2906 {
2907 let (path, stream) = {
2908 let src = &self.project.sources()[source];
2909 (src.path.clone(), src.audio_stream)
2910 };
2911 DecodeSession::open_visualizer(
2912 &path,
2913 stream,
2914 in_frame,
2915 span.expect("matched above").source_len(),
2916 self.meta.frame_rate,
2917 self.project
2918 .composite_color_at(start)
2919 .copied()
2920 .unwrap_or_default(),
2921 self.project
2922 .composite_transform_at(start)
2923 .copied()
2924 .unwrap_or_default(),
2925 Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(start)),
2926 self.project.render_view().composite_visualizer_at(start),
2927 self.project.render_view().composite_viz_paint_at(start),
2928 )
2929 .inspect_err(|e| eprintln!("timeline frame {start}: visualizer open failed: {e}"))
2930 }
2931 Some(Span {
2932 start,
2933 from: Some((source, in_frame)),
2934 speed,
2935 ..
2936 }) => {
2937 // The stand-in where there is one and the switch is on, the
2938 // film itself otherwise -- the one place the picture's file is
2939 // decided ([`Self::picture_path`]). The sound is opened
2940 // elsewhere and is always the film's.
2941 //
2942 // It decides for the reuse door below as well, and that is what
2943 // makes the switch flippable while watching: a worker holding
2944 // the film is asked for a span of the stand-in, declines on the
2945 // path it already has ([`Worker::reseek`]), and the seek
2946 // [`Self::set_proxies`] does becomes a respawn on the other
2947 // file. Asking the *project* here instead would have left every
2948 // proxied span opening a worker from scratch.
2949 let path = self.picture_path(source);
2950 // The file's own frames, which is the only place they exist: a
2951 // clip counts the timeline's ([`Rate`]).
2952 let start_frame = self.span_rate.source_at(in_frame);
2953 // Source frames, which a speed makes more (or fewer) than the
2954 // timeline frames the span covers -- and which a file shot at
2955 // another rate makes fewer (or more) again. One past the last
2956 // frame this span shows, not one past its length: at another
2957 // rate those are two different frames.
2958 let end_frame = self.span_rate.source_at(
2959 in_frame + span.expect("matched above").source_len().saturating_sub(1),
2960 ) + 1;
2961 let color = self
2962 .project
2963 .composite_color_at(start)
2964 .copied()
2965 .unwrap_or_default();
2966 let transform = self
2967 .project
2968 .composite_transform_at(start)
2969 .copied()
2970 .unwrap_or_default();
2971 // ...and the canvas it is placed on: the project's resolution
2972 // and this clip's own fit policy, constant across the span for
2973 // the reason the grade is. Built where it is handed over rather
2974 // than kept in a local, because a `Composer` owns the scratch
2975 // buffers it places through -- the value is not copied about.
2976 let fit = self.project.render_view().composite_fit_at(start);
2977 let canvas = || Composer::new(canvas_w, canvas_h, fit);
2978 // ...and the rendition an HDR source among them is mapped to,
2979 // the project's own and constant across the span for that
2980 // reason too.
2981 let tone = self.project.tone();
2982 // At faster than real time several source frames decode to the
2983 // same timeline frame ([`Speed::timeline_at`]) and only the last
2984 // of a run is ever shown; the worker skips converting the rest
2985 // ([`crate::decode::skip_for_speed`]) rather than paying a full
2986 // colour convert and scale for a picture nothing displays.
2987 //
2988 // corner-cut: correct only when this file plays at the
2989 // timeline's own rate -- `skip_for_speed`'s own math is in the
2990 // file's frame numbers, which a `Rate` conversion would make a
2991 // different sequence than the timeline's. `Speed::NORMAL` (never
2992 // skip) covers that rarer case exactly as every frame was
2993 // delivered before this.
2994 let decode_speed = if self.span_rate.is_real_time() {
2995 speed
2996 } else {
2997 Speed::NORMAL
2998 };
2999 // Playing backward the span is the clip up to the playhead, drawn from
3000 // the playhead down: a forward clip is served last frame first, and a
3001 // reversed one -- whose backward is the file's forward -- first frame
3002 // first, in both cases over the window the span reads.
3003 let backward_window = backward.then(|| {
3004 let sp = span.expect("matched above");
3005 let (_, lo, hi) = sp.source_window().expect("a clip's span has a window");
3006 (
3007 self.span_rate.source_at(lo),
3008 self.span_rate.source_at(hi.saturating_sub(1)) + 1,
3009 )
3010 });
3011 if let Some((lo, hi)) = backward_window
3012 && !span.is_some_and(|s| s.reverse)
3013 {
3014 self.back = Back::Mirror { top: hi - 1 };
3015 let stream = DecodeSession::open_reversed_with(
3016 &path,
3017 hi - 1,
3018 hi - lo,
3019 color,
3020 transform,
3021 canvas(),
3022 tone,
3023 deint,
3024 );
3025 self.frames = stream.frames;
3026 self.backend = stream.backend;
3027 self.retire(stream.worker);
3028 self.span = span;
3029 return;
3030 }
3031 // ...and a reversed clip's backward is the file's forward: the same
3032 // worker as any clip, over the window, numbered by the file.
3033 let (start_frame, end_frame, decode_speed) = match backward_window {
3034 Some((lo, hi)) => {
3035 self.back = Back::Forward;
3036 (lo, hi, Speed::NORMAL)
3037 }
3038 None => (start_frame, end_frame, decode_speed),
3039 };
3040 // A reversed clip is served backwards from the file frame the span
3041 // starts on, a block at a time ([`DecodeSession::open_reversed`]); its
3042 // frames are numbered as a forward stream's would be, so the stamps
3043 // and drops below need no case of their own.
3044 if !backward && span.is_some_and(|s| s.reverse) {
3045 let stream = DecodeSession::open_reversed_with(
3046 &path,
3047 start_frame,
3048 end_frame.saturating_sub(start_frame).max(1),
3049 color,
3050 transform,
3051 canvas(),
3052 tone,
3053 deint,
3054 );
3055 self.frames = stream.frames;
3056 self.backend = stream.backend;
3057 self.retire(stream.worker);
3058 self.span = span;
3059 return;
3060 }
3061 // The worker already decoding this very file takes the new span
3062 // itself: no thread, no container parse, no VA-API init -- the
3063 // whole of what a seek used to cost. It answers `None` for any
3064 // other file (and for a worker whose thread has ended), and the
3065 // deferred opener below is then exactly the path it always was.
3066 if let Some((frames, backend)) = self.worker.reseek_with(
3067 &path,
3068 start_frame,
3069 end_frame,
3070 color,
3071 transform,
3072 canvas(),
3073 tone,
3074 decode_speed,
3075 deint,
3076 ) {
3077 self.frames = frames;
3078 self.backend = backend;
3079 self.span = span;
3080 return;
3081 }
3082 Ok(DecodeSession::open_worker_deferred_with(
3083 &path,
3084 start_frame,
3085 end_frame,
3086 color,
3087 transform,
3088 canvas(),
3089 tone,
3090 decode_speed,
3091 deint,
3092 ))
3093 }
3094 // A gap: black for as long as it runs. An emptied timeline has no
3095 // span at all and gets one frame of it -- enough to put black on
3096 // screen, and it ends where the timeline does, at once.
3097 gap => {
3098 if backward && gap.is_some() {
3099 self.back = Back::Gap;
3100 }
3101 Ok(DecodeSession::open_black(
3102 canvas_w,
3103 canvas_h,
3104 gap.map_or(1, |s| s.len),
3105 ))
3106 }
3107 };
3108 let Ok(stream) = opened else {
3109 // The file would not open. The span still goes in -- the timeline
3110 // moves on, there are simply no more pictures -- but the *frames*
3111 // must not: the old channel's pictures are numbered in the old
3112 // source's frames, and presenting them under the new mapping would
3113 // put the wrong picture at the wrong time (and leave
3114 // [`decode_backend`](Self::decode_backend) describing a worker that
3115 // is no longer feeding anything). A dead receiver instead, which is
3116 // what carries the session on to the next span. The old worker stays
3117 // parked in `self.worker`, where the caller has already abandoned
3118 // the span it was decoding ([`Worker::abandon`]) without ending the
3119 // thread; the next span reseeks it or retires it.
3120 self.frames = std::sync::mpsc::channel().1;
3121 self.backend = BackendCell::new(Backend::Gap);
3122 self.span = span;
3123 return;
3124 };
3125 // Receiver first, worker second: the drop of the *old* receiver is
3126 // what wakes the outgoing worker if it is parked in `send`, and only
3127 // then can it return and be reaped by a later sweep. Nothing here
3128 // joins, so this ordering costs the seek nothing.
3129 self.frames = stream.frames;
3130 self.backend = stream.backend;
3131 self.retire(stream.worker);
3132 self.span = span;
3133 }
3134
3135 /// The deinterlace setting of the clip on screen at `frame`, as it applies to
3136 /// the file `source`'s picture is decoded from (the stand-in when there is one):
3137 /// `Frame` for anything but interlaced H.264, which ignores the setting.
3138 fn deint_at(&self, source: usize, frame: u32) -> crate::project::Deinterlace {
3139 let mode = self.project.composite_clip_at(frame).map_or(crate::project::Deinterlace::Frame, |(lane, idx)| {
3140 self.project.deinterlace_of(lane, idx)
3141 });
3142 let path = &self.project.sources()[source].path;
3143 let file = self.proxies.then(|| crate::proxy::cached(path)).flatten().unwrap_or_else(|| path.clone());
3144 crate::deinterlace::effective(mode, &file)
3145 }
3146
3147 /// Opens B's own decoder for the current span's dissolve, the first time
3148 /// [`try_frame`](Self::try_frame) sees the playhead inside the window --
3149 /// a no-op once it is already open, or if this span has no dissolve at
3150 /// all. Everything [`start_span`](Self::start_span) works out for A's own
3151 /// decoder, worked out again for B: the stand-in switch
3152 /// ([`Self::picture_path`]), the file's own frame numbering
3153 /// ([`Self::rates`]), and B's *own* grade and fit, asked at B's own start
3154 /// on the timeline rather than at the position the blend writes to
3155 /// (still inside A's span) -- the same asymmetry
3156 /// [`crate::export`]'s own `Dissolve` is built with.
3157 fn open_dissolve_b(&mut self) {
3158 let (canvas_w, canvas_h) = self.view_size();
3159 let Some(d) = &self.dissolve else { return };
3160 if d.b.is_some() {
3161 return;
3162 }
3163 let (source, in_frame, window, b_start) = (d.b_source, d.b_in_frame, d.window, d.b_start);
3164 let path = self.picture_path(source);
3165 // B takes one picture per timeline frame: `Field` is its `Frame`; a clip with its
3166 // pulldown removed counts film frames.
3167 let b_deint = match self.deint_at(source, b_start) {
3168 crate::project::Deinterlace::Off => crate::project::Deinterlace::Off,
3169 crate::project::Deinterlace::Ivtc => crate::project::Deinterlace::Ivtc,
3170 _ => crate::project::Deinterlace::Frame,
3171 };
3172 let rate = crate::deinterlace::counted_rate(b_deint, self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME));
3173 let start_frame = rate.source_at(in_frame);
3174 let end_frame = rate.source_at(in_frame + window);
3175 let color = self
3176 .project
3177 .composite_color_at(b_start)
3178 .copied()
3179 .unwrap_or_default();
3180 let transform = self
3181 .project
3182 .composite_transform_at(b_start)
3183 .copied()
3184 .unwrap_or_default();
3185 let canvas = Composer::new(canvas_w, canvas_h, self.project.render_view().composite_fit_at(b_start));
3186 let tone = self.project.tone();
3187 let stream = DecodeSession::open_worker_deferred_with(
3188 &path,
3189 start_frame,
3190 end_frame,
3191 color,
3192 transform,
3193 canvas,
3194 tone,
3195 Speed::NORMAL,
3196 b_deint,
3197 );
3198 if let Some(d) = self.dissolve.as_mut() {
3199 d.b = Some(DissolveB {
3200 frames: stream.frames,
3201 worker: stream.worker,
3202 held: None,
3203 });
3204 }
3205 }
3206
3207 /// Length of the edited timeline in seconds -- what a ruler shows, and it
3208 /// shrinks with every delete.
3209 pub fn timeline_duration(&self) -> f64 {
3210 f64::from(self.project.timeline_frames()) / self.meta.frame_rate
3211 }
3212
3213 /// Whether no lane holds anything: the emptied timeline, which plays black
3214 /// and silent and is zero seconds long. A state, not a failure -- but the
3215 /// one a caller with nothing to render (an export) has to refuse by name
3216 /// rather than write a file of no frames.
3217 pub fn is_empty(&self) -> bool {
3218 self.project.timeline_frames() == 0
3219 }
3220
3221 /// `(start, len)` per clip in timeline seconds, in order: what a clips lane
3222 /// needs to lay itself out. Selection is the caller's business.
3223 pub fn clip_spans(&self) -> Vec<(f64, f64)> {
3224 let fps = self.meta.frame_rate;
3225 self.project
3226 .clip_spans()
3227 .iter()
3228 .map(|&(start, len)| (f64::from(start) / fps, f64::from(len) / fps))
3229 .collect()
3230 }
3231
3232 /// [`clip_spans`](Self::clip_spans) plus the index into
3233 /// [`Project::sources`] each clip plays from -- what a lane needs to colour
3234 /// an imported clip differently from the file the session was opened with.
3235 pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> {
3236 self.lane_spans_by_source(Lane::V1)
3237 }
3238
3239 /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane,
3240 /// with each clip's group id -- what a two-lane front-end draws. The holes
3241 /// between consecutive entries are the gaps.
3242 pub fn lane_spans_by_source(&self, lane: Lane) -> Vec<(f64, f64, usize)> {
3243 let fps = self.meta.frame_rate;
3244 self.project
3245 .lane(lane)
3246 .iter()
3247 .map(|c| (f64::from(c.start) / fps, f64::from(c.len()) / fps, c.source))
3248 .collect()
3249 }
3250
3251 /// Every placement of one lane, in timeline order. What a two-lane
3252 /// front-end draws and nothing
3253 /// [`lane_spans_by_source`](Self::lane_spans_by_source) can answer: a clip
3254 /// carries its group id (which halves a click marks together) and its
3255 /// source range (where a waveform reads its peaks from) as well as its
3256 /// span. The holes between consecutive clips are the gaps.
3257 pub fn lane_clips(&self, lane: Lane) -> &[Clip] {
3258 self.project.lane(lane)
3259 }
3260
3261 /// The empty stretch of `lane` covering `frame`, or `None` when `frame`
3262 /// is inside a clip/caption placement or past the last one
3263 /// ([`Project::gap_at`]). What a right-click on empty bench space asks
3264 /// before offering to close it.
3265 pub fn gap_at(&self, lane: Lane, frame: u32) -> Option<(u32, u32)> {
3266 self.project.gap_at(lane, frame)
3267 }
3268
3269 /// How many bounded gaps that same right-click lane holds. The tail after
3270 /// the last placement is not counted, because nothing would ripple there.
3271 pub fn gap_count(&self, lane: Lane) -> usize {
3272 self.project.gap_count(lane)
3273 }
3274
3275 /// Every lane's handle, in display order -- what a front-end lays out top to
3276 /// bottom, and the list [`add_lane`](Self::add_lane) grows.
3277 pub fn lanes(&self) -> Vec<Lane> {
3278 self.project.lanes()
3279 }
3280
3281 /// The sources whose files are not on disk, as `(index, saved path)`. Their
3282 /// clips stay on the timeline; a frame or an export that reads one is
3283 /// refused naming it.
3284 pub fn offline_sources(&self) -> Vec<(usize, PathBuf)> {
3285 self.project
3286 .sources()
3287 .iter()
3288 .enumerate()
3289 .filter(|(_, s)| !crate::source_present(&s.path))
3290 .map(|(i, s)| (i, s.path.clone()))
3291 .collect()
3292 }
3293
3294 /// Points source `index` at `path`, which must be the same material: the
3295 /// same kind (picture, sound or still), and a picture or sound at least as
3296 /// long as the furthest frame a clip reaches into the source (within a
3297 /// frame). Returns warnings: a length that differs by more than a frame from
3298 /// the file it replaces. The playhead is reopened on it. One undo step
3299 /// ([`Project::relink_source`]): undo points the source back at the old file
3300 /// and reads its length again. Nothing changes on a refusal.
3301 pub fn relink_source(&mut self, index: usize, path: &Path) -> crate::Result<Vec<String>> {
3302 let Some(old) = self.project.sources().get(index).cloned() else {
3303 return Err(format!("there is no source {index}").into());
3304 };
3305 if !path.is_file() {
3306 return Err(format!("{} is not a file", path.display()).into());
3307 }
3308 let kind = |p: &Path| {
3309 if crate::is_image(p) {
3310 "a still"
3311 } else if crate::is_audio(p) {
3312 "a sound file"
3313 } else {
3314 "a picture"
3315 }
3316 };
3317 if kind(&old.path) != kind(path) {
3318 return Err(format!(
3319 "source {index} is {} but {} is {}",
3320 kind(&old.path),
3321 path.display(),
3322 kind(path)
3323 )
3324 .into());
3325 }
3326 let candidate = Source::new(path, old.audio_stream);
3327 let (have, rate) = self.measure_source(&candidate)?;
3328 let expected = self.counts[index];
3329 // What the clips actually read: the furthest out-point any clip on any
3330 // lane takes from this source. A clip reading part of a source needs only
3331 // that part, so refusal is against the reach, not the whole length. Both
3332 // are in timeline-rate frames, the unit `have` is counted in.
3333 let reach = self
3334 .lanes()
3335 .into_iter()
3336 .flat_map(|lane| {
3337 self.lane_clips(lane)
3338 .iter()
3339 .filter(|c| c.source == index)
3340 .map(|c| c.out_frame)
3341 .collect::<Vec<_>>()
3342 })
3343 .max()
3344 .unwrap_or(0);
3345 if have + 1 < reach {
3346 return Err(format!(
3347 "{} has {have} frames but the clips on source {index} reach frame {reach}",
3348 path.display()
3349 )
3350 .into());
3351 }
3352 let mut warnings = Vec::new();
3353 if crate::source_present(&old.path) && have.abs_diff(expected) > 1 {
3354 warnings.push(format!(
3355 "{} has {have} frames; the file it replaces had {expected}",
3356 path.display()
3357 ));
3358 }
3359 self.project.relink_source(index, path)?;
3360 self.counts[index] = have;
3361 self.rates[index] = rate;
3362 let at = self.now();
3363 self.seek(at);
3364 Ok(warnings)
3365 }
3366
3367 /// Points several sources at copies of the same files ([`crate::collect`]) as one undo
3368 /// step. The copies are not measured against the clips: they are the same bytes. Their
3369 /// lengths are read again as an undo reads them, and the playhead is reopened. Returns how
3370 /// many sources moved.
3371 pub fn relink_all(&mut self, pairs: &[(usize, PathBuf)]) -> usize {
3372 let before = self.project.sources().to_vec();
3373 let moved = self.project.relink_sources(pairs);
3374 if moved > 0 {
3375 self.reread_sources(&before);
3376 self.invalidate(Dirty::Both);
3377 }
3378 moved
3379 }
3380
3381 /// Appends an empty lane and hands back its handle. One undo step
3382 /// ([`Project::add_lane`]), and no reseek: an empty lane changes nothing
3383 /// that plays until something is placed on it.
3384 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
3385 self.project.add_lane(kind)
3386 }
3387
3388 /// Drops that empty lane again, in [`Project::remove_lane`]'s words when it
3389 /// refuses. One undo step, and no reseek for the same reason the add needs
3390 /// none: an empty lane was playing nothing.
3391 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
3392 self.project.remove_lane(lane)
3393 }
3394
3395 /// Moves a whole track to display position `to`, clips and all
3396 /// ([`Project::move_lane`]), and hands back the handle it answers to
3397 /// afterwards -- `None` when nothing moved. One undo step.
3398 ///
3399 /// A *video* track that moves rebuilds the picture where the playhead
3400 /// stands, because display order is the stack and the frame on screen may
3401 /// be another lane's from here on; the sound plays on through it, untouched
3402 /// -- a mix is a sum, and a lane's gain travelled with it.
3403 pub fn move_lane(&mut self, lane: Lane, to: usize) -> Option<Lane> {
3404 let moved = self.project.move_lane(lane, to)?;
3405 if lane.kind == LaneKind::Video {
3406 self.invalidate(Dirty::Picture);
3407 }
3408 Some(moved)
3409 }
3410
3411 /// The subtitle lanes in display order -- `S1..Sn`, the rows a front-end
3412 /// lays out beside the picture and sound ones
3413 /// ([`Project::subtitle_lanes`]). Empty until something adds one, which is
3414 /// [`add_lane`](Self::add_lane) with [`LaneKind::Subtitle`], and they come
3415 /// off, move and reorder through the very same doors every other lane does.
3416 pub fn subtitle_lanes(&self) -> Vec<Lane> {
3417 self.project.subtitle_lanes()
3418 }
3419
3420 /// What is placed on one subtitle lane, in timeline order: what a front-end
3421 /// draws as clips, each naming the palette row it plays
3422 /// ([`Self::subtitles`]) and the window of it it keeps
3423 /// ([`Project::sub_lane`]).
3424 pub fn sub_lane(&self, lane: Lane) -> &[SubClip] {
3425 self.project.sub_lane(lane)
3426 }
3427
3428 /// Places a stretch of a subtitle track on `lane` at timeline frame `at`
3429 /// ([`Project::place_sub`], whose words a refusal is shown in). One undo
3430 /// step.
3431 ///
3432 /// No reseek and no invalidation, which is what the whole wrapper layer is
3433 /// here for: cues are drawn from [`sub_lane_cues`](Self::sub_lane_cues)
3434 /// over whatever picture is on screen, so nothing already decoded stops
3435 /// being right.
3436 pub fn place_sub(&mut self, lane: Lane, at: u32, sub: SubClip) -> crate::Result<()> {
3437 self.project.place_sub(lane, at, sub)
3438 }
3439
3440 /// Drags a placement to another subtitle lane or another frame
3441 /// ([`Project::move_sub`]). One undo step, and `Ok` with none for a drop
3442 /// that changed nothing. A caption in a group drags the group's clips with
3443 /// it -- a mapping change -- so this reseeks like a clip's drag does; a
3444 /// caption in no group moves nothing that plays and disturbs nothing.
3445 pub fn move_sub(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> crate::Result<()> {
3446 let grouped = self.caption_grouped_with_clips(from, idx);
3447 let moved = self.project.move_sub(from, idx, to, start);
3448 if moved.is_ok() && grouped {
3449 self.invalidate(Dirty::Both);
3450 }
3451 moved
3452 }
3453
3454 /// Drags one edge of a placement to timeline frame `to`
3455 /// ([`Project::trim_sub`]), **at this timeline's own frame rate** -- a
3456 /// placement's position is in frames while its words are in microseconds,
3457 /// and the rate that joins them is the one thing a [`Project`] does not
3458 /// know. That is why a front-end trims through this door and never converts
3459 /// a cue's microseconds itself. One undo step. A caption in a group trims
3460 /// the group's clips with it, and that half reseeked; a lone caption's trim
3461 /// changes only the words, which are drawn over whatever is decoded.
3462 pub fn trim_sub(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> crate::Result<()> {
3463 let grouped = self.caption_grouped_with_clips(lane, idx);
3464 let trimmed = self
3465 .project
3466 .trim_sub(lane, idx, edge, to, self.meta.frame_rate);
3467 if trimmed.is_ok() && grouped {
3468 self.invalidate(Dirty::Both);
3469 }
3470 trimmed
3471 }
3472
3473 /// How far that edge may travel, `(first, last)` timeline frame inclusive
3474 /// ([`Project::trim_sub_room`]) -- what a front-end drawing the box during
3475 /// a drag asks, at this timeline's rate.
3476 pub fn trim_sub_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
3477 self.project
3478 .trim_sub_room(lane, idx, edge, self.meta.frame_rate)
3479 }
3480
3481 /// Takes one placement off a subtitle lane, leaving a gap
3482 /// ([`Project::lift_sub`]). One undo step; the palette row it played stays
3483 /// on this timeline's list.
3484 pub fn lift_sub(&mut self, lane: Lane, idx: usize) -> bool {
3485 self.project.lift_sub(lane, idx)
3486 }
3487
3488 /// What that subtitle lane shows on *this* timeline, in start order
3489 /// ([`Project::sub_lane_cues`] at this timeline's rate) -- the placed-clip
3490 /// counterpart of [`timeline_cues`](Self::timeline_cues), which carries a
3491 /// whole palette track through the spans that play its media. Pure, so a
3492 /// front-end may ask it per repaint.
3493 pub fn sub_lane_cues(&self, lane: Lane) -> Vec<crate::subtitle::Cue> {
3494 self.project.sub_lane_cues(lane, self.meta.frame_rate)
3495 }
3496
3497 /// Every cue on the subtitle lanes, in start order: the captions that File > Export
3498 /// captions and `export_captions` write as SRT or WebVTT ([`crate::subtitle::write_srt`]).
3499 pub fn caption_cues(&self) -> Vec<crate::subtitle::Cue> {
3500 let mut cues: Vec<crate::subtitle::Cue> = self.subtitle_lanes().into_iter().flat_map(|l| self.sub_lane_cues(l)).collect();
3501 cues.sort_by_key(|c| c.start_us);
3502 cues
3503 }
3504
3505 /// [`sub_lane_cues`](Self::sub_lane_cues) with the cue each one is, as
3506 /// `(start_us, end_us, track, cue)` in the same order ([`Project::sub_lane_cue_refs`]):
3507 /// what a front-end hit-tests a drawn cue against to find the words to edit.
3508 pub fn sub_lane_cue_refs(&self, lane: Lane) -> Vec<(i64, i64, usize, usize)> {
3509 self.project.sub_lane_cue_refs(lane, self.meta.frame_rate)
3510 }
3511
3512 /// [`sub_lane_cue_refs`](Self::sub_lane_cue_refs) with the part of each cue's own clock that
3513 /// is shown ([`Project::sub_lane_cue_spans`]), which its word times are moved by.
3514 pub fn sub_lane_cue_spans(&self, lane: Lane) -> Vec<crate::project::CueSpan> {
3515 self.project.sub_lane_cue_spans(lane, self.meta.frame_rate)
3516 }
3517
3518 /// Retypes one cue's words ([`Project::set_cue_text`]). One undo step, and
3519 /// `false` with none for a cue that is not there or already reads this.
3520 /// No invalidation: the picture's captions are drawn per repaint from the
3521 /// palette ([`sub_lane_cues`](Self::sub_lane_cues)), so the new words are on
3522 /// the next frame without a reseek.
3523 pub fn set_cue_text(&mut self, track: usize, cue: usize, text: &str) -> bool {
3524 self.project.set_cue_text(track, cue, text)
3525 }
3526
3527 /// Removes one cue from its track ([`Project::delete_cue`]): gone from every
3528 /// placement of the track, nothing moves. One undo step, and `false` with
3529 /// none for a cue that is not there.
3530 pub fn delete_cue(&mut self, track: usize, cue: usize) -> bool {
3531 self.project.delete_cue(track, cue)
3532 }
3533
3534 /// The room a cue has on the track's own clock ([`Project::cue_room`]).
3535 pub fn cue_room(&self, track: usize, cue: usize) -> Option<(i64, i64)> {
3536 self.project.cue_room(track, cue)
3537 }
3538
3539 /// Where timeline time `tl_us` is on the track's clock, through the placement on `lane`
3540 /// that shows the cue ([`Project::cue_track_us_at`]).
3541 pub fn cue_track_us_at(&self, lane: Lane, track: usize, cue: usize, tl_us: i64) -> Option<i64> {
3542 self.project.cue_track_us_at(lane, track, cue, tl_us, self.meta.frame_rate)
3543 }
3544
3545 /// Moves or trims one cue ([`Project::set_cue_times`]). One undo step.
3546 pub fn set_cue_times(&mut self, track: usize, cue: usize, start_us: i64, end_us: i64) -> crate::Result<bool> {
3547 self.project.set_cue_times(track, cue, start_us, end_us)
3548 }
3549
3550 /// Joins a cue with the one after it ([`Project::merge_cue_next`]). One undo step.
3551 pub fn merge_cue_next(&mut self, track: usize, cue: usize) -> crate::Result<()> {
3552 self.project.merge_cue_next(track, cue)
3553 }
3554
3555 /// Divides the cue straddling `t_us` on the track's clock ([`Project::split_cues_at`]). One undo step.
3556 pub fn split_cues_at(&mut self, track: usize, t_us: i64) -> bool {
3557 self.project.split_cues_at(track, t_us)
3558 }
3559
3560 /// Adds a cue to a track on the track's own clock ([`Project::add_cue`]): kept
3561 /// in the project and saved with it. One undo step; the index it lands at, or
3562 /// the refusal, which changes nothing.
3563 pub fn add_cue(&mut self, track: usize, start_us: i64, end_us: i64, text: &str, overwrite: bool) -> crate::Result<usize> {
3564 self.project.add_cue(track, start_us, end_us, text, overwrite)
3565 }
3566
3567 /// The title cards and text overlays, in draw order ([`Project::titles`]).
3568 pub fn titles(&self) -> &[crate::project::Title] {
3569 self.project.titles()
3570 }
3571
3572 /// The chapter markers, sorted by frame, at most one per frame
3573 /// ([`Project::chapters`]).
3574 pub fn chapters(&self) -> &[crate::project::Chapter] {
3575 self.project.chapters()
3576 }
3577
3578 /// The chapters as a YouTube description listing, `00:00 Intro` a line each, and the
3579 /// warnings its rules call for ([`chapter_listing`]). The whole timeline, never a range.
3580 pub fn youtube_chapters(&self) -> (String, Vec<String>) {
3581 let fps = self.meta.frame_rate;
3582 let end = (self.timeline_duration() * fps).round() as u32;
3583 let chapters: Vec<(u32, String)> = self.chapters().iter().map(|c| (c.frame, c.title.clone())).collect();
3584 chapter_listing(&chapters, fps, end)
3585 }
3586
3587 /// Adds a chapter at `frame` named `title`, and returns its index in
3588 /// [`chapters`](Self::chapters). One undo step; refused, with nothing changed,
3589 /// for a name the project refuses or a frame that already has a chapter.
3590 pub fn add_chapter(&mut self, frame: u32, title: &str) -> crate::Result<usize> {
3591 self.project.add_chapter(crate::project::Chapter { frame, title: title.to_string() })
3592 }
3593
3594 /// Takes the chapter at `idx` off the list. One undo step; `false`, with
3595 /// nothing changed, for an index that is not there.
3596 pub fn remove_chapter(&mut self, idx: usize) -> bool {
3597 self.project.remove_chapter(idx)
3598 }
3599
3600 /// Renames the chapter at `idx`. One undo step; `false` for an index that
3601 /// is not there, a name the project refuses, or the name it already has.
3602 pub fn set_chapter_title(&mut self, idx: usize, title: &str) -> bool {
3603 self.project.set_chapter_title(idx, title)
3604 }
3605
3606 /// Moves the chapter at `idx` to `frame`, and returns its new index. One undo
3607 /// step; refused for a frame another chapter already holds.
3608 pub fn move_chapter(&mut self, idx: usize, frame: u32) -> crate::Result<usize> {
3609 self.project.move_chapter(idx, frame)
3610 }
3611
3612 /// Maps every chapter's frame through `map` as one undo step, for an edit that
3613 /// moves time (see [`Project::remap_chapters`]). Returns how many chapters a
3614 /// landing on another's frame dropped.
3615 pub fn remap_chapters(&mut self, map: impl Fn(u32) -> u32) -> usize {
3616 self.project.remap_chapters(map)
3617 }
3618
3619 /// How burned captions animate ([`crate::captionanim`]).
3620 pub fn caption_style(&self) -> crate::captionanim::CaptionStyle {
3621 self.project.caption_style()
3622 }
3623
3624 /// Gives a caption track's cues the word times they were written from
3625 /// ([`Project::attach_cue_words`]); `auto_captions` calls it right after the import.
3626 pub fn attach_cue_words(&mut self, track: usize, timed: &[crate::subtitle::Cue]) {
3627 self.project.attach_cue_words(track, timed);
3628 }
3629
3630 /// Sets how burned captions animate; one undo step, `false` when it is already so.
3631 pub fn set_caption_style(&mut self, style: crate::captionanim::CaptionStyle) -> bool {
3632 self.project.set_caption_style(style)
3633 }
3634
3635 /// The comment markers, sorted by frame ([`Project::markers`]).
3636 pub fn markers(&self) -> &[crate::project::Marker] {
3637 self.project.markers()
3638 }
3639
3640 /// Adds a marker and returns its index in [`markers`](Self::markers). One undo step;
3641 /// refused, with nothing changed, for a marker the project refuses.
3642 pub fn add_marker(&mut self, marker: crate::project::Marker) -> crate::Result<usize> {
3643 self.project.add_marker(marker)
3644 }
3645
3646 /// Takes the marker at `idx` off. One undo step; `false` for an index that is not there.
3647 pub fn remove_marker(&mut self, idx: usize) -> bool {
3648 self.project.remove_marker(idx)
3649 }
3650
3651 /// Replaces the marker at `idx` and returns its new index. One undo step; refused for
3652 /// a marker the project refuses or one that changes nothing.
3653 pub fn set_marker(&mut self, idx: usize, marker: crate::project::Marker) -> crate::Result<usize> {
3654 self.project.set_marker(idx, marker)
3655 }
3656
3657 /// Maps every marker's start and end through `map` as one undo step, for an edit that
3658 /// moves time (see [`Project::remap_markers`]). `false` when nothing moved.
3659 pub fn remap_markers(&mut self, map: impl Fn(u32) -> u32) -> bool {
3660 self.project.remap_markers(map)
3661 }
3662
3663 /// The markers as a chapter list for an export of `range`, as [`chapter_list_ns`](Self::chapter_list_ns)
3664 /// lists chapters: `(start_ns, name)` pairs in frame order, the first marker on a frame
3665 /// winning when several share one (a chapter list holds one per instant).
3666 pub fn marker_list_ns(&self, range: Option<(u32, u32)>) -> Vec<(u64, String)> {
3667 let (from, to) = range.unwrap_or((0, u32::MAX));
3668 let fps = self.meta.frame_rate;
3669 let mut out: Vec<(u64, String)> = Vec::new();
3670 for m in self.project.markers().iter().filter(|m| m.frame >= from && m.frame < to) {
3671 let ns = (f64::from(m.frame - from) / fps * 1e9).round() as u64;
3672 if out.last().is_none_or(|(last, _)| *last != ns) {
3673 out.push((ns, m.name.clone()));
3674 }
3675 }
3676 out
3677 }
3678
3679 /// The chapter list an export of `range` (frames, as [`ExportSettings::range`]
3680 /// names it) writes: `(start_ns, name)` pairs in frame order. A chapter's time
3681 /// is measured from the start of the range, so an export that starts at frame
3682 /// 100 writes a chapter at frame 100 as the first one, at 0 ns. Chapters before
3683 /// the range or at or past its end are left out; with no range every chapter
3684 /// is listed from the start of the timeline.
3685 ///
3686 /// Ready for an export's chapter list: the codecs writers take the pairs as
3687 /// they are.
3688 pub fn chapter_list_ns(&self, range: Option<(u32, u32)>) -> Vec<(u64, String)> {
3689 let (from, to) = range.unwrap_or((0, u32::MAX));
3690 let fps = self.meta.frame_rate;
3691 self.project
3692 .chapters()
3693 .iter()
3694 .filter(|c| c.frame >= from && c.frame < to)
3695 .map(|c| {
3696 let ns = f64::from(c.frame - from) / fps * 1e9;
3697 (ns.round() as u64, c.title.clone())
3698 })
3699 .collect()
3700 }
3701
3702 /// Adds a title card or text overlay and recomposes the picture at the
3703 /// playhead. The index it lands at, or the refusal of [`Project::add_title`],
3704 /// which changes nothing.
3705 pub fn add_title(&mut self, title: crate::project::Title) -> crate::Result<usize> {
3706 let idx = self.project.add_title(title)?;
3707 self.invalidate(Dirty::Picture);
3708 Ok(idx)
3709 }
3710
3711 /// Replaces the title at `idx` -- see [`Project::set_title`]. One undo step
3712 /// and a recomposed picture.
3713 pub fn set_title(&mut self, idx: usize, title: crate::project::Title) -> bool {
3714 self.edit(Dirty::Picture, |p| p.set_title(idx, title))
3715 }
3716
3717 /// Takes the title at `idx` off -- see [`Project::remove_title`]. One undo
3718 /// step and a recomposed picture.
3719 pub fn remove_title(&mut self, idx: usize) -> bool {
3720 self.edit(Dirty::Picture, |p| p.remove_title(idx))
3721 }
3722
3723 /// Splits every lane at `timeline_secs`, so the two sides become two
3724 /// groups. Metadata only: a split never changes the timeline->source
3725 /// mapping, so the running decoder stays correct and playback does not
3726 /// blink. `false` at a clip start, in a gap and past the end, where there
3727 /// would be nothing to split off.
3728 pub fn cut_at(&mut self, timeline_secs: f64) -> bool {
3729 self.project
3730 .split(secs_to_frame(timeline_secs, self.meta.frame_rate))
3731 }
3732
3733 /// The frame nearest `frame` within `reach` frames at which [`cut_at`](Self::cut_at)
3734 /// lands cleanly on every lane ([`Project::cut_frame_near`]); `None` when none is that near.
3735 pub fn cut_frame_near(&self, frame: u32, reach: u32) -> Option<u32> {
3736 self.project.cut_frame_near(frame, reach)
3737 }
3738
3739 /// [`cut_at`](Self::cut_at) on the lanes in `lanes` only; the others keep
3740 /// their clips whole across the cut. Metadata only, like `cut_at`.
3741 pub fn cut_at_lanes(&mut self, timeline_secs: f64, lanes: &[Lane]) -> bool {
3742 self.project
3743 .split_on(secs_to_frame(timeline_secs, self.meta.frame_rate), lanes)
3744 }
3745
3746 /// The inverse of [`cut_at`](Self::cut_at): rejoins the clips that meet at
3747 /// `timeline_secs` in every lane and puts them back in one group. `false`
3748 /// unless a split could have produced what is there. Metadata only, like the
3749 /// split -- no reseek.
3750 pub fn regroup_at(&mut self, timeline_secs: f64) -> bool {
3751 self.project
3752 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))
3753 }
3754
3755 /// Takes that clip out of its group, so its picture and its sound are edited
3756 /// apart from here on. Metadata only like a cut -- no reseek -- and one undo
3757 /// step. `false` for a bad index and for a clip that is not grouped with
3758 /// anything, which is already detached.
3759 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
3760 self.project.ungroup(lane, idx)
3761 }
3762
3763 /// Puts two clips covering the same frames back into one group: the regroup
3764 /// of what [`ungroup`](Self::ungroup) took apart. Metadata only, one undo
3765 /// step, and the error says why when it refuses.
3766 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
3767 self.project.group(a, a_idx, b, b_idx)
3768 }
3769
3770 /// Puts every placement the picks name into one group
3771 /// ([`Project::group_all`]) -- the ctrl-click selection's own door, which
3772 /// may name clips and captions alike. Metadata only like the pair above:
3773 /// no reseek, one undo step, and the error says why when it refuses.
3774 pub fn group_all(&mut self, picks: &[(Lane, usize)]) -> crate::Result<()> {
3775 self.project.group_all(picks)
3776 }
3777
3778 /// [`delete_clip`](Self::delete_clip) for the caption the pick named: a
3779 /// caption in no group lifts exactly as [`lift_sub`](Self::lift_sub) lifts
3780 /// it -- no reseek, because nothing that plays has changed -- and a caption
3781 /// in a group takes the group with it, which ripples every member's own
3782 /// lane and reseeks like a delete. `false` for a bad index.
3783 pub fn delete_sub(&mut self, lane: Lane, idx: usize) -> bool {
3784 // Which of the two, asked before anything moves: the reseek a grouped
3785 // delete owes is the whole difference between the paths. A group of
3786 // captions alone (no clip on another lane) still ripples every
3787 // member's *own* sub lane closed (`Project::delete_sub_in`, since
3788 // cdc53a6), and a sub lane counts toward `timeline_frames` exactly
3789 // like a clip lane does -- so the timeline can shrink out from under
3790 // the playhead from a caption-only group too, not only a media one.
3791 // `caption_grouped_with_clips` answers a narrower question than the
3792 // one this dispatch needs; a caption carries a link at all only once
3793 // grouped (`place_sub` always starts one at `None`), so that alone is
3794 // "this delete ripples more than its own lane".
3795 match self
3796 .sub_lane(lane)
3797 .get(idx)
3798 .is_some_and(|s| s.link.is_some())
3799 {
3800 true => self.edit(Dirty::Both, |p| p.delete_sub_in(lane, idx)),
3801 // A caption in no group is the plain lift that touches nothing
3802 // else: no reseek owed.
3803 false => self.project.delete_sub_in(lane, idx),
3804 }
3805 }
3806
3807 /// Whether the caption at `idx` of `lane` is grouped with clips on other
3808 /// lanes: the one question every caption edit that can move media has to
3809 /// ask first, because the answer is whether the edit owes a reseek -- and
3810 /// the front-end owes the same answer, asked before the edit moves the
3811 /// indices, so its flag reset matches the engine's reseek exactly.
3812 pub fn caption_grouped_with_clips(&self, lane: Lane, idx: usize) -> bool {
3813 self.project
3814 .sub_lane(lane)
3815 .get(idx)
3816 .and_then(|s| s.link)
3817 .is_some_and(|id| {
3818 self.project
3819 .lanes()
3820 .into_iter()
3821 .any(|l| l != lane && self.project.lane(l).iter().any(|c| c.link == Some(id)))
3822 })
3823 }
3824
3825 /// What the clip at `idx` of `lane` is equalized with, or `None` for one
3826 /// that plays flat -- what a card shows before it lets anyone drag a band.
3827 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
3828 self.project.eq_of(lane, idx)
3829 }
3830
3831 /// Gives that clip an equalizer, or takes it off with `None`. One undo step,
3832 /// like every other edit -- and it rebuilds the **sound** where the playhead
3833 /// is, so a band changed during playback is heard from the next chunk on
3834 /// rather than at the next play. The picture is not touched: the video
3835 /// worker keeps decoding through it ([`Dirty`]). `false` for a bad index or
3836 /// a non-finite band, and nothing changes.
3837 ///
3838 /// corner-cut: the audio rebuild is what makes it live, so the cost of a
3839 /// change is a decoder restart -- inaudible at a drag's end, but too much to
3840 /// call once per pointer sample (a caller commits one change per gesture).
3841 /// Upgrade path is the per-segment twin of [`crate::audio::MixControls`],
3842 /// which the lane worker would poll per chunk the way the mixer polls the
3843 /// gains.
3844 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
3845 self.edit(Dirty::Sound, |p| p.set_eq(lane, idx, params))
3846 }
3847
3848 /// The clip's own gain in dB at `idx` of `lane`, or `None` for an index
3849 /// that is not there ([`Project::clip_gain`]).
3850 pub fn clip_gain_of(&self, lane: Lane, idx: usize) -> Option<f32> {
3851 self.project.clip_gain(lane, idx)
3852 }
3853
3854 /// Sets that clip's gain in dB, clamped to the clip-gain range. One undo
3855 /// step, and the sound is rebuilt where the playhead is, as for
3856 /// [`set_eq`](Self::set_eq). `false` for a video lane, a bad index, a
3857 /// non-finite value, or a value already set.
3858 pub fn set_clip_gain(&mut self, lane: Lane, idx: usize, db: f32) -> bool {
3859 self.edit(Dirty::Sound, |p| p.set_clip_gain(lane, idx, db))
3860 }
3861
3862 /// Plays the timeline's sound at `at` (timeline seconds) for [`SCRUB_SECS`]: the audible
3863 /// half of a ruler scrub while paused. The decode happens on the scrub thread and nothing
3864 /// here waits for it, so a drag never stalls on the file; a request that arrives while an
3865 /// earlier one is still being read replaces it. Silent, and a no-op, past the end of the
3866 /// timeline or where nothing plays.
3867 pub fn scrub_audio(&mut self, at: f64) {
3868 if !(at.is_finite() && at >= 0.) {
3869 return;
3870 }
3871 let fps = self.meta.frame_rate;
3872 let target = (at * fps) as u32;
3873 let view = self.project.render_view();
3874 let segs = view.audio_segments_from(target, fps);
3875 if segs.is_empty() {
3876 return;
3877 }
3878 let eqs = view.audio_eqs_from(target, fps);
3879 let speeds = view.audio_speeds_from(target, fps);
3880 let fades = view.audio_fades_from(target, fps);
3881 let sources = self.project.audio_sources();
3882 let gains = self.mix_gains();
3883 let ducks = view.audio_ducks();
3884 let voices = view.audio_voices();
3885 let limiter = self.project.limiter();
3886 let sample_rate = self.sample_rate;
3887 let work: ScrubWork = Box::new(move || {
3888 let (meta, rx) = AudioSession::open_mixed_streams_live_fade(
3889 &sources,
3890 &segs,
3891 &eqs,
3892 &speeds,
3893 &fades,
3894 fps,
3895 &gains,
3896 &ducks,
3897 &voices,
3898 limiter,
3899 None,
3900 sample_rate,
3901 )
3902 .ok()??;
3903 let channels = usize::from(meta.channels).max(1);
3904 let want = (SCRUB_SECS * f64::from(meta.sample_rate)) as usize * channels;
3905 let mut buf = Vec::with_capacity(want);
3906 while buf.len() < want {
3907 match rx.recv_timeout(std::time::Duration::from_millis(500)) {
3908 Ok(chunk) => buf.extend_from_slice(&chunk.samples),
3909 Err(_) => break,
3910 }
3911 }
3912 buf.truncate(want);
3913 if buf.is_empty() {
3914 return None;
3915 }
3916 let fade = (SCRUB_FADE_SECS * f64::from(meta.sample_rate)) as usize;
3917 let samples = scrub_snippet(&buf, channels, fade);
3918 Some((meta.sample_rate, u32::from(meta.channels), samples))
3919 });
3920 let tx = self.scrub.tx.get_or_insert_with(|| {
3921 let (tx, rx) = std::sync::mpsc::channel();
3922 let _ = std::thread::Builder::new()
3923 .name("audio-scrub".into())
3924 .spawn(move || scrub_thread(rx));
3925 tx
3926 });
3927 let _ = tx.send(work);
3928 self.scrub.requests += 1;
3929 }
3930
3931 /// How many scrub snippets have been asked for on this session: the count a test reads to see
3932 /// that a drag did, or did not, play sound ([`PlaybackSession::scrub_audio`]).
3933 pub fn scrub_requests(&self) -> u64 {
3934 self.scrub.requests
3935 }
3936
3937 /// The clip's pitch shift in semitones at `idx` of `lane` ([`Project::clip_pitch`]).
3938 pub fn clip_pitch_of(&self, lane: Lane, idx: usize) -> Option<i8> {
3939 self.project.clip_pitch(lane, idx)
3940 }
3941
3942 /// Sets that clip's pitch in semitones, clamped to `-12..=12`. One undo step; the
3943 /// sound is rebuilt where the playhead is, as for [`set_clip_gain`](Self::set_clip_gain).
3944 /// `false` for a video lane, a bad index, or a value already set.
3945 pub fn set_clip_pitch(&mut self, lane: Lane, idx: usize, semitones: i32) -> bool {
3946 self.edit(Dirty::Sound, |p| p.set_clip_pitch(lane, idx, semitones))
3947 }
3948
3949 /// The clip's pan at `idx` of `lane`, `-1.0..=1.0` ([`Project::clip_pan`]).
3950 pub fn clip_pan_of(&self, lane: Lane, idx: usize) -> Option<f32> {
3951 self.project.clip_pan(lane, idx)
3952 }
3953
3954 /// Sets that clip's pan. One undo step; the sound is rebuilt where the playhead is, as for
3955 /// [`set_clip_gain`](Self::set_clip_gain). `false` for a video lane, a bad index, a
3956 /// non-finite value, or a value already set.
3957 pub fn set_clip_pan(&mut self, lane: Lane, idx: usize, pan: f32) -> bool {
3958 self.edit(Dirty::Sound, |p| p.set_clip_pan(lane, idx, pan))
3959 }
3960
3961 /// An audio lane's pan, `-1.0..=1.0` ([`Project::lane_pan`]).
3962 pub fn lane_pan(&self, lane: Lane) -> f32 {
3963 self.project.lane_pan(lane)
3964 }
3965
3966 /// Sets it. One undo step; the pan rides in each clip's envelope, so the sound is rebuilt
3967 /// where the playhead is (a caller commits one change per gesture).
3968 pub fn set_lane_pan(&mut self, lane: Lane, pan: f32) -> bool {
3969 self.edit(Dirty::Sound, |p| p.set_lane_pan(lane, pan))
3970 }
3971
3972 /// How loud that lane plays, in dB -- everything on it, every frequency of
3973 /// it. See [`Project::lane_gain_db`] for what it is *not*.
3974 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
3975 self.project.lane_gain_db(lane)
3976 }
3977
3978 /// Sets it. One undo step -- and **nothing is rebuilt**: a lane's volume
3979 /// lives at the sum, so the running mixer is handed the new number and
3980 /// picks it up at its next block ([`crate::audio::MixControls`]). A fader
3981 /// held down under an arrow key therefore moves the level and nothing else:
3982 /// no flush, no decoder restart, no hole in the sound and no blink in the
3983 /// picture.
3984 ///
3985 /// The one exception is the timeline that is not mixed at all -- a single
3986 /// audio lane at unity with the limiter off, which plays through the
3987 /// bit-exact single-stream path and has no mixer to talk to. Moving *that*
3988 /// off unity opens one, once; every move after it is live.
3989 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
3990 if !self.project.set_lane_gain_db(lane, db) {
3991 return false;
3992 }
3993 self.push_mix();
3994 true
3995 }
3996
3997 /// Sets or clears the auto-duck on an audio lane -- see
3998 /// [`Project::set_lane_duck`]. Live exactly as a volume is: the running
3999 /// mixer is handed the new duck and picks it up at its next block, and
4000 /// nothing is rebuilt.
4001 pub fn set_lane_duck(&mut self, lane: Lane, duck: Option<crate::duck::Duck>) -> bool {
4002 if !self.project.set_lane_duck(lane, duck) {
4003 return false;
4004 }
4005 self.push_mix();
4006 true
4007 }
4008
4009 /// The duck on `lane`, if it has one -- see [`Project::lane_duck`].
4010 pub fn lane_duck(&self, lane: Lane) -> Option<crate::duck::Duck> {
4011 self.project.lane_duck(lane)
4012 }
4013
4014 /// Every duck on `lane`, one per key -- see [`Project::lane_duck_list`].
4015 pub fn lane_duck_list(&self, lane: Lane) -> Vec<crate::duck::Duck> {
4016 self.project.lane_duck_list(lane)
4017 }
4018
4019 /// Removes the duck `lane` has under the key `under` (the key's
4020 /// [`Lane::ord`]) and keeps its others -- see [`Project::clear_lane_duck`].
4021 /// Live like [`set_lane_duck`](Self::set_lane_duck).
4022 pub fn clear_lane_duck(&mut self, lane: Lane, under: usize) -> bool {
4023 if !self.project.clear_lane_duck(lane, under) {
4024 return false;
4025 }
4026 self.push_mix();
4027 true
4028 }
4029
4030 /// The voice processors on `lane` -- see [`Project::lane_voice`].
4031 pub fn lane_voice(&self, lane: Lane) -> crate::voice::VoiceFx {
4032 self.project.lane_voice(lane)
4033 }
4034
4035 /// Sets the voice processors of an audio lane -- see [`Project::set_lane_voice`].
4036 /// One undo step. Not live: the processors run on the lane's own stream, so the
4037 /// sound is rebuilt where the playhead is, as for [`set_eq`](Self::set_eq).
4038 pub fn set_lane_voice(&mut self, lane: Lane, voice: crate::voice::VoiceFx) -> bool {
4039 self.edit(Dirty::Sound, |p| p.set_lane_voice(lane, voice))
4040 }
4041
4042 /// Learns a noise profile from `lane` -- the quietest half second of it, or the
4043 /// `range` (lane seconds) -- see [`crate::voice::learn_noise`]. Reads the lane as it
4044 /// plays and changes nothing.
4045 pub fn learn_noise(
4046 &self,
4047 lane: Lane,
4048 range: Option<(f64, f64)>,
4049 ) -> crate::Result<crate::voice::Learned> {
4050 crate::voice::learn_noise(&self.project, lane, self.meta.frame_rate, self.sample_rate, range)
4051 }
4052
4053 /// Whether the lane is hidden -- see [`Project::lane_hidden`].
4054 pub fn lane_hidden(&self, lane: Lane) -> bool {
4055 self.project.lane_hidden(lane)
4056 }
4057
4058 /// Whether the lane is muted -- see [`Project::lane_muted`].
4059 pub fn lane_muted(&self, lane: Lane) -> bool {
4060 self.project.lane_muted(lane)
4061 }
4062
4063 /// Whether the lane is locked -- see [`Project::lane_locked`]. Nothing here
4064 /// refuses an edit on it; the front-end does.
4065 pub fn lane_locked(&self, lane: Lane) -> bool {
4066 self.project.lane_locked(lane)
4067 }
4068
4069 /// Hides or shows a lane, live. A video lane's picture is recomposed at the
4070 /// playhead, the one rebuild this costs ([`Dirty::Picture`]); the sound keeps
4071 /// playing. A subtitle lane is drawn from the project at every repaint, so
4072 /// nothing is rebuilt for it at all.
4073 pub fn set_lane_hidden(&mut self, lane: Lane, hidden: bool) -> bool {
4074 if !self.project.set_lane_hidden(lane, hidden) {
4075 return false;
4076 }
4077 if lane.kind == LaneKind::Video {
4078 self.invalidate(Dirty::Picture);
4079 }
4080 true
4081 }
4082
4083 /// Mutes or unmutes an audio lane, live: the mix is handed its new gain at
4084 /// the next block exactly as a fader is ([`push_mix`](Self::push_mix)).
4085 pub fn set_lane_muted(&mut self, lane: Lane, muted: bool) -> bool {
4086 if !self.project.set_lane_muted(lane, muted) {
4087 return false;
4088 }
4089 self.push_mix();
4090 true
4091 }
4092
4093 /// Locks or unlocks a lane. Nothing plays differently, so nothing is
4094 /// touched -- it is in the lane list, so it is one undo step like the rest.
4095 pub fn set_lane_locked(&mut self, lane: Lane, locked: bool) -> bool {
4096 self.project.set_lane_locked(lane, locked)
4097 }
4098
4099 /// Names a lane ([`Project::set_lane_name`]). A label only: nothing is rebuilt.
4100 pub fn set_lane_name(&mut self, lane: Lane, name: &str) -> Result<bool, String> {
4101 self.project.set_lane_name(lane, name)
4102 }
4103
4104 /// The name given to a lane, `None` for none ([`Project::lane_name`]).
4105 pub fn lane_name(&self, lane: Lane) -> Option<&str> {
4106 self.project.lane_name(lane)
4107 }
4108
4109 /// What a lane header shows: the name, else the address ([`Project::lane_title`]).
4110 pub fn lane_title(&self, lane: Lane) -> String {
4111 self.project.lane_title(lane)
4112 }
4113
4114 /// Solos audio lanes for listening: while any is soloed, every other audio
4115 /// lane is silent in what this session plays. Monitoring only -- it is not
4116 /// project state, is not saved, and an export never reads it. Lanes that
4117 /// are not audio lanes are ignored, and an empty list clears the solo.
4118 /// `false` when nothing changes. A [`Lane`] is a handle into the lane list,
4119 /// so solo again after a lane is removed or moved.
4120 pub fn set_solo(&mut self, lanes: &[Lane]) -> bool {
4121 let solo: Vec<Lane> = self
4122 .project
4123 .audio_lanes()
4124 .into_iter()
4125 .filter(|lane| lanes.contains(lane))
4126 .collect();
4127 if solo == self.solo {
4128 return false;
4129 }
4130 self.solo = solo;
4131 self.push_mix();
4132 true
4133 }
4134
4135 /// The audio lanes soloed for listening, as [`set_solo`](Self::set_solo) took them.
4136 pub fn soloed(&self) -> &[Lane] {
4137 &self.solo
4138 }
4139
4140 /// The gains the sound plays: the project's own, with the audio lanes
4141 /// outside a solo silenced. A solo that names no audio lane any more is no
4142 /// solo, so a stale handle cannot silence everything. The export reads
4143 /// [`Project::audio_gains`] directly and never comes through here.
4144 fn mix_gains(&self) -> Vec<f32> {
4145 soloed_gains(
4146 self.project.render_view().audio_gains(),
4147 &self.project.render_view().audio_lanes(),
4148 &self.solo,
4149 )
4150 }
4151
4152 /// The level meters, as the sound has reached them since the last call, and
4153 /// starts them over: the highest level each audio lane reached after its own
4154 /// gain (mute and solo read as silence) and the master peak after the
4155 /// limiter, before the device's volume. The flat single-lane path has no
4156 /// mixer, and its one lane is the master. Cheap: atomics and one short lock,
4157 /// nothing on the device's callback.
4158 pub fn levels(&self) -> Levels {
4159 let master = self.audio.as_ref().map_or(0.0, |audio| {
4160 f32::from_bits(audio.peak.swap(0, Ordering::Relaxed))
4161 });
4162 let master_lr = self.master_peaks_lr();
4163 let mut lanes = match self.mix.as_ref() {
4164 Some(mix) => mix.take_lane_peaks(),
4165 None => vec![master],
4166 };
4167 lanes.resize(self.project.audio_lanes().len(), 0.0);
4168 Levels { lanes, master, master_lr }
4169 }
4170
4171 /// The master's left and right peaks since the last read (of this or of [`levels`](Self::levels)),
4172 /// and starts them over: the stereo transport meter's own door, which leaves the lane peaks and
4173 /// the mono master the mix card reads alone.
4174 pub fn master_peaks_lr(&self) -> [f32; 2] {
4175 self.audio.as_ref().map_or([0.0; 2], |audio| {
4176 [0, 1].map(|i| f32::from_bits(audio.peak_lr[i].swap(0, Ordering::Relaxed)))
4177 })
4178 }
4179
4180 /// Hands the mix the running mixer is reading its new settings -- the whole
4181 /// of what a fader and a ceiling cost. With no mixer listening (the
4182 /// single-lane flat path, and a session with no sound at all) the sound is
4183 /// rebuilt instead, which is what opens one.
4184 fn push_mix(&mut self) {
4185 let gains = self.mix_gains();
4186 let ducks = self.project.render_view().audio_ducks();
4187 let limiter = self.project.limiter();
4188 // A mixer reading these, or an open on its way to being one: either way
4189 // the number is heard without a rebuild, and *that* is what a handle
4190 // left over from an open that found nothing cannot do
4191 // ([`crate::audio::MixControls::is_reachable`]).
4192 if let Some(mix) = self.mix.as_ref().filter(|mix| mix.is_reachable()) {
4193 mix.set(gains, ducks, limiter);
4194 return;
4195 }
4196 // Nothing to hand it to. Only a setting that *needs* a mixer is worth
4197 // the flush and the re-open: a ceiling dragged with the limiter off, or
4198 // a fader put back to unity, changes not one sample of the flat
4199 // single-stream path the timeline is already playing
4200 // ([`AudioSession::is_mixed`]), and reseeking per nudge was a hole in
4201 // the sound for a change nobody could hear.
4202 if crate::audio::AudioSession::is_mixed(gains.len(), &gains, limiter, &self.project.render_view().audio_voices()) {
4203 self.reseek_audio();
4204 }
4205 }
4206
4207 /// The master limiter the whole mix is summed through.
4208 pub fn limiter(&self) -> crate::limiter::Limiter {
4209 self.project.limiter()
4210 }
4211
4212 /// Sets it, live like a lane volume and for the same reason -- the ceiling
4213 /// a person is dragging has to be the ceiling they are hearing. Nothing is
4214 /// rebuilt: the running limiter is *retuned* between two blocks
4215 /// ([`crate::limiter::LimiterState::retune`]), so its delay line keeps
4216 /// running and the sample count the master clock is made of does not move.
4217 ///
4218 /// corner-cut: not an undo step, and deliberately -- [`Project::undo`]
4219 /// restores the lane list, and the limiter is not in it, so snapshotting
4220 /// here would push a step whose undo changes nothing a person can see or
4221 /// hear (the twin [`set_lane_gain_db`](Self::set_lane_gain_db) *is*
4222 /// undoable only because a lane volume lives in that list). The project
4223 /// resolution is outside undo for the same reason and says so. Upgrade path
4224 /// is a history that carries the mix beside the lanes, which every existing
4225 /// snapshot site would then have to fill in.
4226 pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool {
4227 if !self.project.set_limiter(limiter) {
4228 return false;
4229 }
4230 self.push_mix();
4231 true
4232 }
4233
4234 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
4235 /// silence on the audio one, and nothing else moves. Reseeks, because what
4236 /// the playhead sits on has changed. `false` for a bad index -- the lift of
4237 /// the last placement there is empties the timeline, which is a state
4238 /// ([`is_empty`](Self::is_empty)) and one undo away.
4239 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {
4240 self.edit(Dirty::Both, |p| p.lift(lane, idx))
4241 }
4242
4243 /// [`swap_clips`](Self::swap_clips) without the ripple: each clip takes the
4244 /// other's head and nothing between them moves ([`Project::swap_in_place`]).
4245 /// The `Err` names the clip the longer one would overlap, and nothing changes.
4246 pub fn swap_clips_in_place(&mut self, lane: Lane, a: usize, b: usize) -> crate::Result<()> {
4247 self.project.swap_in_place(lane, a, b)?;
4248 self.invalidate(Dirty::Both);
4249 Ok(())
4250 }
4251
4252 /// Swaps two placements of one lane ([`Project::swap`]): `b` takes `a`'s
4253 /// start and the ones between them ripple by the difference. One undo step.
4254 pub fn swap_clips(&mut self, lane: Lane, a: usize, b: usize) -> bool {
4255 self.edit(Dirty::Both, |p| p.swap(lane, a, b))
4256 }
4257
4258 /// Moves that clip onto lane `to` with its head at timeline frame `start` --
4259 /// the drag that carries a take along its track or onto another one, and its
4260 /// whole group with it. See [`Project::move_clip`] for the walls `start` is
4261 /// clamped to and the ways a drop is refused. One undo step, and it reseeks
4262 /// like every other edit: which lane a clip sits on is what the compositor's
4263 /// topmost-lane-wins rule reads, and where it starts is what the playhead
4264 /// reads, so the frame on screen is recomposed at once.
4265 ///
4266 /// A *frame*, where the rest of this type takes seconds, for
4267 /// [`trim_clip`](Self::trim_clip)'s reason: the drag has already put the
4268 /// pointer on a frame, and converting it back through seconds would be a
4269 /// rounding step between the box let go of and the box committed.
4270 ///
4271 /// Across kinds (a picture onto an audio lane or back) the clip must fit
4272 /// the new lane's wall ([`held_to_lane`](Self::held_to_lane)): a clip past
4273 /// it is refused rather than cut, since a move is not an edit of its length.
4274 pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
4275 if from.kind != to.kind {
4276 let Some(clip) = self.lane_clips(from).get(idx).cloned() else {
4277 return false;
4278 };
4279 if self.held_to_lane(to, clip.clone()).out_frame != clip.out_frame {
4280 return false;
4281 }
4282 }
4283 self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start))
4284 }
4285
4286 /// [`move_clip_to`](Self::move_clip_to)'s general form: every one of
4287 /// `picks` travels the same frame delta as the dragged clip at `idx` of
4288 /// `from`, all-or-nothing, one undo step for the lot -- what a hand drags
4289 /// on a selection rather than a lone clip. See
4290 /// [`Project::move_selection`] for the clamp that makes it all-or-nothing.
4291 pub fn move_selection_to(
4292 &mut self,
4293 picks: &[(Lane, usize)],
4294 from: Lane,
4295 idx: usize,
4296 to: Lane,
4297 start: u32,
4298 ) -> bool {
4299 self.edit(Dirty::Both, |p| {
4300 p.move_selection(picks, from, idx, to, start)
4301 })
4302 }
4303
4304 /// [`trim_clip`](Self::trim_clip) as a ripple trim ([`Project::ripple_trim`]): the hole the
4305 /// edge leaves closes, or opens, and what follows moves with it. One undo step.
4306 pub fn ripple_trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
4307 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4308 if !self.project.ripple_trim_with_walls(lane, idx, edge, to, SourceWalls { picture: &picture, sound: &sound }) {
4309 return false;
4310 }
4311 let now = self.now();
4312 self.seek(now);
4313 true
4314 }
4315
4316 /// Drags one end of that clip to timeline frame `to`, changing how much of
4317 /// its source it plays and nothing else on the lane -- see [`Project::trim`]
4318 /// for the walls it is clamped by, which this fills the source lengths in
4319 /// for. One undo step per call, so a front-end calls it once, at the release
4320 /// of the drag. Reseeks like every other edit, which is what makes the
4321 /// picture (and the sound) follow a new in-point straight away. `false` for
4322 /// a bad index and for an edge already where it was asked to go.
4323 ///
4324 /// A *frame*, where the rest of this type takes seconds: a drag has already
4325 /// asked [`trim_room`](Self::trim_room) where the edge may land, and that
4326 /// answer is in frames -- converting it back through seconds would be a
4327 /// rounding step between the width drawn and the width committed.
4328 pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
4329 // Spelled out rather than through `edit`, whose closure cannot hold a
4330 // second borrow of the session while it has the project.
4331 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4332 if !self.project.trim_with_walls(lane, idx, edge, to, SourceWalls { picture: &picture, sound: &sound }) {
4333 return false;
4334 }
4335 let now = self.now();
4336 self.seek(now);
4337 true
4338 }
4339
4340 /// **Roll**: moves the cut at the end of the clip at `idx` of `lane` to timeline
4341 /// frame `to` ([`Project::roll`]): the out-point of that clip and the in-point of
4342 /// the one behind it move together. Returns where the cut is now; `None` for a
4343 /// clip with nothing abutting behind it. Reseeks, one undo step.
4344 pub fn roll_clip(&mut self, lane: Lane, idx: usize, to: u32) -> Option<u32> {
4345 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4346 let at = self.project.roll(lane, idx, to, SourceWalls { picture: &picture, sound: &sound })?;
4347 let now = self.now();
4348 self.seek(now);
4349 Some(at)
4350 }
4351
4352 /// Where that cut may travel, `(first, last)` frame inclusive ([`Project::roll_room`]).
4353 pub fn roll_room(&self, lane: Lane, idx: usize) -> Option<(u32, u32)> {
4354 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4355 self.project.roll_room(lane, idx, SourceWalls { picture: &picture, sound: &sound })
4356 }
4357
4358 /// **Slide**: starts that clip at timeline frame `to` between its neighbours
4359 /// ([`Project::slide`]). Returns where it starts now; `None` for a clip
4360 /// without a neighbour on both sides. Reseeks, one undo step.
4361 pub fn slide_clip(&mut self, lane: Lane, idx: usize, to: u32) -> Option<u32> {
4362 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4363 let at = self.project.slide(lane, idx, to, SourceWalls { picture: &picture, sound: &sound })?;
4364 let now = self.now();
4365 self.seek(now);
4366 Some(at)
4367 }
4368
4369 /// Where that clip may start when slid, `(first, last)` frame inclusive ([`Project::slide_room`]).
4370 pub fn slide_room(&self, lane: Lane, idx: usize) -> Option<(u32, u32)> {
4371 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4372 self.project.slide_room(lane, idx, SourceWalls { picture: &picture, sound: &sound })
4373 }
4374
4375 /// **Slip**: shifts that clip's source window by `by` source frames
4376 /// ([`Project::slip`]; [`slip_source_delta`](Self::slip_source_delta) turns timeline
4377 /// frames into them). Returns the frames it moved; `None` for a bad index or a
4378 /// still. Reseeks, one undo step.
4379 pub fn slip_clip(&mut self, lane: Lane, idx: usize, by: i64) -> Option<i64> {
4380 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4381 let moved = self.project.slip(lane, idx, by, SourceWalls { picture: &picture, sound: &sound })?;
4382 if moved != 0 {
4383 let now = self.now();
4384 self.seek(now);
4385 }
4386 Some(moved)
4387 }
4388
4389 /// How far that clip may slip, `(back, forward)` source frames ([`Project::slip_room`]).
4390 pub fn slip_room(&self, lane: Lane, idx: usize) -> Option<(i64, i64)> {
4391 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4392 self.project.slip_room(lane, idx, SourceWalls { picture: &picture, sound: &sound })
4393 }
4394
4395 /// The source frames `by` timeline frames are worth for that clip ([`Project::slip_source_delta`]).
4396 pub fn slip_source_delta(&self, lane: Lane, idx: usize, by: i64) -> Option<i64> {
4397 self.project.slip_source_delta(lane, idx, by)
4398 }
4399
4400 /// How fast the clip at `idx` of `lane` plays -- what a card shows before
4401 /// anyone drags it.
4402 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
4403 self.project.speed_of(lane, idx)
4404 }
4405
4406 /// Sets it, for that clip and its whole group ([`Project::set_speed`]): one
4407 /// undo step for the lot. Reseeks like every other edit, so the picture runs
4408 /// -- and the sound is resampled -- from the next frame on rather than at the
4409 /// next play. The `Err` names the clip in the way when slowing one down
4410 /// would run it into its neighbour, and nothing changes.
4411 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
4412 // Spelled out rather than through `edit`, whose closure hands back a
4413 // bool and would drop the refusal's own words. The playhead moves
4414 let at = self.project.speeded_playhead(
4415 lane,
4416 idx,
4417 speed,
4418 secs_to_frame(self.now(), self.meta.frame_rate),
4419 );
4420 self.project.set_speed(lane, idx, speed)?;
4421 let now = at.map_or_else(
4422 || self.now(),
4423 |frame| f64::from(frame) / self.meta.frame_rate,
4424 );
4425 self.seek(now);
4426 Ok(())
4427 }
4428
4429 /// Whether the clip at `idx` of `lane` plays backwards ([`Project::reversed_of`]).
4430 pub fn reversed_of(&self, lane: Lane, idx: usize) -> bool {
4431 self.project.reversed_of(lane, idx)
4432 }
4433
4434 /// Plays the clip and its whole group backwards, or forwards again
4435 /// ([`Project::set_reverse`]): one undo step, and a reseek at the playhead so
4436 /// the picture and the sound run the new way from the next frame on.
4437 pub fn set_reverse(&mut self, lane: Lane, idx: usize, on: bool) -> crate::Result<()> {
4438 self.project.set_reverse(lane, idx, on)?;
4439 let now = self.now();
4440 self.seek(now);
4441 Ok(())
4442 }
4443
4444 /// Gives the clip at `idx` of `lane` (and its group) a speed ramp, or clears it
4445 /// with empty `keys` ([`Project::set_speed_ramp`]). Reseeks like
4446 /// [`set_speed`](Self::set_speed), and the playhead holds where it stood.
4447 pub fn set_speed_ramp(
4448 &mut self,
4449 lane: Lane,
4450 idx: usize,
4451 keys: &[crate::project::SpeedKey],
4452 ) -> crate::Result<()> {
4453 self.project.set_speed_ramp(lane, idx, keys)?;
4454 let now = self.now();
4455 self.seek(now);
4456 Ok(())
4457 }
4458
4459 /// [`set_speed`](Self::set_speed) without the undo step -- the samples inside
4460 /// one drag ([`Project::set_speed_live`]). Reseeks like the committing one,
4461 /// which is what makes the bar move the picture under the hand.
4462 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
4463 // The mapping on every sample, not just at the commit: the bar moves
4464 // the rate live, and the scene has to stay put across the whole
4465 // gesture or the last picture before the release is not the one the
4466 // commit lands on.
4467 let at = self.project.speeded_playhead(
4468 lane,
4469 idx,
4470 speed,
4471 secs_to_frame(self.now(), self.meta.frame_rate),
4472 );
4473 self.project.set_speed_live(lane, idx, speed)?;
4474 let now = at.map_or_else(
4475 || self.now(),
4476 |frame| f64::from(frame) / self.meta.frame_rate,
4477 );
4478 self.seek(now);
4479 Ok(())
4480 }
4481
4482 /// The picture's source frame at `timeline_secs`: which source, and which
4483 /// frame of it -- the composite a viewer is looking at, through the same
4484 /// span math the decoder walks. What a test asks to prove a reseek kept
4485 /// the scene, and nothing in the editor itself reads.
4486 pub fn video_source_frame_at(&self, timeline_secs: f64) -> Option<(usize, u32)> {
4487 crate::export::stack_span_at(&self.project.render_view(), secs_to_frame(timeline_secs, self.meta.frame_rate))
4488 .and_then(|s| s.from)
4489 }
4490
4491 /// The lanes closing the gap `(start, frames)` on `lane` must ripple
4492 /// together to keep every media take crossing it in sync
4493 /// ([`Project::gap_take_scope`]) -- what a right-click on empty bench
4494 /// space asks before offering to close it. Subtitle gaps stay on their own
4495 /// lane because captions are not A/V take halves.
4496 pub fn gap_take_scope(&self, lane: Lane, start: u32, frames: u32) -> crate::Result<Vec<Lane>> {
4497 self.project.gap_take_scope(lane, start, frames)
4498 }
4499
4500 /// Closes every bounded gap on one lane. Media lanes keep linked takes
4501 /// whole when the other half has the matching empty stretch and report the
4502 /// gaps that were not safe to close; subtitle lanes ripple captions only.
4503 pub fn close_all_gaps_on_lane(&mut self, lane: Lane) -> crate::Result<GapSweep> {
4504 let report = self.project.close_all_gaps_on_lane(lane)?;
4505 if report.closed > 0 {
4506 let now = self.now();
4507 self.seek(now);
4508 }
4509 Ok(report)
4510 }
4511
4512 /// Cuts every one of `regions` -- `(start, len)` in timeline frames -- out
4513 /// of the lanes in `scope` and closes each hole, as **one** edit
4514 /// ([`Project::cut_regions`]): the jumpcut a silence scan
4515 /// ([`crate::silence`]) asks for, one undo press however many silences it
4516 /// found. A lane outside `scope` does not move. Reseeks like every other
4517 /// edit, so what plays is the cut timeline from the playhead on. The `Err`
4518 /// names what is in the way and nothing changes.
4519 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
4520 // Spelled out rather than through `edit`, whose closure hands back a
4521 // bool and would drop the refusal's own words.
4522 self.project.cut_regions(regions, scope)?;
4523 let now = self.now();
4524 self.seek(now);
4525 Ok(())
4526 }
4527
4528 /// Plays every one of those regions at `speed` instead of cutting them,
4529 /// closing the room each one no longer needs ([`Project::speed_regions`]) --
4530 /// one edit, one undo press, and the same scope rule. The `Err` names the
4531 /// lane and frame in the way and nothing changes.
4532 pub fn speed_regions(
4533 &mut self,
4534 regions: &[(u32, u32)],
4535 speed: Speed,
4536 scope: &[Lane],
4537 ) -> crate::Result<()> {
4538 self.project.speed_regions(regions, speed, scope)?;
4539 let now = self.now();
4540 self.seek(now);
4541 Ok(())
4542 }
4543
4544 // The length of each source on a picture lane and on an audio lane
4545 // ([`wall_table`]): a linked take drags both edges together, so a trim
4546 // measures each lane's members against that lane's own length.
4547
4548 /// Where that edge may land, `(first, last)` timeline frame inclusive: what
4549 /// a drag clamps the pointer to so the box it draws is the box
4550 /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
4551 pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
4552 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4553 self.project.trim_room_with_walls(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound })
4554 }
4555
4556 /// [`trim_room`](Self::trim_room) with the walls named: which of the two is
4557 /// the source's media limit, so a drag that stops there can say so. `None`
4558 /// for a bad index.
4559 pub fn trim_walls(&self, lane: Lane, idx: usize, edge: Edge) -> Option<TrimWalls> {
4560 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4561 self.project.trim_walls_with_walls(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound })
4562 }
4563
4564 /// [`trim_walls`](Self::trim_walls) with each wall's bound named
4565 /// ([`Project::trim_bounds`]): the source, a neighbour at a frame, the
4566 /// timeline's first frame, a clip's minimum length or a still's cap. Asked
4567 /// before a trim, so the names are for the walls the trim is measured to.
4568 /// `None` for a bad index.
4569 pub fn trim_bounds(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(WallBound, WallBound)> {
4570 let (picture, sound) = lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
4571 self.project
4572 .trim_bounds(lane, idx, edge, SourceWalls { picture: &picture, sound: &sound })
4573 }
4574
4575 /// Records how long a source is and what rate it was shot at, for a source
4576 /// index that may be one `Project::import` just made or one it handed back.
4577 /// See [`Self::counts`] and [`Self::rates`], which are one table in two
4578 /// vectors and grow together.
4579 fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) {
4580 if source == self.counts.len() {
4581 self.counts.push(frames);
4582 self.rates.push(rate);
4583 }
4584 debug_assert_eq!(self.counts.len(), self.project.sources().len());
4585 debug_assert_eq!(self.rates.len(), self.counts.len());
4586 // A source just joined, which is the one moment the session's audio
4587 // device may need arming ([`Self::arm_audio`]).
4588 self.arm_audio();
4589 }
4590
4591 /// Opens the audio device for the first source in the library that has a
4592 /// track, when this session has none.
4593 ///
4594 /// A session opened silent -- its first file carried no sound, so
4595 /// [`Self::open_library`]/[`Self::open`] had no track to open a device on
4596 /// -- must not stay silent once a source *with* sound joins it: every later
4597 /// clip's audio would go unheard for the rest of the session. That is
4598 /// exactly what the walk [`Self::open_project`] makes at open prevents for
4599 /// a loaded project (c581d41); this is the same walk at the add door, and
4600 /// [`Self::note_frames`] is the one place a source joins.
4601 ///
4602 /// A no-op once a device is open, so it costs a scan of `is_some` on every
4603 /// later import. The clock stays on wall time until the next seek
4604 /// ([`Self::seek`]'s own `switch_to_audio`), which is the seek a front-end
4605 /// makes as it places the file it just imported.
4606 fn arm_audio(&mut self) {
4607 // A device that is there but *dead* is not a device: the walk below
4608 // opens another one, which is also what clears the notice a death put up
4609 // ([`Self::tick`]).
4610 let carried = self
4611 .audio
4612 .as_ref()
4613 .map(|audio| audio.gain.load(Ordering::Acquire));
4614 if let Some(audio) = &self.audio
4615 && !audio.died.load(Ordering::Acquire)
4616 {
4617 return;
4618 }
4619 for source in self
4620 .project
4621 .sources()
4622 .iter()
4623 .filter(|s| !crate::is_image(&s.path))
4624 {
4625 let (audio, disabled) = open_audio(&source.path, source.audio_stream);
4626 if let Some(audio) = audio {
4627 // The device is being replaced under a session that may already
4628 // be running at a level the user chose, so that level comes
4629 // across with it ([`Audio::gain`]) rather than the fresh
4630 // stream's 1.0.
4631 if let Some(bits) = carried {
4632 audio.gain.store(bits, Ordering::Release);
4633 audio.ao.lock().unwrap().set_volume(f32::from_bits(bits));
4634 }
4635 self.audio = Some(audio);
4636 self.audio_disabled = disabled;
4637 return;
4638 }
4639 }
4640 }
4641
4642 /// Opens the output again for a stream that died, at the rate and channel
4643 /// count it carried, and clears the flag that stopped the session feeding.
4644 ///
4645 /// An output that goes away -- a PipeWire daemon restarting, a sink node
4646 /// removed and put back -- leaves every stream that was open on it dead for
4647 /// good: its position is frozen, so the clock can only fall to wall time, and
4648 /// a session that never opens another device is silent for the rest of its
4649 /// life, through every seek and every pause/play, with nothing said about it.
4650 ///
4651 /// The device *only*, never the file: the feeder is [`Self::start_audio`]'s,
4652 /// at the seek that follows. That is what lets [`Self::tick`] call this too,
4653 /// once a frame -- a tick is not a seek and must not reseek the timeline. The
4654 /// clock is on wall time by then and stays there until a seek comes, which is
4655 /// the seek whose feeder opens in step with the picture.
4656 ///
4657 /// `if_idle_for` is the cooldown: a tick passes [`AUDIO_REARM_AFTER`], because
4658 /// sixty opens a second against a device that is gone for good is a spin; a
4659 /// seek passes zero, because that one is a person asking.
4660 ///
4661 /// `false` when there is nothing to open, nothing came back, or the cooldown
4662 /// has not passed -- and the flag stays standing for the next attempt.
4663 fn rearm_audio(&mut self, if_idle_for: Duration) -> bool {
4664 let Some(audio) = &self.audio else {
4665 return false;
4666 };
4667 if !audio.died.load(Ordering::Acquire) {
4668 return true;
4669 }
4670 {
4671 let mut at = audio.rearm_at.lock().unwrap();
4672 if at.is_some_and(|at| at.elapsed() < if_idle_for) {
4673 return false;
4674 }
4675 *at = Some(Instant::now());
4676 }
4677 let Some(ao) = AoSession::open(audio.sample_rate, audio.channels as u32) else {
4678 return false;
4679 };
4680 // A stream comes up streaming and a session starts paused: the fresh one
4681 // is silenced until the seek that feeds it says otherwise, which is the
4682 // same two steps [`open_audio`] takes on the way in.
4683 ao.set_active(false);
4684 // A fresh stream comes up at full volume, so the level this session was
4685 // already running at is put back onto it before it is installed: a
4686 // muted session that lost its device to a daemon restart would
4687 // otherwise come back loud while the window still reads "muted".
4688 ao.set_volume(f32::from_bits(audio.gain.load(Ordering::Acquire)));
4689 // Replacing the session is what closes the dead stream, so it is done
4690 // under the device lock the feeder writes through.
4691 *audio.ao.lock().unwrap() = ao;
4692 // The clock anchor and the played-out arithmetic both belong to the
4693 // stream that died: the new one stamps its own first sample
4694 // ([`Audio::content_at`]), and `start_audio` re-bases the count from the
4695 // device's own position.
4696 audio.content_at.store(-1, Ordering::Release);
4697 audio.died.store(false, Ordering::Release);
4698 if self.audio_disabled.as_deref() == Some(AUDIO_LOST) {
4699 self.audio_disabled = None;
4700 }
4701 true
4702 }
4703
4704 /// The rate noted for whichever source plays `path`, by
4705 /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however
4706 /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session
4707 /// has never taken in.
4708 fn file_rate(&self, path: &Path) -> Rate {
4709 self.source_of(path)
4710 .map_or(Rate::REAL_TIME, |i| self.rates[i])
4711 }
4712
4713 /// Which file this source's **picture** is decoded from: its stand-in when
4714 /// the project is cut on stand-ins and one has been made for it, and the
4715 /// film itself in every other case ([`crate::proxy`]).
4716 ///
4717 /// One `stat` per span open, against a decoder open that costs milliseconds
4718 /// -- so a proxy that appeared (or was deleted) since the last seek is
4719 /// picked up at this one, and no table of attachments exists to disagree
4720 /// with the cache.
4721 ///
4722 /// The sound never comes through here: [`open_audio`] is given the
4723 /// project's own source path, so a mix is the film's however this answers.
4724 pub fn picture_path(&self, source: usize) -> PathBuf {
4725 let path = &self.project.sources()[source].path;
4726 let Some(proxy) = self.proxies.then(|| crate::proxy::cached(path)).flatten() else {
4727 return path.clone();
4728 };
4729 // Said out loud, once per span opened, because "the picture came off
4730 // the stand-in and the delivery did not" is a claim somebody has to be
4731 // able to check: `export` prints the file *it* reads by the same rule.
4732 eprintln!("picture: proxy {}", proxy.display());
4733 proxy
4734 }
4735
4736 /// Whether the picture comes off the stand-ins ([`Self::set_proxies`]).
4737 pub fn proxies(&self) -> bool {
4738 self.proxies
4739 }
4740
4741 /// Cut on the stand-ins, or on the films themselves. Reseeks, so the very
4742 /// next picture comes from the other file -- which is what makes this a
4743 /// switch a person can flip while watching.
4744 ///
4745 /// Says nothing about *which* films have one: a source with no stand-in
4746 /// keeps playing its own pictures either way, and one made while this is on
4747 /// is picked up at the next seek.
4748 ///
4749 /// One undo step ([`Project::push_settings_step`]), and the seek below is
4750 /// what makes the undo of it land on the picture: it reopens the span
4751 /// through [`picture_path`](Self::picture_path), which reads this switch.
4752 pub fn set_proxies(&mut self, on: bool) {
4753 if self.proxies == on {
4754 return;
4755 }
4756 let from = self.settings_value();
4757 self.proxies = on;
4758 self.step_settings(from);
4759 let now = self.now();
4760 self.seek(now);
4761 }
4762
4763 /// Which encoder an export of this project would open its picture on
4764 /// ([`crate::export::EncoderSeat`]). What a front-end puts into the
4765 /// [`ExportSettings`](crate::export::ExportSettings) it starts an export
4766 /// with -- and what the export card shows -- so the pick, the prediction
4767 /// and the file are one answer.
4768 pub fn encoder_seat(&self) -> crate::export::EncoderSeat {
4769 self.encoder_seat
4770 }
4771
4772 /// Gives a loaded project the window's seat when it carries none of its own: nobody
4773 /// picked it, so it is no undo step. Its own copy of the settings is kept in step with
4774 /// the session, as [`Self::set_encoder_seat`] keeps it, and nothing else moves.
4775 pub fn default_encoder_seat(&mut self, seat: crate::export::EncoderSeat) {
4776 if self.encoder_seat == seat {
4777 return;
4778 }
4779 self.encoder_seat = seat;
4780 self.project.mirror_settings(self.settings_value());
4781 }
4782
4783 /// Pick the seat. Nothing to reseek and nothing to re-probe here: this
4784 /// decides what an *export* opens, never what plays. One undo step, like
4785 /// every other pick on the project.
4786 pub fn set_encoder_seat(&mut self, seat: crate::export::EncoderSeat) {
4787 if self.encoder_seat == seat {
4788 return;
4789 }
4790 let from = self.settings_value();
4791 self.encoder_seat = seat;
4792 self.step_settings(from);
4793 }
4794
4795 /// The rate this project's mix was picked to run at
4796 /// ([`Self::set_sample_rate`]), or `None` for the rate the first audio
4797 /// source derives it to.
4798 pub fn sample_rate(&self) -> Option<u32> {
4799 self.sample_rate
4800 }
4801
4802 /// Pick the mix's own rate, overriding the derived one. Nothing to reseek
4803 /// here: it takes effect at the next audio rebuild (a seek, an edit, a
4804 /// reopen), not on the device already playing. One undo step, like every
4805 /// other pick on the project.
4806 pub fn set_sample_rate(&mut self, rate: Option<u32>) {
4807 if self.sample_rate == rate {
4808 return;
4809 }
4810 let from = self.settings_value();
4811 self.sample_rate = rate;
4812 self.step_settings(from);
4813 }
4814
4815 /// Whether an imported film that wants a stand-in gets one made for it
4816 /// there and then ([`Self::set_auto_proxies`]).
4817 pub fn auto_proxies(&self) -> bool {
4818 self.auto_proxies
4819 }
4820
4821 /// Make the stand-ins on import, or make none until asked. Nothing to
4822 /// reseek: this decides what is *started*, never what is decoded -- a proxy
4823 /// already in the cache is still cut on while [`Self::proxies`] is on.
4824 ///
4825 /// One undo step, like every other switch on the project.
4826 pub fn set_auto_proxies(&mut self, on: bool) {
4827 if self.auto_proxies == on {
4828 return;
4829 }
4830 let from = self.settings_value();
4831 self.auto_proxies = on;
4832 self.step_settings(from);
4833 }
4834
4835 /// Which source `path` is, canonicalising only if it has to: a source's own
4836 /// path is canonical ([`Source::new`]), so a caller handing one back from
4837 /// [`sources`](Self::sources) -- which is every library row -- hits on the
4838 /// first walk and never pays for the `canonicalize` syscall the second one
4839 /// makes. One rule, so a path that names a length names a rate too.
4840 fn source_of(&self, path: &Path) -> Option<usize> {
4841 let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted);
4842 at(path).or_else(|| at(&Source::new(path, 0).path))
4843 }
4844
4845 /// How long the whole of `path` is, in timeline frames: the length noted
4846 /// when it became a source, so a file sitting in the library with no clip
4847 /// anywhere still knows how much of itself there is to place. `0` for a
4848 /// file this session has never taken in.
4849 ///
4850 /// By path and not by stream, because a file is one length however many
4851 /// audio tracks it carries -- the picture's frame count for an mp4, the
4852 /// playing time for a song.
4853 pub fn file_frames(&self, path: &Path) -> u32 {
4854 self.source_of(path).map_or(0, |i| self.counts[i])
4855 }
4856
4857 /// What rate the file at `path` was *shot* at, in frames per second -- which
4858 /// is the timeline's own rate for every source that shares it, and is not
4859 /// for one placed at another ([`Rate`]). By path like
4860 /// [`file_frames`](Self::file_frames), and the timeline's rate for a file
4861 /// this session has never taken in (and for a still and a song, which were
4862 /// shot at no rate at all).
4863 ///
4864 /// What a library row names the file with: the timeline's rate there would
4865 /// be a lie about a 23.976 fps file the moment one can join.
4866 pub fn file_fps(&self, path: &Path) -> f64 {
4867 self.file_rate(path).as_f64() * self.meta.frame_rate
4868 }
4869
4870 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
4871 /// on and its index there, by the same topmost-lane-wins rule the decoder
4872 /// follows. `None` over a gap and past the end. What a card that grades
4873 /// "this clip" opens on when nothing has been clicked.
4874 pub fn video_clip_at(&self, timeline_secs: f64) -> Option<(Lane, usize)> {
4875 self.project
4876 .composite_clip_at(secs_to_frame(timeline_secs, self.meta.frame_rate))
4877 }
4878
4879 /// Which clip of `lane` sits at `timeline_secs`, by the same rule
4880 /// [`video_clip_at`](Self::video_clip_at) picks the picture's with -- per
4881 /// lane, so a keyboard walking the lanes for something to select asks the
4882 /// engine rather than re-deriving where a clip ends.
4883 pub fn lane_clip_at(&self, lane: Lane, timeline_secs: f64) -> Option<usize> {
4884 self.project
4885 .lane_clip_at(lane, secs_to_frame(timeline_secs, self.meta.frame_rate))
4886 }
4887
4888 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
4889 /// as it was shot -- what a colour card reads when it opens.
4890 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
4891 self.project.color_of(lane, idx)
4892 }
4893
4894 /// Grades that clip, or takes the grade off with `None`. One undo step like
4895 /// every other edit, and it reseeks like one too -- which is what puts the
4896 /// new grade on the frame that is already on screen, paused or playing,
4897 /// without the caller having to nudge the playhead itself. `false` for an
4898 /// index that is not there and for a value that is not finite.
4899 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
4900 self.edit(Dirty::Picture, |p| p.set_color(lane, idx, params))
4901 }
4902
4903 /// The same grade and the same reseek without the undo step
4904 /// ([`Project::set_color_live`]): what the samples inside one slider drag go
4905 /// through, so the frame regrades under the hand and the whole gesture is
4906 /// still a single `z`.
4907 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
4908 self.edit(Dirty::Picture, |p| p.set_color_live(lane, idx, params))
4909 }
4910
4911 /// [`Project::lut_problems`]: the `.cube` files clips name that cannot be used, and why.
4912 pub fn lut_problems(&self) -> Vec<(PathBuf, String)> {
4913 self.project.lut_problems()
4914 }
4915
4916 /// [`Project::luts`]: every `.cube` file a clip's grade names.
4917 pub fn luts(&self) -> Vec<crate::cube::LutRef> {
4918 self.project.luts()
4919 }
4920
4921 /// [`Project::relink_lut`], with the reseek every picture edit makes.
4922 pub fn relink_lut(&mut self, from: &std::path::Path, to: &std::path::Path) -> usize {
4923 let mut n = 0;
4924 self.edit(Dirty::Picture, |p| {
4925 n = p.relink_lut(from, to);
4926 n > 0
4927 });
4928 n
4929 }
4930
4931 /// Where the clip at `idx` of `lane` is placed -- [`color_of`](Self::color_of)'s
4932 /// twin for geometry instead of grade.
4933 pub fn transform_of(&self, lane: Lane, idx: usize) -> Option<&TransformParams> {
4934 self.project.transform_of(lane, idx)
4935 }
4936
4937 /// Moves/scales/rotates/crops that clip, or takes the placement off with
4938 /// `None` -- [`set_color`](Self::set_color)'s twin, one undo step and one
4939 /// reseek.
4940 pub fn set_transform(
4941 &mut self,
4942 lane: Lane,
4943 idx: usize,
4944 params: Option<TransformParams>,
4945 ) -> bool {
4946 self.edit(Dirty::Picture, |p| p.set_transform(lane, idx, params))
4947 }
4948
4949 /// The placement animation of the clip at `idx` of `lane`, in source order
4950 /// ([`Project::transform_keys_of`]).
4951 pub fn transform_keys_of(&self, lane: Lane, idx: usize) -> &[crate::transform::TransformKey] {
4952 self.project.transform_keys_of(lane, idx)
4953 }
4954
4955 /// Replaces the clip's placement animation, or clears it with an empty list
4956 /// ([`Project::set_transform_keys`]). One undo step and one reseek.
4957 pub fn set_transform_keys(
4958 &mut self,
4959 lane: Lane,
4960 idx: usize,
4961 keys: Vec<crate::transform::TransformKey>,
4962 ) -> bool {
4963 self.edit(Dirty::Picture, |p| p.set_transform_keys(lane, idx, keys))
4964 }
4965
4966 /// The opacity animation of the clip at `idx` of `lane`, in source order
4967 /// ([`Project::opacity_keys_of`]).
4968 pub fn opacity_keys_of(&self, lane: Lane, idx: usize) -> &[crate::transform::OpacityKey] {
4969 self.project.opacity_keys_of(lane, idx)
4970 }
4971
4972 /// Replaces the clip's opacity animation, or clears it with an empty list
4973 /// ([`Project::set_opacity_keys`]). One undo step and one reseek.
4974 pub fn set_opacity_keys(
4975 &mut self,
4976 lane: Lane,
4977 idx: usize,
4978 keys: Vec<crate::transform::OpacityKey>,
4979 ) -> bool {
4980 self.edit(Dirty::Picture, |p| p.set_opacity_keys(lane, idx, keys))
4981 }
4982
4983 /// The colour animation of the clip at `idx` of `lane`, in source order
4984 /// ([`Project::color_keys_of`]).
4985 pub fn color_keys_of(&self, lane: Lane, idx: usize) -> &[crate::color::ColorKey] {
4986 self.project.color_keys_of(lane, idx)
4987 }
4988
4989 /// Replaces the clip's colour animation, or clears it with an empty list
4990 /// ([`Project::set_color_keys`]). One undo step and one reseek.
4991 pub fn set_color_keys(
4992 &mut self,
4993 lane: Lane,
4994 idx: usize,
4995 keys: Vec<crate::color::ColorKey>,
4996 ) -> bool {
4997 self.edit(Dirty::Picture, |p| p.set_color_keys(lane, idx, keys))
4998 }
4999
5000 /// The effects stack of the clip at `idx` of `lane` ([`Project::effects_of`]).
5001 pub fn effects_of(&self, lane: Lane, idx: usize) -> &[crate::effects::Effect] {
5002 self.project.effects_of(lane, idx)
5003 }
5004
5005 /// The keys of the mask at stack position `slot` ([`Project::mask_keys_of`]).
5006 pub fn mask_keys_of(&self, lane: Lane, idx: usize, slot: usize) -> &[crate::effects::MaskKey] {
5007 self.project.mask_keys_of(lane, idx, slot)
5008 }
5009
5010 /// Replaces the keys of the mask at stack position `slot`, or clears them with an
5011 /// empty list ([`Project::set_mask_keys`]). One undo step and one reseek.
5012 pub fn set_mask_keys(&mut self, lane: Lane, idx: usize, slot: usize, keys: Vec<crate::effects::MaskKey>) -> bool {
5013 self.edit(Dirty::Picture, |p| p.set_mask_keys(lane, idx, slot, keys))
5014 }
5015
5016 /// Replaces the clip's effects stack ([`Project::set_effects`]). One undo
5017 /// step and one reseek.
5018 pub fn set_effects(&mut self, lane: Lane, idx: usize, effects: Vec<crate::effects::Effect>) -> bool {
5019 self.edit(Dirty::Picture, |p| p.set_effects(lane, idx, effects))
5020 }
5021
5022 /// [`Project::key_source_frame`].
5023 pub fn key_source_frame(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<u32> {
5024 self.project.key_source_frame(lane, idx, timeline_frame)
5025 }
5026
5027 /// [`Project::is_keyed`].
5028 pub fn is_keyed(&self, lane: Lane, idx: usize, kind: crate::project::KeyKind) -> bool {
5029 self.project.is_keyed(lane, idx, kind)
5030 }
5031
5032 /// [`Project::key_ease_at`].
5033 pub fn key_ease_at(
5034 &self,
5035 lane: Lane,
5036 idx: usize,
5037 kind: crate::project::KeyKind,
5038 timeline_frame: u32,
5039 ) -> Option<crate::transform::KeyEase> {
5040 self.project.key_ease_at(lane, idx, kind, timeline_frame)
5041 }
5042
5043 /// The stopwatch ([`Project::toggle_key`]). One undo step and one reseek.
5044 pub fn toggle_key(
5045 &mut self,
5046 lane: Lane,
5047 idx: usize,
5048 kind: crate::project::KeyKind,
5049 timeline_frame: u32,
5050 ) -> Option<bool> {
5051 let mut out = None;
5052 self.edit(Dirty::Picture, |p| {
5053 out = p.toggle_key(lane, idx, kind, timeline_frame);
5054 out.is_some()
5055 });
5056 out
5057 }
5058
5059 /// [`Project::set_key_ease_at`]. One undo step and one reseek.
5060 pub fn set_key_ease_at(
5061 &mut self,
5062 lane: Lane,
5063 idx: usize,
5064 kind: crate::project::KeyKind,
5065 timeline_frame: u32,
5066 ease: crate::transform::KeyEase,
5067 ) -> bool {
5068 self.edit(Dirty::Picture, |p| p.set_key_ease_at(lane, idx, kind, timeline_frame, ease))
5069 }
5070
5071 /// [`Project::put_transform_key_at`]; `snapshot` false is the live write of a drag.
5072 pub fn put_transform_key_at(
5073 &mut self,
5074 lane: Lane,
5075 idx: usize,
5076 timeline_frame: u32,
5077 params: TransformParams,
5078 snapshot: bool,
5079 ) -> bool {
5080 self.edit(Dirty::Picture, |p| p.put_transform_key_at(lane, idx, timeline_frame, params, snapshot))
5081 }
5082
5083 /// [`Project::put_opacity_key_at`]; `snapshot` false is the live write of a drag.
5084 pub fn put_opacity_key_at(
5085 &mut self,
5086 lane: Lane,
5087 idx: usize,
5088 timeline_frame: u32,
5089 opacity: f32,
5090 snapshot: bool,
5091 ) -> bool {
5092 self.edit(Dirty::Picture, |p| p.put_opacity_key_at(lane, idx, timeline_frame, opacity, snapshot))
5093 }
5094
5095 /// [`Project::put_color_key_at`]; `snapshot` false is the live write of a drag.
5096 pub fn put_color_key_at(
5097 &mut self,
5098 lane: Lane,
5099 idx: usize,
5100 timeline_frame: u32,
5101 params: ColorParams,
5102 snapshot: bool,
5103 ) -> bool {
5104 self.edit(Dirty::Picture, |p| p.put_color_key_at(lane, idx, timeline_frame, params, snapshot))
5105 }
5106
5107 /// The placement the clip shows at timeline `timeline_frame`, keys evaluated
5108 /// ([`Project::transform_at`]).
5109 pub fn transform_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<TransformParams> {
5110 self.project.transform_at(lane, idx, timeline_frame)
5111 }
5112
5113 /// The grade the clip shows at `timeline_frame`, keys evaluated ([`Project::color_at`]).
5114 pub fn color_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<ColorParams> {
5115 self.project.color_at(lane, idx, timeline_frame)
5116 }
5117
5118 /// The opacity the clip shows at `timeline_frame`, keys evaluated, fades not
5119 /// counted ([`Project::opacity_at`]).
5120 pub fn opacity_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> f32 {
5121 self.project.opacity_at(lane, idx, timeline_frame)
5122 }
5123
5124 /// The same placement and the same reseek without the undo step
5125 /// ([`Project::set_transform_live`]) -- [`set_color_live`](Self::set_color_live)'s
5126 /// twin for a slider drag.
5127 pub fn set_transform_live(
5128 &mut self,
5129 lane: Lane,
5130 idx: usize,
5131 params: Option<TransformParams>,
5132 ) -> bool {
5133 self.edit(Dirty::Picture, |p| p.set_transform_live(lane, idx, params))
5134 }
5135
5136 /// The project's resolution: what every clip is composed onto, what the
5137 /// window is sized to and what an export writes -- *not* any one file's.
5138 /// It starts as source 0's picture, which is what a project meant before it
5139 /// could have a resolution of its own.
5140 pub fn resolution(&self) -> (u32, u32) {
5141 (self.meta.width, self.meta.height)
5142 }
5143
5144 /// Source 0's own picture size -- what the project resolution started as,
5145 /// and the one size a caller offering a list of them must not leave out.
5146 pub fn native_resolution(&self) -> (u32, u32) {
5147 self.native
5148 }
5149
5150 /// Sets it. Rebuilds the **picture** where the playhead is, so the frame on
5151 /// screen is recomposed at the new size at once, paused or playing -- and
5152 /// the sound is not touched at all: the size of the canvas is not something
5153 /// a sample can carry, so resizing a 4K film mid-play costs neither a hole
5154 /// in the audio nor an offset against it ([`Dirty`]). `false` for a size
5155 /// that is not a picture -- zero either way, or past 8K, which is where the
5156 /// per-frame buffers stop being a sane thing to allocate from a keystroke.
5157 ///
5158 /// One undo step: the resolution is the project's own, so it rides in the
5159 /// entry beside the lanes and a `z` takes the canvas back to the size it
5160 /// was ([`Project::push_settings_step`]).
5161 pub fn set_resolution(&mut self, width: u32, height: u32) -> bool {
5162 if !crate::is_resolution(width, height) {
5163 return false;
5164 }
5165 if (width, height) == (self.meta.width, self.meta.height) {
5166 return false;
5167 }
5168 let from = self.settings_value();
5169 self.meta.width = width;
5170 self.meta.height = height;
5171 self.step_settings(from);
5172 self.invalidate(Dirty::Picture);
5173 true
5174 }
5175
5176 /// Which HDR-to-SDR rendition this project is watched and exported in
5177 /// ([`crate::tonemap::Preset`]) -- the reference one until somebody picks
5178 /// another, and a setting on the project rather than on any clip.
5179 pub fn tone(&self) -> crate::tonemap::Preset {
5180 self.project.tone()
5181 }
5182
5183 /// The project's notes ([`Project::notes`]).
5184 pub fn notes(&self) -> &str {
5185 self.project.notes()
5186 }
5187
5188 /// Sets the project's notes ([`Project::set_notes`]): one undo step, `false` for the text
5189 /// already in force.
5190 pub fn set_notes(&mut self, notes: &str) -> bool {
5191 self.project.set_notes(notes)
5192 }
5193
5194 /// How long a still is placed for, in seconds ([`Project::still_secs`]).
5195 pub fn still_secs(&self) -> f64 {
5196 self.project.still_secs()
5197 }
5198
5199 /// Sets the still length ([`Project::set_still_secs`]): one undo step, `false` for the length
5200 /// already in force. Stills placed after this take it; clips already on the timeline keep theirs.
5201 pub fn set_still_secs(&mut self, secs: f64) -> bool {
5202 self.project.set_still_secs(secs)
5203 }
5204
5205 /// What source 0's own file declared about how bright it gets
5206 /// ([`ContentLight`]): a property of the film, read once at open, and
5207 /// entirely absent (every field `None`) for an SDR file, a song or a
5208 /// still. Read-only -- the number a file carries, never a project setting
5209 /// a user can override, since nothing in [`Project`] holds one to persist.
5210 pub fn content_light(&self) -> ContentLight {
5211 self.content_light
5212 }
5213
5214 /// Picks one. Rebuilds the **picture** where the playhead is, exactly as
5215 /// [`set_resolution`](Self::set_resolution) does -- the frame on screen is
5216 /// remapped at once, paused or playing, and the sound is not touched: a
5217 /// rendition is not something a sample can carry. `false` for the rendition
5218 /// already in force.
5219 ///
5220 /// An SDR project is unmoved by this by construction: no clip of it builds a
5221 /// tone map at all ([`crate::tonemap`]), so the reseek recomposes the very
5222 /// same bytes.
5223 ///
5224 /// corner-cut: not an undo step, for the reason the resolution is not
5225 /// ([`Project::set_tone`]).
5226 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
5227 if !self.project.set_tone(preset) {
5228 return false;
5229 }
5230 self.invalidate(Dirty::Picture);
5231 true
5232 }
5233
5234 /// The scaffolding source's own frame rate -- what the project rate started
5235 /// as, and the one rate a caller offering a list of them must not leave out
5236 /// ([`native_resolution`](Self::native_resolution)'s reason).
5237 pub fn native_frame_rate(&self) -> f64 {
5238 self.native_fps
5239 }
5240
5241 /// Cuts this timeline at `fps` from here on: every clip is *conformed* to
5242 /// the new rate ([`Project::retime`]), every source is read through a
5243 /// [`Rate`] against it, and an export written from this session comes out at
5244 /// it. The edit survives as the same seconds of the same footage on a finer
5245 /// or coarser grid -- a 30 fps take on a timeline moved to 24 keeps its
5246 /// length and its sync, it is simply counted in 24ths now.
5247 ///
5248 /// Reseeks like [`set_resolution`](Self::set_resolution), so the picture and
5249 /// the sound under the playhead are already the new rate's when this
5250 /// returns. `false` -- changing nothing -- for a rate that is not a rate, for
5251 /// the one already in force, and for one no timescale can name
5252 /// ([`crate::mux::frame_timing`], the same wall a file of an unnameable rate
5253 /// is refused at).
5254 ///
5255 /// One undo step, and the entry it takes is the whole of the change: the
5256 /// lanes as they were in the *old* rate's numbering, with that rate beside
5257 /// them, so a `z` restores the two together ([`Project::retime`]). The
5258 /// step is taken before the retime rather than after, since this is the one
5259 /// settings door that moves the lanes the step holds. Picking the old rate
5260 /// back is still within a frame of where it started rather than on it: the
5261 /// *lanes* come home exactly out of the entry, and the per-source lengths
5262 /// are the half that goes through the map twice
5263 /// ([`PlaybackSession::adopt_settings`]).
5264 pub fn set_frame_rate(&mut self, fps: f64) -> bool {
5265 if !fps.is_finite() || fps <= 0.0 || fps == self.meta.frame_rate || self.project.rate_locked() {
5266 return false;
5267 }
5268 // Old timeline frames per new one, exactly -- the one map every frame
5269 // number on every lane goes through. Built before anything is touched,
5270 // since a rate no timescale can name is a refusal and not a half-retimed
5271 // project.
5272 let Ok(k) = Rate::from_fps(self.meta.frame_rate, fps) else {
5273 return false;
5274 };
5275 let from = self.settings_value();
5276 self.project.push_settings_step(from.clone(), from);
5277 // Lengths first: the retime holds every clip inside its source's *new*
5278 // length, so a clip that played to the last frame of its file still
5279 // does rather than naming one past the end.
5280 for count in &mut self.counts {
5281 *count = k.timeline_nearest(*count).max(1);
5282 }
5283 self.project.retime(k, &self.counts);
5284 // A file's own rate has not changed; what it is *against* has.
5285 for rate in &mut self.rates {
5286 *rate = rate.then(k);
5287 }
5288 self.meta.frame_rate = fps;
5289 self.meta.frame_count = k.timeline_nearest(self.meta.frame_count).max(1);
5290 // The copy the project keeps, now that the change has landed: what the
5291 // next lane edit's entry carries.
5292 self.project.mirror_settings(self.settings_value());
5293 let now = self.now();
5294 self.seek(now);
5295 true
5296 }
5297
5298 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
5299 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
5300 self.project.fit_of(lane, idx)
5301 }
5302
5303 /// Sets that clip's fit policy. One undo step and a reseek, exactly like a
5304 /// grade: the picture on screen is recomposed through the new policy without
5305 /// the caller nudging the playhead. `false` for an index that is not there.
5306 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
5307 self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit))
5308 }
5309
5310 /// [`Project::set_stabilise`]. Reseeks like a grade. The analysis it needs is
5311 /// started in the background ([`Self::stabilise_start`]); until it is done the
5312 /// clip plays as it is.
5313 pub fn set_stabilise(&mut self, lane: Lane, idx: usize, st: Option<crate::stabilise::Stabilise>) -> bool {
5314 let done = self.edit(Dirty::Picture, |p| p.set_stabilise(lane, idx, st));
5315 if done && st.is_some() {
5316 self.stabilise_start(lane, idx);
5317 }
5318 done
5319 }
5320
5321 /// The generator of kind `name` ([`crate::generate::KINDS`]) at its defaults, drawn for this
5322 /// timeline's canvas and rate.
5323 pub fn generator_named(&self, name: &str) -> Option<crate::generate::Gen> {
5324 crate::generate::Gen::named(name, self.meta.width, self.meta.height, self.meta.frame_rate)
5325 }
5326
5327 /// Places a generated clip ([`crate::generate`]) `secs` long on the video lane `onto` (`V1`
5328 /// when none), at `timeline_secs`, like a still. A countdown with no length asked for runs
5329 /// its own count. Overwrites what the stretch lands on, as a still does. `false` when the
5330 /// lane or the place is refused.
5331 pub fn place_generated(&mut self, spec: crate::generate::Gen, timeline_secs: f64, secs: Option<f64>, onto: Option<Lane>) -> crate::Result<bool> {
5332 let fps = self.meta.frame_rate;
5333 let source = self.generator_source(spec);
5334 let secs = secs.unwrap_or(match spec.kind {
5335 crate::generate::Kind::Countdown { from, .. } => f64::from(from),
5336 _ => self.project.still_secs(),
5337 });
5338 let wall = self.counts[source];
5339 let out = ((secs * fps).round() as u32).clamp(1, wall.max(1));
5340 let lane = match onto {
5341 Some(lane) if lane.kind == LaneKind::Video => lane,
5342 Some(_) => return Err("a generated clip goes on a video lane".into()),
5343 None => Lane::V1,
5344 };
5345 if self.project.lane(lane).is_empty() && !self.project.lanes().contains(&lane) {
5346 return Err(format!("{lane:?} is not a lane of this timeline").into());
5347 }
5348 Ok(self.place_at(lane, timeline_secs, Clip::source_range(source, 0, out)))
5349 }
5350
5351 /// Places a test tone ([`crate::generate::Tone`]) `secs` long on the audio lane `onto` (`A1`
5352 /// when none), at `timeline_secs`, as a sound file's stream is placed. The tone's file is made
5353 /// in `dir` the first time (the project's folder for a saved project, else the data folder).
5354 /// `false` when the place is refused.
5355 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> {
5356 let path = tone.write(dir, secs)?;
5357 let lane = match onto {
5358 Some(lane) if lane.kind == LaneKind::Audio => lane,
5359 Some(_) => return Err("a tone goes on an audio lane".into()),
5360 None => Lane::A1,
5361 };
5362 // A tone is a standalone audio file: taken into the library the first time it is
5363 // placed (as a song is), so the placement below finds it.
5364 if self.file_frames(&path) == 0 {
5365 self.import(&path)?;
5366 }
5367 self.place_stream_at(timeline_secs, &path, 0, Some(lane))
5368 }
5369
5370 /// The source index of `spec`, taken into the library the first time it is used.
5371 fn generator_source(&mut self, spec: crate::generate::Gen) -> usize {
5372 let source = self.project.import(spec.path(), 0);
5373 self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME);
5374 source
5375 }
5376
5377 /// Changes the generator the clip at `idx` of `lane` is, keeping its place and length.
5378 /// One undo step; `false` for a clip that is not there or no change.
5379 pub fn set_generator(&mut self, lane: Lane, idx: usize, spec: crate::generate::Gen) -> bool {
5380 let source = self.generator_source(spec);
5381 self.edit(Dirty::Picture, |p| p.set_clip_source(lane, idx, source))
5382 }
5383
5384 /// The generator the clip at `idx` of `lane` is, `None` for a clip made from a file.
5385 pub fn generator_of(&self, lane: Lane, idx: usize) -> Option<crate::generate::Gen> {
5386 let src = self.project.sources().get(self.project.lane(lane).get(idx)?.source)?;
5387 crate::generate::Gen::parse(&src.path)
5388 }
5389
5390 /// [`Project::set_label`].
5391 pub fn set_label(&mut self, lane: Lane, idx: usize, label: u8) -> bool {
5392 self.project.set_label(lane, idx, label)
5393 }
5394
5395 /// [`Project::set_enabled`]: a switched-off clip is skipped by picture and sound.
5396 pub fn set_enabled(&mut self, lane: Lane, idx: usize, enabled: bool) -> bool {
5397 self.edit(Dirty::Both, |p| p.set_enabled(lane, idx, enabled))
5398 }
5399
5400 /// [`Project::mark_of`].
5401 pub fn mark_of(&self, lane: Lane, idx: usize) -> crate::project::ClipMark {
5402 self.project.mark_of(lane, idx)
5403 }
5404
5405 /// [`Project::set_deinterlace`]. Stored only; the render reads it once the engine acts on it.
5406 pub fn set_deinterlace(&mut self, lane: Lane, idx: usize, mode: crate::project::Deinterlace) -> bool {
5407 self.project.set_deinterlace(lane, idx, mode)
5408 }
5409
5410 /// [`Project::deinterlace_of`].
5411 pub fn deinterlace_of(&self, lane: Lane, idx: usize) -> crate::project::Deinterlace {
5412 self.project.deinterlace_of(lane, idx)
5413 }
5414
5415 /// [`Project::stabilise_of`].
5416 pub fn stabilise_of(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Stabilise> {
5417 self.project.stabilise_of(lane, idx)
5418 }
5419
5420 /// The source and file-frame range the clip at `idx` of `lane` is analysed
5421 /// over, `None` for no clip or one that is not footage (a still, a song).
5422 pub fn stabilise_range(&self, lane: Lane, idx: usize) -> Option<(std::path::PathBuf, u32, u32)> {
5423 let c = self.project.lane(lane).get(idx)?;
5424 let path = &self.project.sources().get(c.source)?.path;
5425 if crate::is_image(path) || crate::is_audio(path) {
5426 return None;
5427 }
5428 let (lo, hi) = crate::stabilise::clip_range(path, c, self.meta.frame_rate);
5429 Some((path.clone(), lo, hi))
5430 }
5431
5432 /// Where the clip's stabilisation analysis stands ([`crate::stabilise::status`]).
5433 pub fn stabilise_status(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Status> {
5434 let (path, lo, hi) = self.stabilise_range(lane, idx)?;
5435 Some(crate::stabilise::status(&path, lo, hi))
5436 }
5437
5438 /// Starts the clip's stabilisation analysis in the background unless it is
5439 /// cached or running ([`crate::stabilise::start`]).
5440 pub fn stabilise_start(&self, lane: Lane, idx: usize) -> Option<crate::stabilise::Status> {
5441 let (path, lo, hi) = self.stabilise_range(lane, idx)?;
5442 Some(crate::stabilise::start(&path, lo, hi))
5443 }
5444
5445 /// Stops the clip's running analysis. `false` when none runs.
5446 pub fn stabilise_cancel(&self, lane: Lane, idx: usize) -> bool {
5447 self.stabilise_range(lane, idx).is_some_and(|(path, lo, hi)| crate::stabilise::cancel(&path, lo, hi))
5448 }
5449
5450 /// What auto reframe needs of the clip at `idx` of `lane`: its file range and the
5451 /// geometry its keys are made for ([`crate::reframe`]). `None` for no clip, a
5452 /// still or a song.
5453 pub fn reframe_job(&self, lane: Lane, idx: usize) -> Option<crate::reframe::ReframeJob> {
5454 let (path, lo, hi) = self.stabilise_range(lane, idx)?;
5455 let c = self.project.lane(lane).get(idx)?;
5456 let shown = crate::demux::Demuxer::open(&path).ok()?.0;
5457 let target = crate::reframe::Target {
5458 src_w: shown.width,
5459 src_h: shown.height,
5460 canvas_w: self.meta.width,
5461 canvas_h: self.meta.height,
5462 base: self.project.transform_of(lane, idx).copied().unwrap_or_default(),
5463 in_frame: c.in_frame,
5464 out_frame: c.out_frame,
5465 };
5466 Some(crate::reframe::ReframeJob { path, lo, hi, target })
5467 }
5468
5469 /// Writes reframe `keys` on the clip, and puts it on [`FitPolicy::Fit`] -- the
5470 /// placement they are made for. One undo step; `false` when the keys are refused.
5471 pub fn apply_reframe(&mut self, lane: Lane, idx: usize, keys: Vec<crate::transform::TransformKey>) -> bool {
5472 self.begin_batch();
5473 self.set_fit(lane, idx, FitPolicy::Fit);
5474 let done = self.set_transform_keys(lane, idx, keys);
5475 self.end_batch();
5476 done
5477 }
5478
5479 /// Redraws the picture once an analysis finished, so a stabilised clip shows
5480 /// its correction without an edit.
5481 pub fn stabilise_refresh(&mut self) {
5482 self.invalidate(Dirty::Picture);
5483 }
5484
5485 /// Starts following the rect or ellipse mask at stack position `slot` of the clip at
5486 /// `idx` of `lane` ([`crate::track`]) from source frame `from` to `to`, either order.
5487 /// The mask's centre at `from` is where the feature is; [`Self::track_mask_apply`]
5488 /// writes the path back once the track has finished.
5489 pub fn track_mask_start(&self, lane: Lane, idx: usize, slot: usize, from: u32, to: u32) -> Result<TrackJob, String> {
5490 use crate::effects::EffectKind;
5491 let c = self.project.lane(lane).get(idx).ok_or("there is no clip there")?;
5492 let e = c.effects.get(slot).ok_or("there is no effect in that stack position")?;
5493 if !matches!(e.kind, EffectKind::RectMask | EffectKind::EllipseMask) {
5494 return Err("only a rect or ellipse mask can be tracked".into());
5495 }
5496 let (path, lo, hi) = self.stabilise_range(lane, idx).ok_or("a still or a song has no picture to track")?;
5497 let (from, to) = (from.clamp(lo, hi - 1), to.clamp(lo, hi - 1));
5498 if from == to {
5499 return Err("a track needs two frames: from and to are the same frame".into());
5500 }
5501 let forward = to > from;
5502 let range = if forward { (from, to + 1) } else { (to, from + 1) };
5503 let at = e.posed(f64::from(from));
5504 let (x, y) = (at.values[0], at.values[1]);
5505 let region = crate::track::Region { x, y, w: at.values[2], h: at.values[3] };
5506 // The placement the renderer gives the clip, so the track's points land on the canvas
5507 // where the mask is drawn: the base transform and its keys, on this canvas.
5508 let pose = crate::track::Pose {
5509 base: self.transform_of(lane, idx).copied().unwrap_or_default(),
5510 keys: self.transform_keys_of(lane, idx).to_vec(),
5511 canvas: self.resolution(),
5512 fit: crate::scale::FitPolicy::default(),
5513 };
5514 let id = crate::track::start(&path, range, from, forward, region, pose);
5515 Ok(TrackJob { lane, idx, slot, id, from, anchor: (x, y) })
5516 }
5517
5518 /// Writes every finished track in `jobs` onto its mask ([`Self::track_mask_apply`]) and
5519 /// takes it out of `jobs`; running ones stay. Each landing is one undo step. Returns one
5520 /// entry per track that ended.
5521 pub fn track_settle(&mut self, jobs: &mut Vec<TrackJob>) -> Vec<TrackDone> {
5522 let mut done = Vec::new();
5523 let mut running = Vec::new();
5524 for job in std::mem::take(jobs) {
5525 let result = match crate::track::status(job.id) {
5526 crate::track::Status::Running(_) => {
5527 running.push(job);
5528 continue;
5529 }
5530 crate::track::Status::Gone => continue,
5531 crate::track::Status::Finished => match crate::track::take(job.id) {
5532 None => continue,
5533 Some(Err(e)) => Err(e),
5534 Some(Ok(t)) => self.track_mask_apply(&job, &t).map(|keys| {
5535 let frames = t.points.iter().map(|p| p.0);
5536 TrackOutcome {
5537 keys,
5538 from: frames.clone().min().unwrap_or(job.from),
5539 to: frames.max().unwrap_or(job.from),
5540 lost_at: t.lost_at,
5541 }
5542 }),
5543 },
5544 };
5545 done.push(TrackDone { lane: job.lane, idx: job.idx, slot: job.slot, result });
5546 }
5547 *jobs = running;
5548 done
5549 }
5550
5551 /// Writes a finished track onto its mask: the mask's centre moves by the feature's
5552 /// displacement from where it was at the start, and its size and soft edge keep the
5553 /// values they have at each frame. Keys inside the tracked frames are replaced and
5554 /// keys outside them stay. Returns how many keys were written. One undo step.
5555 pub fn track_mask_apply(&mut self, job: &TrackJob, track: &crate::track::Track) -> Result<usize, String> {
5556 use crate::effects::MaskKey;
5557 use crate::track::{KEY_TOLERANCE, simplify};
5558 use crate::transform::{KeyEase, MAX_TRANSFORM_KEYS};
5559 let Some(&(_, x0, y0)) = track.points.first() else {
5560 return Err("the track has no points".into());
5561 };
5562 let mut pts: Vec<(u32, f32, f32)> = track
5563 .points
5564 .iter()
5565 .map(|&(f, x, y)| (f, job.anchor.0 + x - x0, job.anchor.1 + y - y0))
5566 .collect();
5567 pts.sort_by_key(|p| p.0);
5568 let (first, last) = (pts[0].0, pts[pts.len() - 1].0);
5569 let outside: Vec<MaskKey> =
5570 self.mask_keys_of(job.lane, job.idx, job.slot).iter().filter(|k| k.at < first || k.at > last).copied().collect();
5571 let room = MAX_TRANSFORM_KEYS.saturating_sub(outside.len()).max(2);
5572 let mut tolerance = KEY_TOLERANCE;
5573 let mut kept = simplify(&pts, tolerance);
5574 while kept.len() > room {
5575 tolerance *= 2.0;
5576 kept = simplify(&pts, tolerance);
5577 }
5578 let mut keys = {
5579 let e = self
5580 .project
5581 .lane(job.lane)
5582 .get(job.idx)
5583 .and_then(|c| c.effects.get(job.slot))
5584 .ok_or("the mask is gone")?;
5585 kept.iter()
5586 .map(|&i| {
5587 let (f, x, y) = pts[i];
5588 let v = e.posed(f64::from(f));
5589 MaskKey { at: f, x, y, width: v.values[2], height: v.values[3], feather: v.values[4], ease: KeyEase::Linear }
5590 })
5591 .collect::<Vec<_>>()
5592 };
5593 keys.extend(outside);
5594 keys.sort_by_key(|k| k.at);
5595 let count = keys.len();
5596 if !self.set_mask_keys(job.lane, job.idx, job.slot, keys) {
5597 return Err("the engine refused the keys (is the mask still there?)".into());
5598 }
5599 Ok(count)
5600 }
5601
5602 /// Waveform flags on a visualizer clip. Reseeks like a grade: the
5603 /// painter reads them on the next picture.
5604 pub fn set_visualizer(&mut self, lane: Lane, idx: usize, flags: u8) -> bool {
5605 self.edit(Dirty::Picture, |p| p.set_visualizer(lane, idx, flags))
5606 }
5607
5608 pub fn set_viz_paint(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
5609 self.edit(Dirty::Picture, |p| p.set_viz_paint(lane, idx, paint))
5610 }
5611
5612 /// The same look and the same repaint without the undo step
5613 /// ([`Project::set_viz_paint_live`]): what the samples inside one drag
5614 /// across the colour wheel go through, so the picture follows the hand and
5615 /// the whole gesture is still a single `z`.
5616 pub fn set_viz_paint_live(&mut self, lane: Lane, idx: usize, paint: u64) -> bool {
5617 self.edit(Dirty::Picture, |p| p.set_viz_paint_live(lane, idx, paint))
5618 }
5619
5620 /// Timeline frames of ramp-up from silence at the start of the clip at
5621 /// `idx` of `lane`. `0` for an index that is not there.
5622 pub fn fade_in_of(&self, lane: Lane, idx: usize) -> u32 {
5623 self.project.fade_in_of(lane, idx)
5624 }
5625
5626 /// The volume envelope of the clip at `idx` of `lane`
5627 /// ([`Project::gain_keys_of`]).
5628 pub fn gain_keys_of(&self, lane: Lane, idx: usize) -> &[GainKey] {
5629 self.project.gain_keys_of(lane, idx)
5630 }
5631
5632 /// Replaces the clip's whole volume envelope ([`Project::set_gain_keys`]).
5633 /// A sound-only edit: no reseek of the picture.
5634 pub fn set_gain_keys(&mut self, lane: Lane, idx: usize, keys: Vec<GainKey>) -> bool {
5635 self.edit(Dirty::Sound, |p| p.set_gain_keys(lane, idx, keys))
5636 }
5637
5638 /// Puts one point into the clip's volume envelope ([`Project::add_gain_key`]).
5639 pub fn add_gain_key(&mut self, lane: Lane, idx: usize, key: GainKey) -> bool {
5640 self.edit(Dirty::Sound, |p| p.add_gain_key(lane, idx, key))
5641 }
5642
5643 /// Takes the point at source frame `at` out of the clip's volume envelope
5644 /// ([`Project::remove_gain_key`]).
5645 pub fn remove_gain_key(&mut self, lane: Lane, idx: usize, at: u32) -> bool {
5646 self.edit(Dirty::Sound, |p| p.remove_gain_key(lane, idx, at))
5647 }
5648
5649 /// The effective envelope dB at a timeline frame, keys and clip gain but not
5650 /// the fades ([`Project::gain_db_at`]).
5651 pub fn gain_db_at(&self, lane: Lane, idx: usize, timeline_frame: u32) -> Option<f32> {
5652 self.project.gain_db_at(lane, idx, timeline_frame)
5653 }
5654
5655 /// Sets that clip's fade-in, clamped to its own length. A sound-only
5656 /// edit, same as an equalizer or a fader: no reseek needed.
5657 pub fn set_fade_in(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5658 self.edit(Dirty::Sound, |p| p.set_fade_in(lane, idx, frames))
5659 }
5660
5661 /// Timeline frames of ramp-down to silence at the end of the clip at
5662 /// `idx` of `lane`. `0` for an index that is not there.
5663 pub fn fade_out_of(&self, lane: Lane, idx: usize) -> u32 {
5664 self.project.fade_out_of(lane, idx)
5665 }
5666
5667 /// Sets that clip's fade-out. Same promises as [`Self::set_fade_in`].
5668 pub fn set_fade_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5669 self.edit(Dirty::Sound, |p| p.set_fade_out(lane, idx, frames))
5670 }
5671
5672 /// Crossfades the audio clip at `idx` of `lane` into its neighbour, over
5673 /// `frames`. Same promises as [`Project::crossfade`].
5674 pub fn crossfade(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5675 self.edit(Dirty::Sound, |p| p.crossfade(lane, idx, frames))
5676 }
5677
5678 /// Timeline frames of dissolve at the end of the clip at `idx` of `lane`,
5679 /// into its neighbour. `0` for an index that is not there.
5680 pub fn transition_out_of(&self, lane: Lane, idx: usize) -> u32 {
5681 self.project.transition_out_of(lane, idx)
5682 }
5683
5684 /// The kind of the transition that clip plays into its neighbour.
5685 pub fn transition_kind_of(&self, lane: Lane, idx: usize) -> crate::transitions::TransitionKind {
5686 self.project.transition_kind_of(lane, idx)
5687 }
5688
5689 /// Sets that clip's transition into its neighbour, kind and length in one
5690 /// undo step. A picture edit, like [`Self::set_transition_out`].
5691 pub fn set_transition(
5692 &mut self,
5693 lane: Lane,
5694 idx: usize,
5695 kind: crate::transitions::TransitionKind,
5696 frames: u32,
5697 ) -> bool {
5698 self.edit(Dirty::Picture, |p| p.set_transition(lane, idx, kind, frames))
5699 }
5700
5701 /// Sets that clip's dissolve into its neighbour, clamped to its own
5702 /// length. A picture edit -- same as a grade or fit policy.
5703 pub fn set_transition_out(&mut self, lane: Lane, idx: usize, frames: u32) -> bool {
5704 self.edit(Dirty::Picture, |p| p.set_transition_out(lane, idx, frames))
5705 }
5706
5707 /// The clip at `idx` -- what a caller copies. It is a pair of source frame
5708 /// numbers and nothing else, so a copy stays valid after the clip it came
5709 /// from is deleted. `None` past the end.
5710 pub fn clip_at(&self, idx: usize) -> Option<Clip> {
5711 self.project.clips().get(idx).cloned()
5712 }
5713
5714 /// Inserts `clip` at the playhead, splitting the clip under it. Like a
5715 /// delete this moves every following frame, so the session reseeks; past
5716 /// the end of the timeline the clip is appended. One undo step.
5717 pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool {
5718 // The clipboard's own rule, and only the clipboard's: a paste past the
5719 // end is an append, never a clip with black in front of it. The frame
5720 // itself is honoured in [`Project::paste`], because a *drop* names a
5721 // place on the bed and means it.
5722 let at =
5723 secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames());
5724 let clip = self.held_to_take(clip);
5725 self.edit(Dirty::Both, |p| p.paste(at, clip))
5726 }
5727
5728 /// [`paste_at`](Self::paste_at)'s general form: [`Project::paste_set`]'s
5729 /// door, clamped to the timeline's own end the same way -- a set let go
5730 /// past the last frame lands there rather than carrying black in front of
5731 /// it, exactly as a lone clip's paste does.
5732 pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool {
5733 let at =
5734 secs_to_frame(timeline_secs, self.meta.frame_rate).min(self.project.timeline_frames());
5735 // Each item is held to its own lane's wall, as a lone placement is.
5736 let items: Vec<(Lane, Clip)> = items
5737 .iter()
5738 .map(|(lane, clip)| (*lane, self.held_to_lane(*lane, clip.clone())))
5739 .collect();
5740 self.edit(Dirty::Both, |p| p.paste_set(at, &items))
5741 }
5742
5743 /// Places the whole of `path` played on its audio `stream` at
5744 /// `timeline_secs`, the way [`paste_at`](Self::paste_at) places a copy --
5745 /// the door a library row goes through, and the only way a stream other
5746 /// than the one an import brought in reaches the timeline. The `(file,
5747 /// stream)` pair becomes a source if it is not one already.
5748 ///
5749 /// Refused, changing nothing, unless that stream can join *this* timeline:
5750 /// same audio parameters as the first source, in the same words
5751 /// [`import`](Self::import) refuses a file with. One output device and one
5752 /// copied AAC track mean one *layout* for the whole timeline, so a mono
5753 /// track cannot join a stereo one. Its sample rate may be its own: the
5754 /// segment's resampler conforms it at the decoder's door.
5755 /// A front-end greys such a row out; this is the backstop that keeps a
5756 /// stale one from making the whole timeline silent.
5757 ///
5758 /// Which lane it lands on is decided here, from the file and from `onto` --
5759 /// the lane it was let go over, if it was let go over one at all: a file
5760 /// with a picture asked for by no lane, or for one of the first pair, is
5761 /// pasted across `V1` and `A1` as a grouped take; asked for by a further
5762 /// *video* lane it is *placed* there with its sound on that lane's own audio
5763 /// row (`V2` -> `A2`, added if it is not there yet), overwriting what the two
5764 /// halves land on and rippling nothing; asked for by a further audio lane it
5765 /// is that file's sound alone. A file with no picture ([`crate::is_audio`]) is placed
5766 /// on the audio lane it was asked for, or on `A1`, and never on a video
5767 /// lane. A still image ([`crate::is_image`]) is its mirror: the video lane
5768 /// it was asked for or `V1`, never an audio one, and it goes down
5769 /// the project's still length ([`Project::still_secs`]) long rather than at the length it is
5770 /// *allowed* to be trimmed out to. A caller never has to ask.
5771 pub fn place_stream_at(
5772 &mut self,
5773 timeline_secs: f64,
5774 path: &Path,
5775 stream: usize,
5776 onto: Option<Lane>,
5777 ) -> crate::Result<bool> {
5778 self.place_stream_mode(timeline_secs, path, stream, onto, None)
5779 }
5780
5781 /// [`place_stream_at`](Self::place_stream_at) as an **overwrite**: what the file lands on
5782 /// is replaced for its length and nothing is pushed along ([`SourceEdit::Overwrite`]). The
5783 /// lanes it lands on are chosen exactly as `place_stream_at` chooses them, and a refusal
5784 /// comes back with the engine's own words.
5785 pub fn place_stream_overwrite_at(
5786 &mut self,
5787 timeline_secs: f64,
5788 path: &Path,
5789 stream: usize,
5790 onto: Option<Lane>,
5791 ) -> crate::Result<bool> {
5792 self.place_stream_mode(timeline_secs, path, stream, onto, Some(crate::SourceEdit::Overwrite))
5793 }
5794
5795 /// The one placement behind both doors: `overwrite` of `None` is the insert-and-paste
5796 /// `place_stream_at` has always made; `Some` replaces what is there through
5797 /// [`edit_from_source_at`](Self::edit_from_source_at).
5798 fn place_stream_mode(
5799 &mut self,
5800 timeline_secs: f64,
5801 path: &Path,
5802 stream: usize,
5803 onto: Option<Lane>,
5804 overwrite: Option<crate::SourceEdit>,
5805 ) -> crate::Result<bool> {
5806 let wanted = Source::new(path, stream);
5807 // Another stream of a file this session has taken in: that is what a
5808 // library row is, and it is why nothing here has to check dimensions or
5809 // frame rate -- the file passed that at import. Its length is the one
5810 // the import noted, so a source that has never been placed is as
5811 // placeable as one that is already on a lane.
5812 let frames = self.file_frames(&wanted.path);
5813 if frames == 0 {
5814 return Err(format!("{} is not on this timeline", path.display()).into());
5815 }
5816 // A still has no sound to hold to the timeline's -- and no length
5817 // either, so it goes down at the project's still length rather than at the
5818 // ten minutes it is *allowed* to be dragged out to.
5819 let image = crate::is_image(path);
5820 if !image {
5821 let first = self.first_audio()?;
5822 self.audio_matches_cached(&wanted, &first)?;
5823 }
5824 let rate = self.file_rate(&wanted.path);
5825 let source = self.project.import(path, stream);
5826 self.note_frames(source, frames, rate);
5827 let clip = Clip {
5828 speed_keys: Vec::new(),
5829 reversed: false,
5830 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
5831 angle: Default::default(),
5832 fade_in: 0,
5833 fade_out: 0,
5834 transition_out: 0,
5835 transition_kind: Default::default(),
5836 visualizer: 0,
5837 viz_paint: 0,
5838 gain_db: 0.0,
5839 gain_keys: Vec::new(),
5840 pan: 0,
5841 transform_keys: Vec::new(),
5842 opacity_keys: Vec::new(),
5843 color_keys: Vec::new(),
5844 effects: Vec::new(),
5845 start: 0,
5846 in_frame: 0,
5847 out_frame: match image {
5848 true => place_frames(frames, self.meta.frame_rate, self.project.still_secs()),
5849 false => sound_held_frames(path, stream, frames, self.meta.frame_rate),
5850 },
5851 source,
5852 link: None,
5853 eq: None,
5854 color: None,
5855 transform: None,
5856 fit: FitPolicy::default(),
5857 speed: Speed::NORMAL,
5858 pitch: 0,
5859 };
5860 // Which lane a source may land on is decided here and only here, so a
5861 // front-end never has to make the same call twice: a file with no
5862 // picture goes on an audio lane alone, overwriting and rippling
5863 // nothing, because there is nothing on the video lane to move along
5864 // with it. A lane of the source's own kind takes it as it is dropped;
5865 // only `V1` means the grouped take, since that is the pair the paste
5866 // spans and a second video lane is a layer of its own.
5867 // ...and a still is the mirror of a song: a picture and no sound, so a
5868 // video lane and nothing else -- never the grouped take, which would
5869 // put a clip on `A1` for a source the audio worker cannot open.
5870 if image {
5871 let lane = match onto {
5872 Some(lane) if lane.kind == LaneKind::Video => lane,
5873 _ => Lane::V1,
5874 };
5875 if let Some(edit) = overwrite {
5876 self.edit_from_source_at(edit, timeline_secs, &[(lane, clip)])?;
5877 return Ok(true);
5878 }
5879 return Ok(self.place_at(lane, timeline_secs, clip));
5880 }
5881 let onto = match (sound_only(path), onto) {
5882 // No picture: an audio lane and nothing else, whichever one was
5883 // asked for -- `A1` when none was.
5884 (true, Some(lane)) if lane.kind == LaneKind::Audio => Some(lane),
5885 (true, _) => Some(Lane::A1),
5886 // A picture: the lane it was let go over, unless that is one of the
5887 // first pair. Those two are the grouped take a paste spans, and a
5888 // further lane is a layer of its own -- its picture on `V2`, its
5889 // sound on `A2` (below).
5890 (false, Some(lane)) if lane.ord > 0 => Some(lane),
5891 (false, _) => None,
5892 };
5893 // An overwrite lays the same lanes down as an insert would, replacing what is under
5894 // them: a picture and its sound as one take (a link on both halves), a sound alone
5895 // on its audio lane.
5896 if let Some(edit) = overwrite {
5897 let items: Vec<(Lane, Clip)> = match onto {
5898 Some(lane) if lane.kind == LaneKind::Audio => vec![(lane, clip)],
5899 Some(lane) if lane.kind == LaneKind::Video => vec![
5900 (lane, clip.clone()),
5901 (Lane::new(LaneKind::Audio, lane.ord), clip),
5902 ],
5903 _ => vec![(Lane::V1, clip.clone()), (Lane::A1, clip)],
5904 };
5905 self.edit_from_source_at(edit, timeline_secs, &items)?;
5906 return Ok(true);
5907 }
5908 Ok(match onto {
5909 // A picture let go over a further *video* track lands there with the
5910 // sound it came with -- `V2`'s picture, `A2`'s sound, one take and
5911 // one undo step ([`Project::place_take`]). Dropped on a further
5912 // audio lane it is the sound alone, which is what asking an audio
5913 // row for an mp4 means.
5914 Some(lane) if lane.kind == LaneKind::Video => {
5915 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
5916 let clip = self.held_to_take(clip);
5917 self.edit(Dirty::Both, |p| p.place_take(lane, at, clip))
5918 }
5919 Some(lane) => self.place_at(lane, timeline_secs, clip),
5920 // The grouped take, at the frame it was let go on -- past the last
5921 // clip included, where the bed is black and the ghost was drawn.
5922 // Not [`Self::paste_at`]: that door clamps to the end for the
5923 // clipboard, and a drop that named a place is not a paste.
5924 None => {
5925 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
5926 let clip = self.held_to_take(clip);
5927 self.edit(Dirty::Both, |p| p.paste(at, clip))
5928 }
5929 })
5930 }
5931
5932 /// Takes `path` played on `stream` out of the library -- the door a library
5933 /// row's own remove goes through, naming the row exactly as
5934 /// [`place_stream_at`](Self::place_stream_at) does. Refused in
5935 /// [`Project::remove_source`]'s words while a clip still plays from it, and
5936 /// for a row this timeline does not have.
5937 ///
5938 /// Reseeks like an edit even though nothing playable changed: the clip
5939 /// indexes into the source list have just moved, and the running workers
5940 /// were opened against the old numbering.
5941 ///
5942 /// The index that went, because everything past it moved down: a caller
5943 /// holding a source index of its own (a clipboard) has to fix it up or drop
5944 /// it, or it names a different file afterwards. The **last** row goes like
5945 /// any other and leaves a session with an empty library -- silent, empty of
5946 /// clips, and unsaveable ([`save_project`](Self::save_project)); a
5947 /// front-end showing one is showing an empty window.
5948 /// [`remove_source`](Self::remove_source) for the one source that may go
5949 /// without clearing undo: the **last** entry, when no clip and no undo or
5950 /// redo step names it ([`Project::remove_unused_source`]). Nothing playable
5951 /// changes, so there is no reseek and the timeline and its history stay as
5952 /// they were. Used to roll back a batch that imported a source and then
5953 /// failed, where clearing history would also wipe the user's undo.
5954 pub fn remove_unused_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> {
5955 let wanted = Source::new(path, stream);
5956 let idx = self
5957 .project
5958 .sources()
5959 .iter()
5960 .position(|s| *s == wanted)
5961 .ok_or_else(|| format!("{} is not on this timeline", path.display()))?;
5962 self.project.remove_unused_source(idx)?;
5963 if idx < self.counts.len() {
5964 self.counts.remove(idx);
5965 self.rates.remove(idx);
5966 }
5967 Ok(idx)
5968 }
5969
5970 pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> {
5971 let wanted = Source::new(path, stream);
5972 let idx = self
5973 .project
5974 .sources()
5975 .iter()
5976 .position(|s| *s == wanted)
5977 .ok_or_else(|| format!("{} is not on this timeline", path.display()))?;
5978 self.project.remove_source(idx)?;
5979 // The one thing that shortens the source list, so the one place
5980 // [`Self::counts`] shortens with it: left behind, the gone file's length
5981 // would become the wall a *surviving* source is trimmed against
5982 // ([`trim_room`](Self::trim_room)) and the next import would land its
5983 // count one index late.
5984 if idx < self.counts.len() {
5985 self.counts.remove(idx);
5986 self.rates.remove(idx);
5987 }
5988 let now = self.now();
5989 self.seek(now);
5990 Ok(idx)
5991 }
5992
5993 /// What the timeline's audio *is*: the chosen stream of the first source
5994 /// that could have any ([`audio_source_of`]), probed. Every other source is
5995 /// held to it.
5996 ///
5997 /// Through the session's own memo ([`probes`](Self::probes)), because this
5998 /// is asked on the render thread: the free [`first_audio_of`] is the one a
5999 /// worker with no session to reach for calls.
6000 fn first_audio(&mut self) -> crate::Result<Option<crate::AudioProbe>> {
6001 match audio_source_of(self.project.sources()) {
6002 Some(first) => {
6003 let (path, stream) = (first.path.clone(), first.audio_stream);
6004 self.probe_cached(&path, stream)
6005 }
6006 None => Ok(None),
6007 }
6008 }
6009
6010 /// One audio header, read at most once per session per `(path, stream)`.
6011 fn probe_cached(
6012 &mut self,
6013 path: &Path,
6014 stream: usize,
6015 ) -> crate::Result<Option<crate::AudioProbe>> {
6016 let key = (path.to_path_buf(), stream);
6017 if let Some(probe) = self.probes.get(&key) {
6018 return Ok(*probe);
6019 }
6020 let probe = AudioSession::probe(path, stream)?;
6021 self.probes.insert(key, probe);
6022 Ok(probe)
6023 }
6024
6025 /// [`audio_matches`] with this session's memo behind the new file's own
6026 /// header too -- the second of the two opens a place or an import pays.
6027 fn audio_matches_cached(
6028 &mut self,
6029 source: &Source,
6030 first: &Option<crate::AudioProbe>,
6031 ) -> crate::Result<()> {
6032 let probe = self.probe_cached(&source.path, source.audio_stream)?;
6033 audio_matches_probed(probe, first)
6034 }
6035
6036 /// Places `clip` on `lane` alone at the playhead, overwriting what it lands
6037 /// on and rippling nothing -- the one-lane insert a source with no picture
6038 /// makes, and the only way an audio-only file reaches the timeline. The
6039 /// placement belongs to no group (see [`Project::place`]). One undo step,
6040 /// and it reseeks like every other edit.
6041 ///
6042 /// The clip is held to `lane`'s own wall first ([`held_to_lane`](Self::held_to_lane)):
6043 /// a caller's `out_frame` past the source's length on that lane is cut back
6044 /// to it, so no door places a clip the save would refuse.
6045 pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool {
6046 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6047 let clip = self.held_to_lane(lane, clip);
6048 self.edit(Dirty::Both, |p| p.place(lane, at, clip))
6049 }
6050
6051 /// [`Project::edit_from_source`]'s door: an insert or an overwrite of the
6052 /// halves in `items` at `timeline_secs`. Each half is held to its own lane's
6053 /// wall -- and a take of a picture and its sound to the shorter of the two,
6054 /// so the halves run the same length and stay one link. One undo step; it
6055 /// reseeks like every other edit. The error says why it refused.
6056 pub fn edit_from_source_at(
6057 &mut self,
6058 kind: crate::SourceEdit,
6059 timeline_secs: f64,
6060 items: &[(Lane, Clip)],
6061 ) -> crate::Result<()> {
6062 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6063 let both = items.iter().any(|(l, _)| l.kind == LaneKind::Video)
6064 && items.iter().any(|(l, _)| l.kind == LaneKind::Audio);
6065 let items: Vec<(Lane, Clip)> = items
6066 .iter()
6067 .map(|(lane, clip)| {
6068 let held = if both {
6069 self.held_to_take(clip.clone())
6070 } else {
6071 self.held_to_lane(*lane, clip.clone())
6072 };
6073 (*lane, held)
6074 })
6075 .collect();
6076 let mut result = Ok(());
6077 let done = self.edit(Dirty::Both, |p| match p.edit_from_source(kind, at, &items) {
6078 Ok(()) => true,
6079 Err(e) => {
6080 result = Err(e);
6081 false
6082 }
6083 });
6084 match (done, result) {
6085 (_, Err(e)) => Err(e),
6086 (false, Ok(())) => Err("the edit changed nothing".into()),
6087 (true, Ok(())) => Ok(()),
6088 }
6089 }
6090
6091 /// The longest `clip` may run on `lane`: its source's length on that lane's
6092 /// kind -- the picture's on a video lane, the sound's on an audio lane
6093 /// ([`lane_walls`]), the two tables [`save_project`](Self::save_project)
6094 /// checks each lane against. `out_frame` is held to that wall; a clip the
6095 /// wall leaves no frame of is one [`Project::place`] refuses.
6096 fn held_to_lane(&self, lane: Lane, mut clip: Clip) -> Clip {
6097 let (picture, sound) =
6098 lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
6099 let table = match lane.kind {
6100 LaneKind::Audio => sound,
6101 _ => picture,
6102 };
6103 if let Some(&wall) = table.get(clip.source) {
6104 clip.out_frame = clip.out_frame.min(wall);
6105 }
6106 clip
6107 }
6108
6109 /// [`held_to_lane`](Self::held_to_lane) for a clip placed as one take: a
6110 /// picture on a video lane and its sound on an audio lane, so it is held to
6111 /// the shorter of the source's two walls. Both halves of a take share the
6112 /// one clip, so neither may run past its own lane.
6113 fn held_to_take(&self, mut clip: Clip) -> Clip {
6114 let (picture, sound) =
6115 lane_walls(self.project.sources(), &self.counts, self.meta.frame_rate);
6116 let wall = [picture.get(clip.source), sound.get(clip.source)]
6117 .into_iter()
6118 .flatten()
6119 .min();
6120 if let Some(&wall) = wall {
6121 clip.out_frame = clip.out_frame.min(wall);
6122 }
6123 clip
6124 }
6125
6126 /// Places a waveform-visualizer clip of `path`'s audio on a video lane.
6127 /// The picture is painted from the sound ([`DecodeSession::open_visualizer`]);
6128 /// this does not also put a copy on an audio lane.
6129 pub fn place_visualizer(
6130 &mut self,
6131 start: u32,
6132 path: &Path,
6133 stream: usize,
6134 in_frame: u32,
6135 out_frame: u32,
6136 onto: Option<Lane>,
6137 ) -> crate::Result<bool> {
6138 if out_frame <= in_frame {
6139 return Err("visualizer clip is empty".into());
6140 }
6141 let wanted = Source::new(path, stream);
6142 let first = self.first_audio()?;
6143 self.audio_matches_cached(&wanted, &first)?;
6144 let frames = match self.file_frames(&wanted.path) {
6145 0 => {
6146 let n = audio_frames(path, self.meta.frame_rate)?;
6147 let source = self.project.import(path, stream);
6148 self.note_frames(source, n, Rate::REAL_TIME);
6149 n
6150 }
6151 n => n,
6152 };
6153 let out_frame = out_frame.min(frames);
6154 if out_frame <= in_frame {
6155 return Err("visualizer clip is empty".into());
6156 }
6157 let source = self.project.import(path, stream);
6158 let clip = Clip {
6159 speed_keys: Vec::new(),
6160 reversed: false,
6161 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
6162 angle: Default::default(),
6163 fade_in: 0,
6164 fade_out: 0,
6165 transition_out: 0,
6166 transition_kind: Default::default(),
6167 visualizer: 1,
6168 viz_paint: 0,
6169 gain_db: 0.0,
6170 gain_keys: Vec::new(),
6171 pan: 0,
6172 transform_keys: Vec::new(),
6173 opacity_keys: Vec::new(),
6174 color_keys: Vec::new(),
6175 effects: Vec::new(),
6176 start: 0,
6177 in_frame,
6178 out_frame,
6179 source,
6180 link: None,
6181 eq: None,
6182 color: None,
6183 transform: None,
6184 fit: FitPolicy::default(),
6185 speed: Speed::NORMAL,
6186 pitch: 0,
6187 };
6188 let end = start + clip.frames();
6189 let overlaps = |lane: Lane| {
6190 self.project
6191 .lane(lane)
6192 .iter()
6193 .any(|c| c.start < end && start < c.end())
6194 };
6195 let lane = match onto {
6196 Some(lane) if lane.kind == LaneKind::Video && !overlaps(lane) => lane,
6197 _ => self
6198 .project
6199 .lanes()
6200 .into_iter()
6201 .filter(|l| l.kind == LaneKind::Video)
6202 .find(|&l| !overlaps(l))
6203 .unwrap_or_else(|| self.add_lane(LaneKind::Video)),
6204 };
6205 let clip = self.held_to_lane(lane, clip);
6206 Ok(self.edit(Dirty::Both, |p| p.place(lane, start, clip)))
6207 }
6208
6209 /// Removes `lane`'s clip at `idx` and everything under it, closing the gap
6210 /// on every lane. Unlike a split this *does* move every following frame, so
6211 /// the session reseeks to wherever the playhead now points.
6212 /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead.
6213 /// `false` for a bad index; the last remaining clip goes like any other and
6214 /// leaves the timeline empty ([`is_empty`](Self::is_empty)).
6215 ///
6216 /// The lane travels because the index is a lane's own: `V2`'s third clip is
6217 /// not `V1`'s, and a front-end that could only say "the third clip" would
6218 /// delete the wrong one the moment a second lane exists.
6219 pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool {
6220 self.edit(Dirty::Both, |p| p.delete_in(lane, idx))
6221 }
6222
6223 /// Undoes the last successful edit, and reseeks like a delete. A step on
6224 /// the project's own settings comes back the same way: the canvas, the
6225 /// rate and the switches are put back on the session here
6226 /// ([`Self::adopt_settings`]), so a `z` after a resolution pick, an
6227 /// encoder pick or a proxy switch lands exactly as one after a cut does.
6228 pub fn undo(&mut self) -> bool {
6229 self.restored_step(Project::undo)
6230 }
6231
6232 /// Redoes the last edit [`undo`](Self::undo) took back, and reseeks like
6233 /// a delete -- settings included, exactly as `undo` takes them back.
6234 pub fn redo(&mut self) -> bool {
6235 self.restored_step(Project::redo)
6236 }
6237
6238 /// Every sequence in tab order ([`Project::sequences`]).
6239 pub fn sequences(&self) -> Vec<crate::project::SequenceInfo> {
6240 self.project.sequences()
6241 }
6242
6243 /// The active sequence's id.
6244 pub fn active_sequence(&self) -> u32 {
6245 self.project.active_sequence()
6246 }
6247
6248 /// The name of sequence `id`.
6249 pub fn sequence_name(&self, id: u32) -> Option<String> {
6250 self.project.sequence_name(id).map(str::to_string)
6251 }
6252
6253 /// The sequence called `name`.
6254 pub fn sequence_named(&self, name: &str) -> Option<u32> {
6255 self.project.sequence_named(name)
6256 }
6257
6258 /// See [`Project::source_uses_parked`].
6259 pub fn source_uses_parked(&self, source: usize) -> Vec<(u32, usize)> {
6260 self.project.source_uses_parked(source)
6261 }
6262
6263 /// See [`Project::compound_pieces`].
6264 pub fn compound_pieces(&self, kind: LaneKind, clip: &Clip) -> Vec<Clip> {
6265 self.project.compound_pieces(kind, clip)
6266 }
6267
6268 /// The sequence the compound clip at `lane`/`idx` plays.
6269 pub fn compound_at(&self, lane: Lane, idx: usize) -> Option<u32> {
6270 self.project.compound_at(lane, idx)
6271 }
6272
6273 /// The angle names of sequence `id` when it is a multicam source ([`Project::angle_names`]).
6274 pub fn angle_names(&self, id: u32) -> Option<Vec<String>> {
6275 self.project.angle_names(id).map(<[String]>::to_vec)
6276 }
6277
6278 /// The multicam source the clip at `lane`/`idx` plays and its angle names, when it is a
6279 /// multicam clip.
6280 pub fn multicam_at(&self, lane: Lane, idx: usize) -> Option<(u32, Vec<String>)> {
6281 let c = self.project.lane(lane).get(idx)?;
6282 self.project.multicam_of(c).map(|(id, n)| (id, n.to_vec()))
6283 }
6284
6285 /// Whether the rate and other time-scaled settings are fixed because the
6286 /// project holds more than one sequence.
6287 pub fn rate_locked(&self) -> bool {
6288 self.project.rate_locked()
6289 }
6290
6291 /// An edit that can be refused with a reason: the picture and the sound are
6292 /// rebuilt when it was made.
6293 fn edit_try<T>(&mut self, f: impl FnOnce(&mut Project) -> crate::Result<T>) -> crate::Result<T> {
6294 let made = f(&mut self.project)?;
6295 self.invalidate(Dirty::Both);
6296 Ok(made)
6297 }
6298
6299 /// Adds an empty sequence; see [`Project::new_sequence`]. Not switched to.
6300 pub fn new_sequence(&mut self, name: Option<&str>) -> crate::Result<u32> {
6301 self.edit_try(|p| p.new_sequence(name))
6302 }
6303
6304 /// Makes an editor timeline a new sequence and switches to it ([`crate::interchange::build`]).
6305 /// Each file it names is taken in as a library file is; one that is gone is offline, as a
6306 /// missing file is in a saved project. One undo step.
6307 pub fn import_timeline(&mut self, t: &crate::interchange::Timeline) -> crate::Result<u32> {
6308 let mut reach: Vec<(PathBuf, u32)> = Vec::new();
6309 for item in t.tracks.iter().flat_map(|tr| &tr.items) {
6310 if let crate::interchange::Item::Clip(c) = item {
6311 match reach.iter_mut().find(|(p, _)| *p == c.path) {
6312 Some((_, r)) => *r = (*r).max(c.out_frame),
6313 None => reach.push((c.path.clone(), c.out_frame)),
6314 }
6315 }
6316 }
6317 for (path, furthest) in &reach {
6318 if self.source_of(path).is_some() {
6319 continue;
6320 }
6321 if crate::source_present(path) {
6322 self.import(path)?;
6323 } else {
6324 let source = self.project.import(path, 0);
6325 self.note_frames(source, *furthest, Rate::REAL_TIME);
6326 }
6327 }
6328 self.begin_batch();
6329 let made = self.edit_try(|p| crate::interchange::build(p, t));
6330 self.end_batch();
6331 made
6332 }
6333
6334 /// See [`Project::rename_sequence`].
6335 pub fn rename_sequence(&mut self, id: u32, name: &str) -> crate::Result<()> {
6336 self.edit_try(|p| p.rename_sequence(id, name))
6337 }
6338
6339 /// See [`Project::duplicate_sequence`].
6340 pub fn duplicate_sequence(&mut self, id: u32) -> crate::Result<u32> {
6341 self.edit_try(|p| p.duplicate_sequence(id))
6342 }
6343
6344 /// See [`Project::delete_sequence`]. The picture and sound follow the
6345 /// sequence that is active afterwards.
6346 pub fn delete_sequence(&mut self, id: u32) -> crate::Result<u32> {
6347 self.edit_try(|p| p.delete_sequence(id))
6348 }
6349
6350 /// Makes `id` the sequence on the timeline and in the picture and sound. Not an undo step.
6351 pub fn switch_sequence(&mut self, id: u32) -> crate::Result<()> {
6352 if id == self.project.active_sequence() {
6353 return Ok(());
6354 }
6355 self.edit_try(|p| p.switch_sequence(id))
6356 }
6357
6358 /// See [`Project::nest`].
6359 pub fn nest(&mut self, picks: &[(Lane, usize)], name: Option<&str>) -> crate::Result<crate::project::Nested> {
6360 self.edit_try(|p| p.nest(picks, name))
6361 }
6362
6363 /// See [`Project::break_apart`].
6364 pub fn break_apart(&mut self, picks: &[(Lane, usize)]) -> crate::Result<Vec<(Lane, usize)>> {
6365 self.edit_try(|p| p.break_apart(picks))
6366 }
6367
6368 /// Syncs the sources `picks` and makes a multicam clip of them at `timeline_secs` on `lane`
6369 /// ([`Project::make_multicam`]). With [`MulticamSync::Audio`] every camera is lined up with
6370 /// the first one that has sound by the loudness curve of its track
6371 /// ([`crate::multisync`]); a camera that cannot be matched (no sound, or too weak a match)
6372 /// starts with the others and the report says so. One undo step.
6373 pub fn make_multicam_at(
6374 &mut self,
6375 picks: &[usize],
6376 sync: MulticamSync,
6377 name: Option<&str>,
6378 lane: Lane,
6379 timeline_secs: f64,
6380 ) -> crate::Result<MulticamReport> {
6381 let job = self.multicam_job(picks, sync)?;
6382 let plan = job.run(&std::sync::atomic::AtomicU32::new(0), &std::sync::atomic::AtomicBool::new(false))?;
6383 self.apply_multicam(&plan, name, lane, timeline_secs)
6384 }
6385
6386 /// The part of [`make_multicam_at`](Self::make_multicam_at) that only reads the sources, as a
6387 /// value that can be run on a thread of its own ([`MulticamJob::run`]) while the window stays
6388 /// live; [`apply_multicam`](Self::apply_multicam) then makes the clip, one undo step.
6389 pub fn multicam_job(&self, picks: &[usize], sync: MulticamSync) -> crate::Result<MulticamJob> {
6390 let mut seen = Vec::new();
6391 let mut sources = Vec::new();
6392 for &p in picks {
6393 let Some(src) = self.project.sources().get(p) else {
6394 return Err(format!("source {p} is not in the project").into());
6395 };
6396 if seen.contains(&p) {
6397 return Err(format!("source {p} is picked twice: an angle is one camera").into());
6398 }
6399 seen.push(p);
6400 sources.push(MulticamJobSource {
6401 index: p,
6402 path: src.path.clone(),
6403 audio_stream: src.audio_stream,
6404 frames: self.counts.get(p).copied().unwrap_or(0).max(1),
6405 });
6406 }
6407 Ok(MulticamJob { sources, sync, fps: self.meta.frame_rate })
6408 }
6409
6410 /// The library's bins ([`Project::bins`]).
6411 pub fn bins(&self) -> &[crate::project::Bin] {
6412 self.project.bins()
6413 }
6414
6415 /// Makes a bin; see [`Project::create_bin`]. A label only: nothing is rebuilt.
6416 pub fn create_bin(&mut self, name: &str, parent: u32) -> Result<u32, String> {
6417 self.project.create_bin(name, parent)
6418 }
6419
6420 /// See [`Project::rename_bin`].
6421 pub fn rename_bin(&mut self, id: u32, name: &str) -> Result<bool, String> {
6422 self.project.rename_bin(id, name)
6423 }
6424
6425 /// See [`Project::remove_bin`].
6426 pub fn remove_bin(&mut self, id: u32) -> Result<usize, String> {
6427 self.project.remove_bin(id)
6428 }
6429
6430 /// See [`Project::move_to_bin`].
6431 pub fn move_to_bin(&mut self, srcs: &[usize], bin: u32) -> Result<usize, String> {
6432 self.project.move_to_bin(srcs, bin)
6433 }
6434
6435 /// See [`Project::set_favourite`].
6436 pub fn set_favourite(&mut self, srcs: &[usize], on: bool) -> Result<usize, String> {
6437 self.project.set_favourite(srcs, on)
6438 }
6439
6440 /// Makes the multicam clip a [`MulticamJob::run`] measured, at `timeline_secs` on `lane`. One
6441 /// undo step. Refused when the project's sources are no longer the ones that were measured.
6442 pub fn apply_multicam(&mut self, plan: &MulticamPlan, name: Option<&str>, lane: Lane, timeline_secs: f64) -> crate::Result<MulticamReport> {
6443 for a in &plan.sources {
6444 if self.project.sources().get(a.index).map(|s| &s.path) != Some(&a.path) {
6445 return Err("the media list changed while the angles were being synced".into());
6446 }
6447 }
6448 let fps = self.meta.frame_rate;
6449 let at = secs_to_frame(timeline_secs, fps);
6450 let made = self.edit_try(|p| p.make_multicam(name, &plan.angles, lane, at))?;
6451 Ok(MulticamReport { made, how: plan.how.clone(), offsets_secs: plan.offsets.clone(), starts: plan.angles.iter().map(|a| a.start).collect() })
6452 }
6453
6454 /// See [`Project::switch_angle`], at `timeline_secs`.
6455 pub fn switch_angle_at(
6456 &mut self,
6457 lane: Option<Lane>,
6458 timeline_secs: f64,
6459 video: Option<u8>,
6460 audio: Option<Option<u8>>,
6461 ) -> crate::Result<Vec<(Lane, u32)>> {
6462 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6463 self.edit_try(|p| p.switch_angle(lane, at, video, audio))
6464 }
6465
6466 /// The multicam clip under timeline `frame`, if any ([`Project::multicam_under`]).
6467 pub fn multicam_under(&self, frame: u32) -> Option<crate::project::MulticamUnder> {
6468 self.project.multicam_under(frame)
6469 }
6470
6471 /// One flattened project per angle of the multicam clip under `frame` and the timeline meta
6472 /// to compose them with ([`crate::export::compose_at`]): the angle monitor's tiles, composed
6473 /// off the window's thread.
6474 pub fn angle_views(&self, frame: u32) -> Option<(crate::project::MulticamUnder, Vec<crate::project::Project>, VideoMeta)> {
6475 self.project.angle_views(frame).map(|(u, v)| (u, v, self.meta))
6476 }
6477
6478 /// See [`Project::flatten_multicam`].
6479 pub fn flatten_multicam(&mut self, lane: Lane, idx: usize) -> crate::Result<Vec<(Lane, usize)>> {
6480 self.edit_try(|p| p.flatten_multicam(lane, idx))
6481 }
6482
6483 /// See [`Project::place_sequence`], at `timeline_secs`.
6484 pub fn place_sequence_at(&mut self, seq: u32, lane: Lane, timeline_secs: f64) -> crate::Result<()> {
6485 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
6486 self.edit_try(|p| p.place_sequence(seq, lane, at))
6487 }
6488
6489 /// The project as an edit sees it, compound clips and all, with the undo history left out
6490 /// (what a "did this batch change anything" comparison reads; [`export_snapshot`](Self::export_snapshot)
6491 /// is the expanded one a render reads).
6492 pub fn raw_snapshot(&self) -> (crate::project::Project, VideoMeta) {
6493 (self.project.raw_snapshot(), self.meta)
6494 }
6495
6496 /// [`export_snapshot`](Self::export_snapshot) of sequence `seq` (the active one for `None`).
6497 pub fn export_snapshot_of(&self, seq: Option<u32>) -> crate::Result<(crate::project::Project, VideoMeta)> {
6498 Ok((self.project.render_snapshot(seq)?, self.meta))
6499 }
6500
6501 /// Starts a batch: the edits until [`end_batch`](Self::end_batch) are one
6502 /// undo step, taken before the first of them. Only the caller that opens a
6503 /// batch sees the difference; the GUI never calls this, so its steps stay one per edit.
6504 pub fn begin_batch(&mut self) {
6505 self.project.begin_batch();
6506 }
6507
6508 /// Ends the batch [`begin_batch`](Self::begin_batch) opened.
6509 pub fn end_batch(&mut self) {
6510 self.project.end_batch();
6511 }
6512
6513 /// The mark an action takes before it edits, for [`Self::name_step`].
6514 pub fn step_mark(&mut self) -> u64 {
6515 self.project.step_mark()
6516 }
6517
6518 /// Names the step the action that took `mark` pushed, so Undo and Redo can say what
6519 /// they take back. An action that pushed nothing names nothing.
6520 pub fn name_step(&mut self, mark: u64, label: &str) {
6521 self.project.name_step(mark, label);
6522 }
6523
6524 /// What [`undo`](Self::undo) takes back, when the step was named.
6525 pub fn undo_label(&self) -> Option<&str> {
6526 self.project.undo_label()
6527 }
6528
6529 /// What [`redo`](Self::redo) walks forward to, when the step was named.
6530 pub fn redo_label(&self) -> Option<&str> {
6531 self.project.redo_label()
6532 }
6533
6534 /// The names of the steps [`undo`](Self::undo) can take back, oldest first
6535 /// ([`Project::undo_labels`]).
6536 pub fn undo_labels(&self) -> Vec<Option<String>> {
6537 self.project.undo_labels()
6538 }
6539
6540 /// The names of the steps [`redo`](Self::redo) can walk forward to, the next one last
6541 /// ([`Project::redo_labels`]).
6542 pub fn redo_labels(&self) -> Vec<Option<String>> {
6543 self.project.redo_labels()
6544 }
6545
6546 /// Moves through the undo history by `index` steps from where it stands: negative undoes that
6547 /// many, positive redoes. Each step goes through [`undo`](Self::undo) or [`redo`](Self::redo),
6548 /// so it reseeks like them. Returns how many steps were taken; it stops early at either end.
6549 pub fn jump_to(&mut self, index: isize) -> usize {
6550 let mut taken = 0;
6551 for _ in 0..index.unsigned_abs() {
6552 let moved = match index < 0 {
6553 true => self.undo(),
6554 false => self.redo(),
6555 };
6556 if !moved {
6557 break;
6558 }
6559 taken += 1;
6560 }
6561 taken
6562 }
6563
6564 /// How many steps [`undo`](Self::undo) can still take.
6565 pub fn undo_depth(&self) -> usize {
6566 self.project.history_len()
6567 }
6568
6569 /// How many steps [`redo`](Self::redo) can still take.
6570 pub fn redo_depth(&self) -> usize {
6571 self.project.redo_len()
6572 }
6573
6574 /// Which state the timeline is in ([`Project::revision`]): equal before and
6575 /// after an undo means the undo walked back to the same timeline, so a save
6576 /// taken at one can tell whether the timeline has since moved off it.
6577 pub fn revision(&self) -> u64 {
6578 self.project.revision()
6579 }
6580
6581 /// Every undo snapshot the session has pushed, including those the
6582 /// [`HISTORY_CAP`](crate::project) has since dropped. Unlike
6583 /// [`undo_depth`](Self::undo_depth) it keeps rising at the cap, so a caller
6584 /// counts a batch's steps as the difference of two reads of it.
6585 pub fn history_pushes(&self) -> u64 {
6586 self.project.history_pushes()
6587 }
6588
6589 /// Drops the redo stack with no step taken. For a caller that rolled its own
6590 /// trial edits back: the undone states they left are not a branch to redo.
6591 pub fn clear_redo(&mut self) {
6592 self.project.clear_redo();
6593 }
6594
6595 /// Moves the redo stack out ([`RedoCheckpoint`]) with no step taken, for a
6596 /// caller whose trial edits may be rolled back. The trial's own edits clear
6597 /// it and its rollback fills it, so [`restore_redo`](Self::restore_redo)
6598 /// puts back exactly what was there before the trial.
6599 pub fn take_redo(&mut self) -> RedoCheckpoint {
6600 self.project.take_redo()
6601 }
6602
6603 /// Puts back the redo stack [`take_redo`](Self::take_redo) took out.
6604 pub fn restore_redo(&mut self, cp: RedoCheckpoint) {
6605 self.project.restore_redo(cp);
6606 }
6607
6608 /// Opens (`true`) or closes (`false`) a trial batch's hold on the undo cap:
6609 /// while held, its steps evict nothing, so a rolled-back trial leaves the
6610 /// history exactly as it found it. Closing trims back to the cap.
6611 pub fn hold_history(&mut self, hold: bool) {
6612 self.project.hold_history(hold);
6613 }
6614
6615 /// Takes `path` into the **library**: it becomes a source of this session,
6616 /// with its length noted ([`file_frames`](Self::file_frames)), and nothing
6617 /// is placed on any lane. What reaches the timeline is decided afterwards,
6618 /// by dragging the row onto a lane
6619 /// ([`place_stream_at`](Self::place_stream_at)) -- importing a file is not
6620 /// a decision about where it plays.
6621 ///
6622 /// The source index, new or the one this file already had: importing twice
6623 /// registers once. *Not* an undo step -- a source entry alone changes
6624 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take
6625 /// back, and nothing reseeks.
6626 ///
6627 /// Refused unless it can join the timeline -- a decoder this machine can
6628 /// open, and audio parameters that agree or none at all; the `Err` names
6629 /// the property that disagrees,
6630 /// for a caller to show. Nothing is changed by a refusal. A *resolution* of
6631 /// its own is not a refusal: the clip is placed on the project canvas by its
6632 /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame
6633 /// rate* of its own: the file is placed for the seconds it lasts and read at
6634 /// [`Rate`] against the timeline's rate, so it plays at the speed it was
6635 /// shot at.
6636 /// [`import`](Self::import), with what the import cannot do for the file
6637 /// said back as warnings rather than left on stderr. A file whose sound is in
6638 /// a codec this build does not decode (DTS, say) imports with its picture and
6639 /// plays silent: the one warning is that sentence, naming the track. Empty
6640 /// for a file with nothing to warn about.
6641 pub fn import_with_warnings(&mut self, path: &Path) -> crate::Result<(usize, Vec<String>)> {
6642 let source = self.import(path)?;
6643 let warnings = AudioSession::unsupported(path)
6644 .ok()
6645 .flatten()
6646 .map(|why| format!("{}: {why}; its sound will be silent", path.display()))
6647 .into_iter()
6648 .collect();
6649 Ok((source, warnings))
6650 }
6651
6652 pub fn import(&mut self, path: &Path) -> crate::Result<usize> {
6653 if crate::is_audio(path) {
6654 return self.import_audio(path);
6655 }
6656 // One frame of a numbered run is the whole run: a clip of its frames, asked nothing.
6657 if let Some(run) = crate::sequence::Run::parse(path).or_else(|| crate::sequence::Run::detect(path)) {
6658 return self.import_run(&run);
6659 }
6660 if crate::is_image(path) {
6661 return self.import_image(path);
6662 }
6663 // Both halves on this thread, which is what a caller with nothing else
6664 // to do wants; a front-end splits them across a worker instead
6665 // ([`probe_import`](Self::probe_import)).
6666 // A container with sound but no picture is a song wearing a video
6667 // extension -- the same fallback `open_stream` and the project
6668 // scaffold make, so every door in agrees on what the file is.
6669 match Self::probe_import(self.import_gate(), path) {
6670 Ok(probe) => Ok(self.take_probe(path, probe)),
6671 Err(e) if crate::demux::NoVideoTrack::is_it(&e) => self.import_audio(path),
6672 Err(e) => Err(e),
6673 }
6674 }
6675
6676 /// Everything an import is *checked against*, taken off this timeline in
6677 /// one owned piece: the sources its audio must agree with and the meta its
6678 /// rate is read against. Costs two clones and touches no disk, so the
6679 /// thread holding the session can hand it to a worker and go on painting.
6680 pub fn import_gate(&self) -> ImportGate {
6681 ImportGate {
6682 sources: self.project.sources().to_vec(),
6683 timeline: self.meta,
6684 }
6685 }
6686
6687 /// The reading half of [`import`](Self::import), with no session in it: the
6688 /// container's header, the decoder this machine would open it with, and the
6689 /// audio check against the gate -- every read an import pays.
6690 ///
6691 /// This is the half that costs. Measured on a 24 GB 4K HEVC remux: 21.4 s of
6692 /// header with the pages cold, 429 ms warm, plus 1-4 s of probing the
6693 /// timeline's own first source. So a front-end runs *this* on its background
6694 /// executor and hands what comes back to
6695 /// [`import_probed`](Self::import_probed), which costs a push -- the same
6696 /// split [`parse_subtitles`](Self::parse_subtitles) makes, for the same
6697 /// reason.
6698 ///
6699 /// The container fork only: a song and a still fork before the demuxer
6700 /// ([`import`](Self::import)) and pay a header read of their own.
6701 ///
6702 /// The `Err` is the refusal [`import`](Self::import) would have given, in
6703 /// the same words -- nothing is refused twice and nothing is worded twice.
6704 pub fn probe_import(gate: ImportGate, path: &Path) -> crate::Result<ImportProbe> {
6705 let (meta, _) = Demuxer::open(path)?;
6706 let first = first_audio_of(&gate.sources)?;
6707 // Stream 0: an import brings a file in on its first audio track, and
6708 // [`place_stream_at`](Self::place_stream_at) is how any other one of
6709 // its streams reaches the timeline afterwards.
6710 // ...and the rate it will be read at comes back from the check that
6711 // accepted it, so the number the refusal was decided on is the number
6712 // the file is played by.
6713 let rate = matches_timeline(&Source::new(path, 0), &meta, &gate.timeline, &first)?;
6714 Ok(ImportProbe { gate, meta, rate })
6715 }
6716
6717 /// Registers a file already read by [`probe_import`](Self::probe_import).
6718 /// The whole of what an import costs the thread that calls it: a source
6719 /// entry and its length, no open, no seek, no decode -- which is why the
6720 /// probe is a separate door.
6721 ///
6722 /// The timeline may have moved while the worker read: a source removed or a
6723 /// file opened is a different set of things the probe was checked against,
6724 /// so the probe is re-read here ([`ImportGate`]) and a stale one is simply
6725 /// imported the slow way rather than trusted. Same answer either way, so no
6726 /// caller has to know which arm it took.
6727 pub fn import_probed(&mut self, path: &Path, probe: ImportProbe) -> crate::Result<usize> {
6728 match probe.gate.sources == self.project.sources() && probe.gate.timeline == self.meta {
6729 true => Ok(self.take_probe(path, probe)),
6730 false => self.import(path),
6731 }
6732 }
6733
6734 /// The push both import doors end at.
6735 fn take_probe(&mut self, path: &Path, probe: ImportProbe) -> usize {
6736 let source = self.project.import(path, 0);
6737 // Its length *on this timeline*: a file shot slower than the timeline
6738 // runs covers more frames than it holds, which is the whole of what
6739 // placing it at another rate means ([`Rate`]).
6740 self.note_frames(
6741 source,
6742 probe.rate.timeline_at(probe.meta.frame_count),
6743 probe.rate,
6744 );
6745 source
6746 }
6747
6748 /// The same registration for a standalone audio file: a song has no
6749 /// picture, so the length noted for it is its playing time rounded up to
6750 /// whole frames, which is the only frame count such a source has.
6751 ///
6752 /// Refused in the same words as any other import when its layout disagrees
6753 /// with the timeline's track -- one output device, one layout. A silent
6754 /// timeline has no track to disagree with, so a song joins it and *is* its
6755 /// sound ([`Self::arm_audio`]). Nothing is changed by a refusal.
6756 fn import_audio(&mut self, path: &Path) -> crate::Result<usize> {
6757 let first = self.first_audio()?;
6758 // Stream 0, and there is no other: a standalone audio file carries one
6759 // track (`AudioSession::probe_streams`), so nothing here has a stream
6760 // to pick the way `place_stream_at` does for an mp4.
6761 self.audio_matches_cached(&Source::new(path, 0), &first)?;
6762 let frames = audio_frames(path, self.meta.frame_rate)?;
6763 let source = self.project.import(path, 0);
6764 self.note_frames(source, frames, Rate::REAL_TIME);
6765 Ok(source)
6766 }
6767
6768 /// The registration of a numbered run ([`crate::sequence`]): one source named for the whole
6769 /// run, held to as many frames as the run holds, at the timeline's rate. The first frame is
6770 /// what a refusal is decided on -- a run of pictures this engine cannot compose is refused in
6771 /// the words a single still would be.
6772 fn import_run(&mut self, run: &crate::sequence::Run) -> crate::Result<usize> {
6773 let (width, height) = crate::decode::image_size(&run.frame(0))?;
6774 if !crate::is_resolution(width, height) {
6775 return Err(format!(
6776 "{} is {width}x{height}, which is not a picture this engine composes",
6777 run.frame(0).display()
6778 )
6779 .into());
6780 }
6781 let source = self.project.import(run.spelled(), 0);
6782 self.note_frames(source, run.count, Rate::REAL_TIME);
6783 Ok(source)
6784 }
6785
6786 /// The same registration for a still image, and the shortest of the three:
6787 /// a picture has nothing to agree with. No frame rate (it is one picture),
6788 /// no audio (it is silent), and a resolution of its own is what every
6789 /// import is allowed -- the clip is placed on the project canvas by its fit
6790 /// policy. The one refusal left is a file that is not a picture at all, or
6791 /// one too big to compose ([`crate::is_resolution`]), and the header alone
6792 /// answers both.
6793 ///
6794 /// The length noted is the wall a trim is held to, not a duration the file
6795 /// has: see [`image_frames`].
6796 fn import_image(&mut self, path: &Path) -> crate::Result<usize> {
6797 let (width, height) = crate::decode::image_size(path)?;
6798 if !crate::is_resolution(width, height) {
6799 return Err(format!(
6800 "{} is {width}x{height}, which is not a picture this engine composes",
6801 path.display()
6802 )
6803 .into());
6804 }
6805 let source = self.project.import(path, 0);
6806 self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME);
6807 Ok(source)
6808 }
6809
6810 /// Applies an edit and, if it took, rebuilds **what it dirtied** and nothing
6811 /// else ([`Dirty`]). A structural edit reseeks: `seek` clamps to the new
6812 /// duration and keeps playing playing, so a delete that shortens the
6813 /// timeline past the playhead lands on the last frame. A grade or a fit
6814 /// policy rebuilds the picture where it stands, with the sound running
6815 /// through it untouched -- no flush, no re-open, no hole -- and an
6816 /// equalizer the other way round.
6817 /// The project's own settings as this session has them now
6818 /// ([`ProjectSettings`]): the canvas and the rate are `meta`'s, the
6819 /// switches are this session's own fields, and the rendition and the
6820 /// limiter are the project's -- two halves of one header, which is what
6821 /// every history entry carries beside the lanes ([`Project::snapshot`]).
6822 fn settings_value(&self) -> ProjectSettings {
6823 ProjectSettings {
6824 resolution: (self.meta.width, self.meta.height),
6825 frame_rate: self.meta.frame_rate,
6826 encoder_seat: self.encoder_seat,
6827 sample_rate: self.sample_rate,
6828 proxies: self.proxies,
6829 auto_proxies: self.auto_proxies,
6830 tone: self.project.tone(),
6831 limiter: self.project.limiter(),
6832 caption_style: self.project.caption_style(),
6833 notes: self.project.notes().to_string(),
6834 still_secs: self.project.still_secs(),
6835 }
6836 }
6837
6838 /// One undo step for a change to the project's own settings, taken after
6839 /// the change: `from` is the state the door found, and what the project
6840 /// does with the two values is [`Project::push_settings_step`]'s.
6841 fn step_settings(&mut self, from: ProjectSettings) {
6842 let now = self.settings_value();
6843 self.project.push_settings_step(from, now);
6844 }
6845
6846 /// Puts the project's settings back on this session -- what a step that
6847 /// restored them leaves for the player to take up. The canvas, the rate and
6848 /// the switches live here, and the rendition and the limiter are the
6849 /// project's own, already back in place by the time this runs. Every lane
6850 /// edit's entry comes through here too and moves nothing, which is the
6851 /// common case; the *rate* is the one that needs more than the fields,
6852 /// because every source's frame count is held against it and the conform
6853 /// that scaled them is not in the entry.
6854 fn adopt_settings(&mut self) {
6855 let s = self.project.settings_now();
6856 // A project nobody has handed a canvas to: a fresh [`Project`] carries
6857 // the placeholder ([`ProjectSettings::placeholder`]) and no session is
6858 // on one -- the entries pushed before the first settings door hold lane
6859 // edits and that placeholder, and adopting it would zero the canvas.
6860 if s.frame_rate <= 0.0 {
6861 return;
6862 }
6863 let was = self.meta.frame_rate;
6864 self.meta.width = s.resolution.0;
6865 self.meta.height = s.resolution.1;
6866 self.meta.frame_rate = s.frame_rate;
6867 self.encoder_seat = s.encoder_seat;
6868 self.sample_rate = s.sample_rate;
6869 self.proxies = s.proxies;
6870 self.auto_proxies = s.auto_proxies;
6871 if s.frame_rate != was {
6872 // Within a frame, like the way out ([`Self::set_frame_rate`]'s own
6873 // caveat): the lane frame numbers came home exactly, out of the
6874 // entry, and only the per-source lengths are re-derived through the
6875 // map back.
6876 let Ok(k) = Rate::from_fps(was, s.frame_rate) else {
6877 return;
6878 };
6879 for count in &mut self.counts {
6880 *count = k.timeline_nearest(*count).max(1);
6881 }
6882 for rate in &mut self.rates {
6883 *rate = rate.then(k);
6884 }
6885 self.meta.frame_count = k.timeline_nearest(self.meta.frame_count).max(1);
6886 }
6887 }
6888
6889 /// [`Self::undo`] and [`Self::redo`] themselves: the project's own step,
6890 /// and then whatever it restored for the session to take up
6891 /// ([`Self::adopt_settings`]). Reseeks both halves, so a canvas that moved
6892 /// is repainted and a proxy switch that flipped reopens the file.
6893 fn restored_step(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool {
6894 let before = self.project.sources().to_vec();
6895 if !f(&mut self.project) {
6896 return false;
6897 }
6898 // Adopted *before* the reseek below, never after it: everything the
6899 // reseek reads is one of the settings the entry just put back --
6900 // `landing` the rate and the frame count, `picture_path` the switches,
6901 // the sound the sample rate -- so a landing computed from the values
6902 // the step *undid* lands on the wrong frame of the right project (and
6903 // reopens the file through the switch that just went back).
6904 self.adopt_settings();
6905 // A step that put a relinked file's old path back is read again here,
6906 // before the reseek opens it.
6907 self.reread_sources(&before);
6908 self.invalidate(Dirty::Both);
6909 true
6910 }
6911
6912 /// Takes `other`'s timeline over as one undo step ([`Project::adopt_as_step`]),
6913 /// the way a recovery puts an autosave's edits on the saved project it opened.
6914 /// The settings are adopted and the sources read again exactly as an undo
6915 /// does it. `false`, with nothing changed, when the project refuses it.
6916 pub fn adopt_as_step(&mut self, other: &PlaybackSession) -> bool {
6917 let before = self.project.sources().to_vec();
6918 if !self.project.adopt_as_step(&other.project) {
6919 return false;
6920 }
6921 self.adopt_settings();
6922 self.reread_sources(&before);
6923 self.invalidate(Dirty::Both);
6924 true
6925 }
6926
6927 /// Measures the sources a step moved or added, against the timeline as it
6928 /// stands. `before` is the list the step started from: a source whose path
6929 /// or stream differs from it (a relink undone or redone, an entry adopted
6930 /// from another project) has its length and rate read again, and so does
6931 /// one past the end of the counts. A file that can no longer be read keeps
6932 /// the length it had, or a whole picture's for an entry it never had.
6933 fn reread_sources(&mut self, before: &[Source]) {
6934 let now = self.project.sources().to_vec();
6935 self.counts.truncate(now.len());
6936 self.rates.truncate(now.len());
6937 for (i, source) in now.iter().enumerate() {
6938 if i < self.counts.len() && before.get(i) == Some(source) {
6939 continue;
6940 }
6941 let (count, rate) = match self.measure_source(source) {
6942 Ok(measured) => measured,
6943 Err(_) => (
6944 self.counts.get(i).copied().unwrap_or(self.meta.frame_count),
6945 self.rates.get(i).copied().unwrap_or(Rate::REAL_TIME),
6946 ),
6947 };
6948 if i < self.counts.len() {
6949 self.counts[i] = count;
6950 self.rates[i] = rate;
6951 } else {
6952 self.counts.push(count);
6953 self.rates.push(rate);
6954 }
6955 }
6956 }
6957
6958 /// The frame count and the rate `source`'s file has on this timeline: what a
6959 /// relink measures a new file by, and what an undo measures the file it puts
6960 /// back by. The file must be the kind and the material the timeline holds,
6961 /// as [`Self::relink_source`] checks it.
6962 fn measure_source(&mut self, source: &Source) -> crate::Result<(u32, Rate)> {
6963 let path = source.path.as_path();
6964 let first = self.first_audio()?;
6965 if crate::is_image(path) {
6966 crate::decode::image_size(path)?;
6967 Ok((image_frames(self.meta.frame_rate), Rate::REAL_TIME))
6968 } else if crate::is_audio(path) {
6969 audio_matches(source, &first)?;
6970 Ok((audio_frames(path, self.meta.frame_rate)?, Rate::REAL_TIME))
6971 } else {
6972 let (other, _) = Demuxer::open(path)?;
6973 let rate = matches_timeline(source, &other, &self.meta, &first)?;
6974 Ok((rate.timeline_at(other.frame_count), rate))
6975 }
6976 }
6977
6978 fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool {
6979 let done = f(&mut self.project);
6980 self.project.settle();
6981 if !done {
6982 return false;
6983 }
6984 self.invalidate(dirty);
6985 true
6986 }
6987
6988 /// Where an edit rebuilds from: the clock, except at the end of a played-out
6989 /// timeline, where the clock has kept running on wall time and the edit
6990 /// resumes at the end the viewer saw (so a paste there plays the pasted clip).
6991 fn playhead(&self) -> f64 {
6992 match self.eos {
6993 true => self.now().min(self.eos_end),
6994 false => self.now(),
6995 }
6996 }
6997
6998 /// Rebuilds the dirtied half (or both) at the playhead.
6999 fn invalidate(&mut self, dirty: Dirty) {
7000 match dirty {
7001 Dirty::Picture => {
7002 let (_, target) = self.landing(self.playhead());
7003 self.start_picture(target);
7004 }
7005 Dirty::Sound => self.reseek_audio(),
7006 Dirty::Both => {
7007 let now = self.playhead();
7008 self.seek(now);
7009 }
7010 }
7011 }
7012
7013 /// Says how big the picture is on screen, in device pixels -- what a
7014 /// front-end showing this session pushes once it knows where the picture
7015 /// actually lands. Rendering a 1080p project's visualizer for a 600 px
7016 /// preview costs nine times the pixels for nothing the eye can see; a
7017 /// window that is fullscreen gets the project's own size back by pushing
7018 /// it. `true` when the size moved enough to be worth a new picture: under
7019 /// 8 px on both axes is a resize nobody can see, and a window being
7020 /// dragged would otherwise restart the picture every tick.
7021 pub fn set_view_size(&mut self, width: u32, height: u32) -> bool {
7022 let want = self.view_want(width, height);
7023 match self.view {
7024 Some(now) if now.0.abs_diff(want.0) < 8 && now.1.abs_diff(want.1) < 8 => false,
7025 _ => {
7026 self.view = Some(want);
7027 true
7028 }
7029 }
7030 }
7031
7032 /// [`Self::set_view_size`] with no deadband: what asks for the *exact*
7033 /// size rather than one within 8 px of it. A still saved at the project's
7034 /// own pixels is a file whose dimensions are read back, so "close enough
7035 /// to be invisible" is not close enough to be right. `true` when the view
7036 /// moved, `false` when it was already there -- which is also the answer
7037 /// that lets a caller skip waiting for a frame it already has.
7038 pub fn set_view_size_exact(&mut self, width: u32, height: u32) -> bool {
7039 let want = self.view_want(width, height);
7040 match self.view {
7041 Some(now) if now == want => false,
7042 _ => {
7043 self.view = Some(want);
7044 true
7045 }
7046 }
7047 }
7048
7049 /// The size a push of `(width, height)` settles on: even on both axes
7050 /// (YUV 4:2:0 has no odd chroma) and never past the project's own.
7051 fn view_want(&self, width: u32, height: u32) -> (u32, u32) {
7052 let fit = |n: u32, cap: u32| (n & !1).clamp(2, cap.max(2));
7053 (fit(width, self.meta.width), fit(height, self.meta.height))
7054 }
7055
7056 /// The canvas a span's pictures are painted at: [`Self::set_view_size`]'s
7057 /// size once one has been pushed, the project's own otherwise.
7058 pub fn view_size(&self) -> (u32, u32) {
7059 self.view.unwrap_or((self.meta.width, self.meta.height))
7060 }
7061
7062 /// Current timeline position in seconds.
7063 pub fn now(&self) -> f64 {
7064 self.clock.now()
7065 }
7066
7067 pub fn is_playing(&self) -> bool {
7068 self.clock.is_playing()
7069 }
7070
7071 pub fn play(&mut self) {
7072 if self.clock.is_playing() {
7073 return;
7074 }
7075 // Invariant: the clock is positioned *before* audio restarts. Audio
7076 // reports are relative to the first one after that, so a seek would go
7077 // here too -- `clock.seek_to(t)` and then `set_active(true)`.
7078 self.clock.play();
7079 // Above or below 1x the sound stays off: `set_rate(1.0)` brings it back.
7080 if let Some(audio) = self.audio.as_ref().filter(|_| self.clock.rate() == 1.0) {
7081 audio.set_playing(true);
7082 }
7083 }
7084
7085 /// Sets the playback speed: 1.0 is real time, 2/4/8 forward, -1/-2 backward.
7086 ///
7087 /// Anything but 1x runs the clock on wall time at that rate and keeps the
7088 /// sound silent -- audio cannot play backward or fast without a stretch the
7089 /// engine does not do here. Going back to 1x reopens the sound at the
7090 /// current position, as a seek does. Drawing the picture backward is not
7091 /// done for the sound; the picture is, from the playhead down ([`Back`]), and
7092 /// turning the clock round restarts it there.
7093 pub fn set_rate(&mut self, rate: f64) {
7094 if !rate.is_finite() || rate == 0.0 || rate == self.clock.rate() {
7095 return;
7096 }
7097 let was_backward = self.backward();
7098 if rate != 1.0 {
7099 if let Some(audio) = &self.audio {
7100 audio.set_playing(false);
7101 }
7102 self.clock.set_rate(rate);
7103 } else {
7104 self.clock.set_rate(1.0);
7105 if self.audio.is_some() {
7106 self.reseek_audio();
7107 }
7108 }
7109 if was_backward != self.backward() {
7110 let (_, target) = self.landing(self.now());
7111 self.start_picture(target);
7112 }
7113 }
7114
7115 pub fn pause(&mut self) {
7116 if !self.clock.is_playing() {
7117 return;
7118 }
7119 if let Some(audio) = &self.audio {
7120 audio.set_playing(false);
7121 }
7122 self.clock.pause();
7123 }
7124
7125 pub fn toggle(&mut self) {
7126 if self.clock.is_playing() {
7127 self.pause()
7128 } else {
7129 self.play()
7130 }
7131 }
7132
7133 /// Stops the transport where the timeline stops: the clock is paused and put
7134 /// on the out point.
7135 ///
7136 /// Playing past the last frame is wall time counting on past the end of the
7137 /// media -- there is no picture left to pace it -- so a session left at EOF
7138 /// reports a `now()` that walks off the end of the timeline in real time,
7139 /// and a caller that reads the playhead (a cut, a paste, an insert) then
7140 /// acts at a position no clip is at. How far off depends only on how long
7141 /// the window was left open, so no clamp in a caller is worth writing.
7142 ///
7143 /// End of stream is deliberately left set: the picture is still the last
7144 /// frame and this is still the end. That is what makes it safe to call on
7145 /// the crossing into it -- the state the transport shows does not change,
7146 /// only the running clock stops.
7147 /// Carries the clock on past the last frame, on wall time from where it stands, for a
7148 /// take that runs longer than the timeline. The audio is stopped with it: nothing is
7149 /// left to play. A no-op unless the clock runs on the audio device.
7150 pub fn run_past_end(&mut self) {
7151 if self.clock.source() != ClockSource::Audio {
7152 return;
7153 }
7154 if let Some(audio) = &self.audio {
7155 audio.set_playing(false);
7156 }
7157 self.clock.switch_to_wall();
7158 }
7159
7160 pub fn halt_at_end(&mut self) {
7161 self.pause();
7162 // Played backward the end it ran into is the start, and the rate goes back
7163 // to real time there: the next press plays on from the top.
7164 if self.backward() {
7165 self.set_rate(1.0);
7166 self.clock.seek_to(0.0);
7167 // The picture restart above cleared it; this is still the end.
7168 self.eos = true;
7169 return;
7170 }
7171 self.clock.seek_to(self.timeline_duration());
7172 }
7173
7174 /// The gain this session's device is running at, read back from the device
7175 /// rather than remembered here: `None` with no audio output, or a plugin
7176 /// too old to answer -- the two cases where a remembered answer would be a
7177 /// claim nothing can check.
7178 pub fn gain(&self) -> Option<f32> {
7179 self.audio.as_ref()?.ao.lock().unwrap().gain()
7180 }
7181
7182 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
7183 /// one knob, because muting and turning it down are the same thing to the
7184 /// device, and *which* the user meant is a question only the UI can answer
7185 /// -- it keeps the level to come back to.
7186 ///
7187 /// The level is remembered for as long as this session lives
7188 /// ([`Audio::gain`]) and only so that a device which is *replaced* under
7189 /// the session -- re-armed after a death, armed by a late import -- comes
7190 /// back at the level the session was already running at. It is still not
7191 /// project state: a fresh session starts at 1.0, so a caller still pushes
7192 /// it once per session, and an export -- which renders the file rather
7193 /// than what the speakers are doing -- can never pick it up. Silent with
7194 /// no audio device, which is also the only honest answer there.
7195 ///
7196 /// Mute is not pause: the samples are still consumed and the device clock
7197 /// still runs, so the picture keeps playing against it.
7198 pub fn set_gain(&self, gain: f32) -> bool {
7199 match &self.audio {
7200 // The device is the owner and is told first: a remembered level
7201 // that says something the device does not agree with is worse
7202 // than no memory at all, because the next replacement would
7203 // restore the wrong number.
7204 Some(audio) if audio.ao.lock().unwrap().set_volume(gain) => {
7205 audio.gain.store(gain.to_bits(), Ordering::Release);
7206 true
7207 }
7208 _ => false,
7209 }
7210 }
7211
7212 /// A copy of the most recent mono samples the device was handed, and the
7213 /// rate they play at: the signal *after* every clip's equalizer, speed and
7214 /// the mix, which is what an analyser drawn behind an EQ curve has to show.
7215 /// `None` with no audio output at all, and empty until the feeder has
7216 /// written once (right after a seek, for instance).
7217 ///
7218 /// Never blocks anything that matters: the feeder holds this lock for one
7219 /// memcpy and the device's own callback lives in the plugin, on the far
7220 /// side of a ring buffer, where it cannot see this at all.
7221 pub fn audio_tap(&self) -> Option<(Vec<f32>, u32)> {
7222 let audio = self.audio.as_ref()?;
7223 let tap = audio.tap.lock().unwrap().clone();
7224 Some((tap, audio.sample_rate))
7225 }
7226
7227 /// Says that this session is being **watched in real time**, so a picture
7228 /// whose moment has passed is worth nothing and the decode worker may drop
7229 /// it where it is cheap to drop -- before the conversion (a full BGRA pass
7230 /// over 8 MB at 1080p) and before the queue.
7231 ///
7232 /// Off by default, and that is the contract every *pull* consumer relies on:
7233 /// an export, the file-level [`DecodeSession`] API and a test draining as
7234 /// fast as it can all ask for a range of frames and must be given every one
7235 /// of them, in order. Only a viewer has a moment for a picture to be past.
7236 ///
7237 /// A front-end that turns this on was dropping those very frames itself, one
7238 /// repaint later (`Player::pump` takes everything due and shows the last):
7239 /// what changes is where the work stops, and therefore how quickly a decoder
7240 /// that fell behind catches up.
7241 ///
7242 /// It does not replace [`resync_picture`](Self::resync_picture): both
7243 /// mechanisms are live and this one is the first line. It catches up without
7244 /// restarting anything, which is why the front-end's resync -- a picture
7245 /// restart, once per `RESYNC_GAP` -- now fires only where dropping was not
7246 /// enough (a decoder so far behind that even one picture in nine
7247 /// ([`crate::decode`]'s `LATE_RUN`) cannot close the gap).
7248 pub fn drop_late_pictures(&mut self, on: bool) {
7249 self.drop_late = on;
7250 }
7251
7252 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
7253 /// workers are replaced rather than steered: a fresh channel cannot hold a
7254 /// stale frame, and it works just as well after EOF, where the old workers
7255 /// have already exited.
7256 ///
7257 /// Playing stays playing and paused stays paused -- but a paused seek still
7258 /// decodes, so the caller can show the frame it landed on.
7259 pub fn seek(&mut self, secs: f64) {
7260 let (t, target) = self.landing(secs);
7261 let was_playing = self.clock.is_playing();
7262 self.stop_audio();
7263 self.start_picture(target);
7264 if self.clock.rate() != 1.0 {
7265 // Sound stays silent off-speed; `set_rate(1.0)` reopens it here.
7266 self.clock.seek_to(t);
7267 return;
7268 }
7269 let audio_running = self.start_audio(target);
7270 // Same invariant as `play`: position the clock before audio restarts.
7271 if audio_running && self.clock.source() != ClockSource::Audio {
7272 self.clock.switch_to_audio();
7273 }
7274 self.clock.seek_to(t);
7275 self.resume(was_playing);
7276 }
7277
7278 /// Abandons whatever the picture worker still owes and restarts it at the
7279 /// clock. The sound and the clock are untouched -- this is the *video*
7280 /// catching up to its master, not a seek -- so nothing the ear is following
7281 /// moves, and a caller that is behind by more than it can watch calls this
7282 /// instead of waiting for a decoder that only falls further back
7283 /// (`Player::pump`).
7284 pub fn resync_picture(&mut self) {
7285 self.invalidate(Dirty::Picture);
7286 }
7287
7288 /// Where a seek to `secs` lands: the clamped timeline position and the
7289 /// timeline frame it means. The one place the clamp lives, so every
7290 /// invalidation below lands on the same frame a seek would.
7291 fn landing(&self, secs: f64) -> (f64, u32) {
7292 let fps = self.meta.frame_rate;
7293 let total = self.project.timeline_frames();
7294 let t = secs.clamp(0.0, f64::from(total) / fps);
7295 (t, secs_to_frame(t, fps).min(total.saturating_sub(1)))
7296 }
7297
7298 /// Rebuilds the **picture** at `target` and touches nothing else: the sound
7299 /// keeps playing out of the same stream, the clock keeps running, and a
7300 /// grade dragged during playback is therefore silent.
7301 fn start_picture(&mut self, target: u32) {
7302 // Abandon first, drop second: the old worker may be parked in `send` on
7303 // the bounded channel, where only the disconnect wakes it -- and it
7304 // then finds the span already superseded. The *thread* is kept, and
7305 // with it the open file and the open decoder, so a seek onto the same
7306 // source costs a demuxer seek and a decoder flush rather than the
7307 // VA-API init (98 ms) a new worker would pay; a worker that cannot take
7308 // the new span is retired by [`retire`](Self::retire) instead, and
7309 // nothing on this thread joins either way.
7310 self.worker.abandon();
7311 // The span runs from `target` to the end of whatever it landed in -- a
7312 // clip, or a gap, which starts a black-frame worker instead. `None` is
7313 // the emptied timeline, black too, and `start_span` says so.
7314 let span = match self.backward() {
7315 true => back_span_at(&self.project.render_view(), target),
7316 false => crate::export::stack_span_at(&self.project.render_view(), target),
7317 };
7318 self.start_span(span);
7319 self.eos = false;
7320 }
7321
7322 /// Silences the device and supersedes whatever is feeding it: the first half
7323 /// of every audio restart, and the only thing that ever discards queued
7324 /// sound.
7325 fn stop_audio(&mut self) {
7326 self.mix = None;
7327 if let Some(audio) = &self.audio {
7328 let ao = audio.ao.lock().unwrap();
7329 ao.set_active(false);
7330 // Bumped and flushed while holding the device lock, because the
7331 // feeder re-checks the epoch inside that same lock: whatever it is
7332 // carrying can no longer reach the ring after this point.
7333 audio.epoch.fetch_add(1, Ordering::Release);
7334 // Nothing of the new stream has been played yet, by definition.
7335 audio.content_at.store(-1, Ordering::Release);
7336 ao.flush();
7337 // The flushed samples are not being played any more, so nothing may
7338 // still be drawn from them.
7339 audio.tap.lock().unwrap().clear();
7340 }
7341 }
7342
7343 /// Puts the device back where it was: playing if it was playing, and with
7344 /// the clock held until the new stream is really audible (see
7345 /// [`Audio::content_at`]).
7346 ///
7347 /// Only the *intent* is set here: the open runs on the feeder
7348 /// ([`start_audio`](Self::start_audio)), so the device is started by that
7349 /// stream's first real sample instead ([`Audio::wants_active`]). A device
7350 /// made active over an empty ring plays its own silence and counts one
7351 /// underrun per starved quantum -- a scripted cold play-seek-scrub session
7352 /// used to go from 5 to 1721 of them -- while the ear hears the same silence
7353 /// either way, so nothing is gained for the count that is lost.
7354 fn resume(&mut self, was_playing: bool) {
7355 self.priming = true;
7356 if let Some(audio) = &self.audio {
7357 audio.set_playing(was_playing);
7358 }
7359 }
7360
7361 /// Rebuilds the **sound** from `target` -- the second half of a restart --
7362 /// and says whether a feeder took the job. Not whether it will find
7363 /// anything to play: the stream is opened on that feeder
7364 /// ([`Audio::spawn_feeder_deferred`]), so a silent timeline is heard of
7365 /// there, not here. Nothing on this thread reads the file.
7366 ///
7367 /// The clock is unaffected by the wait, which is the reason it may be a
7368 /// long one: it holds where the seek put it until the *first real sample*
7369 /// is queued ([`Audio::content_at`], [`tick`](Self::tick)), whether that is
7370 /// ten milliseconds later or ten seconds.
7371 ///
7372 /// `true` is therefore *optimistic*, and the callers' `switch_to_audio` with
7373 /// it: a timeline that turns out to have nothing to play ends its feeder at
7374 /// once, which sets `fed_all` and hands the clock back to wall time at the
7375 /// next tick, from where it stood ([`PlaybackClock::switch_to_wall`] is
7376 /// continuous, so nothing jumps).
7377 fn start_audio(&mut self, target: u32) -> bool {
7378 let fps = self.meta.frame_rate;
7379 let mut audio_running = false;
7380 let mut live = None;
7381 // A dead output gets an attempt here without waiting out the cooldown: a
7382 // seek is a person asking, and this is the one moment the sound can come
7383 // back into step with the picture, because the feeder opened below starts
7384 // at the target. If it does not come back the flag stands and the guard
7385 // under it leaves the clock on wall time.
7386 self.rearm_audio(Duration::ZERO);
7387 if let Some(audio) = &self.audio
7388 && !audio.died.load(Ordering::Acquire)
7389 {
7390 // The device position keeps counting across a flush, so re-basing
7391 // `fed` on it is what keeps `played_out` exact for the new stream.
7392 let played = audio.ao.lock().unwrap().position().unwrap_or(0).max(0) as u64;
7393 audio.fed.store(played * audio.channels, Ordering::Relaxed);
7394 audio.fed_all.store(false, Ordering::Release);
7395 // One worker for the whole rest of the timeline, so the joins
7396 // between clips are gapless: the video reopens at a boundary, the
7397 // ear never hears it -- and a join between two *files* is just
7398 // another segment, because every segment names its own source.
7399 // One play list per audio lane, summed by the mixer: what the ear
7400 // hears is every lane at once, and a lane's own gaps are silence in
7401 // it rather than a hole in the count the master clock keeps.
7402 let segs = self.project.render_view().audio_segments_from(target, fps);
7403 // The equalizers beside them, one per segment: the worker filters a
7404 // segment's own samples before the mix, so a clip's curve reaches
7405 // that clip and stops. Rebuilt on every seek, which is what makes an
7406 // EQ edit audible at once -- `edit` reseeks, so the drag that
7407 // changed a band restarts the workers with the new curve already in
7408 // them, and no live channel has to reach into a running one.
7409 let eqs = self.project.render_view().audio_eqs_from(target, fps);
7410 // ...and the rates, the same way again: a speeded segment is
7411 // resampled inside its own worker, before the mix, so what the ear
7412 // hears is what the timeline shows. Empty for a project nobody has
7413 // speeded, which is the path that decodes the same samples it always
7414 // did.
7415 let speeds = self.project.render_view().audio_speeds_from(target, fps);
7416 // ...and the fades, the same way again: a clip's own envelope runs
7417 // inside its worker, after the rate and the equalizer, so a fade
7418 // edit is audible at once exactly as an EQ edit is.
7419 let fades = self.project.render_view().audio_fades_from(target, fps);
7420 // Each source on the stream it was placed with: what plays is what
7421 // the library row said, and what an export copies (`export::run`).
7422 let sources = self.project.audio_sources();
7423 // ...and the mix settings over the lot: each lane's own volume on
7424 // its way into the sum and the master limiter over the sum. These
7425 // two are handed over *live* as well as at the open: they sit at
7426 // the sum, where nothing is decoded, so a fader moved later is a
7427 // number the running mixer picks up rather than a stream rebuilt
7428 // under the ear ([`crate::audio::MixControls`]).
7429 let gains = self.mix_gains();
7430 let ducks = self.project.render_view().audio_ducks();
7431 // ...and the voice processors, which are not live: an edit to one
7432 // rebuilds the sound like an equalizer edit does.
7433 let voices = self.project.render_view().audio_voices();
7434 let limiter = self.project.limiter();
7435 let controls = crate::audio::MixControls::new(gains.clone(), ducks.clone(), limiter);
7436 // Only a mixed timeline has a mixer to talk to; the single-lane
7437 // flat path is the bit-exact one and has none. Decided here from
7438 // the very lists the open is about to be handed
7439 // ([`AudioSession::is_mixed`]) rather than read off the handle
7440 // afterwards, because there *is* no afterwards on this thread any
7441 // more -- the open runs on the feeder.
7442 let mixed = crate::audio::AudioSession::is_mixed(segs.len(), &gains, limiter, &voices);
7443 let worker_controls = Arc::clone(&controls);
7444 // ...and the rate the mix runs at, if the project picked one: the
7445 // same override [`crate::edith::save`] writes and [`Self::open_project`]
7446 // reads back.
7447 let sample_rate = self.sample_rate;
7448 // ...and the open itself -- every track a segment names, its packet
7449 // table, its priming -- happens there too. That is the whole point:
7450 // one `pread` on a cold 25 GB film is seconds, and this is called
7451 // from a ruler drag ([`Audio::spawn_feeder_deferred`]).
7452 audio_running = audio.spawn_feeder_deferred(move || {
7453 match AudioSession::open_mixed_streams_live_fade(
7454 &sources,
7455 &segs,
7456 &eqs,
7457 &speeds,
7458 &fades,
7459 fps,
7460 &gains,
7461 &ducks,
7462 &voices,
7463 limiter,
7464 Some(&worker_controls),
7465 sample_rate,
7466 ) {
7467 Ok(Some((_, rx))) => Some(rx),
7468 // A silent timeline, and a source that will not open: both
7469 // feed nothing, which the feeder itself reports by ending.
7470 // The mix goes with them -- no mixer was started, so a fader
7471 // moved later must rebuild the sound rather than hand its
7472 // number to a thread that does not exist
7473 // ([`crate::audio::MixControls::detach`]).
7474 Ok(None) => {
7475 worker_controls.detach();
7476 None
7477 }
7478 Err(e) => {
7479 worker_controls.detach();
7480 // A read this session abandoned on purpose -- the seek
7481 // after it, or the session going away -- is not a file
7482 // that would not open, and says nothing.
7483 if !crate::demux::is_cancelled(&e) && std::env::var_os("EDITH_DEBUG").is_some() {
7484 eprintln!("timeline audio open failed: {e}");
7485 }
7486 None
7487 }
7488 }
7489 });
7490 live = (audio_running && mixed).then_some(controls);
7491 if !audio_running {
7492 // Nothing will ever be fed again; let `tick` fall to wall time
7493 // instead of waiting on a device that has no more work coming.
7494 audio.fed_all.store(true, Ordering::Release);
7495 }
7496 }
7497 self.mix = live;
7498 audio_running
7499 }
7500
7501 /// Rebuilds the sound alone, from where the playhead is: what a change that
7502 /// no picture can show goes through. The video worker is left decoding, so
7503 /// the picture does not blink -- and the clock, held still by
7504 /// [`resume`](Self::resume) until the new stream is audible, puts the sound
7505 /// back exactly where the picture already is.
7506 ///
7507 /// End of stream is deliberately left alone -- no picture worker is started
7508 /// here, so a timeline that was played out still is; see
7509 /// [`is_eos`](Self::is_eos).
7510 fn reseek_audio(&mut self) {
7511 if self.clock.rate() != 1.0 {
7512 // Off-speed the sound is silent and `set_rate(1.0)` rebuilds it, so a
7513 // change to it now has nothing to rebuild.
7514 return;
7515 }
7516 let (t, target) = self.landing(self.now());
7517 let was_playing = self.clock.is_playing();
7518 self.stop_audio();
7519 let audio_running = self.start_audio(target);
7520 if audio_running && self.clock.source() != ClockSource::Audio {
7521 self.clock.switch_to_audio();
7522 }
7523 self.clock.seek_to(t);
7524 self.resume(was_playing);
7525 }
7526
7527 /// Renders the edited timeline to `out` on a worker thread. The session is
7528 /// untouched -- the export decodes the source file for itself -- but a
7529 /// caller should still [`pause`](PlaybackSession::pause) first, because
7530 /// playback and export otherwise fight over the same decoder hardware.
7531 ///
7532 /// Later edits do not reach a running export: it works from a snapshot of
7533 /// the edit list taken here.
7534 ///
7535 /// corner-cut: this defaults the settings; the app still calls it that way,
7536 /// and the export options card replaces the call with
7537 /// [`export_to_with`](PlaybackSession::export_to_with).
7538 pub fn export_to(&self, out: &Path) -> crate::ExportHandle {
7539 self.export_to_with(out, &crate::export::ExportSettings::default())
7540 }
7541
7542 /// [`export_to`](PlaybackSession::export_to) with the output settings spelled
7543 /// out rather than defaulted.
7544 pub fn export_to_with(
7545 &self,
7546 out: &Path,
7547 settings: &crate::export::ExportSettings,
7548 ) -> crate::ExportHandle {
7549 // The chapter marks, measured from the export's own start (the range's
7550 // `from`, the same clock `chapter_list_ns` uses). A caller's list wins.
7551 let mut settings = settings.clone();
7552 if settings.chapters.is_empty() {
7553 settings.chapters = self.chapter_list_ns(settings.range);
7554 }
7555 let mut snapshot = self.project.export_snapshot();
7556 // A range that never reads a missing file is written without opening it.
7557 if let Some(range) = settings.range {
7558 snapshot.drop_offline_outside(range, crate::source_present);
7559 }
7560 crate::export::start(snapshot, self.meta, out, &settings, self.sample_rate)
7561 }
7562
7563 /// Moves the clock forward; the caller runs this once per rendered frame.
7564 /// Costs an atomic load, and once per session a mode switch.
7565 pub fn tick(&mut self) {
7566 // Before every early return below: where the playhead stands is what the
7567 // decode worker drops its stale pictures against, and a front-end that
7568 // repaints without draining (a slow frame, a busy render thread) must
7569 // still be moving it -- otherwise the queue fills with pictures whose
7570 // moment passed while nobody was taking them.
7571 self.publish_playhead();
7572 // Before the clock-source guard below, and not after it: a dead output is
7573 // what *puts* the clock on wall time, so this branch has to keep running
7574 // while it is there -- the one attempt that can bring the sound back is
7575 // in it.
7576 if self
7577 .audio
7578 .as_ref()
7579 .is_some_and(|audio| audio.died.load(Ordering::Acquire))
7580 {
7581 // Output died mid-stream: its position will never reach `fed`, so the
7582 // EOF comparison below is unreachable. Wall time takes over from
7583 // wherever the clock last stood, and the session says so rather than
7584 // going silent for good without a word: a front-end already has a
7585 // line for a silent session ([`Self::audio_disabled_reason`]).
7586 if self.audio_disabled.is_none() {
7587 self.audio_disabled = Some(AUDIO_LOST.to_string());
7588 }
7589 self.clock.switch_to_wall();
7590 // ...and the output is offered another open, once a second: a
7591 // restarting daemon takes a moment, and this runs once a frame. A
7592 // re-arm that takes is what clears the notice, and the next seek
7593 // feeds it.
7594 self.rearm_audio(AUDIO_REARM_AFTER);
7595 return;
7596 }
7597 let Some(audio) = &self.audio else {
7598 return; // wall time from the start, nothing to poll
7599 };
7600 if self.clock.source() != ClockSource::Audio {
7601 return;
7602 }
7603 // `None` until the device's first callback: the clock holds at its
7604 // anchor rather than guessing, which is why playback starts on time
7605 // instead of a quantum early.
7606 let Some(position) = audio.ao.lock().unwrap().position() else {
7607 return;
7608 };
7609 if audio.played_out(position) {
7610 // Audio EOF. Wall time carries the same timeline on from here, with
7611 // no jump, and this branch cannot be reached again.
7612 //
7613 // The device is stopped with it: nothing will ever be queued for
7614 // this stream again, so every quantum it would go on playing is
7615 // silence counted as a decoder that fell behind -- the tail of a
7616 // stream, where [`crate::ao`]'s own `primed` covers the head of
7617 // one. A seek from here starts it again like any other
7618 // ([`resume`](Self::resume)), which is why the stamp goes with it:
7619 // there is no sample of *this* stream left to start on.
7620 audio.set_playing(false);
7621 audio.content_at.store(-1, Ordering::Release);
7622 self.clock.switch_to_wall();
7623 return;
7624 }
7625 if self.priming {
7626 // A stream that has been started and has not been heard yet: the
7627 // device is playing the silence of its own restart, and none of it
7628 // is timeline time ([`Audio::content_at`]). The clock holds where
7629 // the seek left it -- so the picture holds too, on the frame it
7630 // landed on, rather than sliding ahead of a sound that has not
7631 // started.
7632 let started = audio.content_at.load(Ordering::Acquire);
7633 if started < 0 {
7634 return;
7635 }
7636 // ...and then the *first sample of the stream* becomes the
7637 // reference, not whatever position this poll happened to catch: the
7638 // clock's own anchor is its first report ([`PlaybackClock`]), and
7639 // anchoring it here is what makes a mid-play edit cost no offset.
7640 //
7641 // corner-cut: `started` is the position when the sample was queued,
7642 // and it is heard at the next callback -- up to one quantum (5-21
7643 // ms) later, so that much of the restart is still counted. Upgrade
7644 // path is the position at the first *pop* of real audio, which only
7645 // the plugin's RT thread can see.
7646 self.clock
7647 .set_audio_position(started as u64, audio.sample_rate);
7648 self.priming = false;
7649 }
7650 self.clock
7651 .set_audio_position(position as u64, audio.sample_rate);
7652 }
7653}
7654
7655impl Drop for PlaybackSession {
7656 /// The video workers -- the running one and every cancelled one still in
7657 /// [`retired`](PlaybackSession::retired) -- cancel and join themselves when
7658 /// those fields drop right after this, the running one behind its receiver
7659 /// so a `send` cannot hold the join. *That* is what a session must not exit
7660 /// without: no decode worker outlives it, so none can be inside libva when
7661 /// Mesa's `atexit` handlers free the state under it.
7662 ///
7663 /// This is the audio half: bumping the epoch retires the feeder at its next write,
7664 /// which drops the decode receiver with it. Neither is waited for -- no
7665 /// driver state is torn down on the audio side.
7666 fn drop(&mut self) {
7667 if let Some(audio) = &self.audio {
7668 audio.epoch.fetch_add(1, Ordering::Release);
7669 }
7670 }
7671}
7672
7673/// Whether `path`, already demuxed to `meta`, may join a timeline whose
7674/// parameters are `timeline` and whose audio probes as `first`: a decoder this
7675/// machine can open, audio parameters that agree (or no audio at all), and a
7676/// frame rate that can be named
7677/// against the timeline's. The [`Rate`] it will be read at comes back with the
7678/// answer, so the number the check was decided on is the number it plays by.
7679///
7680/// *Not* the same size any more. A project has its own resolution
7681/// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its
7682/// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
7683/// letterboxed clip rather than a refusal, and so is a frame rate of its own:
7684/// the timeline keeps its own rate and the file is read at [`Rate`] against it
7685/// ([`PlaybackSession::import`] notes how long it is *here*). Nor the same
7686/// codec: every clip opens its own decoder, so a mixed-codec timeline is a
7687/// decoder each rather than a refusal.
7688///
7689/// The `Err` names the property that disagrees, and those strings are what a
7690/// front-end shows verbatim; [`PlaybackSession::import`] and
7691/// [`PlaybackSession::open_project`] share them so a file refused at import is
7692/// refused in the same words at load.
7693fn matches_timeline(
7694 source: &Source,
7695 meta: &VideoMeta,
7696 timeline: &VideoMeta,
7697 first: &Option<crate::AudioProbe>,
7698) -> crate::Result<Rate> {
7699 // The codec is *not* held to the timeline's -- every clip opens its own
7700 // decoder, so an H.264 take and an HEVC one play on one timeline. What the
7701 // codec gate was really protecting against stays, in the one place that
7702 // can actually answer it: on a machine without the VA-API plugin an HEVC
7703 // or VP8 clip would be black frames with the refusal on stderr alone,
7704 // so the file is asked for a decoder *here*, at the door, where the `Err`
7705 // is still something a front-end can show. A zero-length range probes and
7706 // starts no
7707 // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`]
7708 // only enters VA-API off that path.
7709 DecodeSession::open_worker(
7710 &source.path,
7711 0,
7712 0,
7713 ColorParams::default(),
7714 TransformParams::default(),
7715 Composer::passthrough(),
7716 // A zero-length range decodes nothing, so no table is built and the
7717 // rendition cannot matter here.
7718 crate::tonemap::Preset::default(),
7719 )?;
7720 // The frame rate is *not* a refusal any more: a file shot at another rate is
7721 // placed for the seconds it lasts and read through [`Rate`] at the
7722 // decoder's door, so it plays at the speed it was shot at on a timeline
7723 // that counts frames faster or slower.
7724 //
7725 // A rate that cannot be *named* still is, and this is the one place it is
7726 // caught: `Rate::from_fps` builds itself out of the muxer's own timescales,
7727 // and a file whose rate has none of those (a container that says nothing and
7728 // holds one block, so the demuxer measures 0 fps) would otherwise be read
7729 // 1:1 in silence -- the old rate gate refused those too, by arithmetic
7730 // accident. The `Err` is `mux::frame_timing`'s own words.
7731 let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?;
7732 audio_matches(source, first)?;
7733 Ok(rate)
7734}
7735
7736/// Whether a candidate's audio may join a timeline whose first source probes as
7737/// `first`: same layout -- or no audio of its own at all, which is silence over
7738/// the clip's span and agrees with everything. One output device and one
7739/// exported track is all there is, so one width; the *rate* is conformed rather
7740/// than matched ([`crate::audio::Resample`]), which is why it is not asked
7741/// about here.
7742///
7743/// The audio half of [`matches_timeline`], which a stream placed on its own
7744/// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
7745/// comes with is already on the timeline.
7746///
7747/// The format itself is deliberately *not* part of this: an mp3 that agrees on
7748/// layout plays alongside a timeline of mp4s perfectly well. What it
7749/// cannot do is be copied into an export, which is a refusal of its own, at
7750/// export time (`AudioSession::copy_multi_streams`).
7751/// What a timeline's audio is held to: the probe of the first source that could
7752/// have any track.
7753///
7754/// The probe of the first source that really **has a track**, walking forward
7755/// past a still (no track by definition) and past a source whose file carries
7756/// none (a screen recording with no sound). A silent leading source must not
7757/// pin the timeline's layout: pinned to it, a later file with sound could never
7758/// be admitted, and the layout a *following* file is held to would be the
7759/// silent source's `None`. This is the same walk
7760/// [`PlaybackSession::open_project`] makes when it opens the device -- the two
7761/// have to agree, so probing and opening can never name different sources.
7762///
7763/// `Ok(None)` for a timeline with no track anywhere: nothing but stills, with
7764/// no file at all, or every non-still source silent. That is a silent timeline,
7765/// and a file with sound is admitted onto it -- it *becomes* the timeline's
7766/// sound ([`PlaybackSession::arm_audio`] opens the device for it), exactly the
7767/// c581d41 rule ("a later source with real audio must be heard") at the add
7768/// door.
7769fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
7770 for source in sources
7771 .iter()
7772 .filter(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
7773 {
7774 if let Some(probe) = AudioSession::probe(&source.path, source.audio_stream)? {
7775 return Ok(Some(probe));
7776 }
7777 }
7778 Ok(None)
7779}
7780
7781/// Whether a file is sound and no picture, which decides the lane it goes on.
7782/// The extension answers for a song; an mp4 or Matroska file is asked of its
7783/// header the way [`PlaybackSession::import`] asks it, so an audio-only mp4
7784/// lands on an audio lane exactly as it imports and reopens.
7785fn sound_only(path: &Path) -> bool {
7786 if crate::is_audio(path) {
7787 return true;
7788 }
7789 if crate::is_image(path) {
7790 return false;
7791 }
7792 matches!(Demuxer::open(path), Err(ref e) if NoVideoTrack::is_it(e))
7793}
7794
7795/// *Which* source that is: the first one that is not a still. The single answer
7796/// to "what does this timeline's sound come from", so that probing it
7797/// ([`first_audio_of`]) and opening the device on it
7798/// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only
7799/// the scaffolding file until a save renumbers it or a library removal takes it
7800/// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the
7801/// device is a timeline that plays silent although every clip on it has sound.
7802///
7803/// `None` for a library of nothing but stills, and for one with no file at all:
7804/// both are silent timelines.
7805fn audio_source_of(sources: &[Source]) -> Option<&Source> {
7806 sources
7807 .iter()
7808 .find(|s| !crate::is_image(&s.path) && crate::source_present(&s.path))
7809}
7810
7811fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
7812 let probe = AudioSession::probe(&source.path, source.audio_stream)?;
7813 audio_matches_probed(probe, first)
7814}
7815
7816/// The verdict alone, once the file's own header is in hand: the half a session
7817/// with a memo behind it ([`PlaybackSession::audio_matches_cached`]) does not
7818/// have to open the file for.
7819fn audio_matches_probed(
7820 probe: Option<crate::AudioProbe>,
7821 first: &Option<crate::AudioProbe>,
7822) -> crate::Result<()> {
7823 // The layout, which the audio worker holds every source to anyway -- and not
7824 // the rate any more: a file written at another one is resampled to the
7825 // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as
7826 // a file shot at another frame rate is read through [`Rate`]. Both silent is
7827 // a match.
7828 if probe.map(|p| p.channels) == first.map(|p| p.channels) {
7829 return Ok(());
7830 }
7831 // A mono file joins a wider timeline: [`crate::audio::widen`] duplicates
7832 // its one channel into every channel the timeline carries, the inverse of
7833 // the [`crate::audio::downmix`] a wider file already folds through. A
7834 // wider file onto a mono timeline -- beyond a stereo pair -- stays refused
7835 // below; the stereo pair is narrowed by [`crate::audio::widen`] (below).
7836 if let (Some(p), Some(b)) = (probe, first)
7837 && p.channels == 1
7838 && b.channels > 1
7839 {
7840 return Ok(());
7841 }
7842 // ...and a stereo file joins a mono timeline: [`crate::audio::widen`]
7843 // averages its pair into the one channel the timeline carries. Import and
7844 // open both come through here, so a project this accepts always reopens.
7845 if let (Some(p), Some(b)) = (probe, first)
7846 && p.channels == 2
7847 && b.channels == 1
7848 {
7849 return Ok(());
7850 }
7851 // ...and a *silent* file joins whatever the timeline is: it contributes
7852 // silence over its span, which is the very thing both audio paths already
7853 // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays
7854 // it, `AudioSession::copy_multi_streams` writes it). There is no rate and
7855 // no layout to disagree about, so there is nothing left to refuse.
7856 let Some(probe) = probe else {
7857 return Ok(());
7858 };
7859 // The timeline has no track anywhere (nothing but stills, or every
7860 // non-image source silent): there is no layout to disagree with, and the
7861 // arriving file with sound *becomes* the timeline's sound --
7862 // [`PlaybackSession::arm_audio`] opens the device for it, exactly the walk
7863 // [`PlaybackSession::open_project`] makes. Refusing here ("the file has
7864 // audio, the timeline is silent") pinned the timeline to its silent first
7865 // source for good: remove that file and add another, and the second file's
7866 // sound could never be heard.
7867 let Some(b) = first else {
7868 return Ok(());
7869 };
7870 Err(format!(
7871 "audio {} ch does not match the timeline's {} ch",
7872 probe.channels, b.channels
7873 )
7874 .into())
7875}
7876
7877/// How many timeline frames a still image is *held to*: [`IMAGE_MAX_SECS`] of
7878/// them, since an image has no length of its own. The number a source's own
7879/// entry in [`PlaybackSession::counts`] gets, so a trim may drag an image out
7880/// to ten minutes and no further -- and so a saved project reloads, because
7881/// [`PlaybackSession::open_project`] recomputes exactly this and refuses a clip
7882/// that ends past it.
7883fn image_frames(fps: f64) -> u32 {
7884 ((IMAGE_MAX_SECS * fps)
7885 .ceil()
7886 .clamp(1.0, f64::from(u32::MAX))) as u32
7887}
7888
7889/// How long a still is placed for: `secs` (the project's still length), never past the length
7890/// it is held to and never zero (a clip is never empty).
7891fn place_frames(count: u32, fps: f64, secs: f64) -> u32 {
7892 ((secs * fps)
7893 .ceil()
7894 .clamp(1.0, f64::from(count.max(1)))) as u32
7895}
7896
7897/// The project one document of a file describes, on the canvas and rate `meta` gives it.
7898fn project_of(doc: crate::edith::Document, meta: &VideoMeta) -> crate::Result<Project> {
7899 let subtitles = crate::subtitle::open_all(&doc.subtitles);
7900 Ok(
7901Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color, doc.transform)?
7902 .with_mix(&doc.gains, doc.limiter)
7903 .with_ducks(&doc.ducks)
7904 .with_voices(&doc.voices)
7905 .with_lane_names(&doc.names)
7906 .with_bins(doc.bins)
7907 .with_lane_flags(&doc.flags)
7908 .with_tone(doc.tone)
7909 .with_notes(doc.notes)
7910 .with_still_secs(doc.still_secs)
7911 // The palette before what is placed on it: a caption names a row of
7912 // it, and [`Project::with_subs`] refuses one naming a row that is
7913 // not there.
7914 .with_subtitles(subtitles)
7915 .with_sub_langs(&doc.sub_langs)
7916 // The cue overrides, over the words the files gave: a retyped
7917 // cue comes back as it was typed.
7918 .with_cue_edits(&doc.cue_edits)
7919 // ...and the cues added to a track, after the file's own, each at
7920 // its start (see [`crate::edith`]'s `cueadd` lines).
7921 .with_cue_adds(&doc.cue_adds)
7922 // The title cards and text overlays, in the order the file has them.
7923 .with_titles(doc.titles)
7924 // The chapter markers, in frame order (see [`crate::edith`]'s `chapter` lines).
7925 .with_chapters(doc.chapters)
7926 // The comment markers, in frame order (`marker` lines).
7927 .with_markers(doc.markers)
7928 .with_cue_words(&doc.cue_words)
7929 .with_caption_style(doc.caption_style)
7930 .with_subs(doc.subs)?
7931 // The header a load puts back: the canvas and rate above, which a
7932 // save's own `resolution`/`fps` lines may have moved off the
7933 // scaffold's, and the switches the literal below carries -- handed
7934 // in here because they are the project's own and a door that moved
7935 // one after this would snapshot whatever copy it holds, which until
7936 // this line is the placeholder's. No undo step for
7937 // [`Project::with_mix`]'s reason: a project that arrived one `z`
7938 // from a state it was never in is a project whose first undo is a
7939 // surprise.
7940 .with_canvas(meta.width, meta.height, meta.frame_rate)
7941 .with_switches(doc.proxy, doc.auto_proxy, doc.encoder, doc.sample_rate)
7942 )
7943}
7944
7945/// The two tables a trim measures by, `(picture, sound)`: [`wall_table`] for a
7946/// video lane and for an audio one, so a linked take's members each meet their
7947/// own lane's length. Borrows `counts` only, so the caller may hold them across
7948/// a `&mut` to the project.
7949fn lane_walls<'a>(
7950 sources: &[Source],
7951 counts: &'a [u32],
7952 fps: f64,
7953) -> (Cow<'a, [u32]>, Cow<'a, [u32]>) {
7954 (
7955 wall_table(sources, counts, fps, Lane::V1),
7956 wall_table(sources, counts, fps, Lane::A1),
7957 )
7958}
7959
7960/// The length each source's clips are walled by on `lane`, in timeline frames.
7961/// A clip on an audio lane takes the sound, so a video source's own audio stream
7962/// sets its length there (the picture's frame count is the length everywhere
7963/// else, and `counts` is that table). Stills and audio files already are their
7964/// sound's length in `counts`, and a source with no audio stream keeps its
7965/// `counts` entry. Mirrors the length `place` gives an audio-lane placement in
7966/// the MCP (`source_frames`).
7967fn wall_table<'a>(sources: &[Source], counts: &'a [u32], fps: f64, lane: Lane) -> Cow<'a, [u32]> {
7968 if lane.kind != LaneKind::Audio {
7969 return Cow::Borrowed(counts);
7970 }
7971 Cow::Owned(
7972 sources
7973 .iter()
7974 .zip(counts)
7975 .map(|(source, &frames)| {
7976 if crate::is_image(&source.path) || crate::is_audio(&source.path) {
7977 return frames;
7978 }
7979 match audio_stream_secs(&source.path, source.audio_stream) {
7980 Some(secs) if secs > 0.0 => (secs * fps).ceil().clamp(1.0, f64::from(u32::MAX)) as u32,
7981 _ => frames,
7982 }
7983 })
7984 .collect(),
7985 )
7986}
7987
7988/// How long a placed file's clip is: its picture's frame count, held to the length
7989/// its sound is walled by ([`wall_table`]) when it has one. A grouped take puts the
7990/// same clip on the picture lane and the sound lane, so a 2.002 s picture beside a
7991/// 2.000 s sound is 60 frames, not 61 -- the sound's own wall is what the load and
7992/// save checks hold the audio lane to, and one clip must satisfy both lanes.
7993fn sound_held_frames(path: &Path, stream: usize, frames: u32, fps: f64) -> u32 {
7994 if crate::is_image(path) || crate::is_audio(path) {
7995 return frames.max(1);
7996 }
7997 match audio_stream_secs(path, stream) {
7998 Some(secs) if secs > 0.0 => {
7999 let held = (secs * fps).ceil().clamp(1.0, f64::from(u32::MAX)) as u32;
8000 frames.min(held).max(1)
8001 }
8002 _ => frames.max(1),
8003 }
8004}
8005
8006/// [`AudioSession::stream_duration_secs`] for one stream, remembered per file:
8007/// a trim asks for it on every drag step. Only a found length is kept; a file
8008/// that cannot be read now may be back in a moment.
8009fn audio_stream_secs(path: &Path, stream: usize) -> Option<f64> {
8010 static SECS: std::sync::OnceLock<Mutex<std::collections::HashMap<(PathBuf, usize), f64>>> =
8011 std::sync::OnceLock::new();
8012 let cache = SECS.get_or_init(Default::default);
8013 let key = (path.to_path_buf(), stream);
8014 if let Some(&secs) = cache.lock().ok()?.get(&key) {
8015 return Some(secs);
8016 }
8017 let secs = AudioSession::stream_duration_secs(path, stream).ok()??;
8018 cache.lock().ok()?.insert(key, secs);
8019 Some(secs)
8020}
8021
8022/// How many timeline frames a standalone audio file occupies: its playing time
8023/// rounded *up*, so the last partial frame is still covered rather than cut off,
8024/// and never zero (a clip is never empty).
8025fn audio_frames(path: &Path, fps: f64) -> crate::Result<u32> {
8026 let secs = AudioSession::duration_secs(path)?
8027 .ok_or_else(|| format!("{} has no audio track", path.display()))?;
8028 let frames = (secs * fps).ceil();
8029 if !frames.is_finite() || frames < 0.0 || frames > f64::from(u32::MAX) {
8030 return Err(format!(
8031 "{} is {secs} s long, which is not a timeline",
8032 path.display()
8033 )
8034 .into());
8035 }
8036 Ok((frames as u32).max(1))
8037}
8038
8039/// `None` for a silent session -- no audio track, no plugin, no daemon, or a
8040/// track the decoder refuses. Dropping the receiver on the way out stops the
8041/// audio decode worker, so a failure here leaves nothing running.
8042///
8043/// The second half is why, for the cases the *file* is to blame for: those are
8044/// a surprise worth showing (see
8045/// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a
8046/// file with no audio at all and a machine with no output device are not.
8047fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
8048 let sources = [(path.to_path_buf(), stream)];
8049 let (meta, rx) =
8050 match AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) {
8051 Ok(Some(opened)) => opened,
8052 // No AAC track: silent by nature, or sound in a codec we do not
8053 // have -- and only the second of those is worth a word.
8054 Ok(None) => {
8055 let reason = AudioSession::unsupported(path).ok().flatten();
8056 if let Some(reason) = &reason {
8057 crate::audio::debug_once(format!("audio disabled: {reason}"));
8058 }
8059 return (None, reason);
8060 }
8061 Err(e) => {
8062 crate::audio::debug_once(format!("audio disabled: {e}"));
8063 return (None, Some(e.to_string()));
8064 }
8065 };
8066 let Some(ao) = AoSession::open(meta.sample_rate, u32::from(meta.channels)) else {
8067 return (None, None); // no device: the machine's business, not the file's
8068 };
8069 // The stream comes up streaming; a session starts paused, so silence the
8070 // device until `play`. The feeder still fills the ring in the meantime.
8071 ao.set_active(false);
8072
8073 let audio = Audio {
8074 ao: Arc::new(Mutex::new(ao)),
8075 sample_rate: meta.sample_rate,
8076 channels: u64::from(meta.channels),
8077 fed: Arc::new(AtomicU64::new(0)),
8078 fed_all: Arc::new(AtomicBool::new(false)),
8079 died: Arc::new(AtomicBool::new(false)),
8080 epoch: Arc::new(AtomicU64::new(0)),
8081 content_at: Arc::new(AtomicI64::new(-1)),
8082 gain: Arc::new(AtomicU32::new(1.0f32.to_bits())),
8083 wants_active: Arc::new(AtomicBool::new(false)),
8084 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),
8085 peak: Arc::new(AtomicU32::new(0)),
8086 peak_lr: Arc::new([AtomicU32::new(0), AtomicU32::new(0)]),
8087 feeders: Arc::new(AtomicUsize::new(0)),
8088 rearm_at: Arc::new(Mutex::new(None)),
8089 };
8090 (audio.spawn_feeder(rx).then_some(audio), None)
8091}
8092
8093/// Pours decoded chunks into the device, keeping whatever the ring would not
8094/// take. Ends when the decoder is done, the output dies, or a seek supersedes
8095/// this feeder.
8096fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
8097 let mut pending: Vec<f32> = Vec::new();
8098 loop {
8099 if pending.is_empty() {
8100 match rx.recv() {
8101 Ok(chunk) => pending = chunk.samples,
8102 Err(_) => {
8103 // Decoder finished or went away. What is in the ring still
8104 // plays out; what comes after it is the end of the timeline
8105 // and not a decoder that fell behind, so the device is told
8106 // to stop counting it. Under the lock and past the epoch,
8107 // like every other word this thread has with the device: a
8108 // superseded feeder must not say this about the stream that
8109 // replaced it.
8110 let ao = audio.ao.lock().unwrap();
8111 if audio.epoch.load(Ordering::Acquire) == epoch {
8112 ao.stream_ended();
8113 }
8114 return;
8115 }
8116 }
8117 }
8118 let accepted = {
8119 let mut ao = audio.ao.lock().unwrap();
8120 // Under the lock, immediately before the write: `seek` bumps the
8121 // epoch and flushes the ring holding this very lock, so past this
8122 // check no stale sample can be queued behind the flush.
8123 if audio.epoch.load(Ordering::Acquire) != epoch {
8124 return;
8125 }
8126 let accepted = match ao.write(&pending) {
8127 Some(n) => n,
8128 None => {
8129 // Output died; flag it so `tick` moves the clock to wall time.
8130 audio.died.store(true, Ordering::Release);
8131 return;
8132 }
8133 };
8134 // The first sample of this stream to reach the ring, stamped with
8135 // what the device had played by then: everything before it was the
8136 // silence of the restart, and [`PlaybackSession::tick`] anchors the
8137 // clock here so that silence is never timeline time. Under the
8138 // device lock, with the epoch already checked, so the stamp and the
8139 // sample belong to the same stream.
8140 if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 {
8141 let at = ao.position().unwrap_or(0).max(0);
8142 audio.content_at.store(at, Ordering::Release);
8143 // ...and the device position this stream's samples are counted
8144 // from ([`Audio::played_out`]). Rebased *here* rather than at
8145 // the seek, because the open runs on this thread now: every
8146 // millisecond it took is device time nobody fed, and counting
8147 // it would make the stream read as played out that long before
8148 // it really is -- an early hand-off to wall time at the end of
8149 // the timeline. The seek's own rebase still stands for the
8150 // stream that never queues a sample at all.
8151 audio
8152 .fed
8153 .store(at as u64 * audio.channels, Ordering::Relaxed);
8154 // ...and *this* is where a playing timeline's device starts: on
8155 // the first sample there is to play, under the same lock and
8156 // past the same epoch check as the stamp, so the silence of the
8157 // open was never played and never counted
8158 // ([`Audio::wants_active`]).
8159 if audio.wants_active.load(Ordering::Acquire) {
8160 ao.set_active(true);
8161 }
8162 } else if accepted == 0 && audio.content_at.load(Ordering::Acquire) < 0 {
8163 // Nothing taken with nothing yet queued is the *flush* of the
8164 // restart still standing: the ring refuses a write until a
8165 // callback has consumed the flag (`engine_audio::accept`), and
8166 // only a running device has callbacks. So the device is started
8167 // here too -- there is a sample in hand, which is what the wait
8168 // was for -- and the quantum or two of that handshake is the
8169 // silence `Shared::primed` does not count.
8170 if audio.wants_active.load(Ordering::Acquire) {
8171 ao.set_active(true);
8172 }
8173 }
8174 accepted
8175 };
8176 audio.fed.fetch_add(accepted as u64, Ordering::Relaxed);
8177 audio.note_tap(&pending[..accepted]);
8178 pending.drain(..accepted);
8179 if !pending.is_empty() {
8180 // Ring full: nothing to do but let the device drain it. Except when
8181 // *nothing* was taken, which after a flush means the ring is still
8182 // waiting for the device to consume the flush flag rather than
8183 // being full: that is the head of a restart, and every millisecond
8184 // spent parked there is a millisecond of silence.
8185 match accepted {
8186 0 => thread::sleep(FLUSH_WAIT),
8187 _ => thread::sleep(RING_FULL_WAIT),
8188 }
8189 }
8190 }
8191}
8192
8193/// The stretch of the timeline that ends at `frame` (inclusive) and starts where
8194/// whatever is shown there starts: [`crate::export::stack_span_at`] at that
8195/// start, cut short at `frame`. What a backward play draws, from `frame` down.
8196fn back_span_at(project: &Project, frame: u32) -> Option<crate::project::Span> {
8197 let mut lo = 0;
8198 let visible = project
8199 .lanes()
8200 .into_iter()
8201 .filter(|lane| lane.kind == LaneKind::Video && !project.lane_hidden(*lane));
8202 for lane in visible {
8203 let clips = project.lane(lane);
8204 let from = match project.lane_clip_at(lane, frame) {
8205 Some(idx) => clips[idx].start,
8206 None => clips.iter().rfind(|c| c.end() <= frame).map_or(0, |c| c.end()),
8207 };
8208 lo = lo.max(from);
8209 }
8210 let mut span = crate::export::stack_span_at(project, lo)?;
8211 span.len = span.len.min(frame + 1 - lo);
8212 Some(span)
8213}
8214
8215/// Timeline seconds to a 0-based frame index, floor semantics: position `t`
8216/// shows the frame whose interval contains it. The epsilon absorbs float error
8217/// at exact frame boundaries -- `123.0/30.0 * 30.0` is `122.999...`, and a
8218/// bare truncation would land one frame early (S6 finding: 4 of every 300
8219/// frames round-trip wrong through `clip_spans()` seconds without this).
8220fn secs_to_frame(secs: f64, fps: f64) -> u32 {
8221 (secs * fps + 1e-6).floor().max(0.0) as u32
8222}
8223
8224/// Per-byte lerp of two same-sized BGRA8 frames -- [`crate::scale::blend_i420`]'s
8225/// interleaved-buffer twin. By the time a picture reaches [`try_frame`]
8226/// (`PlaybackSession::try_frame`) it is already colour-converted for the
8227/// screen, so there are no separate Y/U/V planes left to blend, only the one
8228/// buffer; straight alpha survives the lerp untouched (255 against 255 is
8229/// still 255). `t` is B's weight, [`crate::export::dissolve_weight`]'s own
8230/// convention.
8231fn blend_bgra(a: &[u8], b: &[u8], t: f32) -> Vec<u8> {
8232 let t = t.clamp(0.0, 1.0);
8233 assert_eq!(a.len(), b.len(), "blend_bgra: mismatched frame sizes");
8234 a.iter()
8235 .zip(b)
8236 .map(|(&av, &bv)| (av as f32 + (bv as f32 - av as f32) * t).round() as u8)
8237 .collect()
8238}
8239
8240/// A chapter time as YouTube writes one in a description: `MM:SS`, or `H:MM:SS` from an hour on.
8241/// The frame is floored to whole seconds.
8242pub fn youtube_time(frame: u32, fps: f64) -> String {
8243 let secs = (f64::from(frame) / fps).floor() as u64;
8244 let (h, m, sec) = (secs / 3600, (secs % 3600) / 60, secs % 60);
8245 if h > 0 {
8246 format!("{h}:{m:02}:{sec:02}")
8247 } else {
8248 format!("{m:02}:{sec:02}")
8249 }
8250}
8251
8252/// The YouTube description listing for `chapters` (frame, name, sorted by frame) and the warnings
8253/// its rules call for: the first chapter at 00:00, each chapter at least 10 seconds long (the last
8254/// runs to `end`), and at least 3 chapters. Empty when there are none.
8255pub fn chapter_listing(chapters: &[(u32, String)], fps: f64, end: u32) -> (String, Vec<String>) {
8256 if chapters.is_empty() {
8257 return (String::new(), Vec::new());
8258 }
8259 let listing = chapters
8260 .iter()
8261 .map(|(f, t)| format!("{} {t}", youtube_time(*f, fps)))
8262 .collect::<Vec<_>>()
8263 .join("\n");
8264 let mut warnings = Vec::new();
8265 if chapters[0].0 != 0 {
8266 warnings.push(format!(
8267 "the first chapter starts at {}, not 00:00: YouTube needs one at 00:00",
8268 youtube_time(chapters[0].0, fps)
8269 ));
8270 }
8271 for (i, (frame, title)) in chapters.iter().enumerate() {
8272 let next = chapters.get(i + 1).map_or(end, |c| c.0);
8273 let secs = f64::from(next.saturating_sub(*frame)) / fps;
8274 if secs < 10.0 {
8275 warnings.push(format!("chapter \"{title}\" at {} lasts {secs:.1} s: YouTube wants 10 s or more", youtube_time(*frame, fps)));
8276 }
8277 }
8278 if chapters.len() < 3 {
8279 warnings.push(format!("YouTube needs at least 3 chapters; this timeline has {}", chapters.len()));
8280 }
8281 (listing, warnings)
8282}
8283
8284#[cfg(test)]
8285mod tests {
8286 use super::{
8287 SCRUB_SECS, scrub_snippet, AUDIO_LOST, Edge, Lane, PlaybackSession, Source, TransformParams, audio_source_of,
8288 blend_bgra, secs_to_frame,
8289 };
8290 use std::path::PathBuf;
8291 use std::sync::atomic::Ordering;
8292
8293 fn asset(name: &str) -> PathBuf {
8294 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
8295 .join("../../assets")
8296 .join(name)
8297 }
8298
8299 /// A scrub snippet is the window it was cut from, as long as [`SCRUB_SECS`], and it rises
8300 /// from silence and falls to it again over its fades, so no edge of it can click.
8301 #[test]
8302 fn a_scrub_snippet_is_the_window_long_and_faded_at_both_ends() {
8303 let rate = 48_000u32;
8304 let frames = (SCRUB_SECS * f64::from(rate)) as usize;
8305 assert_eq!(frames, 3360, "70 ms at 48 kHz");
8306 let fade = (0.01 * f64::from(rate)) as usize;
8307 let src = vec![1.0f32; frames * 2];
8308 let out = scrub_snippet(&src, 2, fade);
8309 assert_eq!(out.len(), frames * 2, "the window's length, both channels");
8310 assert!(out[0].abs() < 0.01 && out[1].abs() < 0.01, "starts at silence: {:?}", &out[..2]);
8311 let last = out.len() - 2;
8312 assert!(out[last].abs() < 0.01 && out[last + 1].abs() < 0.01, "ends at silence");
8313 let mid = frames / 2 * 2;
8314 assert_eq!((out[mid], out[mid + 1]), (1.0, 1.0), "the middle is untouched");
8315 for f in 1..fade {
8316 assert!(out[2 * f] >= out[2 * (f - 1)], "the fade in rises at frame {f}");
8317 let tail = out.len() - 2 * (f + 1);
8318 assert!(out[tail] >= out[tail + 2], "the fade out falls toward the end at frame {f}");
8319 }
8320 // A window shorter than twice the fade has its fade held to half of it.
8321 let short = scrub_snippet(&[1.0; 8], 1, 100);
8322 assert_eq!(short.len(), 8);
8323 assert!(short[0].abs() < 0.5 && short[7].abs() < 0.5, "{short:?}");
8324 assert!(scrub_snippet(&[1.0; 8], 0, 2).len() == 8, "a zero width is read as mono");
8325 }
8326
8327 /// The crash path: a saved project with several sequences (one of them a compound clip
8328 /// over another, plus a marker) is written as an autosave and read back, and the autosave
8329 /// on top of the saved file recovers to the same sequences, compound clips and markers.
8330 #[test]
8331 fn autosave_round_trips_every_sequence_compound_and_marker() {
8332 let dir = crate::scratch::Scratch::dir("ve_sidecar_round_trip");
8333 let media = dir.join("film.mp4");
8334 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture");
8335 let path = dir.join("proj.edith");
8336 let s = PlaybackSession::open(&media).expect("open the fixture");
8337 s.set_gain(0.0);
8338 s.save_project_noted(&path).expect("save the base");
8339 let mut s = PlaybackSession::open_project(&path).expect("reopen the base");
8340 let b = s.new_sequence(Some("Cut B")).expect("a second sequence");
8341 s.switch_sequence(b).expect("switch to it");
8342 assert!(s.place_stream_at(0.0, &media, 0, None).expect("placeable"));
8343 let copy = s.duplicate_sequence(b).expect("duplicate it");
8344 s.switch_sequence(copy).expect("switch to the copy");
8345 s.nest(&[(Lane::V1, 0)], Some("Inner")).expect("nest a clip");
8346 assert_eq!(s.project.sequences().len(), 4, "the base, B, its copy and the nested one");
8347 s.add_marker(crate::project::Marker {
8348 frame: 3,
8349 length: 0,
8350 name: "beat".into(),
8351 note: String::new(),
8352 color: crate::project::MarkerColor::Red,
8353 })
8354 .expect("a marker");
8355 assert_eq!(s.project.markers().len(), 1, "the marker is on the sequence being edited");
8356 let sidecar = dir.join("proj.autosave.edith");
8357 s.save_autosave(&sidecar).expect("the autosave");
8358 let back = PlaybackSession::open_project(&sidecar).expect("the autosave opens");
8359 assert_eq!(back.project.sequences(), s.project.sequences(), "the same sequences, in order");
8360 assert_eq!(back.project.active_sequence(), s.project.active_sequence());
8361 assert_eq!(back.project.markers().len(), 1, "the marker comes back");
8362 assert_eq!(back.project.markers()[0].name, "beat");
8363 // The recovery path: the saved file, with the autosave on top of it.
8364 let mut saved = PlaybackSession::open_project(&path).expect("the saved file");
8365 assert!(saved.adopt_as_step(&back), "the autosave lands on the saved file");
8366 assert_eq!(saved.project.sequences(), s.project.sequences(), "recovery holds every sequence");
8367 assert_eq!(saved.project.markers().len(), 1, "and the marker");
8368 }
8369
8370 /// A clip past its source's end in a parked sequence is shortened on save, just as in the
8371 /// active one, and the save says which sequence it was in. It is never refused.
8372 #[test]
8373 fn save_shortens_the_parked_sequences_over_wall_clips() {
8374 let dir = crate::scratch::Scratch::dir("ve_save_parked_walls");
8375 let media = dir.join("film.mp4");
8376 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture");
8377 let mut s = PlaybackSession::open(&media).expect("open the fixture");
8378 s.set_gain(0.0);
8379 let copy = s.duplicate_sequence(s.project.active_sequence()).expect("duplicate");
8380 let copy_name = s.project.sequence_name(copy).expect("the copy is named").to_string();
8381 let path = dir.join("proj.edith");
8382 assert!(s.save_project_noted(&path).expect("whole walls save").is_empty());
8383 s.counts[0] = 1;
8384 let notes = s.save_project_noted(&path).expect("the save never refuses");
8385 assert!(notes.iter().any(|n| n.contains(&format!("in sequence \"{copy_name}\""))), "{notes:?}");
8386 assert!(notes.iter().all(|n| !n.contains("frame")), "no frame numbers in a note: {notes:?}");
8387 PlaybackSession::open_project(&path).expect("the saved file opens");
8388 }
8389
8390 /// A video file whose sound is shorter than its picture (a 22.96 s picture under 20.67 s of
8391 /// sound): the timeline it opens to holds the grouped take to the sound's length, so an
8392 /// edit chain that splits, ripple-deletes and dissolves saves without a refusal and leaves
8393 /// no audio clip past the sound's end.
8394 #[test]
8395 fn a_picture_longer_than_its_sound_saves_after_edits() {
8396 let dir = crate::scratch::Scratch::dir("ve_short_sound_edits");
8397 let media = dir.join("speech.mp4");
8398 let made = std::process::Command::new("ffmpeg")
8399 .args(["-y", "-v", "error", "-f", "lavfi", "-i", "testsrc=size=160x120:rate=25:duration=22.96",
8400 "-f", "lavfi", "-i", "sine=frequency=440:duration=20.67", "-c:v", "mpeg4", "-c:a", "aac"])
8401 .arg(&media)
8402 .status()
8403 .map(|s| s.success() && media.exists())
8404 .unwrap_or(false);
8405 if !made {
8406 eprintln!("no ffmpeg: a picture longer than its sound cannot be generated, skipping");
8407 return;
8408 }
8409 let mut s = PlaybackSession::open(&media).expect("open the fixture");
8410 s.set_gain(0.0);
8411 let sound_frames = 517;
8412 assert_eq!(s.lane_clips(Lane::A1)[0].out_frame, sound_frames, "the opened take is the sound's length");
8413 assert_eq!(s.lane_clips(Lane::V1)[0].out_frame, sound_frames, "and so is its picture");
8414
8415 let path = dir.join("proj.edith");
8416 assert!(s.cut_at(5.0));
8417 assert!(s.cut_regions(&[(50, 100)], &[Lane::V1, Lane::A1]).is_ok());
8418 assert!(s.set_transition_out(Lane::V1, 0, 10));
8419 assert!(s.place_stream_at(0.0, &media, 0, None).expect("placeable"));
8420 let notes = s.save_project_noted(&path).expect("the edited take saves");
8421 assert!(notes.is_empty(), "nothing needed shortening: {notes:?}");
8422 for lane in [Lane::V1, Lane::A1] {
8423 for c in s.lane_clips(lane) {
8424 assert!(c.out_frame <= sound_frames, "{lane:?} clip ends at {} past the sound", c.out_frame);
8425 }
8426 }
8427 }
8428
8429 /// A relink is one undo step on the session too: undo points the source back at the old file,
8430 /// which reads again (no longer offline), and redo points it at the new one.
8431 #[test]
8432 fn undoing_a_relink_reads_the_old_file_again() {
8433 let dir = crate::scratch::Scratch::dir("ve_relink_undo_session");
8434 let media = dir.join("film.mp4");
8435 std::fs::copy(asset("test_av.mp4"), &media).expect("copy the fixture");
8436 let session = PlaybackSession::open(&media).expect("open the fixture");
8437 session.set_gain(0.0);
8438 let path = dir.join("proj.edith");
8439 session.save_project(&path).expect("save");
8440 let moved = dir.join("moved.mp4");
8441 std::fs::rename(&media, &moved).expect("move the media");
8442
8443 let mut s = PlaybackSession::open_project(&path).expect("opens offline");
8444 assert_eq!(s.offline_sources().len(), 1);
8445 s.relink_source(0, &moved).expect("relinks");
8446 assert!(s.offline_sources().is_empty());
8447 std::fs::copy(&moved, &media).expect("the old file is back beside it");
8448 assert!(s.undo());
8449 assert_eq!(s.sources()[0].path, std::fs::canonicalize(&media).expect("canonical"));
8450 assert!(s.offline_sources().is_empty(), "the old file reads again");
8451 assert!(s.redo());
8452 assert_eq!(s.sources()[0].path, std::fs::canonicalize(&moved).expect("canonical"));
8453 }
8454
8455 /// A dead output is not the end of a session's sound.
8456 ///
8457 /// The stream is stopped the way a seek stops one and then flagged the way a
8458 /// failed write flags it ([`feed`]): nothing is feeding and nothing will. The
8459 /// session must say so -- a dead output used to hand the clock to wall time
8460 /// in silence, for the rest of the session's life, through every seek -- and
8461 /// the play (and the seek after it) must put the output back, which is read
8462 /// off the tap: the samples that actually reached the device. A session that
8463 /// only switched the clock leaves the tap empty.
8464 ///
8465 /// The tick below runs with the cooldown already spent (an attempt stamped
8466 /// just now), which is what makes the notice observable at all *and* what
8467 /// proves the one thing a frame-rate poll must not do: open a device that is
8468 /// gone for good sixty times a second.
8469 #[test]
8470 fn a_dead_output_is_rearmed_and_the_sound_comes_back() {
8471 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8472 assert!(
8473 session.audio_tap().is_some(),
8474 "test_av.mp4 carries an audio track, which is what this drives"
8475 );
8476
8477 session.stop_audio();
8478 let audio = session.audio.as_ref().expect("audio");
8479 audio.died.store(true, Ordering::Release);
8480 *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now());
8481
8482 session.tick();
8483 assert_eq!(
8484 session.audio_disabled_reason(),
8485 Some(AUDIO_LOST),
8486 "a dead output went to wall time without a word"
8487 );
8488 assert!(
8489 session
8490 .audio
8491 .as_ref()
8492 .expect("audio")
8493 .died
8494 .load(Ordering::Acquire),
8495 "a tick opened the output again inside the cooldown"
8496 );
8497 assert!(
8498 session.audio_tap().expect("audio").0.is_empty(),
8499 "something was still feeding the device"
8500 );
8501
8502 // Playing is the ask that is not throttled: the output is opened again,
8503 // the flag clears and a feeder fills the device -- asynchronously, so the
8504 // tap is waited on.
8505 session.play();
8506 session.seek(1.0);
8507 let mut fed = Vec::new();
8508 for _ in 0..200 {
8509 fed = session.audio_tap().expect("audio").0;
8510 if !fed.is_empty() {
8511 break;
8512 }
8513 std::thread::sleep(std::time::Duration::from_millis(5));
8514 }
8515 assert!(
8516 !fed.is_empty(),
8517 "playing after a dead output fed nothing: the session cannot come back"
8518 );
8519 assert!(
8520 !session
8521 .audio
8522 .as_ref()
8523 .expect("audio")
8524 .died
8525 .load(Ordering::Acquire),
8526 "the death flag stood after the output was replaced"
8527 );
8528 assert_eq!(
8529 session.audio_disabled_reason(),
8530 None,
8531 "the notice was left standing over a session that is playing again"
8532 );
8533 }
8534
8535 /// A monitoring level is state, and a device replaced under the session is
8536 /// a new object that knows nothing about it: the re-armed stream came up
8537 /// at full volume, so a session playing muted while PipeWire restarted
8538 /// came back loud with the toolbar still reading "muted". The gain is
8539 /// therefore read back *from the device* ([`PlaybackSession::gain`]) and
8540 /// put back onto the replacement.
8541 ///
8542 /// The silent sink is what makes this a state round-trip rather than a
8543 /// claim about ears: it keeps the gain it was given, so the level after a
8544 /// re-arm is a number this process can read, and a plain open with no gain
8545 /// ever pushed is the control that says 1.0 is a real default rather than
8546 /// a leftover.
8547 #[test]
8548 fn a_rearmed_output_comes_back_at_the_level_the_session_was_running() {
8549 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8550 // The control: a session nobody has pushed a level at is at full
8551 // volume, which is what a *fresh* device is expected to be.
8552 assert_eq!(
8553 session.gain(),
8554 Some(1.0),
8555 "a session that never had a gain pushed is not at full volume"
8556 );
8557 assert!(
8558 session.set_gain(0.0),
8559 "a muted push was refused by the silent sink"
8560 );
8561 assert_eq!(
8562 session.gain(),
8563 Some(0.0),
8564 "the push did not reach the device"
8565 );
8566
8567 // The device goes away the way a daemon restart takes it: the stream is
8568 // stopped and flagged dead, with the cooldown already spent. The
8569 // replacement is opened by the door the sibling re-arm witness drives
8570 // -- a play and the seek that follows, which is `start_audio`'s
8571 // unthrottled attempt -- and the death flag clearing is what says a new
8572 // device really was installed, rather than the read below passing over
8573 // the old one.
8574 session.stop_audio();
8575 let audio = session.audio.as_ref().expect("audio");
8576 audio.died.store(true, Ordering::Release);
8577 *audio.rearm_at.lock().unwrap() = Some(std::time::Instant::now());
8578 session.play();
8579 session.seek(1.0);
8580 assert!(
8581 !session
8582 .audio
8583 .as_ref()
8584 .expect("audio")
8585 .died
8586 .load(Ordering::Acquire),
8587 "the device was never replaced, so the level below says nothing about \
8588 a re-armed stream"
8589 );
8590
8591 assert_eq!(
8592 session.gain(),
8593 Some(0.0),
8594 "the replacement device came up at full volume: a muted session \
8595 that lost its output came back loud while the window still said muted"
8596 );
8597 }
8598
8599 /// The seat declares the canvas's own size; the painter masks the planes it
8600 /// returns to even dimensions, and a canvas the two disagree about used to
8601 /// take the picture down between them. On the revision before the seat masked
8602 /// what it declares, a 1920x1 canvas died *in the painter* -- `decode.rs`
8603 /// clamped the zero line of an h of 0: `max = -1`, `min > max` -- and a
8604 /// 321x181 one died in the conversion on the *canvas's* chroma plane, one row
8605 /// past the masked source's: `index out of bounds: the len is 14400 but the
8606 /// index is 14400`, a full plane and not an empty one.
8607 ///
8608 /// This drives the same path a front-end does (`set_resolution`, then frames
8609 /// out of the session). It is a guard against the shape coming back rather
8610 /// than a reproduction: a frame does still arrive on the parent revision
8611 /// (which is why the masking, not this test, is the fix).
8612 #[test]
8613 fn a_visualizer_seat_paints_a_canvas_it_cannot_evenly_divide() {
8614 for (w, h) in [(1920, 1), (1921, 1081), (320, 1), (321, 181)] {
8615 let mut session =
8616 PlaybackSession::open(asset("test_tone.mp3")).expect("open the audio fixture");
8617 assert!(
8618 session.set_resolution(w, h),
8619 "{w}x{h} should be a resolution this session takes"
8620 );
8621 let mut frame = None;
8622 for _ in 0..400 {
8623 if let Some(f) = session.try_frame() {
8624 frame = Some(f);
8625 break;
8626 }
8627 std::thread::sleep(std::time::Duration::from_millis(5));
8628 }
8629 let frame = frame.unwrap_or_else(|| panic!("no frame from a {w}x{h} canvas"));
8630 assert_eq!(
8631 (frame.width, frame.height),
8632 (w, h),
8633 "a frame at the canvas's own size"
8634 );
8635 }
8636 }
8637
8638 /// `blend_bgra` at the two ends and the midpoint of its weight -- `t=0` is
8639 /// pure A, `t=1` is pure B, `t=0.5` rounds each byte to its own midpoint.
8640 /// Straight alpha (255 in both) survives every weight, which is the one
8641 /// channel a wrong blend would otherwise fog.
8642 #[test]
8643 fn blend_bgra_interpolates_every_byte_including_alpha() {
8644 let a = [10u8, 20, 30, 255];
8645 let b = [110u8, 120, 130, 255];
8646 assert_eq!(blend_bgra(&a, &b, 0.0), a);
8647 assert_eq!(blend_bgra(&a, &b, 1.0), b);
8648 assert_eq!(blend_bgra(&a, &b, 0.5), [60, 70, 80, 255]);
8649 }
8650
8651 /// A still wants the project's own pixels, not a view near them.
8652 /// [`PlaybackSession::set_view_size`] calls under 8 px no change at all (a
8653 /// window being dragged must not restart the picture every tick), so a
8654 /// caller that means "paint at the project's size" has to say it through
8655 /// [`PlaybackSession::set_view_size_exact`] -- and read its `false` as "the
8656 /// view is already there, the frame in hand is the one wanted", which is
8657 /// what stops it waiting for a picture nothing will reseek into existence.
8658 #[test]
8659 fn a_still_gets_the_exact_view_size_where_a_push_settles_for_near() {
8660 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8661 assert!(session.set_resolution(1920, 1080));
8662 let (w, h) = session.resolution();
8663 assert_eq!((w, h), (1920, 1080));
8664 // A preview-sized push, then the ask a still makes: two pixels short on
8665 // each axis, which the deadbanded push calls no change at all.
8666 assert!(session.set_view_size(1918, 1078));
8667 assert!(
8668 std::ops::Not::not(session.set_view_size(w, h)),
8669 "the push's deadband is exactly what a still cannot use"
8670 );
8671 assert_eq!(
8672 session.view_size(),
8673 (1918, 1078),
8674 "the push left the view near, not at, full -- so a still written now would be short"
8675 );
8676 assert!(
8677 session.set_view_size_exact(w, h),
8678 "the exact setter must move a view the push called close enough"
8679 );
8680 assert_eq!(session.view_size(), (w, h));
8681 // ...and at the size already it says so rather than repainting: that
8682 // `false` is the caller's "write the frame you have".
8683 assert!(std::ops::Not::not(session.set_view_size_exact(w, h)));
8684 }
8685
8686 /// The dissolve window's own edges, in the units [`PlaybackSession::start_span`]
8687 /// computes them in: a `tail_start` of `span.start + span.len - window`
8688 /// puts the very first output frame of the window at `idx_in_window == 0`
8689 /// and the very last at `window - 1`, clamped rather than overrun by a
8690 /// frame that lands exactly on the span's own end -- the same off-by-one
8691 /// a stray `%` or unclamped subtraction would have shown on screen as a
8692 /// blend that never quite reached full B.
8693 #[test]
8694 fn dissolve_window_edges_index_zero_to_window_minus_one() {
8695 let (span_start, span_len, window) = (100u32, 30u32, 10u32);
8696 let tail_start = span_start + span_len - window;
8697 assert_eq!(tail_start, 120);
8698 let idx_in_window = |frame: u32| (frame - tail_start).min(window - 1);
8699 assert_eq!(idx_in_window(120), 0, "first frame of the window");
8700 assert_eq!(idx_in_window(129), 9, "last frame of the window");
8701 assert_eq!(
8702 idx_in_window(130),
8703 9,
8704 "one past the span's own end clamps rather than panics"
8705 );
8706 }
8707
8708 /// A picked project rate overrides the derived one, and its absence leaves
8709 /// the source's own -- the seam every explicit-sample-rate caller
8710 /// (playback rebuild, both export encoders) goes through
8711 /// ([`crate::AudioSession::open_multi_streams_speed_at`]). The per-segment
8712 /// conform chain resamples to whatever `meta` names, so the meta *is* the
8713 /// behaviour.
8714 #[test]
8715 fn a_picked_sample_rate_overrides_the_derived_one() {
8716 let file = asset("test_av.mp4");
8717 let sources = [(file, 0)];
8718 let segs = [(Some(0), 0., 1.)];
8719 let derived =
8720 crate::AudioSession::open_multi_streams_speed_at(&sources, &segs, &[], &[], None)
8721 .expect("open the fixture")
8722 .expect("the fixture has sound")
8723 .0
8724 .sample_rate;
8725 let picked = crate::AudioSession::open_multi_streams_speed_at(
8726 &sources,
8727 &segs,
8728 &[],
8729 &[],
8730 Some(32000),
8731 )
8732 .expect("open the fixture")
8733 .expect("the fixture has sound")
8734 .0
8735 .sample_rate;
8736 assert_ne!(
8737 derived, 32000,
8738 "a fixture at the picked rate proves nothing"
8739 );
8740 assert_eq!(picked, 32000);
8741 }
8742
8743 /// Which source the timeline's sound is opened on -- the one rule
8744 /// [`open_project`](PlaybackSession::open_project), the probe every import
8745 /// is held to and the audio worker all read through. A still at index 0 is
8746 /// a picture, not a silent timeline: opening the device on it is a project
8747 /// that plays silent although every clip on it has sound.
8748 #[test]
8749 fn the_audio_reference_is_never_a_still() {
8750 let (video, still) = (asset("test_av.mp4"), asset("test_still.png"));
8751 let sources = [Source::new(&still, 0), Source::new(&video, 3)];
8752 assert_eq!(
8753 audio_source_of(&sources).map(|s| (&s.path, s.audio_stream)),
8754 Some((&sources[1].path, 3)),
8755 "the first source that could have a track, with its own stream"
8756 );
8757 assert!(
8758 audio_source_of(&sources[..1]).is_none(),
8759 "nothing but stills"
8760 );
8761 assert!(audio_source_of(&[]).is_none(), "and no file at all");
8762 }
8763
8764 /// What a front end's "resolution/rate picked before any file is open"
8765 /// setting costs the engine: nothing new. `open` then `set_resolution`/
8766 /// `set_frame_rate` right after construction -- the app's technique for
8767 /// applying a pre-import pick to the session it just made, mirroring
8768 /// [`PlaybackSession::open_project`]'s own `doc.resolution`/`doc.fps`
8769 /// override -- lands exactly where either setter lands it whenever it is
8770 /// called, and a later `import` of another file leaves both untouched: an
8771 /// import registers a source and its length, and never writes `meta.width`,
8772 /// `meta.height` or `meta.frame_rate`.
8773 #[test]
8774 fn a_pre_import_setting_survives_construction_and_a_later_import() {
8775 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8776 let native = session.native_resolution();
8777 let native_fps = session.native_frame_rate();
8778 // The explicit picks a pre-import setting would apply, distinct from
8779 // the fixture's own so a no-op would be caught.
8780 let (picked_w, picked_h) = (1920, 1080);
8781 assert_ne!((picked_w, picked_h), native, "the test needs a real change");
8782 let picked_fps = 24.0;
8783 assert_ne!(picked_fps, native_fps, "the test needs a real change");
8784 assert!(session.set_resolution(picked_w, picked_h));
8785 assert!(session.set_frame_rate(picked_fps));
8786 assert_eq!(session.resolution(), (picked_w, picked_h));
8787 assert_eq!(session.meta().frame_rate, picked_fps);
8788
8789 // A second file joining the timeline is exactly the case the front end
8790 // worried a later import could silently override the explicit pick --
8791 // it cannot, because `import` never touches the canvas.
8792 session
8793 .import(&asset("test_av2.mp4"))
8794 .expect("av2 matches the timeline it was set to");
8795 assert_eq!(
8796 session.resolution(),
8797 (picked_w, picked_h),
8798 "an import must not move the project's own canvas size"
8799 );
8800 assert_eq!(
8801 session.meta().frame_rate,
8802 picked_fps,
8803 "an import must not move the project's own rate"
8804 );
8805 }
8806
8807 #[test]
8808 fn an_audio_lane_walls_a_video_by_its_sound_and_a_video_lane_by_its_picture() {
8809 // A 2 s picture under 60 s of sound: the A1 half of a placed take can be
8810 // trimmed out to the sound's end, the V1 half only to the picture's.
8811 let path = asset("test_short_video_long_audio.mp4");
8812 let mut session = PlaybackSession::open(&path).expect("open the fixture");
8813 session.set_gain(0.0);
8814 let fps = session.meta().frame_rate;
8815 // Placed at the end, so nothing sits in front of it and the walls are the
8816 // source's own, not a neighbour's.
8817 let end = session.timeline_duration();
8818 assert!(
8819 session
8820 .place_stream_at(end, &path, 0, Some(Lane::A1))
8821 .expect("a file on this timeline is placeable")
8822 );
8823 let a1 = session.lane_clips(Lane::A1).len() - 1;
8824 let v1 = session.lane_clips(Lane::V1).len() - 1;
8825
8826 let audio = session.trim_walls(Lane::A1, a1, Edge::End).expect("A1 clip");
8827 let picture = session.trim_walls(Lane::V1, v1, Edge::End).expect("V1 clip");
8828 let placed = (end * fps).round();
8829 assert!(
8830 audio.hi as f64 >= placed + 59.0 * fps,
8831 "the sound is 60 s: the A1 end may reach {} frames at {fps} fps",
8832 audio.hi
8833 );
8834 assert!(
8835 (picture.hi as f64) < placed + 3.0 * fps,
8836 "the picture is 2 s: the V1 end stops at {} frames",
8837 picture.hi
8838 );
8839 assert!(
8840 session.trim_clip(Lane::A1, a1, Edge::End, (placed + 40.0 * fps) as u32),
8841 "the A1 clip trims to 40 s"
8842 );
8843 assert_eq!(session.lane_clips(Lane::A1)[a1].len(), (40.0 * fps) as u32);
8844 }
8845
8846 /// The seam between the two lists a source index reaches: dropping a file
8847 /// from the library shortens `sources`, and `counts` -- the frame length
8848 /// per source, which is what a trim is walled by -- has to lose the same
8849 /// entry. Left behind, the dead file's length would wall the survivor.
8850 #[test]
8851 fn removing_a_source_takes_its_frame_count_with_it() {
8852 // Source 0 is 5 s, source 1 is 4 s: two different walls, so a stale
8853 // count cannot pass for the right one.
8854 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8855 session.set_gain(0.0);
8856 // Imported, then dragged onto the end -- an import alone places nothing
8857 // ([`PlaybackSession::import`]), and this test needs both takes there.
8858 session.import(&asset("test_av2.mp4")).expect("av2 matches");
8859 let end = session.timeline_duration();
8860 assert!(
8861 session
8862 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
8863 .expect("a file just imported is on this timeline")
8864 );
8865 let (long, short) = (session.counts[0], session.counts[1]);
8866 assert!(long > short, "{long} vs {short}");
8867
8868 // Clear source 0's take, then take the file itself out: av2's clip is
8869 // the only one left and it is source 0 now.
8870 assert!(session.delete_clip(Lane::V1, 0));
8871 session
8872 .remove_source(&asset("test_av.mp4"), 0)
8873 .expect("nothing plays it any more");
8874 assert_eq!(session.counts, vec![short], "the dead length went with it");
8875 assert_eq!(session.sources().len(), session.counts.len());
8876
8877 // The wall is the surviving file's own length, not the gone one's: a
8878 // whole-file clip cannot be dragged out any further at all.
8879 let clip = session.lane_clips(Lane::V1)[0].clone();
8880 assert_eq!(clip.len(), short, "av2's take, whole");
8881 assert_eq!(
8882 session.trim_room(Lane::V1, 0, Edge::End),
8883 Some((clip.start + 1, clip.end()))
8884 );
8885 assert!(
8886 !session.trim_clip(Lane::V1, 0, Edge::End, clip.end() + 30),
8887 "past the file's last frame is refused, by ITS length"
8888 );
8889
8890 // ...and the next import still lines the two lists up, which is the
8891 // alignment `note_frames` asserts on.
8892 session
8893 .import(&asset("test_av.mp4"))
8894 .expect("it may come back");
8895 assert_eq!(session.counts, vec![short, long]);
8896 assert_eq!(session.sources().len(), session.counts.len());
8897 }
8898
8899 /// The two headers a place reads are read *once*: an mp4 dropped on a lane
8900 /// used to open its own container and the timeline's first source every
8901 /// time, both on the thread that draws, and a film whose pages have gone
8902 /// cold is 1.7 s of that.
8903 ///
8904 /// Proved by answering, not by timing: the memo is filled with a layout the
8905 /// file does not have, and the place is refused. Only a door that read the
8906 /// remembered header rather than the disk can refuse it.
8907 #[test]
8908 fn a_place_reads_each_audio_header_once() {
8909 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
8910 session.set_gain(0.0);
8911 session.import(&asset("test_av2.mp4")).expect("av2 matches");
8912 let end = session.timeline_duration();
8913 assert!(
8914 session
8915 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
8916 .expect("a file just imported is on this timeline")
8917 );
8918 assert_eq!(
8919 session.probes.len(),
8920 2,
8921 "the timeline's first source and the file placed, once each"
8922 );
8923
8924 // Now say av2 is 5.1. Nothing on disk changed, so a door that opens the
8925 // file still matches; one that trusts the memo refuses by layout.
8926 // Keyed exactly as a [`Source`] names a file -- canonical, symlinks
8927 // resolved -- which is the key the doors look up.
8928 let av2 = Source::new(asset("test_av2.mp4"), 0).path;
8929 session.probes.insert(
8930 (av2, 0),
8931 Some(crate::AudioProbe {
8932 sample_rate: 48_000,
8933 channels: 6,
8934 }),
8935 );
8936 let refused = session
8937 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
8938 .expect_err("the remembered layout disagrees with the timeline's");
8939 assert!(
8940 refused.to_string().contains("6 ch"),
8941 "refused in the layout's own words: {refused}"
8942 );
8943 assert_eq!(session.probes.len(), 2, "and nothing was opened to say so");
8944 }
8945
8946 /// The door a library preview opens a chosen stream through: `test_multiaudio.mp4`
8947 /// has stream 0 stereo and stream 1 mono
8948 /// ([`crate::waveform::tests::each_stream_of_a_file_has_its_own_envelope`]
8949 /// names the same fixture), so a session that actually bound the stream it
8950 /// was asked for plays a different layout than one that did not -- and
8951 /// plain [`PlaybackSession::open`] still lands on stream 0, unchanged.
8952 #[test]
8953 fn open_with_audio_stream_binds_the_named_track() {
8954 let multi = asset("test_multiaudio.mp4");
8955 let zero = PlaybackSession::open_with_audio_stream(&multi, 0).expect("stream 0 opens");
8956 let one = PlaybackSession::open_with_audio_stream(&multi, 1).expect("stream 1 opens");
8957 let default = PlaybackSession::open(&multi).expect("default open");
8958 let (Some(a0), Some(a1), Some(ad)) = (
8959 zero.audio.as_ref(),
8960 one.audio.as_ref(),
8961 default.audio.as_ref(),
8962 ) else {
8963 // No audio device on this machine: nothing further to check --
8964 // the device is the machine's business, not this door's.
8965 return;
8966 };
8967 assert_eq!(a0.channels, 2, "stream 0 is the stereo pair");
8968 assert_eq!(a1.channels, 1, "stream 1 is the mono track");
8969 assert_ne!(a0.channels, a1.channels, "the two streams must differ");
8970 assert_eq!(
8971 ad.channels, a0.channels,
8972 "open() still defaults to stream 0"
8973 );
8974 }
8975
8976 /// The bug this regression pins: a preview paused (or scrubbed) to a
8977 /// frame inside a dissolve window used to show plain A forever, because
8978 /// B's decoder only opened on the tick that landed in the window and
8979 /// nothing polled `try_frame` again while the clock stood still
8980 /// (`Player::pump` only drains while playing or a seek is owed, and one
8981 /// delivered frame clears "owed"). Two clips of real fixtures, touching,
8982 /// with a dissolve set on the join -- seeking into the window and taking
8983 /// exactly one frame (no play, no second tick) must already show a blend:
8984 /// the same position with the dissolve turned off must differ from it.
8985 #[test]
8986 fn a_single_paused_tick_inside_the_dissolve_window_is_already_blended() {
8987 let window = 6u32;
8988 let build = |transition: u32| {
8989 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open a");
8990 s.set_gain(0.0);
8991 s.import(&asset("test_av2.mp4")).expect("av2 matches");
8992 let end = s.timeline_duration();
8993 assert!(
8994 s.place_stream_at(end, &asset("test_av2.mp4"), 0, None)
8995 .expect("av2, placed right after a")
8996 );
8997 if transition > 0 {
8998 assert!(s.set_transition_out(Lane::V1, 0, transition));
8999 }
9000 s
9001 };
9002 let mut on = build(window);
9003 let mut off = build(0);
9004
9005 let fps = on.meta().frame_rate;
9006 let clip0_len = on.lane_clips(Lane::V1)[0].len();
9007 assert!(
9008 clip0_len > window,
9009 "the fixture needs to outlast the window"
9010 );
9011 let mid_of_window = clip0_len - window / 2;
9012 let t = f64::from(mid_of_window) / fps;
9013
9014 // One seek, then one frame -- exactly what a paused preview's single
9015 // repaint asks the engine for. Polled rather than taken on the first
9016 // call because the seek itself just restarted the decoder
9017 // (`start_span`) and its first picture is not synchronous; once
9018 // *a* frame lands this is the one tick under test.
9019 let frame_at = |s: &mut PlaybackSession| -> crate::decode::Frame {
9020 s.seek(t);
9021 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
9022 loop {
9023 if let Some(f) = s.try_frame() {
9024 return f;
9025 }
9026 assert!(
9027 std::time::Instant::now() < deadline,
9028 "no frame within 120s of the seek"
9029 );
9030 std::thread::sleep(std::time::Duration::from_millis(10));
9031 }
9032 };
9033
9034 let off_frame = frame_at(&mut off);
9035 let on_frame = frame_at(&mut on);
9036 assert_eq!(on_frame.index, off_frame.index, "same timeline position");
9037 assert_ne!(
9038 on_frame.bgra, off_frame.bgra,
9039 "paused inside the window, the dissolve must already show B blended in"
9040 );
9041 }
9042
9043 #[test]
9044 fn boundary_seconds_round_trip_to_their_own_frame() {
9045 for f in 0u32..300 {
9046 let secs = f64::from(f) / 30.0;
9047 assert_eq!(secs_to_frame(secs, 30.0), f, "frame {f}");
9048 }
9049 // Mid-frame positions still floor, and negatives clamp.
9050 assert_eq!(secs_to_frame(10.5 / 30.0, 30.0), 10);
9051 assert_eq!(secs_to_frame(-0.2, 30.0), 0);
9052 }
9053
9054 /// A paused transform nudge -- `set_transform_live` at the position the
9055 /// picture already stands on -- never pays a full decoder restart: the
9056 /// worker is reused (`Worker::reseek`), never replaced
9057 /// (`PlaybackSession::retire`), so `restarts()` does not move. Guards the
9058 /// path a card's live edits go through against a future change routing
9059 /// them back through `seek`/a fresh worker, and a gap left between two
9060 /// edits (a person's think-time between nudges) longer than the *old*
9061 /// hardware-idle window still counts zero restarts -- a decoder worker
9062 /// outliving its span is not a "restart" this counter (or a caller) sees,
9063 /// whatever the hardware session inside it did.
9064 #[test]
9065 fn a_paused_transform_nudge_reuses_the_worker_not_a_restart() {
9066 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
9067 s.set_gain(0.0);
9068 let poll = |s: &mut PlaybackSession| -> crate::decode::Frame {
9069 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
9070 loop {
9071 if let Some(f) = s.try_frame() {
9072 return f;
9073 }
9074 assert!(std::time::Instant::now() < deadline, "no frame within 120s");
9075 std::thread::sleep(std::time::Duration::from_millis(10));
9076 }
9077 };
9078 let first = poll(&mut s);
9079 let before = s.restarts();
9080
9081 // A gap past the pre-fix 2s hardware-idle window: the whole point of
9082 // widening it is that a nudge landing here still reuses the worker.
9083 std::thread::sleep(std::time::Duration::from_millis(2500));
9084
9085 let clip = s.video_clip_at(s.now()).expect("a clip under the playhead");
9086 let params = TransformParams {
9087 scale: 1.2,
9088 ..Default::default()
9089 };
9090 assert!(
9091 s.set_transform_live(clip.0, clip.1, Some(params)),
9092 "the edit took"
9093 );
9094 let next = poll(&mut s);
9095
9096 assert_eq!(
9097 before,
9098 s.restarts(),
9099 "a live transform edit must reuse the worker"
9100 );
9101 assert_eq!(
9102 next.index, first.index,
9103 "paused: same timeline position before and after"
9104 );
9105 }
9106
9107 /// A rate undo lands the picture where the playhead is, in the rate that
9108 /// came *back*: the entry a pick takes carries the old numbering beside the
9109 /// old rate, so an undo restores both and the reseek has to be computed
9110 /// after the restore. Computed before it, the landing is the pre-undo
9111 /// rate's reading of the post-undo project -- `now` clamps to the pre-undo
9112 /// rate's idea of the timeline's end and the worker is handed the last
9113 /// frame of a five-second timeline for a playhead at three seconds.
9114 #[test]
9115 fn a_rate_undo_reseeks_at_the_rate_it_restored() {
9116 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
9117 s.set_gain(0.0);
9118 let poll = |s: &mut PlaybackSession| -> crate::decode::Frame {
9119 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(120);
9120 loop {
9121 if let Some(f) = s.try_frame() {
9122 return f;
9123 }
9124 assert!(std::time::Instant::now() < deadline, "no frame within 120s");
9125 std::thread::sleep(std::time::Duration::from_millis(10));
9126 }
9127 };
9128 let native = s.native_frame_rate();
9129 s.seek(3.0);
9130 assert_eq!(s.now(), 3.0, "the fixture is five seconds long");
9131 assert!(s.set_frame_rate(native * 2.0), "the rate pick");
9132 assert!(s.undo(), "the pick is one step");
9133 assert_eq!(s.meta().frame_rate, native, "the rate came back");
9134 assert_eq!(
9135 s.now(),
9136 3.0,
9137 "the playhead is the seconds it was, read at the rate that came back"
9138 );
9139 // The worker's own landing, which is the half the clock alone cannot
9140 // show: a frame 149 of 150 is exactly the pre-undo rate's clamp.
9141 assert_eq!(
9142 s.span.expect("a span for the picture").start,
9143 secs_to_frame(3.0, native),
9144 "the picture was asked for the playhead's own frame"
9145 );
9146 let frame = poll(&mut s);
9147 assert_eq!(
9148 frame.index,
9149 secs_to_frame(3.0, native),
9150 "and that is the frame that arrived"
9151 );
9152 }
9153
9154 /// The session's live look samples leave its history exactly where the
9155 /// press left it -- the colour-wheel drag's twin for the packed look, and
9156 /// what lets the app drive one from a pointer: `z` after a drag lands
9157 /// before the press, not one sample back down the drag.
9158 #[test]
9159 fn a_live_look_drag_is_one_step_of_the_sessions_history() {
9160 let mut s = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
9161 let (lane, idx) = s.video_clip_at(s.now()).expect("a clip under the playhead");
9162 let look = |hue: u8| crate::decode::with_viz_paint_hue(crate::decode::VIZ_PAINT_AZURE, hue);
9163 assert!(s.set_viz_paint(lane, idx, look(1)), "the press");
9164 for hue in 2..=6u8 {
9165 assert!(s.set_viz_paint_live(lane, idx, look(hue)), "a sample");
9166 }
9167 assert_eq!(s.project.lane(lane)[idx].viz_paint, look(6));
9168 assert!(s.undo(), "the drag's own step");
9169 assert_eq!(
9170 s.project.lane(lane)[idx].viz_paint,
9171 0,
9172 "one undo is the whole drag"
9173 );
9174 }
9175
9176 #[test]
9177 fn solo_keeps_only_the_soloed_audio_lanes_audible() {
9178 use super::soloed_gains;
9179 use crate::project::LaneKind;
9180 let a1 = Lane::new(LaneKind::Audio, 0);
9181 let a2 = Lane::new(LaneKind::Audio, 1);
9182 let a3 = Lane::new(LaneKind::Audio, 2);
9183 let v1 = Lane::new(LaneKind::Video, 0);
9184 let audio = [a1, a2, a3];
9185 let gains = vec![1.0, 0.5, 0.0];
9186 assert_eq!(
9187 soloed_gains(gains.clone(), &audio, &[a2]),
9188 vec![0.0, 0.5, 0.0],
9189 "the others go silent, the soloed one keeps its own gain"
9190 );
9191 assert_eq!(
9192 soloed_gains(gains.clone(), &audio, &[]),
9193 vec![1.0, 0.5, 0.0],
9194 "no solo changes nothing"
9195 );
9196 assert_eq!(
9197 soloed_gains(gains.clone(), &audio, &[v1]),
9198 vec![1.0, 0.5, 0.0],
9199 "a video lane is no audio solo"
9200 );
9201 assert_eq!(
9202 soloed_gains(gains.clone(), &[a1, a3], &[a2]),
9203 vec![1.0, 0.5, 0.0],
9204 "a solo naming no audio lane any more is no solo"
9205 );
9206 }
9207}