forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

playback.rs1300 lines, 59.1 KiBHistoryRawDownload
1//! One timeline over one or more files: the decode workers, the audio output
2//! and the master clock wired together so a front-end only has to render and
3//! call [`tick`].
4//!
5//! [`tick`]: PlaybackSession::tick
6//!
7//! Everything degrades to silent-but-correct: no audio track, no plugin, no
8//! PipeWire daemon and an unusable format all end up in [`ClockSource::Wall`],
9//! where the video is paced by real time instead of by the device.
10//!
11//! Drift policy stays with the caller -- this type answers "what time is it",
12//! the renderer decides which frame that means.
13
14use std::path::Path;
15use std::sync::atomic::{AtomicBool, 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::{DecodeSession, Frame, Worker};
26use crate::demux::{Demuxer, VideoMeta};
27use crate::eq::EqParams;
28use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};
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 output half of a session: the device, plus what the feeder has handed it.
36/// Cloned into the feeder thread; every field that matters is shared.
37#[derive(Clone)]
38struct Audio {
39 /// Shared because `write` runs on the feeder thread while `position` and
40 /// `set_active` are called from the caller's. The plugin serialises those
41 /// itself (atomics and a channel), but the lock is what makes it sayable in
42 /// Rust and it is never held for more than a memcpy.
43 ao: Arc<Mutex<AoSession>>,
44 sample_rate: u32,
45 channels: u64,
46 /// Interleaved samples accepted by the device so far.
47 fed: Arc<AtomicU64>,
48 /// The decoder ran out and `fed` is final.
49 fed_all: Arc<AtomicBool>,
50 /// The output plugin failed mid-stream. Its position is frozen from here on,
51 /// so it can never satisfy [`Audio::played_out`] -- the flag is what lets
52 /// [`PlaybackSession::tick`] hand the timeline to wall time instead.
53 died: Arc<AtomicBool>,
54 /// Bumped by every seek. A feeder only owns the device while this still
55 /// matches the value it started with; see [`feed`].
56 epoch: Arc<AtomicU64>,
57}
58
59impl Audio {
60 /// Whether the device has played everything there will ever be, i.e. the
61 /// audio clock is about to stop meaning anything.
62 fn played_out(&self, position: i64) -> bool {
63 self.fed_all.load(Ordering::Acquire)
64 && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed)
65 }
66
67 /// Starts a feeder for the current epoch, draining `rx` into the device.
68 /// `false` if the thread would not start, i.e. nothing will ever be fed.
69 fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool {
70 let me = self.clone();
71 let epoch = self.epoch.load(Ordering::Acquire);
72 thread::Builder::new()
73 .name("audio-feed".into())
74 .spawn(move || {
75 feed(rx, &me, epoch);
76 // Only the current feeder gets to declare the end of the audio:
77 // a superseded one is finished, the stream is not.
78 if me.epoch.load(Ordering::Acquire) == epoch {
79 me.fed_all.store(true, Ordering::Release);
80 }
81 })
82 .is_ok()
83 }
84}
85
86/// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`].
87pub struct PlaybackSession {
88 /// The *timeline's* parameters, not any one file's: its frame rate and codec
89 /// come from source 0 and are what every other source is held to, while
90 /// `width`/`height` are the **project resolution** -- source 0's picture to
91 /// begin with, and whatever [`PlaybackSession::set_resolution`] or a saved
92 /// `resolution` line makes it after that. Every clip is composed onto it, so
93 /// a file of another size is a placed picture rather than a refusal.
94 meta: VideoMeta,
95 /// Source 0's own picture, kept from the open: the project resolution
96 /// starts here, and a caller offering sizes to pick from needs the media's
97 /// own among them or a project moved off it could never come back.
98 native: (u32, u32),
99 frames: Receiver<Frame>,
100 /// The current decode worker.
101 worker: Worker,
102 /// Workers cancelled by a seek or a clip change, waiting to be reaped.
103 /// Joining one inline costs whatever VA-API init it is still inside (98 ms
104 /// measured worst case), which is a visible hitch on the caller's thread;
105 /// parking it here instead makes that free, and [`retire`] drops the ones
106 /// that have already returned every time it adds another.
107 ///
108 /// Never a leak, and that is the invariant: everything in here is joined
109 /// when the session drops (`Vec<Worker>`'s own drop does it, one
110 /// [`Worker::drop`] each), so no decode worker can outlive the session and
111 /// meet Mesa's `atexit` handlers from inside libva.
112 ///
113 /// [`retire`]: PlaybackSession::retire
114 retired: Vec<Worker>,
115 clock: PlaybackClock,
116 audio: Option<Audio>,
117 /// Why this timeline is silent, when the file itself is not: an audio track
118 /// we cannot decode is a session that plays perfectly and says nothing about
119 /// it otherwise. `None` for a file that has usable audio *and* for one that
120 /// has none at all, which is not a surprise worth a notice.
121 audio_disabled: Option<String>,
122 /// The edit list. Everything a caller says in seconds is a *timeline*
123 /// position; only this maps it onto the file.
124 project: Project,
125 /// What the current video worker was opened for: where it sits on the
126 /// timeline, how long it runs, and which source frame it started at --
127 /// together they rewrite a source frame index into a timeline one. Not a
128 /// clip index: a `split` cuts the clip under a running worker, and only the
129 /// mapping survives that. A span with no source is a *gap*, and the worker
130 /// feeding it emits black frames indexed from zero.
131 span: Span,
132 /// The last clip has been played out; see [`PlaybackSession::is_eos`].
133 eos: bool,
134}
135
136impl PlaybackSession {
137 /// Opens `path` and starts both decode workers. Only video failure is fatal:
138 /// a file we cannot hear is still a file we can watch.
139 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {
140 let path = path.as_ref().to_path_buf();
141 // A timeline is scaffolded from source 0's picture -- its size, its
142 // frame rate, its clock. A song has none of that, so it joins a
143 // timeline (`import`) rather than starting one, and saying so beats
144 // failing in the demuxer's words.
145 if crate::is_audio(&path) {
146 return Err(format!(
147 "{} has no picture: open a video first, then import it onto the audio lane",
148 path.display()
149 )
150 .into());
151 }
152 // `open_worker` rather than `open` purely for the worker handle: the
153 // field has to exist from the start for the first seek to use it.
154 // Ungraded: a file just opened has one clip per lane and nothing has
155 // graded it yet. Every later span is opened by `start_span`, which asks
156 // the project.
157 // Passthrough: a freshly opened file *is* the project resolution, so
158 // there is nothing to place it on. Every later span goes through
159 // `start_span`, which builds the canvas from the project.
160 let (meta, stream) = DecodeSession::open_worker(
161 &path,
162 0,
163 u32::MAX,
164 ColorParams::default(),
165 Composer::passthrough(),
166 )?;
167 // A file is opened on its first audio stream, like `Project::single`
168 // names it: nothing has picked one yet.
169 let (audio, audio_disabled) = open_audio(&path, 0);
170 let source = match audio {
171 Some(_) => ClockSource::Audio,
172 None => ClockSource::Wall,
173 };
174 // One clip per lane covering the file, so timeline == source until the
175 // first edit -- and the range opened above is exactly that clip's.
176 let project = Project::single(&path, meta.frame_count);
177 let span = project.composite_span_at(0).expect("never empty");
178 Ok(Self {
179 meta,
180 native: (meta.width, meta.height),
181 frames: stream.frames,
182 worker: stream.worker,
183 retired: Vec::new(),
184 clock: PlaybackClock::new(source),
185 audio,
186 audio_disabled,
187 project,
188 span,
189 eos: false,
190 })
191 }
192
193 /// Opens a project file written by [`save_project`](Self::save_project):
194 /// the whole timeline, restored to where its playhead stood, paused like
195 /// [`open`](Self::open).
196 ///
197 /// A *new* session rather than a reload of this one, so a load that fails
198 /// leaves the caller's current session untouched -- atomic by
199 /// construction. Every named file is opened and checked here: source 0
200 /// defines the timeline exactly as `open` does, every other source has to
201 /// match it the way [`import`](Self::import) demands, and every clip has to
202 /// still be inside the file it plays from. A source that vanished or
203 /// shrank since the save is a refusal naming it, not a silently shorter
204 /// timeline -- the disappearing-file tolerance elsewhere in this type
205 /// applies only *after* a project has loaded.
206 ///
207 /// The undo history is not saved: `undo` is `false` on a fresh load.
208 pub fn open_project(path: &Path) -> crate::Result<Self> {
209 let doc = crate::edith::load(path)?;
210 // Owned: the sources move into the `Project` below, and the device is
211 // opened after that (see the comment there).
212 let first = doc
213 .sources
214 .first()
215 .cloned()
216 .ok_or("the project names no sources")?;
217 // Source 0 both scaffolds the session and defines the timeline, so it
218 // is opened for playback rather than merely probed.
219 // One value, not two locals: everything below this line can refuse, and
220 // locals drop in reverse declaration order -- a bare worker would join
221 // its decode thread while the receiver next to it was still holding
222 // that thread parked in `send`, which is a hang (see [`FrameStream`]).
223 // Ungraded, and superseded before a frame of it is shown: the `seek` at
224 // the end of this function reopens the playhead's span through
225 // `start_span`, which is where a saved grade reaches the picture.
226 let (mut meta, stream) = DecodeSession::open_worker(
227 &first.path,
228 0,
229 u32::MAX,
230 ColorParams::default(),
231 Composer::passthrough(),
232 )
233 .map_err(|e| format!("source {}: {e}", first.path.display()))?;
234 // The project's own resolution, which is source 0's picture unless the
235 // file says otherwise -- every dialect before v7 had no way to say it,
236 // and that default is exactly what those projects meant.
237 let native = (meta.width, meta.height);
238 if let Some((width, height)) = doc.resolution {
239 meta.width = width;
240 meta.height = height;
241 }
242 let first_audio = AudioSession::probe(&first.path, first.audio_stream)?;
243
244 let mut counts = vec![meta.frame_count];
245 for source in &doc.sources[1..] {
246 // A source with no picture is checked on what it does have, and
247 // its length is its playing time -- the same two answers `import`
248 // gave it when it first joined the timeline.
249 if crate::is_audio(&source.path) {
250 audio_matches(source, &first_audio)
251 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
252 counts.push(audio_frames(&source.path, meta.frame_rate)?);
253 continue;
254 }
255 let (other, _) = Demuxer::open(&source.path)
256 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
257 matches_timeline(source, &other, &meta, &first_audio)
258 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
259 counts.push(other.frame_count);
260 }
261 // The video lane can only play files that have pictures. Hand-written
262 // (or hand-edited) project files are the one door this can come in
263 // through, so it is refused by name here rather than becoming a clip
264 // that decodes to nothing.
265 for clip in doc
266 .lanes
267 .iter()
268 .filter(|(kind, _)| *kind == LaneKind::Video)
269 .flat_map(|(_, clips)| clips)
270 {
271 if crate::is_audio(&doc.sources[clip.source].path) {
272 return Err(format!(
273 "{} has no picture: it can only play on an audio lane",
274 doc.sources[clip.source].path.display()
275 )
276 .into());
277 }
278 }
279 for (i, clip) in doc.lanes.iter().flat_map(|(_, clips)| clips).enumerate() {
280 if clip.out_frame > counts[clip.source] {
281 return Err(format!(
282 "clip {i} ends at frame {} but {} has {} frames",
283 clip.out_frame,
284 doc.sources[clip.source].path.display(),
285 counts[clip.source]
286 )
287 .into());
288 }
289 }
290
291 let playhead = doc.playhead;
292 let project = Project::from_parts(doc.sources, doc.lanes, doc.eq, doc.color)?;
293 let span = project.composite_span_at(0).expect("never empty");
294 // Last, because it is the one thing here that cannot be taken back: the
295 // feeder thread outlives the `Audio` value (it holds its own clones) and
296 // only a session's `drop` retires it, so a refusal above this line would
297 // leave a PipeWire stream and a thread behind for a project that never
298 // opened. Nothing before it needs the device.
299 let (audio, audio_disabled) = open_audio(&first.path, first.audio_stream);
300 let mut session = Self {
301 meta,
302 native,
303 frames: stream.frames,
304 worker: stream.worker,
305 retired: Vec::new(),
306 clock: PlaybackClock::new(match audio {
307 Some(_) => ClockSource::Audio,
308 None => ClockSource::Wall,
309 }),
310 audio,
311 audio_disabled,
312 project,
313 span,
314 eos: false,
315 };
316 // The scaffolding above opened source 0 from its first frame and the
317 // whole of its audio; this puts both onto the clip the playhead is
318 // actually in -- a seek replaces the decoder and supersedes the audio
319 // worker by epoch, exactly as it does after an edit. It also clamps,
320 // so a playhead past a hand-shortened timeline lands on the last frame.
321 session.seek(f64::from(playhead) / meta.frame_rate);
322 Ok(session)
323 }
324
325 pub fn meta(&self) -> &VideoMeta {
326 &self.meta
327 }
328
329 /// Why this session plays silent although the file has sound -- an audio
330 /// track in a codec we cannot decode, or one the decoder refused. `None`
331 /// when there is audio, and for a file that never had any. A front-end
332 /// shows it once, at open: without it the whole thing is a stderr line.
333 pub fn audio_disabled_reason(&self) -> Option<&str> {
334 self.audio_disabled.as_deref()
335 }
336
337 /// The files this timeline plays from, index 0 first -- a caller needs it
338 /// to name an export or a window after the media rather than the project.
339 pub fn sources(&self) -> &[Source] {
340 self.project.sources()
341 }
342
343 /// Writes the timeline to `path` as a `.edith`, atomically (see
344 /// [`crate::edith`]). Sources no clip plays from are left out, and the
345 /// playhead is saved with it so a reopened project resumes where it stood.
346 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
347 let (sources, lanes, eq, color) = self.project.without_orphan_sources();
348 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
349 .min(self.project.timeline_frames().saturating_sub(1));
350 crate::edith::save(
351 path,
352 &sources,
353 &lanes,
354 &eq,
355 &color,
356 (self.meta.width, self.meta.height),
357 playhead,
358 )
359 }
360
361 /// The next decoded frame, its `index` rewritten from a source frame to a
362 /// *timeline* frame -- the only frame space that leaves the engine, and the
363 /// one [`PlaybackSession::now`] is in.
364 ///
365 /// `None` means "nothing right now": the decoder is behind, or a clip
366 /// boundary is being reopened (~80 ms, during which the caller simply keeps
367 /// showing its last frame). End of stream is [`PlaybackSession::is_eos`].
368 pub fn try_frame(&mut self) -> Option<Frame> {
369 loop {
370 match self.frames.try_recv() {
371 Ok(mut frame) => {
372 // A gap's worker indexes from zero, a decoder's from its in
373 // point: `base` is whichever this span started at.
374 let base = self.span.from.map_or(0, |(_, in_frame)| in_frame);
375 frame.index = self.span.start + frame.index.saturating_sub(base);
376 return Some(frame);
377 }
378 Err(TryRecvError::Empty) => return None,
379 // The worker stopped: at the end of its range, or on a decode
380 // error -- which is why this skips the rest of a broken clip
381 // rather than stalling on it.
382 Err(TryRecvError::Disconnected) => {
383 if !self.next_clip() {
384 self.eos = true;
385 return None;
386 }
387 }
388 }
389 }
390 }
391
392 /// Whether the timeline has been played out. Any seek clears it, so an edit
393 /// after the end (which reseeks) revives the session.
394 pub fn is_eos(&self) -> bool {
395 self.eos
396 }
397
398 /// Installs `replacement` as the decode worker, parking the outgoing one in
399 /// [`retired`](Self::retired) rather than joining it here, and reaping the
400 /// parked ones that have already returned.
401 ///
402 /// The sweep is what bounds the list: every worker in it was cancelled
403 /// before this ran, and a cancelled worker is out within an access unit
404 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's
405 /// worker on this seek and the list stays a handful long. Nothing waits.
406 fn retire(&mut self, replacement: Worker) {
407 self.retired
408 .push(std::mem::replace(&mut self.worker, replacement));
409 self.retired.retain(|w| !w.is_finished());
410 }
411
412 /// Starts feeding whatever follows the current span on the timeline --
413 /// another clip, or a gap, which is black frames from a worker that opens no
414 /// file. `false` past the end. The next timeline frame is derived rather
415 /// than remembered as a clip index, because a `split` while playing cuts the
416 /// clip under the running worker and only the mapping stays true.
417 fn next_clip(&mut self) -> bool {
418 let next = self.span.end();
419 let Some(span) = self.project.composite_span_at(next) else {
420 return false;
421 };
422 // We only get here on a disconnect, so the old worker has already
423 // returned; cancel anyway, so `retire` treats every path alike.
424 self.worker.cancel();
425 self.start_span(span);
426 true
427 }
428
429 /// Points the video worker at `span`: a decoder over its source range, or a
430 /// black-frame generator for a gap. The old worker must already have been
431 /// cancelled -- this is the half both `seek` and `next_clip` share.
432 ///
433 /// A source that will not open leaves the *span* installed anyway: the
434 /// timeline still moves, there are simply no more pictures, and the
435 /// disconnected receiver carries the session on to the next span.
436 fn start_span(&mut self, span: Span) {
437 let opened = match span.from {
438 // The grade is the composite's at this frame -- the same clip the
439 // span itself came from -- and it is constant across the span, so
440 // the worker carries it and every frame it converts wears it.
441 Some((source, in_frame)) => DecodeSession::open_worker(
442 &self.project.sources()[source].path,
443 in_frame,
444 in_frame + span.len,
445 self.project
446 .composite_color_at(span.start)
447 .copied()
448 .unwrap_or_default(),
449 // ...and the canvas it is placed on: the project's resolution
450 // and this clip's own fit policy, constant across the span for
451 // the reason the grade is.
452 Composer::new(
453 self.meta.width,
454 self.meta.height,
455 self.project.composite_fit_at(span.start),
456 ),
457 )
458 .map(|(_, stream)| stream)
459 .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)),
460 None => Ok(DecodeSession::open_black(
461 self.meta.width,
462 self.meta.height,
463 span.len,
464 )),
465 };
466 if let Ok(stream) = opened {
467 // Receiver first, worker second: the drop of the *old* receiver is
468 // what wakes the outgoing worker if it is parked in `send`, and only
469 // then can it return and be reaped by a later sweep. Nothing here
470 // joins, so this ordering costs the seek nothing.
471 self.frames = stream.frames;
472 self.retire(stream.worker);
473 }
474 self.span = span;
475 }
476
477 /// Length of the edited timeline in seconds -- what a ruler shows, and it
478 /// shrinks with every delete.
479 pub fn timeline_duration(&self) -> f64 {
480 f64::from(self.project.timeline_frames()) / self.meta.frame_rate
481 }
482
483 /// `(start, len)` per clip in timeline seconds, in order: what a clips lane
484 /// needs to lay itself out. Selection is the caller's business.
485 pub fn clip_spans(&self) -> Vec<(f64, f64)> {
486 let fps = self.meta.frame_rate;
487 self.project
488 .clip_spans()
489 .iter()
490 .map(|&(start, len)| (f64::from(start) / fps, f64::from(len) / fps))
491 .collect()
492 }
493
494 /// [`clip_spans`](Self::clip_spans) plus the index into
495 /// [`Project::sources`] each clip plays from -- what a lane needs to colour
496 /// an imported clip differently from the file the session was opened with.
497 pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> {
498 self.lane_spans_by_source(Lane::V1)
499 }
500
501 /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane,
502 /// with each clip's group id -- what a two-lane front-end draws. The holes
503 /// between consecutive entries are the gaps.
504 pub fn lane_spans_by_source(&self, lane: Lane) -> Vec<(f64, f64, usize)> {
505 let fps = self.meta.frame_rate;
506 self.project
507 .lane(lane)
508 .iter()
509 .map(|c| (f64::from(c.start) / fps, f64::from(c.len()) / fps, c.source))
510 .collect()
511 }
512
513 /// Every placement of one lane, in timeline order. What a two-lane
514 /// front-end draws and nothing
515 /// [`lane_spans_by_source`](Self::lane_spans_by_source) can answer: a clip
516 /// carries its group id (which halves a click marks together) and its
517 /// source range (where a waveform reads its peaks from) as well as its
518 /// span. The holes between consecutive clips are the gaps.
519 pub fn lane_clips(&self, lane: Lane) -> &[Clip] {
520 self.project.lane(lane)
521 }
522
523 /// Every lane's handle, in display order -- what a front-end lays out top to
524 /// bottom, and the list [`add_lane`](Self::add_lane) grows.
525 pub fn lanes(&self) -> Vec<Lane> {
526 self.project.lanes()
527 }
528
529 /// Appends an empty lane and hands back its handle. One undo step
530 /// ([`Project::add_lane`]), and no reseek: an empty lane changes nothing
531 /// that plays until something is placed on it.
532 pub fn add_lane(&mut self, kind: LaneKind) -> Lane {
533 self.project.add_lane(kind)
534 }
535
536 /// Splits every lane at `timeline_secs`, so the two sides become two
537 /// groups. Metadata only: a split never changes the timeline->source
538 /// mapping, so the running decoder stays correct and playback does not
539 /// blink. `false` at a clip start, in a gap and past the end, where there
540 /// would be nothing to split off.
541 pub fn cut_at(&mut self, timeline_secs: f64) -> bool {
542 self.project
543 .split(secs_to_frame(timeline_secs, self.meta.frame_rate))
544 }
545
546 /// The inverse of [`cut_at`](Self::cut_at): rejoins the clips that meet at
547 /// `timeline_secs` in every lane and puts them back in one group. `false`
548 /// unless a split could have produced what is there. Metadata only, like the
549 /// split -- no reseek.
550 pub fn regroup_at(&mut self, timeline_secs: f64) -> bool {
551 self.project
552 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))
553 }
554
555 /// What the clip at `idx` of `lane` is equalized with, or `None` for one
556 /// that plays flat -- what a card shows before it lets anyone drag a band.
557 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
558 self.project.eq_of(lane, idx)
559 }
560
561 /// Gives that clip an equalizer, or takes it off with `None`. One undo step,
562 /// like every other edit -- and, like every other edit, it *reseeks*: the
563 /// audio workers are rebuilt from the new curves right where the playhead
564 /// is, so a band changed during playback is heard from the next chunk on
565 /// rather than at the next play. `false` for a bad index or a non-finite
566 /// band, and nothing changes.
567 ///
568 /// ponytail: the reseek is what makes it live, so the cost of a change is a
569 /// decoder restart -- inaudible at a drag's end, but too much to call once
570 /// per pointer sample (a caller commits one change per gesture). Upgrade
571 /// path is an `Arc` swap the running worker polls per chunk.
572 pub fn set_eq(&mut self, lane: Lane, idx: usize, params: Option<EqParams>) -> bool {
573 self.edit(|p| p.set_eq(lane, idx, params))
574 }
575
576 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
577 /// silence on the audio one, and nothing else moves. Reseeks, because what
578 /// the playhead sits on has changed. `false` for a bad index and for the
579 /// lift that would leave the whole timeline empty.
580 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {
581 self.edit(|p| p.lift(lane, idx))
582 }
583
584 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
585 /// on and its index there, by the same topmost-lane-wins rule the decoder
586 /// follows. `None` over a gap and past the end. What a card that grades
587 /// "this clip" opens on when nothing has been clicked.
588 pub fn video_clip_at(&self, timeline_secs: f64) -> Option<(Lane, usize)> {
589 self.project
590 .composite_clip_at(secs_to_frame(timeline_secs, self.meta.frame_rate))
591 }
592
593 /// Which clip of `lane` sits at `timeline_secs`, by the same rule
594 /// [`video_clip_at`](Self::video_clip_at) picks the picture's with -- per
595 /// lane, so a keyboard walking the lanes for something to select asks the
596 /// engine rather than re-deriving where a clip ends.
597 pub fn lane_clip_at(&self, lane: Lane, timeline_secs: f64) -> Option<usize> {
598 self.project
599 .lane_clip_at(lane, secs_to_frame(timeline_secs, self.meta.frame_rate))
600 }
601
602 /// How the clip at `idx` of `lane` is graded, or `None` for one that plays
603 /// as it was shot -- what a colour card reads when it opens.
604 pub fn color_of(&self, lane: Lane, idx: usize) -> Option<&ColorParams> {
605 self.project.color_of(lane, idx)
606 }
607
608 /// Grades that clip, or takes the grade off with `None`. One undo step like
609 /// every other edit, and it reseeks like one too -- which is what puts the
610 /// new grade on the frame that is already on screen, paused or playing,
611 /// without the caller having to nudge the playhead itself. `false` for an
612 /// index that is not there and for a value that is not finite.
613 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
614 self.edit(|p| p.set_color(lane, idx, params))
615 }
616
617 /// The project's resolution: what every clip is composed onto, what the
618 /// window is sized to and what an export writes -- *not* any one file's.
619 /// It starts as source 0's picture, which is what a project meant before it
620 /// could have a resolution of its own.
621 pub fn resolution(&self) -> (u32, u32) {
622 (self.meta.width, self.meta.height)
623 }
624
625 /// Source 0's own picture size -- what the project resolution started as,
626 /// and the one size a caller offering a list of them must not leave out.
627 pub fn native_resolution(&self) -> (u32, u32) {
628 self.native
629 }
630
631 /// Sets it. Reseeks like an edit, so the frame on screen is recomposed at
632 /// the new size at once, paused or playing. `false` for a size that is not a
633 /// picture -- zero either way, or past 8K, which is where the per-frame
634 /// buffers stop being a sane thing to allocate from a keystroke.
635 ///
636 /// ponytail: not an undo step. The project resolution is not in the lane
637 /// snapshots [`Project::undo`] restores, so cycling it back is one more
638 /// keypress rather than a `z`. Upgrade path is snapshotting it beside the
639 /// lanes, which every existing snapshot site would then have to carry.
640 pub fn set_resolution(&mut self, width: u32, height: u32) -> bool {
641 if !crate::is_resolution(width, height) {
642 return false;
643 }
644 if (width, height) == (self.meta.width, self.meta.height) {
645 return false;
646 }
647 self.meta.width = width;
648 self.meta.height = height;
649 let now = self.now();
650 self.seek(now);
651 true
652 }
653
654 /// How the clip at `idx` of `lane` meets a project canvas of another shape.
655 pub fn fit_of(&self, lane: Lane, idx: usize) -> FitPolicy {
656 self.project.fit_of(lane, idx)
657 }
658
659 /// Sets that clip's fit policy. One undo step and a reseek, exactly like a
660 /// grade: the picture on screen is recomposed through the new policy without
661 /// the caller nudging the playhead. `false` for an index that is not there.
662 pub fn set_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy) -> bool {
663 self.edit(|p| p.set_fit(lane, idx, fit))
664 }
665
666 /// The clip at `idx` -- what a caller copies. It is a pair of source frame
667 /// numbers and nothing else, so a copy stays valid after the clip it came
668 /// from is deleted. `None` past the end.
669 pub fn clip_at(&self, idx: usize) -> Option<Clip> {
670 self.project.clips().get(idx).copied()
671 }
672
673 /// Inserts `clip` at the playhead, splitting the clip under it. Like a
674 /// delete this moves every following frame, so the session reseeks; past
675 /// the end of the timeline the clip is appended. One undo step.
676 pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool {
677 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
678 self.edit(|p| p.paste(at, clip))
679 }
680
681 /// Places `frames` of `path` played on its audio `stream` at
682 /// `timeline_secs`, the way [`paste_at`](Self::paste_at) places a copy --
683 /// the door a library row goes through, and the only way a stream other
684 /// than the one an import brought in reaches the timeline. The `(file,
685 /// stream)` pair becomes a source if it is not one already.
686 ///
687 /// Refused, changing nothing, unless that stream can join *this* timeline:
688 /// same audio parameters as the first source, in the same words
689 /// [`import`](Self::import) refuses a file with. One output device and one
690 /// copied AAC track mean one set of audio parameters for the whole
691 /// timeline, so a 22 kHz mono track cannot join a 44.1 kHz stereo one --
692 /// there is no resampler here, and no AAC encoder to write the join with.
693 /// A front-end greys such a row out; this is the backstop that keeps a
694 /// stale one from making the whole timeline silent.
695 ///
696 /// Which lane it lands on is decided here, from the file and from `onto` --
697 /// the lane it was let go over, if it was let go over one at all: a file
698 /// with a picture asked for by no lane, or for one of the first pair, is
699 /// pasted across `V1` and `A1` as a grouped take; asked for by any further
700 /// lane it is *placed* there alone, overwriting what it lands on and
701 /// rippling nothing. A file with no picture ([`crate::is_audio`]) is placed
702 /// on the audio lane it was asked for, or on `A1`, and never on a video
703 /// lane. A caller never has to ask.
704 pub fn place_stream_at(
705 &mut self,
706 timeline_secs: f64,
707 path: &Path,
708 stream: usize,
709 frames: u32,
710 onto: Option<Lane>,
711 ) -> crate::Result<bool> {
712 let wanted = Source::new(path, stream);
713 // Another stream of a file whose picture is *already* on the timeline:
714 // that is what a library row is, and it is why nothing here has to
715 // check dimensions or frame rate -- the file passed that at import.
716 if !self.project.sources().iter().any(|s| s.path == wanted.path) {
717 return Err(format!("{} is not on this timeline", path.display()).into());
718 }
719 let first = self.first_audio()?;
720 audio_matches(&wanted, &first)?;
721 let source = self.project.import(path, stream);
722 let clip = Clip {
723 start: 0,
724 in_frame: 0,
725 out_frame: frames.max(1),
726 source,
727 link: None,
728 eq: None,
729 color: None,
730 fit: FitPolicy::default(),
731 };
732 // Which lane a source may land on is decided here and only here, so a
733 // front-end never has to make the same call twice: a file with no
734 // picture goes on an audio lane alone, overwriting and rippling
735 // nothing, because there is nothing on the video lane to move along
736 // with it. A lane of the source's own kind takes it as it is dropped;
737 // only `V1` means the grouped take, since that is the pair the paste
738 // spans and a second video lane is a layer of its own.
739 let onto = match (crate::is_audio(path), onto) {
740 // No picture: an audio lane and nothing else, whichever one was
741 // asked for -- `A1` when none was.
742 (true, Some(lane)) if lane.kind == LaneKind::Audio => Some(lane),
743 (true, _) => Some(Lane::A1),
744 // A picture: the lane it was let go over, unless that is one of the
745 // first pair. Those two are the grouped take a paste spans, and a
746 // further lane is a layer of its own -- its picture on `V2`, its
747 // sound on `A2`.
748 (false, Some(lane)) if lane.ord > 0 => Some(lane),
749 (false, _) => None,
750 };
751 Ok(match onto {
752 Some(lane) => self.place_at(lane, timeline_secs, clip),
753 None => self.paste_at(timeline_secs, clip),
754 })
755 }
756
757 /// What the timeline's audio *is*: source 0's chosen stream, probed. Every
758 /// other source is held to it.
759 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {
760 let first = &self.project.sources()[0];
761 AudioSession::probe(&first.path, first.audio_stream)
762 }
763
764 /// Places `clip` on `lane` alone at the playhead, overwriting what it lands
765 /// on and rippling nothing -- the one-lane insert a source with no picture
766 /// makes, and the only way an audio-only file reaches the timeline. The
767 /// placement belongs to no group (see [`Project::place`]). One undo step,
768 /// and it reseeks like every other edit.
769 pub fn place_at(&mut self, lane: Lane, timeline_secs: f64, clip: Clip) -> bool {
770 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
771 self.edit(|p| p.place(lane, at, clip))
772 }
773
774 /// Removes `lane`'s clip at `idx` and everything under it, closing the gap
775 /// on every lane. Unlike a split this *does* move every following frame, so
776 /// the session reseeks to wherever the playhead now points.
777 /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead.
778 /// `false` for a bad index or the last remaining clip.
779 ///
780 /// The lane travels because the index is a lane's own: `V2`'s third clip is
781 /// not `V1`'s, and a front-end that could only say "the third clip" would
782 /// delete the wrong one the moment a second lane exists.
783 pub fn delete_clip(&mut self, lane: Lane, idx: usize) -> bool {
784 self.edit(|p| p.delete_in(lane, idx))
785 }
786
787 /// Undoes the last successful edit, and reseeks like a delete.
788 pub fn undo(&mut self) -> bool {
789 self.edit(Project::undo)
790 }
791
792 /// Appends the whole of `path` to the end of the timeline. One undo step,
793 /// and the file becomes a source only if it is not one already.
794 ///
795 /// Refused unless it can join the timeline -- same codec, same frame rate,
796 /// same audio parameters or both silent; the `Err` names the property that
797 /// disagrees, for a caller to show. Nothing is changed by a refusal. A
798 /// *resolution* of its own is not a refusal: the clip is placed on the
799 /// project canvas by its fit policy ([`PlaybackSession::set_fit`]).
800 pub fn import(&mut self, path: &Path) -> crate::Result<()> {
801 if crate::is_audio(path) {
802 return self.import_audio(path);
803 }
804 let (meta, _) = Demuxer::open(path)?;
805 let first = self.first_audio()?;
806 // Stream 0: an import brings a file in on its first audio track, and
807 // [`place_stream_at`](Self::place_stream_at) is how any other one of
808 // its streams reaches the timeline afterwards.
809 matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?;
810
811 let old_end = self.timeline_duration();
812 let source = self.project.import(path, 0);
813 // Refused only for an unknown index, and this one just came from `import`.
814 self.project.append_clip(source, meta.frame_count);
815 // Reseek like any other edit, even though nothing before the playhead
816 // moved: the running audio worker's segment list stops at the old end,
817 // so without this the appended clip would play silent. At EOS the wall
818 // clock has run on past the timeline, so resume from the join instead
819 // of wherever it got to -- and the seek is what clears `eos`.
820 let at = if self.eos { old_end } else { self.now() };
821 self.seek(at);
822 Ok(())
823 }
824
825 /// Appends a standalone audio file to the end of the timeline, on the
826 /// **audio lane alone**: a song has no picture, so there is nothing to put
827 /// on the video lane and the timeline shows black under it. Its length is
828 /// its playing time rounded up to whole frames, which is the only frame
829 /// count such a source has.
830 ///
831 /// Refused in the same words as any other import when its rate or layout
832 /// disagrees with the timeline's -- one output device, one set of
833 /// parameters -- and refused outright on a silent timeline, which has no
834 /// device open at all. Nothing is changed by a refusal.
835 fn import_audio(&mut self, path: &Path) -> crate::Result<()> {
836 let first = self.first_audio()?;
837 // Stream 0, and there is no other: a standalone audio file carries one
838 // track (`AudioSession::probe_streams`), so nothing here has a stream
839 // to pick the way `place_stream_at` does for an mp4.
840 audio_matches(&Source::new(path, 0), &first)?;
841 let frames = audio_frames(path, self.meta.frame_rate)?;
842
843 let old_end = self.timeline_duration();
844 let source = self.project.import(path, 0);
845 let at = self.project.timeline_frames();
846 self.project.place(
847 Lane::A1,
848 at,
849 Clip {
850 start: at,
851 in_frame: 0,
852 out_frame: frames,
853 source,
854 link: None,
855 eq: None,
856 color: None,
857 fit: FitPolicy::default(),
858 },
859 );
860 // Same reason as a video import: the running audio worker's segment
861 // list stops at the old end, so without a reseek the appended clip
862 // would play silent.
863 let at = if self.eos { old_end } else { self.now() };
864 self.seek(at);
865 Ok(())
866 }
867
868 /// Applies an edit and, if it took, reseeks onto the new mapping. `seek`
869 /// clamps to the new duration and keeps playing playing, so a delete that
870 /// shortens the timeline past the playhead lands on the last frame.
871 fn edit(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool {
872 if !f(&mut self.project) {
873 return false;
874 }
875 let now = self.now();
876 self.seek(now);
877 true
878 }
879
880 /// Current timeline position in seconds.
881 pub fn now(&self) -> f64 {
882 self.clock.now()
883 }
884
885 pub fn is_playing(&self) -> bool {
886 self.clock.is_playing()
887 }
888
889 pub fn play(&mut self) {
890 if self.clock.is_playing() {
891 return;
892 }
893 // Invariant: the clock is positioned *before* audio restarts. Audio
894 // reports are relative to the first one after that, so a seek would go
895 // here too -- `clock.seek_to(t)` and then `set_active(true)`.
896 self.clock.play();
897 if let Some(audio) = &self.audio {
898 audio.ao.lock().unwrap().set_active(true);
899 }
900 }
901
902 pub fn pause(&mut self) {
903 if !self.clock.is_playing() {
904 return;
905 }
906 if let Some(audio) = &self.audio {
907 audio.ao.lock().unwrap().set_active(false);
908 }
909 self.clock.pause();
910 }
911
912 pub fn toggle(&mut self) {
913 if self.clock.is_playing() {
914 self.pause()
915 } else {
916 self.play()
917 }
918 }
919
920 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
921 /// one knob, because muting and turning it down are the same thing to the
922 /// device, and *which* the user meant is a question only the UI can answer
923 /// -- it keeps the level to come back to.
924 ///
925 /// Deliberately not session state: nothing here remembers it, so a caller
926 /// pushes it once per session and an export -- which renders the file
927 /// rather than what the speakers are doing -- can never pick it up. Silent
928 /// with no audio device, which is also the only honest answer there.
929 ///
930 /// Mute is not pause: the samples are still consumed and the device clock
931 /// still runs, so the picture keeps playing against it.
932 pub fn set_gain(&self, gain: f32) -> bool {
933 match &self.audio {
934 Some(audio) => audio.ao.lock().unwrap().set_volume(gain),
935 None => false,
936 }
937 }
938
939 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
940 /// workers are replaced rather than steered: a fresh channel cannot hold a
941 /// stale frame, and it works just as well after EOF, where the old workers
942 /// have already exited.
943 ///
944 /// Playing stays playing and paused stays paused -- but a paused seek still
945 /// decodes, so the caller can show the frame it landed on.
946 pub fn seek(&mut self, secs: f64) {
947 let fps = self.meta.frame_rate;
948 let total = self.project.timeline_frames();
949 let t = secs.clamp(0.0, f64::from(total) / fps);
950 let target = secs_to_frame(t, fps).min(total.saturating_sub(1));
951 let was_playing = self.clock.is_playing();
952
953 if let Some(audio) = &self.audio {
954 let ao = audio.ao.lock().unwrap();
955 ao.set_active(false);
956 // Bumped and flushed while holding the device lock, because the
957 // feeder re-checks the epoch inside that same lock: whatever it is
958 // carrying can no longer reach the ring after this point.
959 audio.epoch.fetch_add(1, Ordering::Release);
960 ao.flush();
961 }
962
963 // Cancel first, drop second: the old worker may be parked in `send` on
964 // the bounded channel, where only the disconnect wakes it -- and it
965 // then finds the flag already set. It is then parked, not joined; see
966 // [`retire`](Self::retire), which is what keeps a scrub off the price
967 // of a VA-API init.
968 self.worker.cancel();
969 // `target` is inside the timeline (never empty), so this always spans;
970 // the span runs from there to the end of whatever it landed in -- a
971 // clip, or a gap, which starts a black-frame worker instead.
972 if let Some(span) = self.project.composite_span_at(target) {
973 self.start_span(span);
974 }
975 self.eos = false;
976
977 let mut audio_running = false;
978 if let Some(audio) = &self.audio
979 && !audio.died.load(Ordering::Acquire)
980 {
981 // The device position keeps counting across a flush, so re-basing
982 // `fed` on it is what keeps `played_out` exact for the new stream.
983 let played = audio.ao.lock().unwrap().position().unwrap_or(0).max(0) as u64;
984 audio.fed.store(played * audio.channels, Ordering::Relaxed);
985 audio.fed_all.store(false, Ordering::Release);
986 // One worker for the whole rest of the timeline, so the joins
987 // between clips are gapless: the video reopens at a boundary, the
988 // ear never hears it -- and a join between two *files* is just
989 // another segment, because every segment names its own source.
990 // One play list per audio lane, summed by the mixer: what the ear
991 // hears is every lane at once, and a lane's own gaps are silence in
992 // it rather than a hole in the count the master clock keeps.
993 let segs = self.project.audio_segments_from(target, fps);
994 // The equalizers beside them, one per segment: the worker filters a
995 // segment's own samples before the mix, so a clip's curve reaches
996 // that clip and stops. Rebuilt on every seek, which is what makes an
997 // EQ edit audible at once -- `edit` reseeks, so the drag that
998 // changed a band restarts the workers with the new curve already in
999 // them, and no live channel has to reach into a running one.
1000 let eqs = self.project.audio_eqs_from(target, fps);
1001 // Each source on the stream it was placed with: what plays is what
1002 // the library row said, and what an export copies (`export::run`).
1003 let sources = self.project.audio_sources();
1004 audio_running = match AudioSession::open_mixed_streams_eq(&sources, &segs, &eqs) {
1005 Ok(Some((_, rx))) => audio.spawn_feeder(rx),
1006 _ => false,
1007 };
1008 if !audio_running {
1009 // Nothing will ever be fed again; let `tick` fall to wall time
1010 // instead of waiting on a device that has no more work coming.
1011 audio.fed_all.store(true, Ordering::Release);
1012 }
1013 }
1014
1015 // Same invariant as `play`: position the clock before audio restarts.
1016 if audio_running && self.clock.source() != ClockSource::Audio {
1017 self.clock.switch_to_audio();
1018 }
1019 self.clock.seek_to(t);
1020 if was_playing && let Some(audio) = &self.audio {
1021 audio.ao.lock().unwrap().set_active(true);
1022 }
1023 }
1024
1025 /// Renders the edited timeline to `out` on a worker thread. The session is
1026 /// untouched -- the export decodes the source file for itself -- but a
1027 /// caller should still [`pause`](PlaybackSession::pause) first, because
1028 /// playback and export otherwise fight over the same decoder hardware.
1029 ///
1030 /// Later edits do not reach a running export: it works from a snapshot of
1031 /// the edit list taken here.
1032 ///
1033 /// ponytail: this defaults the settings; the app still calls it that way,
1034 /// and the export options card replaces the call with
1035 /// [`export_to_with`](PlaybackSession::export_to_with).
1036 pub fn export_to(&self, out: &Path) -> crate::ExportHandle {
1037 self.export_to_with(out, &crate::export::ExportSettings::default())
1038 }
1039
1040 /// [`export_to`](PlaybackSession::export_to) with the output settings spelled
1041 /// out rather than defaulted.
1042 pub fn export_to_with(
1043 &self,
1044 out: &Path,
1045 settings: &crate::export::ExportSettings,
1046 ) -> crate::ExportHandle {
1047 crate::export::start(self.project.clone(), self.meta, out, settings)
1048 }
1049
1050 /// Moves the clock forward; the caller runs this once per rendered frame.
1051 /// Costs an atomic load, and once per session a mode switch.
1052 pub fn tick(&mut self) {
1053 let Some(audio) = &self.audio else {
1054 return; // wall time from the start, nothing to poll
1055 };
1056 if self.clock.source() != ClockSource::Audio {
1057 return;
1058 }
1059 if audio.died.load(Ordering::Acquire) {
1060 // Output died mid-stream: its position will never reach `fed`, so
1061 // the EOF comparison below is unreachable. Wall time takes over
1062 // from wherever the clock last stood.
1063 self.clock.switch_to_wall();
1064 return;
1065 }
1066 // `None` until the device's first callback: the clock holds at its
1067 // anchor rather than guessing, which is why playback starts on time
1068 // instead of a quantum early.
1069 let Some(position) = audio.ao.lock().unwrap().position() else {
1070 return;
1071 };
1072 if audio.played_out(position) {
1073 // Audio EOF. Wall time carries the same timeline on from here, with
1074 // no jump, and this branch cannot be reached again.
1075 self.clock.switch_to_wall();
1076 } else {
1077 self.clock
1078 .set_audio_position(position as u64, audio.sample_rate);
1079 }
1080 }
1081}
1082
1083impl Drop for PlaybackSession {
1084 /// The video workers -- the running one and every cancelled one still in
1085 /// [`retired`](PlaybackSession::retired) -- cancel and join themselves when
1086 /// those fields drop right after this, the running one behind its receiver
1087 /// so a `send` cannot hold the join. *That* is what a session must not exit
1088 /// without: no decode worker outlives it, so none can be inside libva when
1089 /// Mesa's `atexit` handlers free the state under it.
1090 ///
1091 /// This is the audio half: bumping the epoch retires the feeder at its next write,
1092 /// which drops the decode receiver with it. Neither is waited for -- no
1093 /// driver state is torn down on the audio side.
1094 fn drop(&mut self) {
1095 if let Some(audio) = &self.audio {
1096 audio.epoch.fetch_add(1, Ordering::Release);
1097 }
1098 }
1099}
1100
1101/// Whether `path`, already demuxed to `meta`, may join a timeline whose
1102/// parameters are `timeline` and whose audio probes as `first`: same codec,
1103/// same frame rate, same audio parameters or both silent.
1104///
1105/// *Not* the same size any more. A project has its own resolution
1106/// ([`PlaybackSession::set_resolution`]) and every clip is placed on it by its
1107/// own fit policy, so a 640x360 file joining a 1920x1080 timeline is a
1108/// letterboxed clip rather than a refusal. The frame rate stays refused on
1109/// purpose: mixing rates means resampling the *timeline*, which is a different
1110/// problem from resampling a picture, and a refusal is the honest answer until
1111/// it is solved.
1112///
1113/// The `Err` names the property that disagrees, and those strings are what a
1114/// front-end shows verbatim; [`PlaybackSession::import`] and
1115/// [`PlaybackSession::open_project`] share them so a file refused at import is
1116/// refused in the same words at load.
1117fn matches_timeline(
1118 source: &Source,
1119 meta: &VideoMeta,
1120 timeline: &VideoMeta,
1121 first: &Option<crate::AudioProbe>,
1122) -> crate::Result<()> {
1123 // Codec first: one timeline is one kind of source. Mixing them would decode
1124 // (every clip opens its own decoder) but on a machine without the VA-API
1125 // plugin the VP9 half would be black frames with the refusal only on
1126 // stderr, which is exactly what a front-end cannot show.
1127 if meta.codec != timeline.codec {
1128 return Err(format!(
1129 "{} does not match the timeline's {}",
1130 meta.codec.name(),
1131 timeline.codec.name()
1132 )
1133 .into());
1134 }
1135 // Container frame rates are computed from timescales, so never `==`.
1136 if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 {
1137 return Err(format!(
1138 "{:.3} fps does not match the timeline's {:.3} fps",
1139 meta.frame_rate, timeline.frame_rate
1140 )
1141 .into());
1142 }
1143 audio_matches(source, first)
1144}
1145
1146/// Whether a candidate's audio may join a timeline whose first source probes as
1147/// `first`: same rate, same layout, or both silent. One output device and one
1148/// exported track is all there is, and no resampler.
1149///
1150/// The audio half of [`matches_timeline`], which a stream placed on its own
1151/// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
1152/// comes with is already on the timeline.
1153///
1154/// The format itself is deliberately *not* part of this: an mp3 that agrees on
1155/// rate and layout plays alongside a timeline of mp4s perfectly well. What it
1156/// cannot do is be copied into an export, which is a refusal of its own, at
1157/// export time (`AudioSession::copy_multi_streams`).
1158fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
1159 // Whole-probe equality: rate and layout, which the audio worker holds every
1160 // source to anyway. Both silent is a match.
1161 let probe = AudioSession::probe(&source.path, source.audio_stream)?;
1162 if probe == *first {
1163 return Ok(());
1164 }
1165 Err(match (probe, first) {
1166 (None, _) => "the file is silent, the timeline has audio".to_string(),
1167 (_, None) => "the file has audio, the timeline is silent".to_string(),
1168 (Some(a), Some(b)) => format!(
1169 "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",
1170 a.sample_rate, a.channels, b.sample_rate, b.channels
1171 ),
1172 }
1173 .into())
1174}
1175
1176/// How many timeline frames a standalone audio file occupies: its playing time
1177/// rounded *up*, so the last partial frame is still covered rather than cut off,
1178/// and never zero (a clip is never empty).
1179fn audio_frames(path: &Path, fps: f64) -> crate::Result<u32> {
1180 let secs = AudioSession::duration_secs(path)?
1181 .ok_or_else(|| format!("{} has no audio track", path.display()))?;
1182 let frames = (secs * fps).ceil();
1183 if !frames.is_finite() || frames < 0.0 || frames > f64::from(u32::MAX) {
1184 return Err(format!(
1185 "{} is {secs} s long, which is not a timeline",
1186 path.display()
1187 )
1188 .into());
1189 }
1190 Ok((frames as u32).max(1))
1191}
1192
1193/// `None` for a silent session -- no audio track, no plugin, no daemon, or a
1194/// track the decoder refuses. Dropping the receiver on the way out stops the
1195/// audio decode worker, so a failure here leaves nothing running.
1196///
1197/// The second half is why, for the cases the *file* is to blame for: those are
1198/// a surprise worth showing (see
1199/// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a
1200/// file with no audio at all and a machine with no output device are not.
1201fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
1202 let sources = [(path.to_path_buf(), stream)];
1203 let (meta, rx) =
1204 match AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) {
1205 Ok(Some(opened)) => opened,
1206 // No AAC track: silent by nature, or sound in a codec we do not
1207 // have -- and only the second of those is worth a word.
1208 Ok(None) => {
1209 let reason = AudioSession::unsupported(path).ok().flatten();
1210 if let Some(reason) = &reason {
1211 eprintln!("audio disabled: {reason}");
1212 }
1213 return (None, reason);
1214 }
1215 Err(e) => {
1216 eprintln!("audio disabled: {e}");
1217 return (None, Some(e.to_string()));
1218 }
1219 };
1220 let Some(ao) = AoSession::open(meta.sample_rate, u32::from(meta.channels)) else {
1221 return (None, None); // no device: the machine's business, not the file's
1222 };
1223 // The stream comes up streaming; a session starts paused, so silence the
1224 // device until `play`. The feeder still fills the ring in the meantime.
1225 ao.set_active(false);
1226
1227 let audio = Audio {
1228 ao: Arc::new(Mutex::new(ao)),
1229 sample_rate: meta.sample_rate,
1230 channels: u64::from(meta.channels),
1231 fed: Arc::new(AtomicU64::new(0)),
1232 fed_all: Arc::new(AtomicBool::new(false)),
1233 died: Arc::new(AtomicBool::new(false)),
1234 epoch: Arc::new(AtomicU64::new(0)),
1235 };
1236 (audio.spawn_feeder(rx).then_some(audio), None)
1237}
1238
1239/// Pours decoded chunks into the device, keeping whatever the ring would not
1240/// take. Ends when the decoder is done, the output dies, or a seek supersedes
1241/// this feeder.
1242fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
1243 let mut pending: Vec<f32> = Vec::new();
1244 loop {
1245 if pending.is_empty() {
1246 match rx.recv() {
1247 Ok(chunk) => pending = chunk.samples,
1248 Err(_) => return, // decoder finished or went away
1249 }
1250 }
1251 let accepted = {
1252 let mut ao = audio.ao.lock().unwrap();
1253 // Under the lock, immediately before the write: `seek` bumps the
1254 // epoch and flushes the ring holding this very lock, so past this
1255 // check no stale sample can be queued behind the flush.
1256 if audio.epoch.load(Ordering::Acquire) != epoch {
1257 return;
1258 }
1259 match ao.write(&pending) {
1260 Some(n) => n,
1261 None => {
1262 // Output died; flag it so `tick` moves the clock to wall time.
1263 audio.died.store(true, Ordering::Release);
1264 return;
1265 }
1266 }
1267 };
1268 audio.fed.fetch_add(accepted as u64, Ordering::Relaxed);
1269 pending.drain(..accepted);
1270 if !pending.is_empty() {
1271 // Ring full: nothing to do but let the device drain it.
1272 thread::sleep(RING_FULL_WAIT);
1273 }
1274 }
1275}
1276
1277/// Timeline seconds to a 0-based frame index, floor semantics: position `t`
1278/// shows the frame whose interval contains it. The epsilon absorbs float error
1279/// at exact frame boundaries -- `123.0/30.0 * 30.0` is `122.999...`, and a
1280/// bare truncation would land one frame early (S6 finding: 4 of every 300
1281/// frames round-trip wrong through `clip_spans()` seconds without this).
1282fn secs_to_frame(secs: f64, fps: f64) -> u32 {
1283 (secs * fps + 1e-6).floor().max(0.0) as u32
1284}
1285
1286#[cfg(test)]
1287mod tests {
1288 use super::secs_to_frame;
1289
1290 #[test]
1291 fn boundary_seconds_round_trip_to_their_own_frame() {
1292 for f in 0u32..300 {
1293 let secs = f64::from(f) / 30.0;
1294 assert_eq!(secs_to_frame(secs, 30.0), f, "frame {f}");
1295 }
1296 // Mid-frame positions still floor, and negatives clamp.
1297 assert_eq!(secs_to_frame(10.5 / 30.0, 30.0), 10);
1298 assert_eq!(secs_to_frame(-0.2, 30.0), 0);
1299 }
1300}