forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB3fc6753Tahinli3 months ago345 commits

playback.rs3078 lines, 150.7 KiBHistoryRawDownload
1//! One timeline over one or more files: the decode workers, the audio output
2//! and the master clock wired together so a front-end only has to render and
3//! call [`tick`].
4//!
5//! [`tick`]: PlaybackSession::tick
6//!
7//! Everything degrades to silent-but-correct: no audio track, no plugin, no
8//! PipeWire daemon and an unusable format all end up in [`ClockSource::Wall`],
9//! where the video is paced by real time instead of by the device.
10//!
11//! Drift policy stays with the caller -- this type answers "what time is it",
12//! the renderer decides which frame that means.
13
14use std::path::Path;
15use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU64, Ordering};
16use std::sync::mpsc::{Receiver, TryRecvError};
17use std::sync::{Arc, Mutex};
18use std::thread;
19use std::time::Duration;
20
21use crate::ao::AoSession;
22use crate::audio::{AudioChunk, AudioSession};
23use crate::clock::{ClockSource, PlaybackClock};
24use crate::color::ColorParams;
25use crate::colorspace::ColorDescription;
26use crate::decode::{Backend, BackendCell, DecodeSession, Frame, Worker};
27use crate::demux::{Codec, Demuxer, VideoMeta};
28use crate::eq::EqParams;
29use crate::project::{Clip, Edge, Lane, LaneKind, Project, Rate, Source, Span, Speed};
30use crate::scale::{Composer, FitPolicy};
31
32/// How long the feeder waits out a full ring. The ring holds a second, so this
33/// only has to be short next to that; it costs one wakeup per 10 ms of audio.
34const RING_FULL_WAIT: Duration = Duration::from_millis(10);
35
36/// How long the feeder waits out a ring that took *nothing*: the flush of a
37/// restart, which only the device's own callback can clear (`engine-audio`
38/// refuses a write queued behind one). Short, because this is the gap at the
39/// head of every restart and the ear is in it -- one wakeup per millisecond,
40/// for the millisecond or two it lasts.
41const FLUSH_WAIT: Duration = Duration::from_millis(1);
42
43/// The timeline a file with no picture scaffolds: 1080p at 30 fps, H.264 --
44/// nothing was shot on it, so it is the canvas a *later* import meets rather
45/// than a description of the song. H.264 because it is the one codec that
46/// decodes without the plugin, 30 fps because a rounded-up audio length is what
47/// the frame count means and a whole number of frames per second keeps it
48/// honest; both are what a video imported onto such a timeline is held to
49/// ([`matches_timeline`]).
50///
51/// ponytail: a 25 fps video imported onto an audio-only timeline it could have
52/// defined plays at 25 fps, correctly, but on a 30 fps timeline -- it is read
53/// through [`Rate`] like any other file shot at another rate rather than
54/// defining one. Upgrade path is adopting the first *picture's* rate and codec
55/// on import, which means retiming every audio clip already placed in frames.
56const AUDIO_ONLY_CANVAS: (u32, u32, f64) = (1920, 1080, 30.0);
57
58/// The frame rate a timeline scaffolded from a still image runs at, for
59/// [`AUDIO_ONLY_CANVAS`]'s reason: nothing was shot on it. The *size* is not
60/// invented the same way -- an image has a picture of its own, and that picture
61/// is the canvas a later import meets.
62const IMAGE_ONLY_RATE: f64 = 30.0;
63
64/// How long a still image *is*, in seconds: the wall a trim may drag its edge
65/// out to, since an image has no length of its own to be walled by. Ten
66/// minutes, which is a title card nobody will run out of and still a finite
67/// number -- a `u32::MAX` sentinel here would make [`Self::trim_room`] hand a
68/// drag a wall past what the timeline can hold.
69///
70/// ponytail: a still cannot be held longer than this. Upgrade path is a
71/// per-source length the project file carries, which every `counts` reader
72/// would then have to take from the document rather than from the file.
73const IMAGE_MAX_SECS: f64 = 600.0;
74
75/// How long a still image is *placed* for: five seconds, the length a picture
76/// gets when nobody has said one -- trimmable either way up to
77/// [`IMAGE_MAX_SECS`].
78const IMAGE_PLACE_SECS: f64 = 5.0;
79
80/// The output half of a session: the device, plus what the feeder has handed it.
81/// Cloned into the feeder thread; every field that matters is shared.
82#[derive(Clone)]
83struct Audio {
84 /// Shared because `write` runs on the feeder thread while `position` and
85 /// `set_active` are called from the caller's. The plugin serialises those
86 /// itself (atomics and a channel), but the lock is what makes it sayable in
87 /// Rust and it is never held for more than a memcpy.
88 ao: Arc<Mutex<AoSession>>,
89 sample_rate: u32,
90 channels: u64,
91 /// Interleaved samples accepted by the device so far.
92 fed: Arc<AtomicU64>,
93 /// The decoder ran out and `fed` is final.
94 fed_all: Arc<AtomicBool>,
95 /// The output plugin failed mid-stream. Its position is frozen from here on,
96 /// so it can never satisfy [`Audio::played_out`] -- the flag is what lets
97 /// [`PlaybackSession::tick`] hand the timeline to wall time instead.
98 died: Arc<AtomicBool>,
99 /// Bumped by every seek. A feeder only owns the device while this still
100 /// matches the value it started with; see [`feed`].
101 epoch: Arc<AtomicU64>,
102 /// The device position the *current* stream's first real sample was queued
103 /// at, `-1` until the feeder has queued one. Written by the feeder under the
104 /// device lock, read by [`tick`](PlaybackSession::tick).
105 ///
106 /// This is what keeps a restart out of the timeline. Between a flush and the
107 /// first sample of the new stream the device plays silence -- a decoder open
108 /// is tens of milliseconds -- and that silence is elapsed *device* time
109 /// ([`crate::ao`] counts it, as it must: it really was played). It is not
110 /// elapsed *timeline* time, and a clock anchored on the first poll after a
111 /// seek counts it as such, which is a permanent offset between the picture
112 /// and the sound, re-rolled by every edit made while playing.
113 content_at: Arc<AtomicI64>,
114 /// The last [`TAP_SAMPLES`] mono samples handed to the device, oldest
115 /// first: what a meter or an analyser draws. Written by the feeder, which
116 /// is not the device's own callback -- the plugin's RT thread never sees
117 /// this lock, and the feeder holds it for one memcpy per write.
118 tap: Arc<Mutex<Vec<f32>>>,
119}
120
121/// How much of the played signal the tap keeps. A power of two, because what
122/// reads it transforms it, and long enough that the lowest band the editor
123/// draws (20 Hz) has a whole cycle in the window at any rate we open.
124const TAP_SAMPLES: usize = 2048;
125
126impl Audio {
127 /// Whether the device has played everything there will ever be, i.e. the
128 /// audio clock is about to stop meaning anything.
129 fn played_out(&self, position: i64) -> bool {
130 self.fed_all.load(Ordering::Acquire)
131 && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed)
132 }
133
134 /// Keeps the newest [`TAP_SAMPLES`] of what was just queued, downmixed to
135 /// mono. Called from the feeder only, once per accepted write.
136 fn note_tap(&self, accepted: &[f32]) {
137 let channels = self.channels.max(1) as usize;
138 let mut tap = self.tap.lock().unwrap();
139 // Only the tail can survive anyway: a big write replaces the window
140 // outright rather than being summed into it and then thrown away.
141 let from = accepted.len().saturating_sub(TAP_SAMPLES * channels);
142 for frame in accepted[from..].chunks_exact(channels) {
143 tap.push(frame.iter().sum::<f32>() / channels as f32);
144 }
145 let over = tap.len().saturating_sub(TAP_SAMPLES);
146 tap.drain(..over);
147 }
148
149 /// Starts a feeder for the current epoch, draining `rx` into the device.
150 /// `false` if the thread would not start, i.e. nothing will ever be fed.
151 fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool {
152 self.spawn_feeder_deferred(move || Some(rx))
153 }
154
155 /// As [`spawn_feeder`](Self::spawn_feeder), but the *stream* is opened on
156 /// the feeder too: `open` runs on that thread, so nothing here touches the
157 /// disk and the caller pays a thread spawn instead of a demux -- seconds off
158 /// a cold cache on a big film, which is what a seek used to cost the UI
159 /// thread ([`crate::DecodeSession::open_worker_deferred`] is the picture's
160 /// half of the same move).
161 ///
162 /// The price is the same one: there is no [`crate::audio::AudioMeta`] to
163 /// hand back and no synchronous answer to "will anything play". `None` from
164 /// `open` -- a silent timeline, a source that will not open -- is a feeder
165 /// with nothing to feed, which ends exactly as a played-out stream does and
166 /// hands the clock to wall time ([`tick`](PlaybackSession::tick)).
167 ///
168 /// The epoch is captured *here*, at the seek, not when the open returns: a
169 /// scrub abandons opens by the dozen and every one of them must still be
170 /// the stale stream it was started as, however late it lands.
171 fn spawn_feeder_deferred(
172 &self,
173 open: impl FnOnce() -> Option<Receiver<AudioChunk>> + Send + 'static,
174 ) -> bool {
175 let me = self.clone();
176 let epoch = self.epoch.load(Ordering::Acquire);
177 thread::Builder::new()
178 .name("audio-feed".into())
179 .spawn(move || {
180 // Superseded before this thread was even scheduled: do not open
181 // anything at all. A scrub leaves all but the last one here.
182 if me.epoch.load(Ordering::Acquire) != epoch {
183 return;
184 }
185 if let Some(rx) = open() {
186 feed(rx, &me, epoch);
187 }
188 // Only the current feeder gets to declare the end of the audio:
189 // a superseded one is finished, the stream is not.
190 if me.epoch.load(Ordering::Acquire) == epoch {
191 me.fed_all.store(true, Ordering::Release);
192 }
193 })
194 .is_ok()
195 }
196}
197
198/// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`].
199pub struct PlaybackSession {
200 /// The *timeline's* parameters, not any one file's: its frame rate and codec
201 /// come from source 0 and are what every other source is held to, while
202 /// `width`/`height` are the **project resolution** -- source 0's picture to
203 /// begin with, and whatever [`PlaybackSession::set_resolution`] or a saved
204 /// `resolution` line makes it after that. Every clip is composed onto it, so
205 /// a file of another size is a placed picture rather than a refusal.
206 meta: VideoMeta,
207 /// Source 0's own picture, kept from the open: the project resolution
208 /// starts here, and a caller offering sizes to pick from needs the media's
209 /// own among them or a project moved off it could never come back.
210 native: (u32, u32),
211 /// ...and the scaffolding source's own frame rate, kept for exactly that
212 /// reason: the project rate starts here, and the list a caller offers rates
213 /// from needs the media's own on it or a project moved off it has no way
214 /// back ([`PlaybackSession::set_frame_rate`] is not an undo step either).
215 native_fps: f64,
216 frames: Receiver<Frame>,
217 /// The current decode worker.
218 worker: Worker,
219 /// What that worker opened -- hardware, software, a still, a gap -- written
220 /// by the worker itself and read by [`decode_backend`](Self::decode_backend).
221 /// Replaced with the stream at every seek, so it always describes the
222 /// pictures currently arriving and never the clip before them.
223 backend: BackendCell,
224 /// Workers cancelled by a seek or a clip change, waiting to be reaped.
225 /// Joining one inline costs whatever VA-API init it is still inside (98 ms
226 /// measured worst case), which is a visible hitch on the caller's thread;
227 /// parking it here instead makes that free, and [`retire`] drops the ones
228 /// that have already returned every time it adds another.
229 ///
230 /// Never a leak, and that is the invariant: everything in here is joined
231 /// when the session drops (`Vec<Worker>`'s own drop does it, one
232 /// [`Worker::drop`] each), so no decode worker can outlive the session and
233 /// meet Mesa's `atexit` handlers from inside libva.
234 ///
235 /// [`retire`]: PlaybackSession::retire
236 retired: Vec<Worker>,
237 clock: PlaybackClock,
238 audio: Option<Audio>,
239 /// Why this timeline is silent, when the file itself is not: an audio track
240 /// we cannot decode is a session that plays perfectly and says nothing about
241 /// it otherwise. `None` for a file that has usable audio *and* for one that
242 /// has none at all, which is not a surprise worth a notice.
243 audio_disabled: Option<String>,
244 /// The edit list. Everything a caller says in seconds is a *timeline*
245 /// position; only this maps it onto the file.
246 project: Project,
247 /// How many frames each source actually holds, indexed exactly as
248 /// [`Project::sources`] is and grown with it. The project itself does not
249 /// know -- a clip names a source by index and carries its own range -- and
250 /// [`Self::trim_clip`] is the one edit that could ask for frames past the
251 /// end of a file, which is a save that would not open again
252 /// ([`Self::open_project`] refuses one by name). Append-only for
253 /// `sources`'s reason: an index handed out stays valid, undone import or
254 /// not -- with the single exception `sources` itself has,
255 /// [`Self::remove_source`], which takes the same entry out of both.
256 counts: Vec<u32>,
257 /// What each source's own frame rate is against this timeline's, indexed
258 /// and grown exactly as [`Self::counts`] is (and shortened with it by
259 /// [`Self::remove_source`]). [`Rate::REAL_TIME`] for a file shot at the
260 /// timeline's rate -- and for a still and a song, which have no rate of
261 /// their own -- so a single-rate project converts nothing anywhere.
262 ///
263 /// A clip counts *timeline* frames ([`Rate`]); this is the one thing that
264 /// knows which frames of the file those are, and only
265 /// [`start_span`](Self::start_span) and [`try_frame`](Self::try_frame) ask.
266 rates: Vec<Rate>,
267 /// The rate of the source the current worker is decoding, kept beside
268 /// [`Self::span`] because the frames coming back are numbered in *its*
269 /// file's frames and nothing else can put them back on the timeline.
270 span_rate: Rate,
271 /// What the current video worker was opened for: where it sits on the
272 /// timeline, how long it runs, and which source frame it started at --
273 /// together they rewrite a source frame index into a timeline one. Not a
274 /// clip index: a `split` cuts the clip under a running worker, and only the
275 /// mapping survives that. A span with no source is a *gap*, and the worker
276 /// feeding it emits black frames indexed from zero.
277 ///
278 /// `None` is the *emptied* timeline -- no clip on any lane, so there is no
279 /// stretch to be inside of. It is a state, not a failure: the picture is
280 /// black ([`start_span`](Self::start_span) feeds one black frame for it),
281 /// the sound is silence, the duration is zero, and placing anything reseeks
282 /// straight back out of it.
283 span: Option<Span>,
284 /// The last clip has been played out; see [`PlaybackSession::is_eos`].
285 eos: bool,
286 /// The mix the running mixer is reading, when there is one: what lets a
287 /// fader and the master ceiling move without rebuilding the audio pipeline
288 /// at all ([`crate::audio::MixControls`]). `None` for a timeline that is
289 /// not mixed -- one audio lane at unity with the limiter off, which is the
290 /// bit-exact single-stream path -- and the first move off that reopens the
291 /// stream once, mixed, and lives from there.
292 mix: Option<Arc<crate::audio::MixControls>>,
293 /// An audio stream has been started and has not yet played a sample: the
294 /// window [`tick`](Self::tick) holds the clock still through, so the silence
295 /// of a restart is never counted as timeline time. See
296 /// [`Audio::content_at`].
297 priming: bool,
298}
299
300/// What an edit dirtied -- which half of the pipeline has to be rebuilt for the
301/// change to be seen or heard, and, far more to the point, which half must not
302/// be.
303///
304/// Rebuilding a half is expensive and *audible*: the video worker costs a
305/// decoder open (98 ms of VA-API init, worst case, measured) and the audio one
306/// costs a flush, a re-open and a hole in the sound. A grade changes no sample
307/// and a fader changes no picture, so neither may pay the other's price -- that
308/// is the whole of this type.
309#[derive(Clone, Copy, PartialEq, Eq, Debug)]
310enum Dirty {
311 /// The picture only: a grade, a fit policy, the project resolution. The
312 /// sound keeps playing, untouched, and the clock never moves.
313 Picture,
314 /// The sound only: a clip's equalizer. The picture keeps playing.
315 Sound,
316 /// The timeline itself -- what is where, how long, how fast. Both halves
317 /// are rebuilt, because both are decoding the wrong thing.
318 Both,
319}
320
321/// What an import is held to, off a timeline that is already up: the sources
322/// its sound has to agree with and the meta its rate is read against. Owned and
323/// `Send`, so the check itself can run on a worker with no session in reach --
324/// which is the whole point ([`PlaybackSession::probe_import`]).
325#[derive(Clone, Debug, PartialEq)]
326pub struct ImportGate {
327 sources: Vec<Source>,
328 timeline: VideoMeta,
329}
330
331/// A file read and accepted, waiting to be registered: what
332/// [`PlaybackSession::probe_import`] found and
333/// [`PlaybackSession::import_probed`] pushes. Carries the gate it was decided
334/// against, so a timeline that moved under it can be noticed rather than
335/// trusted.
336#[derive(Clone, Debug)]
337pub struct ImportProbe {
338 gate: ImportGate,
339 meta: VideoMeta,
340 rate: Rate,
341}
342
343impl PlaybackSession {
344 /// Opens `path` and starts both decode workers. Only video failure is fatal:
345 /// a file we cannot hear is still a file we can watch.
346 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {
347 let path = path.as_ref().to_path_buf();
348 // A timeline is normally scaffolded from source 0's picture -- its size,
349 // its frame rate, its clock. A song has none of that, so it scaffolds
350 // the *canvas* instead and its own sound keeps the clock: an audio-only
351 // project is a project like any other, it simply plays black.
352 if crate::is_audio(&path) {
353 return Self::open_audio_only(&path);
354 }
355 // A still is the other source with no timeline in it: it has a picture
356 // (which becomes the canvas) but no rate and no length, so it too
357 // scaffolds rather than describes.
358 if crate::is_image(&path) {
359 return Self::open_image_only(&path);
360 }
361 // `open_worker` rather than `open` purely for the worker handle: the
362 // field has to exist from the start for the first seek to use it.
363 // Ungraded: a file just opened has one clip per lane and nothing has
364 // graded it yet. Every later span is opened by `start_span`, which asks
365 // the project.
366 // Passthrough: a freshly opened file *is* the project resolution, so
367 // there is nothing to place it on. Every later span goes through
368 // `start_span`, which builds the canvas from the project.
369 let (meta, stream) = DecodeSession::open_worker(
370 &path,
371 0,
372 u32::MAX,
373 ColorParams::default(),
374 Composer::passthrough(),
375 // The default rendition: a file just opened is a project nobody has
376 // picked one for, exactly as it is a project nobody has graded.
377 crate::tonemap::Preset::default(),
378 )?;
379 // A file is opened on its first audio stream, like `Project::single`
380 // names it: nothing has picked one yet.
381 let (audio, audio_disabled) = open_audio(&path, 0);
382 let source = match audio {
383 Some(_) => ClockSource::Audio,
384 None => ClockSource::Wall,
385 };
386 // One clip per lane covering the file, so timeline == source until the
387 // first edit -- and the range opened above is exactly that clip's.
388 let project = Project::single(&path, meta.frame_count);
389 let span = project.composite_span_at(0);
390 Ok(Self {
391 meta,
392 native: (meta.width, meta.height),
393 native_fps: meta.frame_rate,
394 frames: stream.frames,
395 worker: stream.worker,
396 backend: stream.backend,
397 retired: Vec::new(),
398 clock: PlaybackClock::new(source),
399 audio,
400 audio_disabled,
401 project,
402 counts: vec![meta.frame_count],
403 // Source 0 *is* the timeline's rate: it defined it.
404 rates: vec![Rate::REAL_TIME],
405 span_rate: Rate::REAL_TIME,
406 span,
407 eos: false,
408 mix: None,
409 priming: false,
410 })
411 }
412
413 /// Opens `path` into the **library alone**: everything
414 /// [`open`](Self::open) scaffolds from it -- the resolution, the frame
415 /// rate, the clock, the source entry and its length -- over an *empty*
416 /// timeline. What an import into a window that has no session yet makes,
417 /// since an import registers a source and never places a clip
418 /// ([`import`](Self::import)); the file reaches a lane when it is dragged
419 /// there.
420 ///
421 /// Nothing to undo, like the import it stands in for: the lanes start
422 /// empty rather than being emptied, so no snapshot is pushed.
423 pub fn open_library(path: impl AsRef<Path>) -> crate::Result<Self> {
424 let mut session = Self::open(path)?;
425 // The pair of lanes an opened file comes up with (`Project::single`,
426 // `open_audio_only`), emptied -- the source list and so the noted
427 // counts are carried over untouched, which is what keeps a library row
428 // placeable at its full length.
429 session.project = Project::from_parts(
430 session.project.sources().to_vec(),
431 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, Vec::new())],
432 Vec::new(),
433 Vec::new(),
434 )?;
435 // Onto the emptied mapping: black picture, silence, zero duration.
436 session.seek(0.);
437 Ok(session)
438 }
439
440 /// Opens a standalone audio file ([`crate::is_audio`]) as a timeline of its
441 /// own: one clip on `A1`, nothing on the video lane, and a picture that is
442 /// the black of an uncovered canvas ([`AUDIO_ONLY_CANVAS`]) for as long as
443 /// the song runs. Its own sound keeps the clock, exactly as a video's does.
444 ///
445 /// Refused when the file has no sound to time it by: a source with neither a
446 /// picture nor a playable length is not a timeline, and that is what
447 /// [`audio_frames`] answers -- the *device* is a different question, and a
448 /// machine without one opens this like any other session, silently.
449 fn open_audio_only(path: &Path) -> crate::Result<Self> {
450 let (width, height, frame_rate) = AUDIO_ONLY_CANVAS;
451 let meta = VideoMeta {
452 width,
453 height,
454 frame_rate,
455 // Rounded up to whole frames, which is the only frame count a
456 // source with no picture has -- the same length `import_audio`
457 // gives a song joining a timeline of video. The demuxer's words are
458 // named with the file, since this is the door a file that is not
459 // really audio at all comes to.
460 frame_count: audio_frames(path, frame_rate)
461 .map_err(|e| format!("{}: {e}", path.display()))?,
462 codec: Codec::H264,
463 // A canvas this engine drew itself, not a stream that was read:
464 // the default description is what it is drawn in.
465 color: ColorDescription::default(),
466 };
467 let (audio, audio_disabled) = open_audio(path, 0);
468 // Through `from_parts` rather than `Project::single`, which is the
469 // *video* open's pair of grouped clips: here there is no picture to
470 // group the sound with, so the video lane starts empty.
471 let clip = Clip {
472 start: 0,
473 in_frame: 0,
474 out_frame: meta.frame_count,
475 source: 0,
476 link: None,
477 eq: None,
478 color: None,
479 fit: FitPolicy::default(),
480 speed: Speed::NORMAL,
481 };
482 let project = Project::from_parts(
483 vec![Source::new(path, 0)],
484 vec![(LaneKind::Video, Vec::new()), (LaneKind::Audio, vec![clip])],
485 Vec::new(),
486 Vec::new(),
487 )?;
488 // Every frame of this timeline is a gap, since no video lane covers
489 // anything: `composite_span_at` says so and the black worker
490 // `start_span` would open is opened here instead, for the reason `open`
491 // opens its decoder inline -- the field has to exist for the first seek.
492 let span = project.composite_span_at(0);
493 let stream = DecodeSession::open_black(width, height, span.map_or(1, |s| s.len));
494 Ok(Self {
495 meta,
496 native: (width, height),
497 native_fps: frame_rate,
498 frames: stream.frames,
499 worker: stream.worker,
500 backend: stream.backend,
501 retired: Vec::new(),
502 // The song keeps the clock, as a video's own sound does -- and wall
503 // time keeps it on a machine with no device, where the picture
504 // (black) still has to move at some rate.
505 clock: PlaybackClock::new(match audio {
506 Some(_) => ClockSource::Audio,
507 None => ClockSource::Wall,
508 }),
509 audio,
510 audio_disabled,
511 project,
512 counts: vec![meta.frame_count],
513 // Source 0 *is* the timeline's rate: it defined it.
514 rates: vec![Rate::REAL_TIME],
515 span_rate: Rate::REAL_TIME,
516 span,
517 eos: false,
518 mix: None,
519 priming: false,
520 })
521 }
522
523 /// Opens a still image ([`crate::is_image`]) as a timeline of its own: one
524 /// clip on `V1`, [`IMAGE_PLACE_SECS`] long, over silence. The *canvas* is
525 /// the image's own picture -- unlike a song, a still has one, and inventing
526 /// a 1080p canvas around a 640x360 PNG would letterbox it against nothing.
527 /// The frame rate is [`IMAGE_ONLY_RATE`], for the reason an audio-only
528 /// timeline has one at all: nothing was shot on it.
529 ///
530 /// Wall time keeps the clock, as it does for any silent source.
531 fn open_image_only(path: &Path) -> crate::Result<Self> {
532 // Decoded here rather than probed: this is the door a `.png` that is
533 // not one comes to, and the picture is wanted a line later anyway.
534 let still = crate::decode::Still::open(path)?;
535 let meta = VideoMeta {
536 width: still.width,
537 height: still.height,
538 frame_rate: IMAGE_ONLY_RATE,
539 // Its length is the wall a trim is held to, exactly as a song's
540 // playing time is -- see [`image_frames`].
541 frame_count: image_frames(IMAGE_ONLY_RATE),
542 codec: Codec::H264,
543 color: ColorDescription::default(),
544 };
545 let clip = Clip {
546 start: 0,
547 in_frame: 0,
548 out_frame: place_frames(meta.frame_count, IMAGE_ONLY_RATE),
549 source: 0,
550 link: None,
551 eq: None,
552 color: None,
553 fit: FitPolicy::default(),
554 speed: Speed::NORMAL,
555 };
556 // No group and no audio clip: a still is silent, and a clip on `A1`
557 // playing from a PNG is a source the audio worker cannot open.
558 let project = Project::from_parts(
559 vec![Source::new(path, 0)],
560 vec![(LaneKind::Video, vec![clip]), (LaneKind::Audio, Vec::new())],
561 Vec::new(),
562 Vec::new(),
563 )?;
564 let span = project.composite_span_at(0);
565 // The placeholder the first seek supersedes, opened here for `open`'s
566 // reason: the field has to exist before anything can seek.
567 let stream = DecodeSession::open_still(
568 path,
569 0,
570 span.map_or(1, |s| s.len),
571 ColorParams::default(),
572 Composer::passthrough(),
573 )?;
574 Ok(Self {
575 meta,
576 native: (meta.width, meta.height),
577 native_fps: IMAGE_ONLY_RATE,
578 frames: stream.frames,
579 worker: stream.worker,
580 backend: stream.backend,
581 retired: Vec::new(),
582 clock: PlaybackClock::new(ClockSource::Wall),
583 audio: None,
584 audio_disabled: None,
585 project,
586 counts: vec![meta.frame_count],
587 // Source 0 *is* the timeline's rate: it defined it.
588 rates: vec![Rate::REAL_TIME],
589 span_rate: Rate::REAL_TIME,
590 span,
591 eos: false,
592 mix: None,
593 priming: false,
594 })
595 }
596
597 /// Opens a project file written by [`save_project`](Self::save_project):
598 /// the whole timeline, restored to where its playhead stood, paused like
599 /// [`open`](Self::open).
600 ///
601 /// A *new* session rather than a reload of this one, so a load that fails
602 /// leaves the caller's current session untouched -- atomic by
603 /// construction. Every named file is opened and checked here: the
604 /// *scaffolding* source -- the first that is not a still, since a picture
605 /// carries no rate -- defines the timeline exactly as `open` does, every
606 /// other source has to match it the way [`import`](Self::import) demands
607 /// (a save renumbers, so which index that is says nothing), and every clip
608 /// has to still be inside the file it plays from. A source that vanished or
609 /// shrank since the save is a refusal naming it, not a silently shorter
610 /// timeline -- the disappearing-file tolerance elsewhere in this type
611 /// applies only *after* a project has loaded.
612 ///
613 /// The undo history is not saved: `undo` is `false` on a fresh load.
614 pub fn open_project(path: &Path) -> crate::Result<Self> {
615 let doc = crate::edith::load(path)?;
616 // *Which* source scaffolds it: the first that is not a still, and index
617 // 0 only when there is no other. A still defines no frame rate -- it is
618 // given [`IMAGE_ONLY_RATE`] -- so scaffolding a timeline of 24 fps
619 // footage off a PNG that a save happened to renumber to index 0
620 // (`Project::without_orphan_sources` numbers by first use, and a
621 // library removal moves indexes too) reads the timeline as 30 fps and
622 // then refuses every file on it for not matching. The rule this and
623 // [`audio_source_of`] share: nothing may assume what source 0 *is*.
624 //
625 // A v9 file says what rate it was cut at, and that answer beats the
626 // scaffold's *where the scaffold has none to give*: a still and a song
627 // are both given a made-up rate (`IMAGE_ONLY_RATE`,
628 // `AUDIO_ONLY_CANVAS`), so a timeline of nothing but those used to come
629 // back at 30 fps however it was cut. A scaffold with a picture keeps
630 // defining the timeline as it always did -- it is the file every clip
631 // on the lane was conformed to, and the two agree by construction.
632 let saved_fps = doc.fps.filter(|f| f.is_finite() && *f > 0.0);
633 let scaffold = doc
634 .sources
635 .iter()
636 .position(|s| !crate::is_image(&s.path))
637 .unwrap_or(0);
638 // Owned: the sources move into the `Project` below, and the device is
639 // opened after that (see the comment there).
640 let first = doc
641 .sources
642 .get(scaffold)
643 .cloned()
644 .ok_or("the project names no sources")?;
645 // The scaffolding source both defines the timeline and is what the
646 // playhead's first picture comes from, so it is opened for playback
647 // rather than merely probed.
648 // One value, not two locals: everything below this line can refuse, and
649 // locals drop in reverse declaration order -- a bare worker would join
650 // its decode thread while the receiver next to it was still holding
651 // that thread parked in `send`, which is a hang (see [`FrameStream`]).
652 // Ungraded, and superseded before a frame of it is shown: the `seek` at
653 // the end of this function reopens the playhead's span through
654 // `start_span`, which is where a saved grade reaches the picture.
655 // ...unless it has no picture to open: a project whose source 0 is a
656 // song scaffolds the canvas the same way a fresh audio-only open does
657 // ([`open_audio_only`](Self::open_audio_only)), and the placeholder
658 // black stream is superseded by the `seek` at the end of this function
659 // like every other worker opened here.
660 let (mut meta, stream) = match crate::is_audio(&first.path) {
661 true => {
662 let (width, height, canvas_fps) = AUDIO_ONLY_CANVAS;
663 let frame_rate = saved_fps.unwrap_or(canvas_fps);
664 let meta = VideoMeta {
665 width,
666 height,
667 frame_rate,
668 frame_count: audio_frames(&first.path, frame_rate)
669 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
670 codec: Codec::H264,
671 color: ColorDescription::default(),
672 };
673 (meta, DecodeSession::open_black(width, height, 1))
674 }
675 // ...and a still scaffolds its own picture as the canvas, exactly
676 // as a fresh `open_image_only` does, with the same placeholder
677 // stream the `seek` at the end supersedes.
678 false if crate::is_image(&first.path) => {
679 let still = crate::decode::Still::open(&first.path)
680 .map_err(|e| format!("source {}: {e}", first.path.display()))?;
681 let frame_rate = saved_fps.unwrap_or(IMAGE_ONLY_RATE);
682 let meta = VideoMeta {
683 width: still.width,
684 height: still.height,
685 frame_rate,
686 frame_count: image_frames(frame_rate),
687 codec: Codec::H264,
688 color: ColorDescription::default(),
689 };
690 let stream = DecodeSession::open_still(
691 &first.path,
692 0,
693 1,
694 ColorParams::default(),
695 Composer::passthrough(),
696 )?;
697 (meta, stream)
698 }
699 false => DecodeSession::open_worker(
700 &first.path,
701 0,
702 u32::MAX,
703 ColorParams::default(),
704 Composer::passthrough(),
705 // The saved rendition, from the document rather than from the
706 // project (which is built below): this placeholder is what the
707 // window shows until the `seek` at the end reopens the span.
708 doc.tone,
709 )
710 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
711 };
712 // The project's own resolution, which is source 0's picture unless the
713 // file says otherwise -- every dialect before v7 had no way to say it,
714 // and that default is exactly what those projects meant.
715 let native = (meta.width, meta.height);
716 if let Some((width, height)) = doc.resolution {
717 meta.width = width;
718 meta.height = height;
719 }
720 // ...and the project's own *rate*, which is the scaffold's unless the
721 // file says otherwise. The two made-up rates above already took the
722 // saved one (their counts are computed from it); a scaffold with a
723 // picture keeps its own here, so a project cut at a rate nobody picked
724 // is the file it always was -- and one where a rate *was* picked
725 // ([`set_frame_rate`](Self::set_frame_rate)) comes back at it rather
726 // than at the media's, which would leave every clip number counted in
727 // frames the timeline no longer has.
728 let native_fps = match crate::is_audio(&first.path) {
729 true => AUDIO_ONLY_CANVAS.2,
730 false if crate::is_image(&first.path) => IMAGE_ONLY_RATE,
731 false => meta.frame_rate,
732 };
733 if let Some(fps) = saved_fps {
734 meta.frame_rate = fps;
735 }
736 // A song and a still have no rate of their own to be conformed from:
737 // their length above was counted in the timeline's frames already,
738 // whatever those are. A file with pictures is read through [`Rate`] like
739 // any other source when the project is cut at another rate.
740 let made_up = crate::is_audio(&first.path) || crate::is_image(&first.path);
741 let scaffold_rate = match made_up || native_fps == meta.frame_rate {
742 true => Rate::REAL_TIME,
743 false => Rate::from_fps(native_fps, meta.frame_rate)
744 .map_err(|e| format!("source {}: {e}", first.path.display()))?,
745 };
746 let first_audio = first_audio_of(&doc.sources)?;
747
748 // In source order, with the scaffold's own count in its own slot: the
749 // clip check below indexes this list by source, so it must line up with
750 // `doc.sources` whichever entry the scaffolding came from.
751 let mut counts = Vec::with_capacity(doc.sources.len());
752 // Beside it, one entry per source, grown at every `push` below: the
753 // scaffold defines the rate, so it is read frame for frame; every other
754 // one is however long it is *in this timeline's frames*, which is the
755 // length `import` noted for it and the wall the clip check below holds
756 // it to.
757 let mut rates = Vec::with_capacity(doc.sources.len());
758 for (i, source) in doc.sources.iter().enumerate() {
759 if i == scaffold {
760 counts.push(scaffold_rate.timeline_at(meta.frame_count));
761 rates.push(scaffold_rate);
762 continue;
763 }
764 // A still has neither a rate to match nor a track to match with:
765 // its length is the one it is held to, recomputed exactly as the
766 // import that first noted it did ([`image_frames`]), which is what
767 // makes the clip check below meaningful on a reload.
768 if crate::is_image(&source.path) {
769 crate::decode::image_size(&source.path)
770 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
771 counts.push(image_frames(meta.frame_rate));
772 rates.push(Rate::REAL_TIME);
773 continue;
774 }
775 // A source with no picture is checked on what it does have, and
776 // its length is its playing time -- the same two answers `import`
777 // gave it when it first joined the timeline.
778 if crate::is_audio(&source.path) {
779 audio_matches(source, &first_audio)
780 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
781 counts.push(audio_frames(&source.path, meta.frame_rate)?);
782 rates.push(Rate::REAL_TIME);
783 continue;
784 }
785 let (other, _) = Demuxer::open(&source.path)
786 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
787 let rate = matches_timeline(source, &other, &meta, &first_audio)
788 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
789 counts.push(rate.timeline_at(other.frame_count));
790 rates.push(rate);
791 }
792 // The video lane can only play files that have pictures. Hand-written
793 // (or hand-edited) project files are the one door this can come in
794 // through, so it is refused by name here rather than becoming a clip
795 // that decodes to nothing.
796 for (kind, clip) in doc
797 .lanes
798 .iter()
799 .flat_map(|(kind, clips)| clips.iter().map(move |clip| (*kind, clip)))
800 {
801 let path = &doc.sources[clip.source].path;
802 if kind == LaneKind::Video && crate::is_audio(path) {
803 return Err(format!(
804 "{} has no picture: it can only play on an audio lane",
805 path.display()
806 )
807 .into());
808 }
809 // ...and the mirror of it: a still is silent, so a clip playing one
810 // on an audio lane is a segment the audio worker would open a PNG
811 // for. Refused by name here, which is the one door it can arrive
812 // through (`place_stream_at` never puts one there).
813 if kind == LaneKind::Audio && crate::is_image(path) {
814 return Err(format!(
815 "{} is a still image: it can only play on a video lane",
816 path.display()
817 )
818 .into());
819 }
820 }
821 for (i, clip) in doc.lanes.iter().flat_map(|(_, clips)| clips).enumerate() {
822 if clip.out_frame > counts[clip.source] {
823 return Err(format!(
824 "clip {i} ends at frame {} but {} has {} frames",
825 clip.out_frame,
826 doc.sources[clip.source].path.display(),
827 counts[clip.source]
828 )
829 .into());
830 }
831 }
832
833 let playhead = doc.playhead;
834 // The subtitle files are read here rather than in the parser: a
835 // `.edith` names them and holds no cues. One that has gone missing, or
836 // whose track is a codec of pictures, comes back listed and refused by
837 // name ([`crate::subtitle::open_all`]) -- a project does not stop
838 // opening over a subtitle, and a re-save does not lose the row.
839 //
840 // All of them in one call, in saved order, because a file is walked
841 // whole to reach one track: a film whose project names many of its
842 // tracks is one walk here rather than one per row.
843 let subtitles = crate::subtitle::open_all(&doc.subtitles);
844 let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?
845 .with_mix(&doc.gains, doc.limiter)
846 .with_tone(doc.tone)
847 .with_subtitles(subtitles);
848 let span = project.composite_span_at(0);
849 // Last, because it is the one thing here that cannot be taken back: the
850 // feeder thread outlives the `Audio` value (it holds its own clones) and
851 // only a session's `drop` retires it, so a refusal above this line would
852 // leave a PipeWire stream and a thread behind for a project that never
853 // opened. Nothing before it needs the device.
854 //
855 // On the source the timeline's *sound* is defined by, which is the
856 // scaffold unless that one is a still ([`audio_source_of`]): opening a
857 // PNG as the device is a session with no audio at all, however many
858 // clips with sound are on its lanes.
859 let (audio, audio_disabled) = match audio_source_of(project.sources()) {
860 Some(source) => open_audio(&source.path, source.audio_stream),
861 None => (None, None),
862 };
863 let mut session = Self {
864 meta,
865 native,
866 native_fps,
867 frames: stream.frames,
868 worker: stream.worker,
869 backend: stream.backend,
870 retired: Vec::new(),
871 clock: PlaybackClock::new(match audio {
872 Some(_) => ClockSource::Audio,
873 None => ClockSource::Wall,
874 }),
875 audio,
876 audio_disabled,
877 project,
878 counts,
879 rates,
880 span_rate: Rate::REAL_TIME,
881 span,
882 eos: false,
883 mix: None,
884 priming: false,
885 };
886 // The scaffolding above opened source 0 from its first frame and the
887 // whole of its audio; this puts both onto the clip the playhead is
888 // actually in -- a seek replaces the decoder and supersedes the audio
889 // worker by epoch, exactly as it does after an edit. It also clamps,
890 // so a playhead past a hand-shortened timeline lands on the last frame.
891 session.seek(f64::from(playhead) / meta.frame_rate);
892 Ok(session)
893 }
894
895 pub fn meta(&self) -> &VideoMeta {
896 &self.meta
897 }
898
899 /// What the pictures now arriving are being decoded by: the clip under the
900 /// playhead, since one video worker feeds the composite at a time. An
901 /// atomic load -- a front-end may ask it every repaint -- and it is what
902 /// *opened*, so a clip whose hardware session fell back to software reads
903 /// [`Backend::Software`] from the frame that fallback happened.
904 pub fn decode_backend(&self) -> Backend {
905 self.backend.get()
906 }
907
908 /// What an export of this timeline would encode the *sound* with, before
909 /// one is started: the copy an mp4 normally makes, or the software encoder
910 /// the format (or an equalized lane) forces. Pure -- no probe, no file
911 /// opened -- so a card may ask it per repaint; the picture's half costs a
912 /// plugin open and lives in [`crate::export::planned_video`].
913 pub fn planned_audio(&self, format: crate::export::Format) -> &'static str {
914 crate::export::planned_audio(&self.project, format)
915 }
916
917 /// The timeline an export started right now would be run against, owned:
918 /// what lets a front-end ask [`crate::export::planned_seats`] what that
919 /// export would open *off* its render thread, which is the only way to ask
920 /// a question that opens files. The very snapshot
921 /// [`export_to_with`](Self::export_to_with) hands the worker, so the answer
922 /// is about the export that would really start.
923 pub fn export_snapshot(&self) -> (crate::project::Project, VideoMeta) {
924 (self.project.export_snapshot(), self.meta)
925 }
926
927 /// What an export would do about the tracks at `picks` --
928 /// [`crate::export::planned_subtitles`], asked of the project a front-end is
929 /// holding, and pure for the same reason. `picks` is any run of rows of
930 /// [`subtitles`](Self::subtitles): the whole
931 /// [`ExportSettings::subtitles`](crate::export::ExportSettings::subtitles)
932 /// list a card is about to send (`picks.iter().copied()`) as much as a
933 /// single `Some(row)`.
934 pub fn planned_subtitles(
935 &self,
936 format: crate::export::Format,
937 picks: impl IntoIterator<Item = usize>,
938 ) -> String {
939 crate::export::planned_subtitles(&self.project, format, picks)
940 }
941
942 /// Where the cues of the track at `pick` land on *this* timeline --
943 /// [`crate::export::timeline_cues`], the very map an export writes the file
944 /// with, so a front-end that draws these draws what the file will say. On a
945 /// rippled or cut timeline that is the whole point: an embedded track rides
946 /// the spans that still play it, and a standalone `.srt` keeps the
947 /// timeline's own clock, clipped to its length.
948 ///
949 /// Empty for a row that is not there and for a track that could not be read.
950 /// Pure and file-free, so it may be asked per repaint; the cost is a walk of
951 /// the spans and of the cues.
952 pub fn timeline_cues(&self, pick: usize) -> Vec<crate::subtitle::Cue> {
953 self.project
954 .subtitles()
955 .get(pick)
956 .map_or_else(Vec::new, |t| {
957 crate::export::timeline_cues(&self.project, t, self.meta.frame_rate)
958 })
959 }
960
961 /// Why the sound's rate is not a choice for this timeline in this format --
962 /// [`crate::export::audio_rate_refusal`], asked of the project a front-end
963 /// is holding, and pure for the same reason.
964 pub fn audio_rate_refusal(&self, format: crate::export::Format) -> Option<&'static str> {
965 crate::export::audio_rate_refusal(&self.project, format)
966 }
967
968 /// Why this session plays silent although the file has sound -- an audio
969 /// track in a codec we cannot decode, or one the decoder refused. `None`
970 /// when there is audio, and for a file that never had any. A front-end
971 /// shows it once, at open: without it the whole thing is a stderr line.
972 pub fn audio_disabled_reason(&self) -> Option<&str> {
973 self.audio_disabled.as_deref()
974 }
975
976 /// The files this timeline plays from, index 0 first -- a caller needs it
977 /// to name an export or a window after the media rather than the project.
978 pub fn sources(&self) -> &[Source] {
979 self.project.sources()
980 }
981
982 /// The subtitle tracks on this timeline, in the order they were added: what
983 /// a front-end lists and what [`save_project`](Self::save_project) writes.
984 /// A track that could not be read is *in* this list, saying why
985 /// ([`crate::subtitle::SubtitleTrack::refused`]) -- listed and skipped, not
986 /// dropped.
987 pub fn subtitles(&self) -> &[crate::subtitle::SubtitleTrack] {
988 self.project.subtitles()
989 }
990
991 /// Adds subtitles from `path`: every subtitle track of a Matroska file, or
992 /// the one track a standalone `.srt`/`.vtt`/`.ass` is. Hands back how many
993 /// were added -- 0 for a file whose tracks are all on the timeline already,
994 /// since importing the same file twice is the same subtitles.
995 ///
996 /// An error only when the file cannot be read *at all*; a track this cannot
997 /// parse is added refused by name, for the reason
998 /// [`crate::subtitle::open`] gives. Nothing else about the timeline moves:
999 /// subtitles are not clips and land on no lane.
1000 pub fn import_subtitles(&mut self, path: &Path) -> crate::Result<usize> {
1001 Ok(self.add_subtitle_tracks(Self::parse_subtitles(path)?))
1002 }
1003
1004 /// The reading half of [`import_subtitles`](Self::import_subtitles), with no
1005 /// session in it: every subtitle track of a Matroska file, or the one track
1006 /// a standalone `.srt`/`.vtt`/`.ass` is, cues and all. Same refusal rule.
1007 ///
1008 /// This is the half that costs -- a walk of the whole container, measured at
1009 /// 210 ms on a 25 GB 35-track file and 1.3 s on a 3 GB one whose pages were
1010 /// cold -- so a front-end runs *this* on its background executor and hands
1011 /// what comes back to [`add_subtitle_tracks`](Self::add_subtitle_tracks),
1012 /// which costs a push. Both doors are this one function, so the import
1013 /// button and the background one cannot drift apart.
1014 pub fn parse_subtitles(path: &Path) -> crate::Result<Vec<crate::subtitle::SubtitleTrack>> {
1015 // The containers that carry subtitle tracks *inside* them: every
1016 // Matroska one ([`crate::demux::is_matroska`], which is where `.mks` --
1017 // the subtitles alone -- comes in) and the mp4 family, whose `tx3g`
1018 // timed text is what an mp4 export of this project's own writes, so a
1019 // file edith wrote is a file edith imports back.
1020 let tracks = match crate::demux::is_matroska(path)
1021 || path.extension().is_some_and(|e| {
1022 matches!(
1023 e.to_string_lossy().to_ascii_lowercase().as_str(),
1024 "mp4" | "m4v" | "mov"
1025 )
1026 }) {
1027 true => crate::subtitle::of_media(path)?,
1028 false => vec![crate::subtitle::open(path, None)],
1029 };
1030 // A standalone file that could not be parsed is a refusal here rather
1031 // than a row nobody asked for: the import is the moment to say so, and
1032 // the load is the moment to keep it.
1033 if let [one] = &tracks[..]
1034 && one.track.is_none()
1035 && let Some(why) = &one.refused
1036 {
1037 return Err(why.clone().into());
1038 }
1039 Ok(tracks)
1040 }
1041
1042 /// Puts tracks already read by [`parse_subtitles`](Self::parse_subtitles)
1043 /// on this timeline, in the order given. Hands back how many actually went
1044 /// on: [`Project::add_subtitles`] drops the ones already here -- same file,
1045 /// same track number -- so 0 is "this file's subtitles are on the timeline
1046 /// already", which is the sentence a front-end says.
1047 ///
1048 /// The whole of what an import costs the thread that calls it, which is why
1049 /// the parse is a separate door: nothing here opens, seeks or decodes.
1050 /// Subtitles are not clips and land on no lane, so nothing playable changes
1051 /// and no undo step is pushed ([`Project::remove_subtitles`] says why).
1052 pub fn add_subtitle_tracks(&mut self, tracks: Vec<crate::subtitle::SubtitleTrack>) -> usize {
1053 tracks
1054 .into_iter()
1055 .filter(|t| self.project.add_subtitles(t))
1056 .count()
1057 }
1058
1059 /// Takes the track at `idx` off this timeline -- the door a subtitle row's
1060 /// own remove goes through, the way [`import_subtitles`](
1061 /// Self::import_subtitles) is the door that puts one on. Refused in
1062 /// [`Project::remove_subtitles`]'s words for a row this timeline does not
1063 /// have.
1064 ///
1065 /// Nothing playable changes and no worker was opened against a cue, so
1066 /// unlike [`remove_source`](Self::remove_source) this does not reseek. Rows
1067 /// past `idx` move down by one: a caller holding a picked row (the export's
1068 /// subtitle pick) has to fix it up or drop it. Not an undo step, for the
1069 /// reason [`Project::remove_subtitles`] gives -- the inverse is a
1070 /// re-import.
1071 pub fn remove_subtitles(&mut self, idx: usize) -> crate::Result<()> {
1072 self.project.remove_subtitles(idx)
1073 }
1074
1075 /// Writes the timeline to `path` as a `.edith`, atomically (see
1076 /// [`crate::edith`]). Sources no clip plays from are left out, and the
1077 /// playhead is saved with it so a reopened project resumes where it stood.
1078 ///
1079 /// Refused, writing nothing, for a session whose library is empty (every
1080 /// row removed, [`Project::remove_source`]): a file naming no source has no
1081 /// timeline in it and [`open_project`](Self::open_project) could only
1082 /// refuse it, so the refusal belongs here, where nothing has been
1083 /// overwritten yet.
1084 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
1085 if self.project.sources().is_empty() {
1086 return Err("this project names no file: there is nothing to save".into());
1087 }
1088 let (sources, lanes, eq, color) = self.project.without_orphan_sources();
1089 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
1090 .min(self.project.timeline_frames().saturating_sub(1));
1091 crate::edith::save(
1092 path,
1093 &sources,
1094 &lanes,
1095 // The lane volumes and the limiter with them: a mix that vanished
1096 // on a reload would be a mix nobody could keep, and both are the
1097 // project's, not this machine's (the monitoring volume is not
1098 // written and never will be).
1099 &self.project.lane_gains(),
1100 // The subtitle tracks with them, by reference: which file the cues
1101 // are in, never the cues (see [`crate::edith`]).
1102 self.project.subtitles(),
1103 &eq,
1104 &color,
1105 (self.meta.width, self.meta.height),
1106 // ...and the rate it was cut at, which nothing else in the file
1107 // says: a timeline of stills and songs used to come back at
1108 // whatever its scaffold implied (`open_project`).
1109 Some(self.meta.frame_rate),
1110 // ...and which rendition its HDR media is watched in, for the same
1111 // reason: a picked look that vanished on a reload is a look nobody
1112 // could keep.
1113 self.project.tone(),
1114 self.project.limiter(),
1115 playhead,
1116 )
1117 }
1118
1119 /// The next decoded frame, its `index` rewritten from a source frame to a
1120 /// *timeline* frame -- the only frame space that leaves the engine, and the
1121 /// one [`PlaybackSession::now`] is in.
1122 ///
1123 /// `None` means "nothing right now": the decoder is behind, or a clip
1124 /// boundary is being reopened -- and *that* now happens entirely on the new
1125 /// worker ([`DecodeSession::open_worker_deferred`]), so it costs this
1126 /// thread a thread spawn and the caller simply keeps showing its last frame
1127 /// for however long the source takes to open (hundreds of milliseconds on a
1128 /// big film, seconds off a cold cache). End of stream is
1129 /// [`PlaybackSession::is_eos`].
1130 pub fn try_frame(&mut self) -> Option<Frame> {
1131 loop {
1132 match self.frames.try_recv() {
1133 Ok(mut frame) => {
1134 // A gap's worker indexes from zero, a decoder's from its in
1135 // point, and the span itself knows which: [`Span::timeline_at`]
1136 // is the *stamp*, and it is the ceil half of the pair whose
1137 // floor half an export encodes with -- so the frame the pump
1138 // is holding at any timeline frame is the very frame the
1139 // export writes there, at every rate
1140 // (`speed_maps_both_ways`). An empty timeline has no span,
1141 // and its one black frame is frame 0. Real time is the
1142 // arithmetic this always did, frame for frame.
1143 // ...through the file's own rate first, which is the ceil
1144 // half of *that* pair: the picture at source frame `i` is
1145 // due at the first timeline-rate frame that shows it, and a
1146 // slower file's picture is therefore held for the frames in
1147 // between. Real time for a gap and for a single-rate
1148 // project, where this is the identity.
1149 frame.index = self.span.map_or(frame.index, |s| {
1150 s.timeline_at(self.span_rate.timeline_at(frame.index))
1151 });
1152 return Some(frame);
1153 }
1154 Err(TryRecvError::Empty) => return None,
1155 // The worker stopped: at the end of its range, or on a decode
1156 // error -- which is why this skips the rest of a broken clip
1157 // rather than stalling on it.
1158 Err(TryRecvError::Disconnected) => {
1159 if !self.next_clip() {
1160 self.eos = true;
1161 return None;
1162 }
1163 }
1164 }
1165 }
1166 }
1167
1168 /// Whether the timeline has been played out: the picture worker ran to the
1169 /// end and there was no next clip. It is exactly that and nothing more,
1170 /// which is what decides who clears it -- **starting a picture does**
1171 /// (`start_picture`), so a seek clears it and so does every edit that
1172 /// rebuilds the picture (`Dirty::Picture`, `Dirty::Both` -- a paste or a
1173 /// placement past the end revives the session, and it has a new picture to
1174 /// show for it).
1175 ///
1176 /// A **sound-only** edit does not (`Dirty::Sound`: an equalizer, a fader):
1177 /// it rebuilds the sound where the playhead stands and starts no picture
1178 /// worker, so the last frame is still the last frame and this is still the
1179 /// end. A front-end's `Ended` therefore survives an EQ tweak made after the
1180 /// timeline ran out -- the parameters are on the project either way, and the
1181 /// next press restarts from the top with them, which is what `Ended` means.
1182 pub fn is_eos(&self) -> bool {
1183 self.eos
1184 }
1185
1186 /// Installs `replacement` as the decode worker, parking the outgoing one in
1187 /// [`retired`](Self::retired) rather than joining it here, and reaping the
1188 /// parked ones that have already returned.
1189 ///
1190 /// The sweep is what bounds the list: every worker in it was cancelled
1191 /// before this ran, and a cancelled worker is out within an access unit
1192 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's
1193 /// worker on this seek and the list stays a handful long. Nothing waits.
1194 fn retire(&mut self, replacement: Worker) {
1195 self.retired
1196 .push(std::mem::replace(&mut self.worker, replacement));
1197 self.retired.retain(|w| !w.is_finished());
1198 }
1199
1200 /// Starts feeding whatever follows the current span on the timeline --
1201 /// another clip, or a gap, which is black frames from a worker that opens no
1202 /// file. `false` past the end. The next timeline frame is derived rather
1203 /// than remembered as a clip index, because a `split` while playing cuts the
1204 /// clip under the running worker and only the mapping stays true.
1205 fn next_clip(&mut self) -> bool {
1206 // No span is the emptied timeline: it was played out the moment its one
1207 // black frame went by, and there is no "next" to walk to.
1208 let next = match self.span {
1209 Some(span) => span.end(),
1210 None => return false,
1211 };
1212 let Some(span) = self.project.composite_span_at(next) else {
1213 return false;
1214 };
1215 // We only get here on a disconnect, so the old worker has already
1216 // returned; cancel anyway, so `retire` treats every path alike.
1217 self.worker.cancel();
1218 self.start_span(Some(span));
1219 true
1220 }
1221
1222 /// Points the video worker at `span`: a decoder over its source range, or a
1223 /// black-frame generator for a gap -- and for `None`, the emptied timeline,
1224 /// which is one frame of black so the viewer shows the nothing that is
1225 /// there rather than the last picture of the clip that was deleted. The old
1226 /// worker must already have been cancelled -- this is the half both `seek`
1227 /// and `next_clip` share.
1228 ///
1229 /// A source that will not open leaves the *span* installed anyway: the
1230 /// timeline still moves, there are simply no more pictures, and the
1231 /// disconnected receiver carries the session on to the next span. For a
1232 /// video that is now the worker's own doing -- it opens the file, so it is
1233 /// the one that finds out -- and nothing on this thread waits to hear it.
1234 fn start_span(&mut self, span: Option<Span>) {
1235 // Which file's frames the worker about to be opened will number its
1236 // pictures in: the span's own source, and real time for a gap, whose
1237 // black worker counts timeline frames already. Set before the open,
1238 // because the open is the first thing that converts with it.
1239 self.span_rate = match span.and_then(|s| s.from) {
1240 Some((source, _)) => self.rates.get(source).copied().unwrap_or(Rate::REAL_TIME),
1241 None => Rate::REAL_TIME,
1242 };
1243 let opened = match span {
1244 // The grade is the composite's at this frame -- the same clip the
1245 // span itself came from -- and it is constant across the span, so
1246 // the worker carries it and every frame it converts wears it.
1247 Some(Span {
1248 start,
1249 from: Some((source, in_frame)),
1250 ..
1251 }) if crate::is_image(&self.project.sources()[source].path) => {
1252 // A still: the same grade and the same canvas as any other
1253 // clip, over a picture decoded once and repeated for the span.
1254 // As many pictures as the span reads *source* frames, so a still
1255 // is numbered like a decoder's output and a speed reaches it
1256 // through the same rewrite (`try_frame`) as any other clip.
1257 DecodeSession::open_still(
1258 &self.project.sources()[source].path,
1259 in_frame,
1260 span.expect("matched above").source_len(),
1261 self.project
1262 .composite_color_at(start)
1263 .copied()
1264 .unwrap_or_default(),
1265 Composer::new(
1266 self.meta.width,
1267 self.meta.height,
1268 self.project.composite_fit_at(start),
1269 ),
1270 )
1271 .inspect_err(|e| eprintln!("timeline frame {start}: image open failed: {e}"))
1272 }
1273 Some(Span {
1274 start,
1275 from: Some((source, in_frame)),
1276 ..
1277 }) => Ok(DecodeSession::open_worker_deferred(
1278 &self.project.sources()[source].path,
1279 // The file's own frames, which is the only place they exist:
1280 // a clip counts the timeline's ([`Rate`]).
1281 self.span_rate.source_at(in_frame),
1282 // Source frames, which a speed makes more (or fewer) than the
1283 // timeline frames the span covers -- and which a file shot at
1284 // another rate makes fewer (or more) again. One past the last
1285 // frame this span shows, not one past its length: at another
1286 // rate those are two different frames.
1287 self.span_rate.source_at(
1288 in_frame + span.expect("matched above").source_len().saturating_sub(1),
1289 ) + 1,
1290 self.project
1291 .composite_color_at(start)
1292 .copied()
1293 .unwrap_or_default(),
1294 // ...and the canvas it is placed on: the project's resolution
1295 // and this clip's own fit policy, constant across the span for
1296 // the reason the grade is.
1297 Composer::new(
1298 self.meta.width,
1299 self.meta.height,
1300 self.project.composite_fit_at(start),
1301 ),
1302 // ...and the rendition an HDR source among them is mapped to,
1303 // the project's own and constant across the span for that reason
1304 // too.
1305 self.project.tone(),
1306 )),
1307 // A gap: black for as long as it runs. An emptied timeline has no
1308 // span at all and gets one frame of it -- enough to put black on
1309 // screen, and it ends where the timeline does, at once.
1310 gap => Ok(DecodeSession::open_black(
1311 self.meta.width,
1312 self.meta.height,
1313 gap.map_or(1, |s| s.len),
1314 )),
1315 };
1316 let Ok(stream) = opened else {
1317 // The file would not open. The span still goes in -- the timeline
1318 // moves on, there are simply no more pictures -- but the *frames*
1319 // must not: the old channel's pictures are numbered in the old
1320 // source's frames, and presenting them under the new mapping would
1321 // put the wrong picture at the wrong time (and leave
1322 // [`decode_backend`](Self::decode_backend) describing a worker that
1323 // is no longer feeding anything). A dead receiver instead, which is
1324 // what carries the session on to the next span. The old worker stays
1325 // parked in `self.worker` where the caller already cancelled it; the
1326 // next span retires it.
1327 self.frames = std::sync::mpsc::channel().1;
1328 self.backend = BackendCell::new(Backend::Gap);
1329 self.span = span;
1330 return;
1331 };
1332 // Receiver first, worker second: the drop of the *old* receiver is
1333 // what wakes the outgoing worker if it is parked in `send`, and only
1334 // then can it return and be reaped by a later sweep. Nothing here
1335 // joins, so this ordering costs the seek nothing.
1336 self.frames = stream.frames;
1337 self.backend = stream.backend;
1338 self.retire(stream.worker);
1339 self.span = span;
1340 }
1341
1342 /// Length of the edited timeline in seconds -- what a ruler shows, and it
1343 /// shrinks with every delete.
1344 pub fn timeline_duration(&self) -> f64 {
1345 f64::from(self.project.timeline_frames()) / self.meta.frame_rate
1346 }
1347
1348 /// Whether no lane holds anything: the emptied timeline, which plays black
1349 /// and silent and is zero seconds long. A state, not a failure -- but the
1350 /// one a caller with nothing to render (an export) has to refuse by name
1351 /// rather than write a file of no frames.
1352 pub fn is_empty(&self) -> bool {
1353 self.project.timeline_frames() == 0
1354 }
1355
1356 /// `(start, len)` per clip in timeline seconds, in order: what a clips lane
1357 /// needs to lay itself out. Selection is the caller's business.
1358 pub fn clip_spans(&self) -> Vec<(f64, f64)> {
1359 let fps = self.meta.frame_rate;
1360 self.project
1361 .clip_spans()
1362 .iter()
1363 .map(|&(start, len)| (f64::from(start) / fps, f64::from(len) / fps))
1364 .collect()
1365 }
1366
1367 /// [`clip_spans`](Self::clip_spans) plus the index into
1368 /// [`Project::sources`] each clip plays from -- what a lane needs to colour
1369 /// an imported clip differently from the file the session was opened with.
1370 pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> {
1371 self.lane_spans_by_source(Lane::V1)
1372 }
1373
1374 /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane,
1375 /// with each clip's group id -- what a two-lane front-end draws. The holes
1376 /// between consecutive entries are the gaps.
1377 pub fn lane_spans_by_source(&self, lane: Lane) -> Vec<(f64, f64, usize)> {
1378 let fps = self.meta.frame_rate;
1379 self.project
1380 .lane(lane)
1381 .iter()
1382 .map(|c| (f64::from(c.start) / fps, f64::from(c.len()) / fps, c.source))
1383 .collect()
1384 }
1385
1386 /// Every placement of one lane, in timeline order. What a two-lane
1387 /// front-end draws and nothing
1388 /// [`lane_spans_by_source`](Self::lane_spans_by_source) can answer: a clip
1389 /// carries its group id (which halves a click marks together) and its
1390 /// source range (where a waveform reads its peaks from) as well as its
1391 /// span. The holes between consecutive clips are the gaps.
1392 pub fn lane_clips(&self, lane: Lane) -> &[Clip] {
1393 self.project.lane(lane)
1394 }
1395
1396 /// Every lane's handle, in display order -- what a front-end lays out top to
1397 /// bottom, and the list [`add_lane`](Self::add_lane) grows.
1398 pub fn lanes(&self) -> Vec<Lane> {
1399 self.project.lanes()
1400 }
1401
1402 /// Appends an empty lane and hands back its handle. One undo step
1403 /// ([`Project::add_lane`]), and no reseek: an empty lane changes nothing
1404 /// that plays until something is placed on it.
1405 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
1406 self.project.add_lane(kind)
1407 }
1408
1409 /// Drops that empty lane again, in [`Project::remove_lane`]'s words when it
1410 /// refuses. One undo step, and no reseek for the same reason the add needs
1411 /// none: an empty lane was playing nothing.
1412 pub fn remove_lane(&mut self, lane: Lane) -> crate::Result<()> {
1413 self.project.remove_lane(lane)
1414 }
1415
1416 /// Splits every lane at `timeline_secs`, so the two sides become two
1417 /// groups. Metadata only: a split never changes the timeline->source
1418 /// mapping, so the running decoder stays correct and playback does not
1419 /// blink. `false` at a clip start, in a gap and past the end, where there
1420 /// would be nothing to split off.
1421 pub fn cut_at(&mut self, timeline_secs: f64) -> bool {
1422 self.project
1423 .split(secs_to_frame(timeline_secs, self.meta.frame_rate))
1424 }
1425
1426 /// The inverse of [`cut_at`](Self::cut_at): rejoins the clips that meet at
1427 /// `timeline_secs` in every lane and puts them back in one group. `false`
1428 /// unless a split could have produced what is there. Metadata only, like the
1429 /// split -- no reseek.
1430 pub fn regroup_at(&mut self, timeline_secs: f64) -> bool {
1431 self.project
1432 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))
1433 }
1434
1435 /// Takes that clip out of its group, so its picture and its sound are edited
1436 /// apart from here on. Metadata only like a cut -- no reseek -- and one undo
1437 /// step. `false` for a bad index and for a clip that is not grouped with
1438 /// anything, which is already detached.
1439 pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
1440 self.project.ungroup(lane, idx)
1441 }
1442
1443 /// Puts two clips covering the same frames back into one group: the regroup
1444 /// of what [`ungroup`](Self::ungroup) took apart. Metadata only, one undo
1445 /// step, and the error says why when it refuses.
1446 pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
1447 self.project.group(a, a_idx, b, b_idx)
1448 }
1449
1450 /// What the clip at `idx` of `lane` is equalized with, or `None` for one
1451 /// that plays flat -- what a card shows before it lets anyone drag a band.
1452 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
1453 self.project.eq_of(lane, idx)
1454 }
1455
1456 /// Gives that clip an equalizer, or takes it off with `None`. One undo step,
1457 /// like every other edit -- and it rebuilds the **sound** where the playhead
1458 /// is, so a band changed during playback is heard from the next chunk on
1459 /// rather than at the next play. The picture is not touched: the video
1460 /// worker keeps decoding through it ([`Dirty`]). `false` for a bad index or
1461 /// a non-finite band, and nothing changes.
1462 ///
1463 /// ponytail: the audio rebuild is what makes it live, so the cost of a
1464 /// change is a decoder restart -- inaudible at a drag's end, but too much to
1465 /// call once per pointer sample (a caller commits one change per gesture).
1466 /// Upgrade path is the per-segment twin of [`crate::audio::MixControls`],
1467 /// which the lane worker would poll per chunk the way the mixer polls the
1468 /// gains.
1469 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
1470 self.edit(Dirty::Sound, |p| p.set_eq(lane, idx, params))
1471 }
1472
1473 /// How loud that lane plays, in dB -- everything on it, every frequency of
1474 /// it. See [`Project::lane_gain_db`] for what it is *not*.
1475 pub fn lane_gain_db(&self, lane: Lane) -> f32 {
1476 self.project.lane_gain_db(lane)
1477 }
1478
1479 /// Sets it. One undo step -- and **nothing is rebuilt**: a lane's volume
1480 /// lives at the sum, so the running mixer is handed the new number and
1481 /// picks it up at its next block ([`crate::audio::MixControls`]). A fader
1482 /// held down under an arrow key therefore moves the level and nothing else:
1483 /// no flush, no decoder restart, no hole in the sound and no blink in the
1484 /// picture.
1485 ///
1486 /// The one exception is the timeline that is not mixed at all -- a single
1487 /// audio lane at unity with the limiter off, which plays through the
1488 /// bit-exact single-stream path and has no mixer to talk to. Moving *that*
1489 /// off unity opens one, once; every move after it is live.
1490 pub fn set_lane_gain_db(&mut self, lane: Lane, db: f32) -> bool {
1491 if !self.project.set_lane_gain_db(lane, db) {
1492 return false;
1493 }
1494 self.push_mix();
1495 true
1496 }
1497
1498 /// Hands the mix the running mixer is reading its new settings -- the whole
1499 /// of what a fader and a ceiling cost. With no mixer listening (the
1500 /// single-lane flat path, and a session with no sound at all) the sound is
1501 /// rebuilt instead, which is what opens one.
1502 fn push_mix(&mut self) {
1503 let gains = self.project.audio_gains();
1504 let limiter = self.project.limiter();
1505 match &self.mix {
1506 Some(mix) => mix.set(gains, limiter),
1507 None => self.reseek_audio(),
1508 }
1509 }
1510
1511 /// The master limiter the whole mix is summed through.
1512 pub fn limiter(&self) -> crate::limiter::Limiter {
1513 self.project.limiter()
1514 }
1515
1516 /// Sets it, live like a lane volume and for the same reason -- the ceiling
1517 /// a person is dragging has to be the ceiling they are hearing. Nothing is
1518 /// rebuilt: the running limiter is *retuned* between two blocks
1519 /// ([`crate::limiter::LimiterState::retune`]), so its delay line keeps
1520 /// running and the sample count the master clock is made of does not move.
1521 ///
1522 /// ponytail: not an undo step, and deliberately -- [`Project::undo`]
1523 /// restores the lane list, and the limiter is not in it, so snapshotting
1524 /// here would push a step whose undo changes nothing a person can see or
1525 /// hear (the twin [`set_lane_gain_db`](Self::set_lane_gain_db) *is*
1526 /// undoable only because a lane volume lives in that list). The project
1527 /// resolution is outside undo for the same reason and says so. Upgrade path
1528 /// is a history that carries the mix beside the lanes, which every existing
1529 /// snapshot site would then have to fill in.
1530 pub fn set_limiter(&mut self, limiter: crate::limiter::Limiter) -> bool {
1531 if !self.project.set_limiter(limiter) {
1532 return false;
1533 }
1534 self.push_mix();
1535 true
1536 }
1537
1538 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
1539 /// silence on the audio one, and nothing else moves. Reseeks, because what
1540 /// the playhead sits on has changed. `false` for a bad index -- the lift of
1541 /// the last placement there is empties the timeline, which is a state
1542 /// ([`is_empty`](Self::is_empty)) and one undo away.
1543 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {
1544 self.edit(Dirty::Both, |p| p.lift(lane, idx))
1545 }
1546
1547 /// Moves that clip onto lane `to` with its head at timeline frame `start` --
1548 /// the drag that carries a take along its track or onto another one, and its
1549 /// whole group with it. See [`Project::move_clip`] for the walls `start` is
1550 /// clamped to and the ways a drop is refused. One undo step, and it reseeks
1551 /// like every other edit: which lane a clip sits on is what the compositor's
1552 /// topmost-lane-wins rule reads, and where it starts is what the playhead
1553 /// reads, so the frame on screen is recomposed at once.
1554 ///
1555 /// A *frame*, where the rest of this type takes seconds, for
1556 /// [`trim_clip`](Self::trim_clip)'s reason: the drag has already put the
1557 /// pointer on a frame, and converting it back through seconds would be a
1558 /// rounding step between the box let go of and the box committed.
1559 pub fn move_clip_to(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool {
1560 self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start))
1561 }
1562
1563 /// Drags one end of that clip to timeline frame `to`, changing how much of
1564 /// its source it plays and nothing else on the lane -- see [`Project::trim`]
1565 /// for the walls it is clamped by, which this fills the source lengths in
1566 /// for. One undo step per call, so a front-end calls it once, at the release
1567 /// of the drag. Reseeks like every other edit, which is what makes the
1568 /// picture (and the sound) follow a new in-point straight away. `false` for
1569 /// a bad index and for an edge already where it was asked to go.
1570 ///
1571 /// A *frame*, where the rest of this type takes seconds: a drag has already
1572 /// asked [`trim_room`](Self::trim_room) where the edge may land, and that
1573 /// answer is in frames -- converting it back through seconds would be a
1574 /// rounding step between the width drawn and the width committed.
1575 pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
1576 // Spelled out rather than through `edit`, whose closure cannot hold a
1577 // second borrow of the session while it has the project.
1578 if !self.project.trim(lane, idx, edge, to, &self.counts) {
1579 return false;
1580 }
1581 let now = self.now();
1582 self.seek(now);
1583 true
1584 }
1585
1586 /// How fast the clip at `idx` of `lane` plays -- what a card shows before
1587 /// anyone drags it.
1588 pub fn speed_of(&self, lane: Lane, idx: usize) -> Speed {
1589 self.project.speed_of(lane, idx)
1590 }
1591
1592 /// Sets it, for that clip and its whole group ([`Project::set_speed`]): one
1593 /// undo step for the lot. Reseeks like every other edit, so the picture runs
1594 /// -- and the sound is resampled -- from the next frame on rather than at the
1595 /// next play. The `Err` names the clip in the way when slowing one down
1596 /// would run it into its neighbour, and nothing changes.
1597 pub fn set_speed(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
1598 // Spelled out rather than through `edit`, whose closure hands back a
1599 // bool and would drop the refusal's own words.
1600 self.project.set_speed(lane, idx, speed)?;
1601 let now = self.now();
1602 self.seek(now);
1603 Ok(())
1604 }
1605
1606 /// [`set_speed`](Self::set_speed) without the undo step -- the samples inside
1607 /// one drag ([`Project::set_speed_live`]). Reseeks like the committing one,
1608 /// which is what makes the bar move the picture under the hand.
1609 pub fn set_speed_live(&mut self, lane: Lane, idx: usize, speed: Speed) -> crate::Result<()> {
1610 self.project.set_speed_live(lane, idx, speed)?;
1611 let now = self.now();
1612 self.seek(now);
1613 Ok(())
1614 }
1615
1616 /// Cuts every one of `regions` -- `(start, len)` in timeline frames -- out
1617 /// of the lanes in `scope` and closes each hole, as **one** edit
1618 /// ([`Project::cut_regions`]): the jumpcut a silence scan
1619 /// ([`crate::silence`]) asks for, one undo press however many silences it
1620 /// found. A lane outside `scope` does not move. Reseeks like every other
1621 /// edit, so what plays is the cut timeline from the playhead on. The `Err`
1622 /// names what is in the way and nothing changes.
1623 pub fn cut_regions(&mut self, regions: &[(u32, u32)], scope: &[Lane]) -> crate::Result<()> {
1624 // Spelled out rather than through `edit`, whose closure hands back a
1625 // bool and would drop the refusal's own words.
1626 self.project.cut_regions(regions, scope)?;
1627 let now = self.now();
1628 self.seek(now);
1629 Ok(())
1630 }
1631
1632 /// Plays every one of those regions at `speed` instead of cutting them,
1633 /// closing the room each one no longer needs ([`Project::speed_regions`]) --
1634 /// one edit, one undo press, and the same scope rule. The `Err` names the
1635 /// lane and frame in the way and nothing changes.
1636 pub fn speed_regions(
1637 &mut self,
1638 regions: &[(u32, u32)],
1639 speed: Speed,
1640 scope: &[Lane],
1641 ) -> crate::Result<()> {
1642 self.project.speed_regions(regions, speed, scope)?;
1643 let now = self.now();
1644 self.seek(now);
1645 Ok(())
1646 }
1647
1648 /// Where that edge may land, `(first, last)` timeline frame inclusive: what
1649 /// a drag clamps the pointer to so the box it draws is the box
1650 /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
1651 pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
1652 self.project.trim_room(lane, idx, edge, &self.counts)
1653 }
1654
1655 /// Records how long a source is and what rate it was shot at, for a source
1656 /// index that may be one `Project::import` just made or one it handed back.
1657 /// See [`Self::counts`] and [`Self::rates`], which are one table in two
1658 /// vectors and grow together.
1659 fn note_frames(&mut self, source: usize, frames: u32, rate: Rate) {
1660 if source == self.counts.len() {
1661 self.counts.push(frames);
1662 self.rates.push(rate);
1663 }
1664 debug_assert_eq!(self.counts.len(), self.project.sources().len());
1665 debug_assert_eq!(self.rates.len(), self.counts.len());
1666 }
1667
1668 /// The rate noted for whichever source plays `path`, by
1669 /// [`file_frames`](Self::file_frames)'s rule: one file is one rate however
1670 /// many audio tracks it carries. [`Rate::REAL_TIME`] for a file this session
1671 /// has never taken in.
1672 fn file_rate(&self, path: &Path) -> Rate {
1673 self.source_of(path)
1674 .map_or(Rate::REAL_TIME, |i| self.rates[i])
1675 }
1676
1677 /// Which source `path` is, canonicalising only if it has to: a source's own
1678 /// path is canonical ([`Source::new`]), so a caller handing one back from
1679 /// [`sources`](Self::sources) -- which is every library row -- hits on the
1680 /// first walk and never pays for the `canonicalize` syscall the second one
1681 /// makes. One rule, so a path that names a length names a rate too.
1682 fn source_of(&self, path: &Path) -> Option<usize> {
1683 let at = |wanted: &Path| self.project.sources().iter().position(|s| s.path == wanted);
1684 at(path).or_else(|| at(&Source::new(path, 0).path))
1685 }
1686
1687 /// How long the whole of `path` is, in timeline frames: the length noted
1688 /// when it became a source, so a file sitting in the library with no clip
1689 /// anywhere still knows how much of itself there is to place. `0` for a
1690 /// file this session has never taken in.
1691 ///
1692 /// By path and not by stream, because a file is one length however many
1693 /// audio tracks it carries -- the picture's frame count for an mp4, the
1694 /// playing time for a song.
1695 pub fn file_frames(&self, path: &Path) -> u32 {
1696 self.source_of(path).map_or(0, |i| self.counts[i])
1697 }
1698
1699 /// What rate the file at `path` was *shot* at, in frames per second -- which
1700 /// is the timeline's own rate for every source that shares it, and is not
1701 /// for one placed at another ([`Rate`]). By path like
1702 /// [`file_frames`](Self::file_frames), and the timeline's rate for a file
1703 /// this session has never taken in (and for a still and a song, which were
1704 /// shot at no rate at all).
1705 ///
1706 /// What a library row names the file with: the timeline's rate there would
1707 /// be a lie about a 23.976 fps file the moment one can join.
1708 pub fn file_fps(&self, path: &Path) -> f64 {
1709 self.file_rate(path).as_f64() * self.meta.frame_rate
1710 }
1711
1712 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
1713 /// on and its index there, by the same topmost-lane-wins rule the decoder
1714 /// follows. `None` over a gap and past the end. What a card that grades
1715 /// "this clip" opens on when nothing has been clicked.
1716 pub fn video_clip_at(&self, timeline_secs: f64) -> Option<(Lane, usize)> {
1717 self.project
1718 .composite_clip_at(secs_to_frame(timeline_secs, self.meta.frame_rate))
1719 }
1720
1721 /// Which clip of `lane` sits at `timeline_secs`, by the same rule
1722 /// [`video_clip_at`](Self::video_clip_at) picks the picture's with -- per
1723 /// lane, so a keyboard walking the lanes for something to select asks the
1724 /// engine rather than re-deriving where a clip ends.
1725 pub fn lane_clip_at(&self, lane: Lane, timeline_secs: f64) -> Option<usize> {
1726 self.project
1727 .lane_clip_at(lane, secs_to_frame(timeline_secs, self.meta.frame_rate))
1728 }
1729
1730 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
1731 /// as it was shot -- what a colour card reads when it opens.
1732 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
1733 self.project.color_of(lane, idx)
1734 }
1735
1736 /// Grades that clip, or takes the grade off with `None`. One undo step like
1737 /// every other edit, and it reseeks like one too -- which is what puts the
1738 /// new grade on the frame that is already on screen, paused or playing,
1739 /// without the caller having to nudge the playhead itself. `false` for an
1740 /// index that is not there and for a value that is not finite.
1741 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
1742 self.edit(Dirty::Picture, |p| p.set_color(lane, idx, params))
1743 }
1744
1745 /// The same grade and the same reseek without the undo step
1746 /// ([`Project::set_color_live`]): what the samples inside one slider drag go
1747 /// through, so the frame regrades under the hand and the whole gesture is
1748 /// still a single `z`.
1749 pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
1750 self.edit(Dirty::Picture, |p| p.set_color_live(lane, idx, params))
1751 }
1752
1753 /// The project's resolution: what every clip is composed onto, what the
1754 /// window is sized to and what an export writes -- *not* any one file's.
1755 /// It starts as source 0's picture, which is what a project meant before it
1756 /// could have a resolution of its own.
1757 pub fn resolution(&self) -> (u32, u32) {
1758 (self.meta.width, self.meta.height)
1759 }
1760
1761 /// Source 0's own picture size -- what the project resolution started as,
1762 /// and the one size a caller offering a list of them must not leave out.
1763 pub fn native_resolution(&self) -> (u32, u32) {
1764 self.native
1765 }
1766
1767 /// Sets it. Rebuilds the **picture** where the playhead is, so the frame on
1768 /// screen is recomposed at the new size at once, paused or playing -- and
1769 /// the sound is not touched at all: the size of the canvas is not something
1770 /// a sample can carry, so resizing a 4K film mid-play costs neither a hole
1771 /// in the audio nor an offset against it ([`Dirty`]). `false` for a size
1772 /// that is not a picture -- zero either way, or past 8K, which is where the
1773 /// per-frame buffers stop being a sane thing to allocate from a keystroke.
1774 ///
1775 /// ponytail: not an undo step. The project resolution is not in the lane
1776 /// snapshots [`Project::undo`] restores, so cycling it back is one more
1777 /// keypress rather than a `z`. Upgrade path is snapshotting it beside the
1778 /// lanes, which every existing snapshot site would then have to carry.
1779 pub fn set_resolution(&mut self, width: u32, height: u32) -> bool {
1780 if !crate::is_resolution(width, height) {
1781 return false;
1782 }
1783 if (width, height) == (self.meta.width, self.meta.height) {
1784 return false;
1785 }
1786 self.meta.width = width;
1787 self.meta.height = height;
1788 self.invalidate(Dirty::Picture);
1789 true
1790 }
1791
1792 /// Which HDR-to-SDR rendition this project is watched and exported in
1793 /// ([`crate::tonemap::Preset`]) -- the reference one until somebody picks
1794 /// another, and a setting on the project rather than on any clip.
1795 pub fn tone(&self) -> crate::tonemap::Preset {
1796 self.project.tone()
1797 }
1798
1799 /// Picks one. Rebuilds the **picture** where the playhead is, exactly as
1800 /// [`set_resolution`](Self::set_resolution) does -- the frame on screen is
1801 /// remapped at once, paused or playing, and the sound is not touched: a
1802 /// rendition is not something a sample can carry. `false` for the rendition
1803 /// already in force.
1804 ///
1805 /// An SDR project is unmoved by this by construction: no clip of it builds a
1806 /// tone map at all ([`crate::tonemap`]), so the reseek recomposes the very
1807 /// same bytes.
1808 ///
1809 /// ponytail: not an undo step, for the reason the resolution is not
1810 /// ([`Project::set_tone`]).
1811 pub fn set_tone(&mut self, preset: crate::tonemap::Preset) -> bool {
1812 if !self.project.set_tone(preset) {
1813 return false;
1814 }
1815 self.invalidate(Dirty::Picture);
1816 true
1817 }
1818
1819 /// The scaffolding source's own frame rate -- what the project rate started
1820 /// as, and the one rate a caller offering a list of them must not leave out
1821 /// ([`native_resolution`](Self::native_resolution)'s reason).
1822 pub fn native_frame_rate(&self) -> f64 {
1823 self.native_fps
1824 }
1825
1826 /// Cuts this timeline at `fps` from here on: every clip is *conformed* to
1827 /// the new rate ([`Project::retime`]), every source is read through a
1828 /// [`Rate`] against it, and an export written from this session comes out at
1829 /// it. The edit survives as the same seconds of the same footage on a finer
1830 /// or coarser grid -- a 30 fps take on a timeline moved to 24 keeps its
1831 /// length and its sync, it is simply counted in 24ths now.
1832 ///
1833 /// Reseeks like [`set_resolution`](Self::set_resolution), so the picture and
1834 /// the sound under the playhead are already the new rate's when this
1835 /// returns. `false` -- changing nothing -- for a rate that is not a rate, for
1836 /// the one already in force, and for one no timescale can name
1837 /// ([`crate::mux::frame_timing`], the same wall a file of an unnameable rate
1838 /// is refused at).
1839 ///
1840 /// ponytail: not an undo step, exactly as the project resolution is not --
1841 /// and this one *moves the frame numbers*, so the way back is picking the
1842 /// old rate (or the media's, [`native_frame_rate`](Self::native_frame_rate))
1843 /// rather than a `z`, and it lands within a frame of where it started rather
1844 /// than on it (see [`Project::retime`]). Upgrade path is the same one: the
1845 /// project's settings snapshotted beside the lanes.
1846 pub fn set_frame_rate(&mut self, fps: f64) -> bool {
1847 if !fps.is_finite() || fps <= 0.0 || fps == self.meta.frame_rate {
1848 return false;
1849 }
1850 // Old timeline frames per new one, exactly -- the one map every frame
1851 // number on every lane goes through. Built before anything is touched,
1852 // since a rate no timescale can name is a refusal and not a half-retimed
1853 // project.
1854 let Ok(k) = Rate::from_fps(self.meta.frame_rate, fps) else {
1855 return false;
1856 };
1857 // Lengths first: the retime holds every clip inside its source's *new*
1858 // length, so a clip that played to the last frame of its file still
1859 // does rather than naming one past the end.
1860 for count in &mut self.counts {
1861 *count = k.timeline_at(*count).max(1);
1862 }
1863 self.project.retime(k, &self.counts);
1864 // A file's own rate has not changed; what it is *against* has.
1865 for rate in &mut self.rates {
1866 *rate = rate.then(k);
1867 }
1868 self.meta.frame_rate = fps;
1869 self.meta.frame_count = k.timeline_at(self.meta.frame_count).max(1);
1870 let now = self.now();
1871 self.seek(now);
1872 true
1873 }
1874
1875 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
1876 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
1877 self.project.fit_of(lane, idx)
1878 }
1879
1880 /// Sets that clip's fit policy. One undo step and a reseek, exactly like a
1881 /// grade: the picture on screen is recomposed through the new policy without
1882 /// the caller nudging the playhead. `false` for an index that is not there.
1883 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
1884 self.edit(Dirty::Picture, |p| p.set_fit(lane, idx, fit))
1885 }
1886
1887 /// The clip at `idx` -- what a caller copies. It is a pair of source frame
1888 /// numbers and nothing else, so a copy stays valid after the clip it came
1889 /// from is deleted. `None` past the end.
1890 pub fn clip_at(&self, idx: usize) -> Option<Clip> {
1891 self.project.clips().get(idx).copied()
1892 }
1893
1894 /// Inserts `clip` at the playhead, splitting the clip under it. Like a
1895 /// delete this moves every following frame, so the session reseeks; past
1896 /// the end of the timeline the clip is appended. One undo step.
1897 pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool {
1898 // The clipboard's own rule, and only the clipboard's: a paste past the
1899 // end is an append, never a clip with black in front of it. The frame
1900 // itself is honoured in [`Project::paste`], because a *drop* names a
1901 // place on the bed and means it.
1902 let at = secs_to_frame(timeline_secs, self.meta.frame_rate)
1903 .min(self.project.timeline_frames());
1904 self.edit(Dirty::Both, |p| p.paste(at, clip))
1905 }
1906
1907 /// Places the whole of `path` played on its audio `stream` at
1908 /// `timeline_secs`, the way [`paste_at`](Self::paste_at) places a copy --
1909 /// the door a library row goes through, and the only way a stream other
1910 /// than the one an import brought in reaches the timeline. The `(file,
1911 /// stream)` pair becomes a source if it is not one already.
1912 ///
1913 /// Refused, changing nothing, unless that stream can join *this* timeline:
1914 /// same audio parameters as the first source, in the same words
1915 /// [`import`](Self::import) refuses a file with. One output device and one
1916 /// copied AAC track mean one *layout* for the whole timeline, so a mono
1917 /// track cannot join a stereo one. Its sample rate may be its own: the
1918 /// segment's resampler conforms it at the decoder's door.
1919 /// A front-end greys such a row out; this is the backstop that keeps a
1920 /// stale one from making the whole timeline silent.
1921 ///
1922 /// Which lane it lands on is decided here, from the file and from `onto` --
1923 /// the lane it was let go over, if it was let go over one at all: a file
1924 /// with a picture asked for by no lane, or for one of the first pair, is
1925 /// pasted across `V1` and `A1` as a grouped take; asked for by any further
1926 /// lane it is *placed* there alone, overwriting what it lands on and
1927 /// rippling nothing. A file with no picture ([`crate::is_audio`]) is placed
1928 /// on the audio lane it was asked for, or on `A1`, and never on a video
1929 /// lane. A still image ([`crate::is_image`]) is its mirror: the video lane
1930 /// it was asked for or `V1`, never an audio one, and it goes down
1931 /// [`IMAGE_PLACE_SECS`] long rather than at the length it is *allowed* to
1932 /// be trimmed out to. A caller never has to ask.
1933 pub fn place_stream_at(
1934 &mut self,
1935 timeline_secs: f64,
1936 path: &Path,
1937 stream: usize,
1938 onto: Option<Lane>,
1939 ) -> crate::Result<bool> {
1940 let wanted = Source::new(path, stream);
1941 // Another stream of a file this session has taken in: that is what a
1942 // library row is, and it is why nothing here has to check dimensions or
1943 // frame rate -- the file passed that at import. Its length is the one
1944 // the import noted, so a source that has never been placed is as
1945 // placeable as one that is already on a lane.
1946 let frames = self.file_frames(&wanted.path);
1947 if frames == 0 {
1948 return Err(format!("{} is not on this timeline", path.display()).into());
1949 }
1950 // A still has no sound to hold to the timeline's -- and no length
1951 // either, so it goes down at [`IMAGE_PLACE_SECS`] rather than at the
1952 // ten minutes it is *allowed* to be dragged out to.
1953 let image = crate::is_image(path);
1954 if !image {
1955 let first = self.first_audio()?;
1956 audio_matches(&wanted, &first)?;
1957 }
1958 let rate = self.file_rate(&wanted.path);
1959 let source = self.project.import(path, stream);
1960 self.note_frames(source, frames, rate);
1961 let clip = Clip {
1962 start: 0,
1963 in_frame: 0,
1964 out_frame: match image {
1965 true => place_frames(frames, self.meta.frame_rate),
1966 false => frames.max(1),
1967 },
1968 source,
1969 link: None,
1970 eq: None,
1971 color: None,
1972 fit: FitPolicy::default(),
1973 speed: Speed::NORMAL,
1974 };
1975 // Which lane a source may land on is decided here and only here, so a
1976 // front-end never has to make the same call twice: a file with no
1977 // picture goes on an audio lane alone, overwriting and rippling
1978 // nothing, because there is nothing on the video lane to move along
1979 // with it. A lane of the source's own kind takes it as it is dropped;
1980 // only `V1` means the grouped take, since that is the pair the paste
1981 // spans and a second video lane is a layer of its own.
1982 // ...and a still is the mirror of a song: a picture and no sound, so a
1983 // video lane and nothing else -- never the grouped take, which would
1984 // put a clip on `A1` for a source the audio worker cannot open.
1985 if image {
1986 let lane = match onto {
1987 Some(lane) if lane.kind == LaneKind::Video => lane,
1988 _ => Lane::V1,
1989 };
1990 return Ok(self.place_at(lane, timeline_secs, clip));
1991 }
1992 let onto = match (crate::is_audio(path), onto) {
1993 // No picture: an audio lane and nothing else, whichever one was
1994 // asked for -- `A1` when none was.
1995 (true, Some(lane)) if lane.kind == LaneKind::Audio => Some(lane),
1996 (true, _) => Some(Lane::A1),
1997 // A picture: the lane it was let go over, unless that is one of the
1998 // first pair. Those two are the grouped take a paste spans, and a
1999 // further lane is a layer of its own -- its picture on `V2`, its
2000 // sound on `A2`.
2001 (false, Some(lane)) if lane.ord > 0 => Some(lane),
2002 (false, _) => None,
2003 };
2004 Ok(match onto {
2005 Some(lane) => self.place_at(lane, timeline_secs, clip),
2006 // The grouped take, at the frame it was let go on -- past the last
2007 // clip included, where the bed is black and the ghost was drawn.
2008 // Not [`Self::paste_at`]: that door clamps to the end for the
2009 // clipboard, and a drop that named a place is not a paste.
2010 None => {
2011 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
2012 self.edit(Dirty::Both, |p| p.paste(at, clip))
2013 }
2014 })
2015 }
2016
2017 /// Takes `path` played on `stream` out of the library -- the door a library
2018 /// row's own remove goes through, naming the row exactly as
2019 /// [`place_stream_at`](Self::place_stream_at) does. Refused in
2020 /// [`Project::remove_source`]'s words while a clip still plays from it, and
2021 /// for a row this timeline does not have.
2022 ///
2023 /// Reseeks like an edit even though nothing playable changed: the clip
2024 /// indexes into the source list have just moved, and the running workers
2025 /// were opened against the old numbering.
2026 ///
2027 /// The index that went, because everything past it moved down: a caller
2028 /// holding a source index of its own (a clipboard) has to fix it up or drop
2029 /// it, or it names a different file afterwards. The **last** row goes like
2030 /// any other and leaves a session with an empty library -- silent, empty of
2031 /// clips, and unsaveable ([`save_project`](Self::save_project)); a
2032 /// front-end showing one is showing an empty window.
2033 pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<usize> {
2034 let wanted = Source::new(path, stream);
2035 let idx = self
2036 .project
2037 .sources()
2038 .iter()
2039 .position(|s| *s == wanted)
2040 .ok_or_else(|| format!("{} is not on this timeline", path.display()))?;
2041 self.project.remove_source(idx)?;
2042 // The one thing that shortens the source list, so the one place
2043 // [`Self::counts`] shortens with it: left behind, the gone file's length
2044 // would become the wall a *surviving* source is trimmed against
2045 // ([`trim_room`](Self::trim_room)) and the next import would land its
2046 // count one index late.
2047 if idx < self.counts.len() {
2048 self.counts.remove(idx);
2049 self.rates.remove(idx);
2050 }
2051 let now = self.now();
2052 self.seek(now);
2053 Ok(idx)
2054 }
2055
2056 /// What the timeline's audio *is*: the chosen stream of the first source
2057 /// that could have any ([`audio_source_of`]), probed. Every other source is
2058 /// held to it.
2059 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {
2060 first_audio_of(self.project.sources())
2061 }
2062
2063 /// Places `clip` on `lane` alone at the playhead, overwriting what it lands
2064 /// on and rippling nothing -- the one-lane insert a source with no picture
2065 /// makes, and the only way an audio-only file reaches the timeline. The
2066 /// placement belongs to no group (see [`Project::place`]). One undo step,
2067 /// and it reseeks like every other edit.
2068 pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool {
2069 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
2070 self.edit(Dirty::Both, |p| p.place(lane, at, clip))
2071 }
2072
2073 /// Removes `lane`'s clip at `idx` and everything under it, closing the gap
2074 /// on every lane. Unlike a split this *does* move every following frame, so
2075 /// the session reseeks to wherever the playhead now points.
2076 /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead.
2077 /// `false` for a bad index; the last remaining clip goes like any other and
2078 /// leaves the timeline empty ([`is_empty`](Self::is_empty)).
2079 ///
2080 /// The lane travels because the index is a lane's own: `V2`'s third clip is
2081 /// not `V1`'s, and a front-end that could only say "the third clip" would
2082 /// delete the wrong one the moment a second lane exists.
2083 pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool {
2084 self.edit(Dirty::Both, |p| p.delete_in(lane, idx))
2085 }
2086
2087 /// Undoes the last successful edit, and reseeks like a delete.
2088 pub fn undo(&mut self) -> bool {
2089 self.edit(Dirty::Both, Project::undo)
2090 }
2091
2092 /// Takes `path` into the **library**: it becomes a source of this session,
2093 /// with its length noted ([`file_frames`](Self::file_frames)), and nothing
2094 /// is placed on any lane. What reaches the timeline is decided afterwards,
2095 /// by dragging the row onto a lane
2096 /// ([`place_stream_at`](Self::place_stream_at)) -- importing a file is not
2097 /// a decision about where it plays.
2098 ///
2099 /// The source index, new or the one this file already had: importing twice
2100 /// registers once. *Not* an undo step -- a source entry alone changes
2101 /// nothing playable, so there is nothing for [`undo`](Self::undo) to take
2102 /// back, and nothing reseeks.
2103 ///
2104 /// Refused unless it can join the timeline -- a decoder this machine can
2105 /// open, and audio parameters that agree or none at all; the `Err` names
2106 /// the property that disagrees,
2107 /// for a caller to show. Nothing is changed by a refusal. A *resolution* of
2108 /// its own is not a refusal: the clip is placed on the project canvas by its
2109 /// fit policy ([`PlaybackSession::set_fit`]) -- and neither is a *frame
2110 /// rate* of its own: the file is placed for the seconds it lasts and read at
2111 /// [`Rate`] against the timeline's rate, so it plays at the speed it was
2112 /// shot at.
2113 pub fn import(&mut self, path: &Path) -> crate::Result<usize> {
2114 if crate::is_audio(path) {
2115 return self.import_audio(path);
2116 }
2117 if crate::is_image(path) {
2118 return self.import_image(path);
2119 }
2120 // Both halves on this thread, which is what a caller with nothing else
2121 // to do wants; a front-end splits them across a worker instead
2122 // ([`probe_import`](Self::probe_import)).
2123 let probe = Self::probe_import(self.import_gate(), path)?;
2124 Ok(self.take_probe(path, probe))
2125 }
2126
2127 /// Everything an import is *checked against*, taken off this timeline in
2128 /// one owned piece: the sources its audio must agree with and the meta its
2129 /// rate is read against. Costs two clones and touches no disk, so the
2130 /// thread holding the session can hand it to a worker and go on painting.
2131 pub fn import_gate(&self) -> ImportGate {
2132 ImportGate {
2133 sources: self.project.sources().to_vec(),
2134 timeline: self.meta,
2135 }
2136 }
2137
2138 /// The reading half of [`import`](Self::import), with no session in it: the
2139 /// container's header, the decoder this machine would open it with, and the
2140 /// audio check against the gate -- every read an import pays.
2141 ///
2142 /// This is the half that costs. Measured on a 24 GB 4K HEVC remux: 21.4 s of
2143 /// header with the pages cold, 429 ms warm, plus 1-4 s of probing the
2144 /// timeline's own first source. So a front-end runs *this* on its background
2145 /// executor and hands what comes back to
2146 /// [`import_probed`](Self::import_probed), which costs a push -- the same
2147 /// split [`parse_subtitles`](Self::parse_subtitles) makes, for the same
2148 /// reason.
2149 ///
2150 /// The container fork only: a song and a still fork before the demuxer
2151 /// ([`import`](Self::import)) and pay a header read of their own.
2152 ///
2153 /// The `Err` is the refusal [`import`](Self::import) would have given, in
2154 /// the same words -- nothing is refused twice and nothing is worded twice.
2155 pub fn probe_import(gate: ImportGate, path: &Path) -> crate::Result<ImportProbe> {
2156 let (meta, _) = Demuxer::open(path)?;
2157 let first = first_audio_of(&gate.sources)?;
2158 // Stream 0: an import brings a file in on its first audio track, and
2159 // [`place_stream_at`](Self::place_stream_at) is how any other one of
2160 // its streams reaches the timeline afterwards.
2161 // ...and the rate it will be read at comes back from the check that
2162 // accepted it, so the number the refusal was decided on is the number
2163 // the file is played by.
2164 let rate = matches_timeline(&Source::new(path, 0), &meta, &gate.timeline, &first)?;
2165 Ok(ImportProbe { gate, meta, rate })
2166 }
2167
2168 /// Registers a file already read by [`probe_import`](Self::probe_import).
2169 /// The whole of what an import costs the thread that calls it: a source
2170 /// entry and its length, no open, no seek, no decode -- which is why the
2171 /// probe is a separate door.
2172 ///
2173 /// The timeline may have moved while the worker read: a source removed or a
2174 /// file opened is a different set of things the probe was checked against,
2175 /// so the probe is re-read here ([`ImportGate`]) and a stale one is simply
2176 /// imported the slow way rather than trusted. Same answer either way, so no
2177 /// caller has to know which arm it took.
2178 pub fn import_probed(&mut self, path: &Path, probe: ImportProbe) -> crate::Result<usize> {
2179 match probe.gate.sources == self.project.sources() && probe.gate.timeline == self.meta {
2180 true => Ok(self.take_probe(path, probe)),
2181 false => self.import(path),
2182 }
2183 }
2184
2185 /// The push both import doors end at.
2186 fn take_probe(&mut self, path: &Path, probe: ImportProbe) -> usize {
2187 let source = self.project.import(path, 0);
2188 // Its length *on this timeline*: a file shot slower than the timeline
2189 // runs covers more frames than it holds, which is the whole of what
2190 // placing it at another rate means ([`Rate`]).
2191 self.note_frames(
2192 source,
2193 probe.rate.timeline_at(probe.meta.frame_count),
2194 probe.rate,
2195 );
2196 source
2197 }
2198
2199 /// The same registration for a standalone audio file: a song has no
2200 /// picture, so the length noted for it is its playing time rounded up to
2201 /// whole frames, which is the only frame count such a source has.
2202 ///
2203 /// Refused in the same words as any other import when its rate or layout
2204 /// disagrees with the timeline's -- one output device, one set of
2205 /// parameters -- and refused outright on a silent timeline, which has no
2206 /// device open at all. Nothing is changed by a refusal.
2207 fn import_audio(&mut self, path: &Path) -> crate::Result<usize> {
2208 let first = self.first_audio()?;
2209 // Stream 0, and there is no other: a standalone audio file carries one
2210 // track (`AudioSession::probe_streams`), so nothing here has a stream
2211 // to pick the way `place_stream_at` does for an mp4.
2212 audio_matches(&Source::new(path, 0), &first)?;
2213 let frames = audio_frames(path, self.meta.frame_rate)?;
2214 let source = self.project.import(path, 0);
2215 self.note_frames(source, frames, Rate::REAL_TIME);
2216 Ok(source)
2217 }
2218
2219 /// The same registration for a still image, and the shortest of the three:
2220 /// a picture has nothing to agree with. No frame rate (it is one picture),
2221 /// no audio (it is silent), and a resolution of its own is what every
2222 /// import is allowed -- the clip is placed on the project canvas by its fit
2223 /// policy. The one refusal left is a file that is not a picture at all, or
2224 /// one too big to compose ([`crate::is_resolution`]), and the header alone
2225 /// answers both.
2226 ///
2227 /// The length noted is the wall a trim is held to, not a duration the file
2228 /// has: see [`image_frames`].
2229 fn import_image(&mut self, path: &Path) -> crate::Result<usize> {
2230 let (width, height) = crate::decode::image_size(path)?;
2231 if !crate::is_resolution(width, height) {
2232 return Err(format!(
2233 "{} is {width}x{height}, which is not a picture this engine composes",
2234 path.display()
2235 )
2236 .into());
2237 }
2238 let source = self.project.import(path, 0);
2239 self.note_frames(source, image_frames(self.meta.frame_rate), Rate::REAL_TIME);
2240 Ok(source)
2241 }
2242
2243 /// Applies an edit and, if it took, rebuilds **what it dirtied** and nothing
2244 /// else ([`Dirty`]). A structural edit reseeks: `seek` clamps to the new
2245 /// duration and keeps playing playing, so a delete that shortens the
2246 /// timeline past the playhead lands on the last frame. A grade or a fit
2247 /// policy rebuilds the picture where it stands, with the sound running
2248 /// through it untouched -- no flush, no re-open, no hole -- and an
2249 /// equalizer the other way round.
2250 fn edit(&mut self, dirty: Dirty, f: impl FnOnce(&mut Project) -> bool) -> bool {
2251 if !f(&mut self.project) {
2252 return false;
2253 }
2254 self.invalidate(dirty);
2255 true
2256 }
2257
2258 /// Rebuilds the dirtied half (or both) at the playhead.
2259 fn invalidate(&mut self, dirty: Dirty) {
2260 match dirty {
2261 Dirty::Picture => {
2262 let (_, target) = self.landing(self.now());
2263 self.start_picture(target);
2264 }
2265 Dirty::Sound => self.reseek_audio(),
2266 Dirty::Both => {
2267 let now = self.now();
2268 self.seek(now);
2269 }
2270 }
2271 }
2272
2273 /// Current timeline position in seconds.
2274 pub fn now(&self) -> f64 {
2275 self.clock.now()
2276 }
2277
2278 pub fn is_playing(&self) -> bool {
2279 self.clock.is_playing()
2280 }
2281
2282 pub fn play(&mut self) {
2283 if self.clock.is_playing() {
2284 return;
2285 }
2286 // Invariant: the clock is positioned *before* audio restarts. Audio
2287 // reports are relative to the first one after that, so a seek would go
2288 // here too -- `clock.seek_to(t)` and then `set_active(true)`.
2289 self.clock.play();
2290 if let Some(audio) = &self.audio {
2291 audio.ao.lock().unwrap().set_active(true);
2292 }
2293 }
2294
2295 pub fn pause(&mut self) {
2296 if !self.clock.is_playing() {
2297 return;
2298 }
2299 if let Some(audio) = &self.audio {
2300 audio.ao.lock().unwrap().set_active(false);
2301 }
2302 self.clock.pause();
2303 }
2304
2305 pub fn toggle(&mut self) {
2306 if self.clock.is_playing() {
2307 self.pause()
2308 } else {
2309 self.play()
2310 }
2311 }
2312
2313 /// Stops the transport where the timeline stops: the clock is paused and put
2314 /// on the out point.
2315 ///
2316 /// Playing past the last frame is wall time counting on past the end of the
2317 /// media -- there is no picture left to pace it -- so a session left at EOF
2318 /// reports a `now()` that walks off the end of the timeline in real time,
2319 /// and a caller that reads the playhead (a cut, a paste, an insert) then
2320 /// acts at a position no clip is at. How far off depends only on how long
2321 /// the window was left open, so no clamp in a caller is worth writing.
2322 ///
2323 /// End of stream is deliberately left set: the picture is still the last
2324 /// frame and this is still the end. That is what makes it safe to call on
2325 /// the crossing into it -- the state the transport shows does not change,
2326 /// only the running clock stops.
2327 pub fn halt_at_end(&mut self) {
2328 self.pause();
2329 self.clock.seek_to(self.timeline_duration());
2330 }
2331
2332 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
2333 /// one knob, because muting and turning it down are the same thing to the
2334 /// device, and *which* the user meant is a question only the UI can answer
2335 /// -- it keeps the level to come back to.
2336 ///
2337 /// Deliberately not session state: nothing here remembers it, so a caller
2338 /// pushes it once per session and an export -- which renders the file
2339 /// rather than what the speakers are doing -- can never pick it up. Silent
2340 /// with no audio device, which is also the only honest answer there.
2341 ///
2342 /// Mute is not pause: the samples are still consumed and the device clock
2343 /// still runs, so the picture keeps playing against it.
2344 pub fn set_gain(&self, gain: f32) -> bool {
2345 match &self.audio {
2346 Some(audio) => audio.ao.lock().unwrap().set_volume(gain),
2347 None => false,
2348 }
2349 }
2350
2351 /// A copy of the most recent mono samples the device was handed, and the
2352 /// rate they play at: the signal *after* every clip's equalizer, speed and
2353 /// the mix, which is what an analyser drawn behind an EQ curve has to show.
2354 /// `None` with no audio output at all, and empty until the feeder has
2355 /// written once (right after a seek, for instance).
2356 ///
2357 /// Never blocks anything that matters: the feeder holds this lock for one
2358 /// memcpy and the device's own callback lives in the plugin, on the far
2359 /// side of a ring buffer, where it cannot see this at all.
2360 pub fn audio_tap(&self) -> Option<(Vec<f32>, u32)> {
2361 let audio = self.audio.as_ref()?;
2362 let tap = audio.tap.lock().unwrap().clone();
2363 Some((tap, audio.sample_rate))
2364 }
2365
2366 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
2367 /// workers are replaced rather than steered: a fresh channel cannot hold a
2368 /// stale frame, and it works just as well after EOF, where the old workers
2369 /// have already exited.
2370 ///
2371 /// Playing stays playing and paused stays paused -- but a paused seek still
2372 /// decodes, so the caller can show the frame it landed on.
2373 pub fn seek(&mut self, secs: f64) {
2374 let (t, target) = self.landing(secs);
2375 let was_playing = self.clock.is_playing();
2376 self.stop_audio();
2377 self.start_picture(target);
2378 let audio_running = self.start_audio(target);
2379 // Same invariant as `play`: position the clock before audio restarts.
2380 if audio_running && self.clock.source() != ClockSource::Audio {
2381 self.clock.switch_to_audio();
2382 }
2383 self.clock.seek_to(t);
2384 self.resume(was_playing);
2385 }
2386
2387 /// Where a seek to `secs` lands: the clamped timeline position and the
2388 /// timeline frame it means. The one place the clamp lives, so every
2389 /// invalidation below lands on the same frame a seek would.
2390 fn landing(&self, secs: f64) -> (f64, u32) {
2391 let fps = self.meta.frame_rate;
2392 let total = self.project.timeline_frames();
2393 let t = secs.clamp(0.0, f64::from(total) / fps);
2394 (t, secs_to_frame(t, fps).min(total.saturating_sub(1)))
2395 }
2396
2397 /// Rebuilds the **picture** at `target` and touches nothing else: the sound
2398 /// keeps playing out of the same stream, the clock keeps running, and a
2399 /// grade dragged during playback is therefore silent.
2400 fn start_picture(&mut self, target: u32) {
2401 // Cancel first, drop second: the old worker may be parked in `send` on
2402 // the bounded channel, where only the disconnect wakes it -- and it
2403 // then finds the flag already set. It is then parked, not joined; see
2404 // [`retire`](Self::retire), which is what keeps a scrub off the price
2405 // of a VA-API init.
2406 self.worker.cancel();
2407 // The span runs from `target` to the end of whatever it landed in -- a
2408 // clip, or a gap, which starts a black-frame worker instead. `None` is
2409 // the emptied timeline, black too, and `start_span` says so.
2410 self.start_span(self.project.composite_span_at(target));
2411 self.eos = false;
2412 }
2413
2414 /// Silences the device and supersedes whatever is feeding it: the first half
2415 /// of every audio restart, and the only thing that ever discards queued
2416 /// sound.
2417 fn stop_audio(&mut self) {
2418 self.mix = None;
2419 if let Some(audio) = &self.audio {
2420 let ao = audio.ao.lock().unwrap();
2421 ao.set_active(false);
2422 // Bumped and flushed while holding the device lock, because the
2423 // feeder re-checks the epoch inside that same lock: whatever it is
2424 // carrying can no longer reach the ring after this point.
2425 audio.epoch.fetch_add(1, Ordering::Release);
2426 // Nothing of the new stream has been played yet, by definition.
2427 audio.content_at.store(-1, Ordering::Release);
2428 ao.flush();
2429 // The flushed samples are not being played any more, so nothing may
2430 // still be drawn from them.
2431 audio.tap.lock().unwrap().clear();
2432 }
2433 }
2434
2435 /// Puts the device back where it was: playing if it was playing, and with
2436 /// the clock held until the new stream is really audible (see
2437 /// [`Audio::content_at`]).
2438 ///
2439 /// ponytail: the device is made active here, before the new stream has been
2440 /// opened ([`start_audio`](Self::start_audio) opens on the feeder now), so a
2441 /// cold open leaves it playing its own silence with an empty ring -- audibly
2442 /// the same silence as before, and counted: a scripted cold play-seek-scrub
2443 /// session goes from 5 to 1721 `engine_audio: N underruns`, one per starved
2444 /// quantum, while a warm one is unchanged (46 -> 53 over the suite's 11
2445 /// sessions). Ceiling: the count stops meaning "the decoder was late" during
2446 /// a cold seek. Upgrade path is a `wants_active` flag written here and read
2447 /// by the feeder under the device lock beside the [`Audio::content_at`]
2448 /// stamp, so the device is started by the first real sample rather than by
2449 /// the intent to play -- it has to be the lock and the epoch check, or a
2450 /// pause during the open would be overtaken by a late activation and the
2451 /// timeline would play while it says it is paused.
2452 fn resume(&mut self, was_playing: bool) {
2453 self.priming = true;
2454 if was_playing && let Some(audio) = &self.audio {
2455 audio.ao.lock().unwrap().set_active(true);
2456 }
2457 }
2458
2459 /// Rebuilds the **sound** from `target` -- the second half of a restart --
2460 /// and says whether a feeder took the job. Not whether it will find
2461 /// anything to play: the stream is opened on that feeder
2462 /// ([`Audio::spawn_feeder_deferred`]), so a silent timeline is heard of
2463 /// there, not here. Nothing on this thread reads the file.
2464 ///
2465 /// The clock is unaffected by the wait, which is the reason it may be a
2466 /// long one: it holds where the seek put it until the *first real sample*
2467 /// is queued ([`Audio::content_at`], [`tick`](Self::tick)), whether that is
2468 /// ten milliseconds later or ten seconds.
2469 ///
2470 /// `true` is therefore *optimistic*, and the callers' `switch_to_audio` with
2471 /// it: a timeline that turns out to have nothing to play ends its feeder at
2472 /// once, which sets `fed_all` and hands the clock back to wall time at the
2473 /// next tick, from where it stood ([`PlaybackClock::switch_to_wall`] is
2474 /// continuous, so nothing jumps).
2475 fn start_audio(&mut self, target: u32) -> bool {
2476 let fps = self.meta.frame_rate;
2477 let mut audio_running = false;
2478 let mut live = None;
2479 if let Some(audio) = &self.audio
2480 && !audio.died.load(Ordering::Acquire)
2481 {
2482 // The device position keeps counting across a flush, so re-basing
2483 // `fed` on it is what keeps `played_out` exact for the new stream.
2484 let played = audio.ao.lock().unwrap().position().unwrap_or(0).max(0) as u64;
2485 audio.fed.store(played * audio.channels, Ordering::Relaxed);
2486 audio.fed_all.store(false, Ordering::Release);
2487 // One worker for the whole rest of the timeline, so the joins
2488 // between clips are gapless: the video reopens at a boundary, the
2489 // ear never hears it -- and a join between two *files* is just
2490 // another segment, because every segment names its own source.
2491 // One play list per audio lane, summed by the mixer: what the ear
2492 // hears is every lane at once, and a lane's own gaps are silence in
2493 // it rather than a hole in the count the master clock keeps.
2494 let segs = self.project.audio_segments_from(target, fps);
2495 // The equalizers beside them, one per segment: the worker filters a
2496 // segment's own samples before the mix, so a clip's curve reaches
2497 // that clip and stops. Rebuilt on every seek, which is what makes an
2498 // EQ edit audible at once -- `edit` reseeks, so the drag that
2499 // changed a band restarts the workers with the new curve already in
2500 // them, and no live channel has to reach into a running one.
2501 let eqs = self.project.audio_eqs_from(target, fps);
2502 // ...and the rates, the same way again: a speeded segment is
2503 // resampled inside its own worker, before the mix, so what the ear
2504 // hears is what the timeline shows. Empty for a project nobody has
2505 // speeded, which is the path that decodes the same samples it always
2506 // did.
2507 let speeds = self.project.audio_speeds_from(target, fps);
2508 // Each source on the stream it was placed with: what plays is what
2509 // the library row said, and what an export copies (`export::run`).
2510 let sources = self.project.audio_sources();
2511 // ...and the mix settings over the lot: each lane's own volume on
2512 // its way into the sum and the master limiter over the sum. These
2513 // two are handed over *live* as well as at the open: they sit at
2514 // the sum, where nothing is decoded, so a fader moved later is a
2515 // number the running mixer picks up rather than a stream rebuilt
2516 // under the ear ([`crate::audio::MixControls`]).
2517 let gains = self.project.audio_gains();
2518 let limiter = self.project.limiter();
2519 let controls = crate::audio::MixControls::new(gains.clone(), limiter);
2520 // Only a mixed timeline has a mixer to talk to; the single-lane
2521 // flat path is the bit-exact one and has none. Decided here from
2522 // the very lists the open is about to be handed
2523 // ([`AudioSession::is_mixed`]) rather than read off the handle
2524 // afterwards, because there *is* no afterwards on this thread any
2525 // more -- the open runs on the feeder.
2526 let mixed = crate::audio::AudioSession::is_mixed(segs.len(), &gains, limiter);
2527 let worker_controls = Arc::clone(&controls);
2528 // ...and the open itself -- every track a segment names, its packet
2529 // table, its priming -- happens there too. That is the whole point:
2530 // one `pread` on a cold 25 GB film is seconds, and this is called
2531 // from a ruler drag ([`Audio::spawn_feeder_deferred`]).
2532 audio_running = audio.spawn_feeder_deferred(move || {
2533 match AudioSession::open_mixed_streams_live(
2534 &sources,
2535 &segs,
2536 &eqs,
2537 &speeds,
2538 &gains,
2539 limiter,
2540 Some(&worker_controls),
2541 ) {
2542 Ok(Some((_, rx))) => Some(rx),
2543 // A silent timeline, and a source that will not open: both
2544 // feed nothing, which the feeder itself reports by ending.
2545 Ok(None) => None,
2546 Err(e) => {
2547 eprintln!("timeline audio open failed: {e}");
2548 None
2549 }
2550 }
2551 });
2552 live = (audio_running && mixed).then_some(controls);
2553 if !audio_running {
2554 // Nothing will ever be fed again; let `tick` fall to wall time
2555 // instead of waiting on a device that has no more work coming.
2556 audio.fed_all.store(true, Ordering::Release);
2557 }
2558 }
2559 self.mix = live;
2560 audio_running
2561 }
2562
2563 /// Rebuilds the sound alone, from where the playhead is: what a change that
2564 /// no picture can show goes through. The video worker is left decoding, so
2565 /// the picture does not blink -- and the clock, held still by
2566 /// [`resume`](Self::resume) until the new stream is audible, puts the sound
2567 /// back exactly where the picture already is.
2568 ///
2569 /// End of stream is deliberately left alone -- no picture worker is started
2570 /// here, so a timeline that was played out still is; see
2571 /// [`is_eos`](Self::is_eos).
2572 fn reseek_audio(&mut self) {
2573 let (t, target) = self.landing(self.now());
2574 let was_playing = self.clock.is_playing();
2575 self.stop_audio();
2576 let audio_running = self.start_audio(target);
2577 if audio_running && self.clock.source() != ClockSource::Audio {
2578 self.clock.switch_to_audio();
2579 }
2580 self.clock.seek_to(t);
2581 self.resume(was_playing);
2582 }
2583
2584 /// Renders the edited timeline to `out` on a worker thread. The session is
2585 /// untouched -- the export decodes the source file for itself -- but a
2586 /// caller should still [`pause`](PlaybackSession::pause) first, because
2587 /// playback and export otherwise fight over the same decoder hardware.
2588 ///
2589 /// Later edits do not reach a running export: it works from a snapshot of
2590 /// the edit list taken here.
2591 ///
2592 /// ponytail: this defaults the settings; the app still calls it that way,
2593 /// and the export options card replaces the call with
2594 /// [`export_to_with`](PlaybackSession::export_to_with).
2595 pub fn export_to(&self, out: &Path) -> crate::ExportHandle {
2596 self.export_to_with(out, &crate::export::ExportSettings::default())
2597 }
2598
2599 /// [`export_to`](PlaybackSession::export_to) with the output settings spelled
2600 /// out rather than defaulted.
2601 pub fn export_to_with(
2602 &self,
2603 out: &Path,
2604 settings: &crate::export::ExportSettings,
2605 ) -> crate::ExportHandle {
2606 crate::export::start(self.project.export_snapshot(), self.meta, out, settings)
2607 }
2608
2609 /// Moves the clock forward; the caller runs this once per rendered frame.
2610 /// Costs an atomic load, and once per session a mode switch.
2611 pub fn tick(&mut self) {
2612 let Some(audio) = &self.audio else {
2613 return; // wall time from the start, nothing to poll
2614 };
2615 if self.clock.source() != ClockSource::Audio {
2616 return;
2617 }
2618 if audio.died.load(Ordering::Acquire) {
2619 // Output died mid-stream: its position will never reach `fed`, so
2620 // the EOF comparison below is unreachable. Wall time takes over
2621 // from wherever the clock last stood.
2622 self.clock.switch_to_wall();
2623 return;
2624 }
2625 // `None` until the device's first callback: the clock holds at its
2626 // anchor rather than guessing, which is why playback starts on time
2627 // instead of a quantum early.
2628 let Some(position) = audio.ao.lock().unwrap().position() else {
2629 return;
2630 };
2631 if audio.played_out(position) {
2632 // Audio EOF. Wall time carries the same timeline on from here, with
2633 // no jump, and this branch cannot be reached again.
2634 self.clock.switch_to_wall();
2635 return;
2636 }
2637 if self.priming {
2638 // A stream that has been started and has not been heard yet: the
2639 // device is playing the silence of its own restart, and none of it
2640 // is timeline time ([`Audio::content_at`]). The clock holds where
2641 // the seek left it -- so the picture holds too, on the frame it
2642 // landed on, rather than sliding ahead of a sound that has not
2643 // started.
2644 let started = audio.content_at.load(Ordering::Acquire);
2645 if started < 0 {
2646 return;
2647 }
2648 // ...and then the *first sample of the stream* becomes the
2649 // reference, not whatever position this poll happened to catch: the
2650 // clock's own anchor is its first report ([`PlaybackClock`]), and
2651 // anchoring it here is what makes a mid-play edit cost no offset.
2652 //
2653 // ponytail: `started` is the position when the sample was queued,
2654 // and it is heard at the next callback -- up to one quantum (5-21
2655 // ms) later, so that much of the restart is still counted. Upgrade
2656 // path is the position at the first *pop* of real audio, which only
2657 // the plugin's RT thread can see.
2658 self.clock
2659 .set_audio_position(started as u64, audio.sample_rate);
2660 self.priming = false;
2661 }
2662 self.clock
2663 .set_audio_position(position as u64, audio.sample_rate);
2664 }
2665}
2666
2667impl Drop for PlaybackSession {
2668 /// The video workers -- the running one and every cancelled one still in
2669 /// [`retired`](PlaybackSession::retired) -- cancel and join themselves when
2670 /// those fields drop right after this, the running one behind its receiver
2671 /// so a `send` cannot hold the join. *That* is what a session must not exit
2672 /// without: no decode worker outlives it, so none can be inside libva when
2673 /// Mesa's `atexit` handlers free the state under it.
2674 ///
2675 /// This is the audio half: bumping the epoch retires the feeder at its next write,
2676 /// which drops the decode receiver with it. Neither is waited for -- no
2677 /// driver state is torn down on the audio side.
2678 fn drop(&mut self) {
2679 if let Some(audio) = &self.audio {
2680 audio.epoch.fetch_add(1, Ordering::Release);
2681 }
2682 }
2683}
2684
2685/// Whether `path`, already demuxed to `meta`, may join a timeline whose
2686/// parameters are `timeline` and whose audio probes as `first`: a decoder this
2687/// machine can open, audio parameters that agree (or no audio at all), and a
2688/// frame rate that can be named
2689/// against the timeline's. The [`Rate`] it will be read at comes back with the
2690/// answer, so the number the check was decided on is the number it plays by.
2691///
2692/// *Not* the same size any more. A project has its own resolution
2693/// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its
2694/// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
2695/// letterboxed clip rather than a refusal, and so is a frame rate of its own:
2696/// the timeline keeps its own rate and the file is read at [`Rate`] against it
2697/// ([`PlaybackSession::import`] notes how long it is *here*). Nor the same
2698/// codec: every clip opens its own decoder, so a mixed-codec timeline is a
2699/// decoder each rather than a refusal.
2700///
2701/// The `Err` names the property that disagrees, and those strings are what a
2702/// front-end shows verbatim; [`PlaybackSession::import`] and
2703/// [`PlaybackSession::open_project`] share them so a file refused at import is
2704/// refused in the same words at load.
2705fn matches_timeline(
2706 source: &Source,
2707 meta: &VideoMeta,
2708 timeline: &VideoMeta,
2709 first: &Option<crate::AudioProbe>,
2710) -> crate::Result<Rate> {
2711 // The codec is *not* held to the timeline's -- every clip opens its own
2712 // decoder, so an H.264 take and an HEVC one play on one timeline. What the
2713 // codec gate was really protecting against stays, in the one place that can
2714 // actually answer it: on a machine without the VA-API plugin an HEVC or VP9
2715 // clip would be black frames with the refusal on stderr alone, so the file
2716 // is asked for a decoder *here*, at the door, where the `Err` is still
2717 // something a front-end can show. A zero-length range probes and starts no
2718 // worker, and H.264 costs nothing at all -- [`DecodeSession::open_worker`]
2719 // only enters VA-API off that path.
2720 DecodeSession::open_worker(
2721 &source.path,
2722 0,
2723 0,
2724 ColorParams::default(),
2725 Composer::passthrough(),
2726 // A zero-length range decodes nothing, so no table is built and the
2727 // rendition cannot matter here.
2728 crate::tonemap::Preset::default(),
2729 )?;
2730 // The frame rate is *not* a refusal any more: a file shot at another rate is
2731 // placed for the seconds it lasts and read through [`Rate`] at the
2732 // decoder's door, so it plays at the speed it was shot at on a timeline
2733 // that counts frames faster or slower.
2734 //
2735 // A rate that cannot be *named* still is, and this is the one place it is
2736 // caught: `Rate::from_fps` builds itself out of the muxer's own timescales,
2737 // and a file whose rate has none of those (a container that says nothing and
2738 // holds one block, so the demuxer measures 0 fps) would otherwise be read
2739 // 1:1 in silence -- the old rate gate refused those too, by arithmetic
2740 // accident. The `Err` is `mux::frame_timing`'s own words.
2741 let rate = Rate::from_fps(meta.frame_rate, timeline.frame_rate)?;
2742 audio_matches(source, first)?;
2743 Ok(rate)
2744}
2745
2746/// Whether a candidate's audio may join a timeline whose first source probes as
2747/// `first`: same layout -- or no audio of its own at all, which is silence over
2748/// the clip's span and agrees with everything. One output device and one
2749/// exported track is all there is, so one width; the *rate* is conformed rather
2750/// than matched ([`crate::audio::Resample`]), which is why it is not asked
2751/// about here.
2752///
2753/// The audio half of [`matches_timeline`], which a stream placed on its own
2754/// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
2755/// comes with is already on the timeline.
2756///
2757/// The format itself is deliberately *not* part of this: an mp3 that agrees on
2758/// layout plays alongside a timeline of mp4s perfectly well. What it
2759/// cannot do is be copied into an export, which is a refusal of its own, at
2760/// export time (`AudioSession::copy_multi_streams`).
2761/// What a timeline's audio is held to: the probe of the first source that could
2762/// have any. A still image is never it -- a picture defines no rate and no
2763/// layout, so a PNG at index 0 would otherwise be *probed* as a broken mp4 and
2764/// fail the open outright.
2765///
2766/// `Ok(None)` for a timeline whose first such source is silent, and for one of
2767/// nothing but stills. That is a silent timeline, and a file with sound is
2768/// still refused by [`audio_matches`] in the words it always used ("the file
2769/// has audio, the timeline is silent") -- the device was opened on source 0's
2770/// track and there is none to open. This function widens which source is asked,
2771/// not what the answer means.
2772fn first_audio_of(sources: &[Source]) -> crate::Result<Option<crate::AudioProbe>> {
2773 match audio_source_of(sources) {
2774 Some(first) => AudioSession::probe(&first.path, first.audio_stream),
2775 None => Ok(None),
2776 }
2777}
2778
2779/// *Which* source that is: the first one that is not a still. The single answer
2780/// to "what does this timeline's sound come from", so that probing it
2781/// ([`first_audio_of`]) and opening the device on it
2782/// ([`PlaybackSession::open_project`]) can never disagree -- source 0 is only
2783/// the scaffolding file until a save renumbers it or a library removal takes it
2784/// away ([`crate::Project::remove_source`]), and a PNG at index 0 opened as the
2785/// device is a timeline that plays silent although every clip on it has sound.
2786///
2787/// `None` for a library of nothing but stills, and for one with no file at all:
2788/// both are silent timelines.
2789fn audio_source_of(sources: &[Source]) -> Option<&Source> {
2790 sources.iter().find(|s| !crate::is_image(&s.path))
2791}
2792
2793fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
2794 // The layout, which the audio worker holds every source to anyway -- and not
2795 // the rate any more: a file written at another one is resampled to the
2796 // timeline's at the decoder's door ([`crate::audio::Resample`]), exactly as
2797 // a file shot at another frame rate is read through [`Rate`]. Both silent is
2798 // a match.
2799 let probe = AudioSession::probe(&source.path, source.audio_stream)?;
2800 if probe.map(|p| p.channels) == first.map(|p| p.channels) {
2801 return Ok(());
2802 }
2803 // ...and a *silent* file joins whatever the timeline is: it contributes
2804 // silence over its span, which is the very thing both audio paths already
2805 // synthesise for a gap ([`AudioSession::open_multi_streams_speed`] plays
2806 // it, `AudioSession::copy_multi_streams` writes it). There is no rate and
2807 // no layout to disagree about, so there is nothing left to refuse.
2808 let Some(probe) = probe else {
2809 return Ok(());
2810 };
2811 Err(match first {
2812 None => "the file has audio, the timeline is silent".to_string(),
2813 Some(b) => format!(
2814 "audio {} ch does not match the timeline's {} ch",
2815 probe.channels, b.channels
2816 ),
2817 }
2818 .into())
2819}
2820
2821/// How many timeline frames a still image is *held to*: [`IMAGE_MAX_SECS`] of
2822/// them, since an image has no length of its own. The number a source's own
2823/// entry in [`PlaybackSession::counts`] gets, so a trim may drag an image out
2824/// to ten minutes and no further -- and so a saved project reloads, because
2825/// [`PlaybackSession::open_project`] recomputes exactly this and refuses a clip
2826/// that ends past it.
2827fn image_frames(fps: f64) -> u32 {
2828 ((IMAGE_MAX_SECS * fps)
2829 .ceil()
2830 .clamp(1.0, f64::from(u32::MAX))) as u32
2831}
2832
2833/// How long a still is placed for: [`IMAGE_PLACE_SECS`], never past the length
2834/// it is held to and never zero (a clip is never empty).
2835fn place_frames(count: u32, fps: f64) -> u32 {
2836 ((IMAGE_PLACE_SECS * fps)
2837 .ceil()
2838 .clamp(1.0, f64::from(count.max(1)))) as u32
2839}
2840
2841/// How many timeline frames a standalone audio file occupies: its playing time
2842/// rounded *up*, so the last partial frame is still covered rather than cut off,
2843/// and never zero (a clip is never empty).
2844fn audio_frames(path: &Path, fps: f64) -> crate::Result<u32> {
2845 let secs = AudioSession::duration_secs(path)?
2846 .ok_or_else(|| format!("{} has no audio track", path.display()))?;
2847 let frames = (secs * fps).ceil();
2848 if !frames.is_finite() || frames < 0.0 || frames > f64::from(u32::MAX) {
2849 return Err(format!(
2850 "{} is {secs} s long, which is not a timeline",
2851 path.display()
2852 )
2853 .into());
2854 }
2855 Ok((frames as u32).max(1))
2856}
2857
2858/// `None` for a silent session -- no audio track, no plugin, no daemon, or a
2859/// track the decoder refuses. Dropping the receiver on the way out stops the
2860/// audio decode worker, so a failure here leaves nothing running.
2861///
2862/// The second half is why, for the cases the *file* is to blame for: those are
2863/// a surprise worth showing (see
2864/// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a
2865/// file with no audio at all and a machine with no output device are not.
2866fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
2867 let sources = [(path.to_path_buf(), stream)];
2868 let (meta, rx) =
2869 match AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) {
2870 Ok(Some(opened)) => opened,
2871 // No AAC track: silent by nature, or sound in a codec we do not
2872 // have -- and only the second of those is worth a word.
2873 Ok(None) => {
2874 let reason = AudioSession::unsupported(path).ok().flatten();
2875 if let Some(reason) = &reason {
2876 eprintln!("audio disabled: {reason}");
2877 }
2878 return (None, reason);
2879 }
2880 Err(e) => {
2881 eprintln!("audio disabled: {e}");
2882 return (None, Some(e.to_string()));
2883 }
2884 };
2885 let Some(ao) = AoSession::open(meta.sample_rate, u32::from(meta.channels)) else {
2886 return (None, None); // no device: the machine's business, not the file's
2887 };
2888 // The stream comes up streaming; a session starts paused, so silence the
2889 // device until `play`. The feeder still fills the ring in the meantime.
2890 ao.set_active(false);
2891
2892 let audio = Audio {
2893 ao: Arc::new(Mutex::new(ao)),
2894 sample_rate: meta.sample_rate,
2895 channels: u64::from(meta.channels),
2896 fed: Arc::new(AtomicU64::new(0)),
2897 fed_all: Arc::new(AtomicBool::new(false)),
2898 died: Arc::new(AtomicBool::new(false)),
2899 epoch: Arc::new(AtomicU64::new(0)),
2900 content_at: Arc::new(AtomicI64::new(-1)),
2901 tap: Arc::new(Mutex::new(Vec::with_capacity(TAP_SAMPLES))),
2902 };
2903 (audio.spawn_feeder(rx).then_some(audio), None)
2904}
2905
2906/// Pours decoded chunks into the device, keeping whatever the ring would not
2907/// take. Ends when the decoder is done, the output dies, or a seek supersedes
2908/// this feeder.
2909fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
2910 let mut pending: Vec<f32> = Vec::new();
2911 loop {
2912 if pending.is_empty() {
2913 match rx.recv() {
2914 Ok(chunk) => pending = chunk.samples,
2915 Err(_) => return, // decoder finished or went away
2916 }
2917 }
2918 let accepted = {
2919 let mut ao = audio.ao.lock().unwrap();
2920 // Under the lock, immediately before the write: `seek` bumps the
2921 // epoch and flushes the ring holding this very lock, so past this
2922 // check no stale sample can be queued behind the flush.
2923 if audio.epoch.load(Ordering::Acquire) != epoch {
2924 return;
2925 }
2926 let accepted = match ao.write(&pending) {
2927 Some(n) => n,
2928 None => {
2929 // Output died; flag it so `tick` moves the clock to wall time.
2930 audio.died.store(true, Ordering::Release);
2931 return;
2932 }
2933 };
2934 // The first sample of this stream to reach the ring, stamped with
2935 // what the device had played by then: everything before it was the
2936 // silence of the restart, and [`PlaybackSession::tick`] anchors the
2937 // clock here so that silence is never timeline time. Under the
2938 // device lock, with the epoch already checked, so the stamp and the
2939 // sample belong to the same stream.
2940 if accepted > 0 && audio.content_at.load(Ordering::Acquire) < 0 {
2941 let at = ao.position().unwrap_or(0).max(0);
2942 audio.content_at.store(at, Ordering::Release);
2943 // ...and the device position this stream's samples are counted
2944 // from ([`Audio::played_out`]). Rebased *here* rather than at
2945 // the seek, because the open runs on this thread now: every
2946 // millisecond it took is device time nobody fed, and counting
2947 // it would make the stream read as played out that long before
2948 // it really is -- an early hand-off to wall time at the end of
2949 // the timeline. The seek's own rebase still stands for the
2950 // stream that never queues a sample at all.
2951 audio
2952 .fed
2953 .store(at as u64 * audio.channels, Ordering::Relaxed);
2954 }
2955 accepted
2956 };
2957 audio.fed.fetch_add(accepted as u64, Ordering::Relaxed);
2958 audio.note_tap(&pending[..accepted]);
2959 pending.drain(..accepted);
2960 if !pending.is_empty() {
2961 // Ring full: nothing to do but let the device drain it. Except when
2962 // *nothing* was taken, which after a flush means the ring is still
2963 // waiting for the device to consume the flush flag rather than
2964 // being full: that is the head of a restart, and every millisecond
2965 // spent parked there is a millisecond of silence.
2966 match accepted {
2967 0 => thread::sleep(FLUSH_WAIT),
2968 _ => thread::sleep(RING_FULL_WAIT),
2969 }
2970 }
2971 }
2972}
2973
2974/// Timeline seconds to a 0-based frame index, floor semantics: position `t`
2975/// shows the frame whose interval contains it. The epsilon absorbs float error
2976/// at exact frame boundaries -- `123.0/30.0 * 30.0` is `122.999...`, and a
2977/// bare truncation would land one frame early (S6 finding: 4 of every 300
2978/// frames round-trip wrong through `clip_spans()` seconds without this).
2979fn secs_to_frame(secs: f64, fps: f64) -> u32 {
2980 (secs * fps + 1e-6).floor().max(0.0) as u32
2981}
2982
2983#[cfg(test)]
2984mod tests {
2985 use super::{Edge, Lane, PlaybackSession, Source, audio_source_of, secs_to_frame};
2986 use std::path::PathBuf;
2987
2988 fn asset(name: &str) -> PathBuf {
2989 PathBuf::from(env!("CARGO_MANIFEST_DIR"))
2990 .join("../../assets")
2991 .join(name)
2992 }
2993
2994 /// Which source the timeline's sound is opened on -- the one rule
2995 /// [`open_project`](PlaybackSession::open_project), the probe every import
2996 /// is held to and the audio worker all read through. A still at index 0 is
2997 /// a picture, not a silent timeline: opening the device on it is a project
2998 /// that plays silent although every clip on it has sound.
2999 #[test]
3000 fn the_audio_reference_is_never_a_still() {
3001 let (video, still) = (asset("test_av.mp4"), asset("test_still.png"));
3002 let sources = [Source::new(&still, 0), Source::new(&video, 3)];
3003 assert_eq!(
3004 audio_source_of(&sources).map(|s| (&s.path, s.audio_stream)),
3005 Some((&sources[1].path, 3)),
3006 "the first source that could have a track, with its own stream"
3007 );
3008 assert!(
3009 audio_source_of(&sources[..1]).is_none(),
3010 "nothing but stills"
3011 );
3012 assert!(audio_source_of(&[]).is_none(), "and no file at all");
3013 }
3014
3015 /// The seam between the two lists a source index reaches: dropping a file
3016 /// from the library shortens `sources`, and `counts` -- the frame length
3017 /// per source, which is what a trim is walled by -- has to lose the same
3018 /// entry. Left behind, the dead file's length would wall the survivor.
3019 #[test]
3020 fn removing_a_source_takes_its_frame_count_with_it() {
3021 // Source 0 is 5 s, source 1 is 4 s: two different walls, so a stale
3022 // count cannot pass for the right one.
3023 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3024 session.set_gain(0.0);
3025 // Imported, then dragged onto the end -- an import alone places nothing
3026 // ([`PlaybackSession::import`]), and this test needs both takes there.
3027 session.import(&asset("test_av2.mp4")).expect("av2 matches");
3028 let end = session.timeline_duration();
3029 assert!(
3030 session
3031 .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
3032 .expect("a file just imported is on this timeline")
3033 );
3034 let (long, short) = (session.counts[0], session.counts[1]);
3035 assert!(long > short, "{long} vs {short}");
3036
3037 // Clear source 0's take, then take the file itself out: av2's clip is
3038 // the only one left and it is source 0 now.
3039 assert!(session.delete_clip(Lane::V1, 0));
3040 session
3041 .remove_source(&asset("test_av.mp4"), 0)
3042 .expect("nothing plays it any more");
3043 assert_eq!(session.counts, vec![short], "the dead length went with it");
3044 assert_eq!(session.sources().len(), session.counts.len());
3045
3046 // The wall is the surviving file's own length, not the gone one's: a
3047 // whole-file clip cannot be dragged out any further at all.
3048 let clip = session.lane_clips(Lane::V1)[0];
3049 assert_eq!(clip.len(), short, "av2's take, whole");
3050 assert_eq!(
3051 session.trim_room(Lane::V1, 0, Edge::End),
3052 Some((clip.start + 1, clip.end()))
3053 );
3054 assert!(
3055 !session.trim_clip(Lane::V1, 0, Edge::End, clip.end() + 30),
3056 "past the file's last frame is refused, by ITS length"
3057 );
3058
3059 // ...and the next import still lines the two lists up, which is the
3060 // alignment `note_frames` asserts on.
3061 session
3062 .import(&asset("test_av.mp4"))
3063 .expect("it may come back");
3064 assert_eq!(session.counts, vec![short, long]);
3065 assert_eq!(session.sources().len(), session.counts.len());
3066 }
3067
3068 #[test]
3069 fn boundary_seconds_round_trip_to_their_own_frame() {
3070 for f in 0u32..300 {
3071 let secs = f64::from(f) / 30.0;
3072 assert_eq!(secs_to_frame(secs, 30.0), f, "frame {f}");
3073 }
3074 // Mid-frame positions still floor, and negatives clamp.
3075 assert_eq!(secs_to_frame(10.5 / 30.0, 30.0), 10);
3076 assert_eq!(secs_to_frame(-0.2, 30.0), 0);
3077 }
3078}