forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB80ecf3dTahinli3 months ago230 commits

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