forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

playback.rs938 lines, 41.6 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::decode::{DecodeSession, Frame, Worker};
25use crate::demux::{Demuxer, VideoMeta};
26use crate::project::{Clip, Lane, Project, Source, Span};
27
28/// How long the feeder waits out a full ring. The ring holds a second, so this
29/// only has to be short next to that; it costs one wakeup per 10 ms of audio.
30const RING_FULL_WAIT: Duration = Duration::from_millis(10);
31
32/// The output half of a session: the device, plus what the feeder has handed it.
33/// Cloned into the feeder thread; every field that matters is shared.
34#[derive(Clone)]
35struct Audio {
36 /// Shared because `write` runs on the feeder thread while `position` and
37 /// `set_active` are called from the caller's. The plugin serialises those
38 /// itself (atomics and a channel), but the lock is what makes it sayable in
39 /// Rust and it is never held for more than a memcpy.
40 ao: Arc<Mutex<AoSession>>,
41 sample_rate: u32,
42 channels: u64,
43 /// Interleaved samples accepted by the device so far.
44 fed: Arc<AtomicU64>,
45 /// The decoder ran out and `fed` is final.
46 fed_all: Arc<AtomicBool>,
47 /// The output plugin failed mid-stream. Its position is frozen from here on,
48 /// so it can never satisfy [`Audio::played_out`] -- the flag is what lets
49 /// [`PlaybackSession::tick`] hand the timeline to wall time instead.
50 died: Arc<AtomicBool>,
51 /// Bumped by every seek. A feeder only owns the device while this still
52 /// matches the value it started with; see [`feed`].
53 epoch: Arc<AtomicU64>,
54}
55
56impl Audio {
57 /// Whether the device has played everything there will ever be, i.e. the
58 /// audio clock is about to stop meaning anything.
59 fn played_out(&self, position: i64) -> bool {
60 self.fed_all.load(Ordering::Acquire)
61 && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed)
62 }
63
64 /// Starts a feeder for the current epoch, draining `rx` into the device.
65 /// `false` if the thread would not start, i.e. nothing will ever be fed.
66 fn spawn_feeder(&self, rx: Receiver<AudioChunk>) -> bool {
67 let me = self.clone();
68 let epoch = self.epoch.load(Ordering::Acquire);
69 thread::Builder::new()
70 .name("audio-feed".into())
71 .spawn(move || {
72 feed(rx, &me, epoch);
73 // Only the current feeder gets to declare the end of the audio:
74 // a superseded one is finished, the stream is not.
75 if me.epoch.load(Ordering::Acquire) == epoch {
76 me.fed_all.store(true, Ordering::Release);
77 }
78 })
79 .is_ok()
80 }
81}
82
83/// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`].
84pub struct PlaybackSession {
85 meta: VideoMeta,
86 frames: Receiver<Frame>,
87 /// The current decode worker.
88 worker: Worker,
89 /// Workers cancelled by a seek or a clip change, waiting to be reaped.
90 /// Joining one inline costs whatever VA-API init it is still inside (98 ms
91 /// measured worst case), which is a visible hitch on the caller's thread;
92 /// parking it here instead makes that free, and [`retire`] drops the ones
93 /// that have already returned every time it adds another.
94 ///
95 /// Never a leak, and that is the invariant: everything in here is joined
96 /// when the session drops (`Vec<Worker>`'s own drop does it, one
97 /// [`Worker::drop`] each), so no decode worker can outlive the session and
98 /// meet Mesa's `atexit` handlers from inside libva.
99 ///
100 /// [`retire`]: PlaybackSession::retire
101 retired: Vec<Worker>,
102 clock: PlaybackClock,
103 audio: Option<Audio>,
104 /// Why this timeline is silent, when the file itself is not: an audio track
105 /// we cannot decode is a session that plays perfectly and says nothing about
106 /// it otherwise. `None` for a file that has usable audio *and* for one that
107 /// has none at all, which is not a surprise worth a notice.
108 audio_disabled: Option<String>,
109 /// The edit list. Everything a caller says in seconds is a *timeline*
110 /// position; only this maps it onto the file.
111 project: Project,
112 /// What the current video worker was opened for: where it sits on the
113 /// timeline, how long it runs, and which source frame it started at --
114 /// together they rewrite a source frame index into a timeline one. Not a
115 /// clip index: a `split` cuts the clip under a running worker, and only the
116 /// mapping survives that. A span with no source is a *gap*, and the worker
117 /// feeding it emits black frames indexed from zero.
118 span: Span,
119 /// The last clip has been played out; see [`PlaybackSession::is_eos`].
120 eos: bool,
121}
122
123impl PlaybackSession {
124 /// Opens `path` and starts both decode workers. Only video failure is fatal:
125 /// a file we cannot hear is still a file we can watch.
126 pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> {
127 let path = path.as_ref().to_path_buf();
128 // `open_worker` rather than `open` purely for the worker handle: the
129 // field has to exist from the start for the first seek to use it.
130 let (meta, stream) = DecodeSession::open_worker(&path, 0, u32::MAX)?;
131 // A file is opened on its first audio stream, like `Project::single`
132 // names it: nothing has picked one yet.
133 let (audio, audio_disabled) = open_audio(&path, 0);
134 let source = match audio {
135 Some(_) => ClockSource::Audio,
136 None => ClockSource::Wall,
137 };
138 // One clip per lane covering the file, so timeline == source until the
139 // first edit -- and the range opened above is exactly that clip's.
140 let project = Project::single(&path, meta.frame_count);
141 let span = project.span_at(Lane::Video, 0).expect("never empty");
142 Ok(Self {
143 meta,
144 frames: stream.frames,
145 worker: stream.worker,
146 retired: Vec::new(),
147 clock: PlaybackClock::new(source),
148 audio,
149 audio_disabled,
150 project,
151 span,
152 eos: false,
153 })
154 }
155
156 /// Opens a project file written by [`save_project`](Self::save_project):
157 /// the whole timeline, restored to where its playhead stood, paused like
158 /// [`open`](Self::open).
159 ///
160 /// A *new* session rather than a reload of this one, so a load that fails
161 /// leaves the caller's current session untouched -- atomic by
162 /// construction. Every named file is opened and checked here: source 0
163 /// defines the timeline exactly as `open` does, every other source has to
164 /// match it the way [`import`](Self::import) demands, and every clip has to
165 /// still be inside the file it plays from. A source that vanished or
166 /// shrank since the save is a refusal naming it, not a silently shorter
167 /// timeline -- the disappearing-file tolerance elsewhere in this type
168 /// applies only *after* a project has loaded.
169 ///
170 /// The undo history is not saved: `undo` is `false` on a fresh load.
171 pub fn open_project(path: &Path) -> crate::Result<Self> {
172 let doc = crate::edith::load(path)?;
173 // Owned: the sources move into the `Project` below, and the device is
174 // opened after that (see the comment there).
175 let first = doc
176 .sources
177 .first()
178 .cloned()
179 .ok_or("the project names no sources")?;
180 // Source 0 both scaffolds the session and defines the timeline, so it
181 // is opened for playback rather than merely probed.
182 // One value, not two locals: everything below this line can refuse, and
183 // locals drop in reverse declaration order -- a bare worker would join
184 // its decode thread while the receiver next to it was still holding
185 // that thread parked in `send`, which is a hang (see [`FrameStream`]).
186 let (meta, stream) = DecodeSession::open_worker(&first.path, 0, u32::MAX)
187 .map_err(|e| format!("source {}: {e}", first.path.display()))?;
188 let first_audio = AudioSession::probe(&first.path, first.audio_stream)?;
189
190 let mut counts = vec![meta.frame_count];
191 for source in &doc.sources[1..] {
192 let (other, _) = Demuxer::open(&source.path)
193 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
194 matches_timeline(source, &other, &meta, &first_audio)
195 .map_err(|e| format!("source {}: {e}", source.path.display()))?;
196 counts.push(other.frame_count);
197 }
198 for (i, clip) in doc.video.iter().chain(&doc.audio).enumerate() {
199 if clip.out_frame > counts[clip.source] {
200 return Err(format!(
201 "clip {i} ends at frame {} but {} has {} frames",
202 clip.out_frame,
203 doc.sources[clip.source].path.display(),
204 counts[clip.source]
205 )
206 .into());
207 }
208 }
209
210 let playhead = doc.playhead;
211 let project = Project::from_parts(doc.sources, doc.video, doc.audio)?;
212 let span = project.span_at(Lane::Video, 0).expect("never empty");
213 // Last, because it is the one thing here that cannot be taken back: the
214 // feeder thread outlives the `Audio` value (it holds its own clones) and
215 // only a session's `drop` retires it, so a refusal above this line would
216 // leave a PipeWire stream and a thread behind for a project that never
217 // opened. Nothing before it needs the device.
218 let (audio, audio_disabled) = open_audio(&first.path, first.audio_stream);
219 let mut session = Self {
220 meta,
221 frames: stream.frames,
222 worker: stream.worker,
223 retired: Vec::new(),
224 clock: PlaybackClock::new(match audio {
225 Some(_) => ClockSource::Audio,
226 None => ClockSource::Wall,
227 }),
228 audio,
229 audio_disabled,
230 project,
231 span,
232 eos: false,
233 };
234 // The scaffolding above opened source 0 from its first frame and the
235 // whole of its audio; this puts both onto the clip the playhead is
236 // actually in -- a seek replaces the decoder and supersedes the audio
237 // worker by epoch, exactly as it does after an edit. It also clamps,
238 // so a playhead past a hand-shortened timeline lands on the last frame.
239 session.seek(f64::from(playhead) / meta.frame_rate);
240 Ok(session)
241 }
242
243 pub fn meta(&self) -> &VideoMeta {
244 &self.meta
245 }
246
247 /// Why this session plays silent although the file has sound -- an audio
248 /// track in a codec we cannot decode, or one the decoder refused. `None`
249 /// when there is audio, and for a file that never had any. A front-end
250 /// shows it once, at open: without it the whole thing is a stderr line.
251 pub fn audio_disabled_reason(&self) -> Option<&str> {
252 self.audio_disabled.as_deref()
253 }
254
255 /// The files this timeline plays from, index 0 first -- a caller needs it
256 /// to name an export or a window after the media rather than the project.
257 pub fn sources(&self) -> &[Source] {
258 self.project.sources()
259 }
260
261 /// Writes the timeline to `path` as a `.edith`, atomically (see
262 /// [`crate::edith`]). Sources no clip plays from are left out, and the
263 /// playhead is saved with it so a reopened project resumes where it stood.
264 pub fn save_project(&self, path: &Path) -> crate::Result<()> {
265 let (sources, video, audio) = self.project.without_orphan_sources();
266 let playhead = secs_to_frame(self.now(), self.meta.frame_rate)
267 .min(self.project.timeline_frames().saturating_sub(1));
268 crate::edith::save(path, &sources, &video, &audio, playhead)
269 }
270
271 /// The next decoded frame, its `index` rewritten from a source frame to a
272 /// *timeline* frame -- the only frame space that leaves the engine, and the
273 /// one [`PlaybackSession::now`] is in.
274 ///
275 /// `None` means "nothing right now": the decoder is behind, or a clip
276 /// boundary is being reopened (~80 ms, during which the caller simply keeps
277 /// showing its last frame). End of stream is [`PlaybackSession::is_eos`].
278 pub fn try_frame(&mut self) -> Option<Frame> {
279 loop {
280 match self.frames.try_recv() {
281 Ok(mut frame) => {
282 // A gap's worker indexes from zero, a decoder's from its in
283 // point: `base` is whichever this span started at.
284 let base = self.span.from.map_or(0, |(_, in_frame)| in_frame);
285 frame.index = self.span.start + frame.index.saturating_sub(base);
286 return Some(frame);
287 }
288 Err(TryRecvError::Empty) => return None,
289 // The worker stopped: at the end of its range, or on a decode
290 // error -- which is why this skips the rest of a broken clip
291 // rather than stalling on it.
292 Err(TryRecvError::Disconnected) => {
293 if !self.next_clip() {
294 self.eos = true;
295 return None;
296 }
297 }
298 }
299 }
300 }
301
302 /// Whether the timeline has been played out. Any seek clears it, so an edit
303 /// after the end (which reseeks) revives the session.
304 pub fn is_eos(&self) -> bool {
305 self.eos
306 }
307
308 /// Installs `replacement` as the decode worker, parking the outgoing one in
309 /// [`retired`](Self::retired) rather than joining it here, and reaping the
310 /// parked ones that have already returned.
311 ///
312 /// The sweep is what bounds the list: every worker in it was cancelled
313 /// before this ran, and a cancelled worker is out within an access unit
314 /// (plus whatever VA-API init it was inside), so a scrub reaps last seek's
315 /// worker on this seek and the list stays a handful long. Nothing waits.
316 fn retire(&mut self, replacement: Worker) {
317 self.retired
318 .push(std::mem::replace(&mut self.worker, replacement));
319 self.retired.retain(|w| !w.is_finished());
320 }
321
322 /// Starts feeding whatever follows the current span on the timeline --
323 /// another clip, or a gap, which is black frames from a worker that opens no
324 /// file. `false` past the end. The next timeline frame is derived rather
325 /// than remembered as a clip index, because a `split` while playing cuts the
326 /// clip under the running worker and only the mapping stays true.
327 fn next_clip(&mut self) -> bool {
328 let next = self.span.end();
329 let Some(span) = self.project.span_at(Lane::Video, next) else {
330 return false;
331 };
332 // We only get here on a disconnect, so the old worker has already
333 // returned; cancel anyway, so `retire` treats every path alike.
334 self.worker.cancel();
335 self.start_span(span);
336 true
337 }
338
339 /// Points the video worker at `span`: a decoder over its source range, or a
340 /// black-frame generator for a gap. The old worker must already have been
341 /// cancelled -- this is the half both `seek` and `next_clip` share.
342 ///
343 /// A source that will not open leaves the *span* installed anyway: the
344 /// timeline still moves, there are simply no more pictures, and the
345 /// disconnected receiver carries the session on to the next span.
346 fn start_span(&mut self, span: Span) {
347 let opened = match span.from {
348 Some((source, in_frame)) => DecodeSession::open_worker(
349 &self.project.sources()[source].path,
350 in_frame,
351 in_frame + span.len,
352 )
353 .map(|(_, stream)| stream)
354 .inspect_err(|e| eprintln!("timeline frame {}: video open failed: {e}", span.start)),
355 None => Ok(DecodeSession::open_black(
356 self.meta.width,
357 self.meta.height,
358 span.len,
359 )),
360 };
361 if let Ok(stream) = opened {
362 // Receiver first, worker second: the drop of the *old* receiver is
363 // what wakes the outgoing worker if it is parked in `send`, and only
364 // then can it return and be reaped by a later sweep. Nothing here
365 // joins, so this ordering costs the seek nothing.
366 self.frames = stream.frames;
367 self.retire(stream.worker);
368 }
369 self.span = span;
370 }
371
372 /// Length of the edited timeline in seconds -- what a ruler shows, and it
373 /// shrinks with every delete.
374 pub fn timeline_duration(&self) -> f64 {
375 f64::from(self.project.timeline_frames()) / self.meta.frame_rate
376 }
377
378 /// `(start, len)` per clip in timeline seconds, in order: what a clips lane
379 /// needs to lay itself out. Selection is the caller's business.
380 pub fn clip_spans(&self) -> Vec<(f64, f64)> {
381 let fps = self.meta.frame_rate;
382 self.project
383 .clip_spans()
384 .iter()
385 .map(|&(start, len)| (f64::from(start) / fps, f64::from(len) / fps))
386 .collect()
387 }
388
389 /// [`clip_spans`](Self::clip_spans) plus the index into
390 /// [`Project::sources`] each clip plays from -- what a lane needs to colour
391 /// an imported clip differently from the file the session was opened with.
392 pub fn clip_spans_by_source(&self) -> Vec<(f64, f64, usize)> {
393 self.lane_spans_by_source(Lane::Video)
394 }
395
396 /// [`clip_spans_by_source`](Self::clip_spans_by_source) for either lane,
397 /// with each clip's group id -- what a two-lane front-end draws. The holes
398 /// between consecutive entries are the gaps.
399 pub fn lane_spans_by_source(&self, lane: Lane) -> Vec<(f64, f64, usize)> {
400 let fps = self.meta.frame_rate;
401 self.project
402 .lane(lane)
403 .iter()
404 .map(|c| (f64::from(c.start) / fps, f64::from(c.len()) / fps, c.source))
405 .collect()
406 }
407
408 /// Every placement of one lane, in timeline order. What a two-lane
409 /// front-end draws and nothing
410 /// [`lane_spans_by_source`](Self::lane_spans_by_source) can answer: a clip
411 /// carries its group id (which halves a click marks together) and its
412 /// source range (where a waveform reads its peaks from) as well as its
413 /// span. The holes between consecutive clips are the gaps.
414 pub fn lane_clips(&self, lane: Lane) -> &[Clip] {
415 self.project.lane(lane)
416 }
417
418 /// Splits every lane at `timeline_secs`, so the two sides become two
419 /// groups. Metadata only: a split never changes the timeline->source
420 /// mapping, so the running decoder stays correct and playback does not
421 /// blink. `false` at a clip start, in a gap and past the end, where there
422 /// would be nothing to split off.
423 pub fn cut_at(&mut self, timeline_secs: f64) -> bool {
424 self.project
425 .split(secs_to_frame(timeline_secs, self.meta.frame_rate))
426 }
427
428 /// The inverse of [`cut_at`](Self::cut_at): rejoins the clips that meet at
429 /// `timeline_secs` in every lane and puts them back in one group. `false`
430 /// unless a split could have produced what is there. Metadata only, like the
431 /// split -- no reseek.
432 pub fn regroup_at(&mut self, timeline_secs: f64) -> bool {
433 self.project
434 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))
435 }
436
437 /// Lifts one lane's clip out, leaving a gap: black frames on the video lane,
438 /// silence on the audio one, and nothing else moves. Reseeks, because what
439 /// the playhead sits on has changed. `false` for a bad index and for the
440 /// lift that would leave the whole timeline empty.
441 pub fn lift_clip(&mut self, lane: Lane, idx: usize) -> bool {
442 self.edit(|p| p.lift(lane, idx))
443 }
444
445 /// The clip at `idx` -- what a caller copies. It is a pair of source frame
446 /// numbers and nothing else, so a copy stays valid after the clip it came
447 /// from is deleted. `None` past the end.
448 pub fn clip_at(&self, idx: usize) -> Option<Clip> {
449 self.project.clips().get(idx).copied()
450 }
451
452 /// Inserts `clip` at the playhead, splitting the clip under it. Like a
453 /// delete this moves every following frame, so the session reseeks; past
454 /// the end of the timeline the clip is appended. One undo step.
455 pub fn paste_at(&mut self, timeline_secs: f64, clip: Clip) -> bool {
456 let at = secs_to_frame(timeline_secs, self.meta.frame_rate);
457 self.edit(|p| p.paste(at, clip))
458 }
459
460 /// Places `frames` of `path` played on its audio `stream` at
461 /// `timeline_secs`, the way [`paste_at`](Self::paste_at) places a copy --
462 /// the door a library row goes through, and the only way a stream other
463 /// than the one an import brought in reaches the timeline. The `(file,
464 /// stream)` pair becomes a source if it is not one already.
465 ///
466 /// Refused, changing nothing, unless that stream can join *this* timeline:
467 /// same audio parameters as the first source, in the same words
468 /// [`import`](Self::import) refuses a file with. One output device and one
469 /// copied AAC track mean one set of audio parameters for the whole
470 /// timeline, so a 22 kHz mono track cannot join a 44.1 kHz stereo one --
471 /// there is no resampler here, and no AAC encoder to write the join with.
472 /// A front-end greys such a row out; this is the backstop that keeps a
473 /// stale one from making the whole timeline silent.
474 pub fn place_stream_at(
475 &mut self,
476 timeline_secs: f64,
477 path: &Path,
478 stream: usize,
479 frames: u32,
480 ) -> crate::Result<bool> {
481 let wanted = Source::new(path, stream);
482 // Another stream of a file whose picture is *already* on the timeline:
483 // that is what a library row is, and it is why nothing here has to
484 // check dimensions or frame rate -- the file passed that at import.
485 if !self.project.sources().iter().any(|s| s.path == wanted.path) {
486 return Err(format!("{} is not on this timeline", path.display()).into());
487 }
488 let first = self.first_audio()?;
489 audio_matches(&wanted, &first)?;
490 let source = self.project.import(path, stream);
491 Ok(self.paste_at(
492 timeline_secs,
493 Clip {
494 start: 0,
495 in_frame: 0,
496 out_frame: frames.max(1),
497 source,
498 link: None,
499 },
500 ))
501 }
502
503 /// What the timeline's audio *is*: source 0's chosen stream, probed. Every
504 /// other source is held to it.
505 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {
506 let first = &self.project.sources()[0];
507 AudioSession::probe(&first.path, first.audio_stream)
508 }
509
510 /// Removes the video clip at `idx` and everything under it, closing the gap
511 /// on every lane. Unlike a split this *does* move every following frame, so
512 /// the session reseeks to wherever the playhead now points.
513 /// [`lift_clip`](Self::lift_clip) is the one that leaves a hole instead.
514 /// `false` for a bad index or the last remaining clip.
515 pub fn delete_clip(&mut self, idx: usize) -> bool {
516 self.edit(|p| p.delete(idx))
517 }
518
519 /// Undoes the last successful edit, and reseeks like a delete.
520 pub fn undo(&mut self) -> bool {
521 self.edit(Project::undo)
522 }
523
524 /// Appends the whole of `path` to the end of the timeline. One undo step,
525 /// and the file becomes a source only if it is not one already.
526 ///
527 /// Refused unless it matches the timeline exactly -- same dimensions, same
528 /// frame rate, same audio parameters or both silent -- because one timeline
529 /// this slice means one set of encoder/device parameters; the `Err` names
530 /// the property that disagrees, for a caller to show. Nothing is changed by
531 /// a refusal.
532 pub fn import(&mut self, path: &Path) -> crate::Result<()> {
533 let (meta, _) = Demuxer::open(path)?;
534 let first = self.first_audio()?;
535 // Stream 0: an import brings a file in on its first audio track, and
536 // [`place_stream_at`](Self::place_stream_at) is how any other one of
537 // its streams reaches the timeline afterwards.
538 matches_timeline(&Source::new(path, 0), &meta, &self.meta, &first)?;
539
540 let old_end = self.timeline_duration();
541 let source = self.project.import(path, 0);
542 // Refused only for an unknown index, and this one just came from `import`.
543 self.project.append_clip(source, meta.frame_count);
544 // Reseek like any other edit, even though nothing before the playhead
545 // moved: the running audio worker's segment list stops at the old end,
546 // so without this the appended clip would play silent. At EOS the wall
547 // clock has run on past the timeline, so resume from the join instead
548 // of wherever it got to -- and the seek is what clears `eos`.
549 let at = if self.eos { old_end } else { self.now() };
550 self.seek(at);
551 Ok(())
552 }
553
554 /// Applies an edit and, if it took, reseeks onto the new mapping. `seek`
555 /// clamps to the new duration and keeps playing playing, so a delete that
556 /// shortens the timeline past the playhead lands on the last frame.
557 fn edit(&mut self, f: impl FnOnce(&mut Project) -> bool) -> bool {
558 if !f(&mut self.project) {
559 return false;
560 }
561 let now = self.now();
562 self.seek(now);
563 true
564 }
565
566 /// Current timeline position in seconds.
567 pub fn now(&self) -> f64 {
568 self.clock.now()
569 }
570
571 pub fn is_playing(&self) -> bool {
572 self.clock.is_playing()
573 }
574
575 pub fn play(&mut self) {
576 if self.clock.is_playing() {
577 return;
578 }
579 // Invariant: the clock is positioned *before* audio restarts. Audio
580 // reports are relative to the first one after that, so a seek would go
581 // here too -- `clock.seek_to(t)` and then `set_active(true)`.
582 self.clock.play();
583 if let Some(audio) = &self.audio {
584 audio.ao.lock().unwrap().set_active(true);
585 }
586 }
587
588 pub fn pause(&mut self) {
589 if !self.clock.is_playing() {
590 return;
591 }
592 if let Some(audio) = &self.audio {
593 audio.ao.lock().unwrap().set_active(false);
594 }
595 self.clock.pause();
596 }
597
598 pub fn toggle(&mut self) {
599 if self.clock.is_playing() {
600 self.pause()
601 } else {
602 self.play()
603 }
604 }
605
606 /// Sets the monitoring gain, 0.0 (silent) to 1.0. Mute is a gain of 0.0:
607 /// one knob, because muting and turning it down are the same thing to the
608 /// device, and *which* the user meant is a question only the UI can answer
609 /// -- it keeps the level to come back to.
610 ///
611 /// Deliberately not session state: nothing here remembers it, so a caller
612 /// pushes it once per session and an export -- which renders the file
613 /// rather than what the speakers are doing -- can never pick it up. Silent
614 /// with no audio device, which is also the only honest answer there.
615 ///
616 /// Mute is not pause: the samples are still consumed and the device clock
617 /// still runs, so the picture keeps playing against it.
618 pub fn set_gain(&self, gain: f32) -> bool {
619 match &self.audio {
620 Some(audio) => audio.ao.lock().unwrap().set_volume(gain),
621 None => false,
622 }
623 }
624
625 /// Repositions the timeline to `secs`, clamped to the *timeline*. Both decode
626 /// workers are replaced rather than steered: a fresh channel cannot hold a
627 /// stale frame, and it works just as well after EOF, where the old workers
628 /// have already exited.
629 ///
630 /// Playing stays playing and paused stays paused -- but a paused seek still
631 /// decodes, so the caller can show the frame it landed on.
632 pub fn seek(&mut self, secs: f64) {
633 let fps = self.meta.frame_rate;
634 let total = self.project.timeline_frames();
635 let t = secs.clamp(0.0, f64::from(total) / fps);
636 let target = secs_to_frame(t, fps).min(total.saturating_sub(1));
637 let was_playing = self.clock.is_playing();
638
639 if let Some(audio) = &self.audio {
640 let ao = audio.ao.lock().unwrap();
641 ao.set_active(false);
642 // Bumped and flushed while holding the device lock, because the
643 // feeder re-checks the epoch inside that same lock: whatever it is
644 // carrying can no longer reach the ring after this point.
645 audio.epoch.fetch_add(1, Ordering::Release);
646 ao.flush();
647 }
648
649 // Cancel first, drop second: the old worker may be parked in `send` on
650 // the bounded channel, where only the disconnect wakes it -- and it
651 // then finds the flag already set. It is then parked, not joined; see
652 // [`retire`](Self::retire), which is what keeps a scrub off the price
653 // of a VA-API init.
654 self.worker.cancel();
655 // `target` is inside the timeline (never empty), so this always spans;
656 // the span runs from there to the end of whatever it landed in -- a
657 // clip, or a gap, which starts a black-frame worker instead.
658 if let Some(span) = self.project.span_at(Lane::Video, target) {
659 self.start_span(span);
660 }
661 self.eos = false;
662
663 let mut audio_running = false;
664 if let Some(audio) = &self.audio
665 && !audio.died.load(Ordering::Acquire)
666 {
667 // The device position keeps counting across a flush, so re-basing
668 // `fed` on it is what keeps `played_out` exact for the new stream.
669 let played = audio.ao.lock().unwrap().position().unwrap_or(0).max(0) as u64;
670 audio.fed.store(played * audio.channels, Ordering::Relaxed);
671 audio.fed_all.store(false, Ordering::Release);
672 // One worker for the whole rest of the timeline, so the joins
673 // between clips are gapless: the video reopens at a boundary, the
674 // ear never hears it -- and a join between two *files* is just
675 // another segment, because every segment names its own source.
676 let segs = self.project.segments_from(target, fps);
677 // Each source on the stream it was placed with: what plays is what
678 // the library row said, and what an export copies (`export::run`).
679 let sources = self.project.audio_sources();
680 audio_running = match AudioSession::open_multi_streams(&sources, &segs) {
681 Ok(Some((_, rx))) => audio.spawn_feeder(rx),
682 _ => false,
683 };
684 if !audio_running {
685 // Nothing will ever be fed again; let `tick` fall to wall time
686 // instead of waiting on a device that has no more work coming.
687 audio.fed_all.store(true, Ordering::Release);
688 }
689 }
690
691 // Same invariant as `play`: position the clock before audio restarts.
692 if audio_running && self.clock.source() != ClockSource::Audio {
693 self.clock.switch_to_audio();
694 }
695 self.clock.seek_to(t);
696 if was_playing && let Some(audio) = &self.audio {
697 audio.ao.lock().unwrap().set_active(true);
698 }
699 }
700
701 /// Renders the edited timeline to `out` on a worker thread. The session is
702 /// untouched -- the export decodes the source file for itself -- but a
703 /// caller should still [`pause`](PlaybackSession::pause) first, because
704 /// playback and export otherwise fight over the same decoder hardware.
705 ///
706 /// Later edits do not reach a running export: it works from a snapshot of
707 /// the edit list taken here.
708 ///
709 /// ponytail: this defaults the settings; the app still calls it that way,
710 /// and the export options card replaces the call with
711 /// [`export_to_with`](PlaybackSession::export_to_with).
712 pub fn export_to(&self, out: &Path) -> crate::ExportHandle {
713 self.export_to_with(out, &crate::export::ExportSettings::default())
714 }
715
716 /// [`export_to`](PlaybackSession::export_to) with the output settings spelled
717 /// out rather than defaulted.
718 pub fn export_to_with(
719 &self,
720 out: &Path,
721 settings: &crate::export::ExportSettings,
722 ) -> crate::ExportHandle {
723 crate::export::start(self.project.clone(), self.meta, out, settings)
724 }
725
726 /// Moves the clock forward; the caller runs this once per rendered frame.
727 /// Costs an atomic load, and once per session a mode switch.
728 pub fn tick(&mut self) {
729 let Some(audio) = &self.audio else {
730 return; // wall time from the start, nothing to poll
731 };
732 if self.clock.source() != ClockSource::Audio {
733 return;
734 }
735 if audio.died.load(Ordering::Acquire) {
736 // Output died mid-stream: its position will never reach `fed`, so
737 // the EOF comparison below is unreachable. Wall time takes over
738 // from wherever the clock last stood.
739 self.clock.switch_to_wall();
740 return;
741 }
742 // `None` until the device's first callback: the clock holds at its
743 // anchor rather than guessing, which is why playback starts on time
744 // instead of a quantum early.
745 let Some(position) = audio.ao.lock().unwrap().position() else {
746 return;
747 };
748 if audio.played_out(position) {
749 // Audio EOF. Wall time carries the same timeline on from here, with
750 // no jump, and this branch cannot be reached again.
751 self.clock.switch_to_wall();
752 } else {
753 self.clock
754 .set_audio_position(position as u64, audio.sample_rate);
755 }
756 }
757}
758
759impl Drop for PlaybackSession {
760 /// The video workers -- the running one and every cancelled one still in
761 /// [`retired`](PlaybackSession::retired) -- cancel and join themselves when
762 /// those fields drop right after this, the running one behind its receiver
763 /// so a `send` cannot hold the join. *That* is what a session must not exit
764 /// without: no decode worker outlives it, so none can be inside libva when
765 /// Mesa's `atexit` handlers free the state under it.
766 ///
767 /// This is the audio half: bumping the epoch retires the feeder at its next write,
768 /// which drops the decode receiver with it. Neither is waited for -- no
769 /// driver state is torn down on the audio side.
770 fn drop(&mut self) {
771 if let Some(audio) = &self.audio {
772 audio.epoch.fetch_add(1, Ordering::Release);
773 }
774 }
775}
776
777/// Whether `path`, already demuxed to `meta`, may join a timeline whose
778/// parameters are `timeline` and whose audio probes as `first`: same
779/// dimensions, same frame rate, same audio parameters or both silent -- one
780/// timeline this slice means one set of encoder/device parameters.
781///
782/// The `Err` names the property that disagrees, and those strings are what a
783/// front-end shows verbatim; [`PlaybackSession::import`] and
784/// [`PlaybackSession::open_project`] share them so a file refused at import is
785/// refused in the same words at load.
786fn matches_timeline(
787 source: &Source,
788 meta: &VideoMeta,
789 timeline: &VideoMeta,
790 first: &Option<crate::AudioProbe>,
791) -> crate::Result<()> {
792 if (meta.width, meta.height) != (timeline.width, timeline.height) {
793 return Err(format!(
794 "{}x{} does not match the timeline's {}x{}",
795 meta.width, meta.height, timeline.width, timeline.height
796 )
797 .into());
798 }
799 // Container frame rates are computed from timescales, so never `==`.
800 if (meta.frame_rate - timeline.frame_rate).abs() > 0.01 {
801 return Err(format!(
802 "{:.3} fps does not match the timeline's {:.3} fps",
803 meta.frame_rate, timeline.frame_rate
804 )
805 .into());
806 }
807 audio_matches(source, first)
808}
809
810/// The audio half of [`matches_timeline`], which a stream placed on its own
811/// ([`PlaybackSession::place_stream_at`]) has to pass while the picture it
812/// comes with is already on the timeline.
813fn audio_matches(source: &Source, first: &Option<crate::AudioProbe>) -> crate::Result<()> {
814 // Whole-probe equality: rate, layout and the esds fields, which the audio
815 // worker holds every source to anyway. Both silent is a match.
816 let probe = AudioSession::probe(&source.path, source.audio_stream)?;
817 if probe != *first {
818 return Err(match (probe, first) {
819 (None, _) => "the file is silent, the timeline has audio".to_string(),
820 (_, None) => "the file has audio, the timeline is silent".to_string(),
821 (Some(a), Some(b)) => format!(
822 "audio {} Hz {} ch does not match the timeline's {} Hz {} ch",
823 a.params.sample_rate, a.channels, b.params.sample_rate, b.channels
824 ),
825 }
826 .into());
827 }
828 Ok(())
829}
830
831/// `None` for a silent session -- no audio track, no plugin, no daemon, or a
832/// track the decoder refuses. Dropping the receiver on the way out stops the
833/// audio decode worker, so a failure here leaves nothing running.
834///
835/// The second half is why, for the cases the *file* is to blame for: those are
836/// a surprise worth showing (see
837/// [`audio_disabled_reason`](PlaybackSession::audio_disabled_reason)), where a
838/// file with no audio at all and a machine with no output device are not.
839fn open_audio(path: &Path, stream: usize) -> (Option<Audio>, Option<String>) {
840 let sources = [(path.to_path_buf(), stream)];
841 let (meta, rx) =
842 match AudioSession::open_multi_streams(&sources, &[(Some(0), 0.0, f64::INFINITY)]) {
843 Ok(Some(opened)) => opened,
844 // No AAC track: silent by nature, or sound in a codec we do not
845 // have -- and only the second of those is worth a word.
846 Ok(None) => {
847 let reason = AudioSession::unsupported(path).ok().flatten();
848 if let Some(reason) = &reason {
849 eprintln!("audio disabled: {reason}");
850 }
851 return (None, reason);
852 }
853 Err(e) => {
854 eprintln!("audio disabled: {e}");
855 return (None, Some(e.to_string()));
856 }
857 };
858 let Some(ao) = AoSession::open(meta.sample_rate, u32::from(meta.channels)) else {
859 return (None, None); // no device: the machine's business, not the file's
860 };
861 // The stream comes up streaming; a session starts paused, so silence the
862 // device until `play`. The feeder still fills the ring in the meantime.
863 ao.set_active(false);
864
865 let audio = Audio {
866 ao: Arc::new(Mutex::new(ao)),
867 sample_rate: meta.sample_rate,
868 channels: u64::from(meta.channels),
869 fed: Arc::new(AtomicU64::new(0)),
870 fed_all: Arc::new(AtomicBool::new(false)),
871 died: Arc::new(AtomicBool::new(false)),
872 epoch: Arc::new(AtomicU64::new(0)),
873 };
874 (audio.spawn_feeder(rx).then_some(audio), None)
875}
876
877/// Pours decoded chunks into the device, keeping whatever the ring would not
878/// take. Ends when the decoder is done, the output dies, or a seek supersedes
879/// this feeder.
880fn feed(rx: Receiver<AudioChunk>, audio: &Audio, epoch: u64) {
881 let mut pending: Vec<f32> = Vec::new();
882 loop {
883 if pending.is_empty() {
884 match rx.recv() {
885 Ok(chunk) => pending = chunk.samples,
886 Err(_) => return, // decoder finished or went away
887 }
888 }
889 let accepted = {
890 let mut ao = audio.ao.lock().unwrap();
891 // Under the lock, immediately before the write: `seek` bumps the
892 // epoch and flushes the ring holding this very lock, so past this
893 // check no stale sample can be queued behind the flush.
894 if audio.epoch.load(Ordering::Acquire) != epoch {
895 return;
896 }
897 match ao.write(&pending) {
898 Some(n) => n,
899 None => {
900 // Output died; flag it so `tick` moves the clock to wall time.
901 audio.died.store(true, Ordering::Release);
902 return;
903 }
904 }
905 };
906 audio.fed.fetch_add(accepted as u64, Ordering::Relaxed);
907 pending.drain(..accepted);
908 if !pending.is_empty() {
909 // Ring full: nothing to do but let the device drain it.
910 thread::sleep(RING_FULL_WAIT);
911 }
912 }
913}
914
915/// Timeline seconds to a 0-based frame index, floor semantics: position `t`
916/// shows the frame whose interval contains it. The epsilon absorbs float error
917/// at exact frame boundaries -- `123.0/30.0 * 30.0` is `122.999...`, and a
918/// bare truncation would land one frame early (S6 finding: 4 of every 300
919/// frames round-trip wrong through `clip_spans()` seconds without this).
920fn secs_to_frame(secs: f64, fps: f64) -> u32 {
921 (secs * fps + 1e-6).floor().max(0.0) as u32
922}
923
924#[cfg(test)]
925mod tests {
926 use super::secs_to_frame;
927
928 #[test]
929 fn boundary_seconds_round_trip_to_their_own_frame() {
930 for f in 0u32..300 {
931 let secs = f64::from(f) / 30.0;
932 assert_eq!(secs_to_frame(secs, 30.0), f, "frame {f}");
933 }
934 // Mid-frame positions still floor, and negatives clamp.
935 assert_eq!(secs_to_frame(10.5 / 30.0, 30.0), 10);
936 assert_eq!(secs_to_frame(-0.2, 30.0), 0);
937 }
938}