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