forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2c8e3aaTahinli3 months ago335 commits

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