forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBa3e9dc2Tahinli3 months ago134 commits

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