forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBcc667e6Tahinli3 months ago285 commits

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