A/V session — audio-master clock, real-speed video, space to pause
Browse files at this commit63e6964f3ee36b751a6f1345d59a49885b08aff8Parent: 229a569- feat
- A/V session — audio-master clock, real-speed video, space to pause
4 changed files +435 -29
- crates/app/src/main.rs +108 -29
- crates/engine/src/lib.rs +2 -0
- crates/engine/src/playback.rs +217 -0
- crates/engine/tests/playback.rs +108 -0
crates/app/src/main.rsmodified+108 -29
| @@ -1,48 +1,114 @@ | |||
| 1 | use std::sync::Arc; | 1 | use std::sync::Arc; |
| 2 | -use std::sync::mpsc::{Receiver, TryRecvError}; | 2 | +use std::sync::mpsc::TryRecvError; |
| 3 | +use std::time::Instant; | ||
| 3 | 4 | ||
| 4 | -use engine::{DecodeSession, Frame}; | 5 | +use engine::{Frame, PlaybackSession}; |
| 5 | use gpui::{ | 6 | use gpui::{ |
| 6 | - App, Application, Bounds, Context, RenderImage, TitlebarOptions, Window, WindowBounds, | 7 | + App, Application, Bounds, Context, FocusHandle, KeyDownEvent, RenderImage, TitlebarOptions, |
| 7 | - WindowOptions, div, img, prelude::*, px, rgb, size, | 8 | + Window, WindowBounds, WindowOptions, div, img, prelude::*, px, rgb, size, |
| 8 | }; | 9 | }; |
| 9 | 10 | ||
| 10 | struct Player { | 11 | struct Player { |
| 11 | - rx: Receiver<Frame>, | 12 | + session: PlaybackSession, |
| 13 | + /// Timeline seconds -> frame index, so the clock can be compared to what | ||
| 14 | + /// the decoder hands over. | ||
| 15 | + fps: f64, | ||
| 12 | image: Option<Arc<RenderImage>>, | 16 | image: Option<Arc<RenderImage>>, |
| 13 | - finished: bool, | 17 | + /// A frame that arrived before its time; shown on the tick it comes due. |
| 18 | + held: Option<Frame>, | ||
| 19 | + /// The decoder's channel closed. Frames may still be waiting in `held`. | ||
| 20 | + eos: bool, | ||
| 21 | + /// Last frame shown; nothing left to animate. | ||
| 22 | + done: bool, | ||
| 23 | + /// Playback was started once, on the first render. Space owns it after that. | ||
| 24 | + launched: bool, | ||
| 25 | + displayed: u32, | ||
| 26 | + dropped: u32, | ||
| 27 | + /// Wall clock of the first displayed frame -- the real-speed measurement. | ||
| 28 | + started: Option<Instant>, | ||
| 29 | + focus: FocusHandle, | ||
| 14 | } | 30 | } |
| 15 | 31 | ||
| 16 | impl Player { | 32 | impl Player { |
| 17 | - /// Takes at most one frame per rendered frame; the decoder's channel is | 33 | + /// Catches the display up to the clock: everything already due is taken off |
| 18 | - /// bounded so it simply waits for us. | 34 | + /// the channel and only the last of them is shown, which *is* the |
| 35 | + /// drop-when-behind policy. A frame that is not due yet waits in `held`. | ||
| 19 | fn pump(&mut self, window: &mut Window) { | 36 | fn pump(&mut self, window: &mut Window) { |
| 20 | - match self.rx.try_recv() { | 37 | + let target = self.session.now() * self.fps; |
| 21 | - Ok(frame) => { | 38 | + let mut newest: Option<Frame> = None; |
| 22 | - let buf = | 39 | + loop { |
| 23 | - image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra) | 40 | + let frame = match self.held.take() { |
| 24 | - .expect("frame buffer sized width*height*4"); | 41 | + Some(frame) => frame, |
| 25 | - let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)])); | 42 | + None => match self.session.frames().try_recv() { |
| 26 | - if let Some(old) = self.image.replace(next) { | 43 | + Ok(frame) => frame, |
| 27 | - // Every RenderImage gets a fresh id and its own atlas tile: | 44 | + Err(TryRecvError::Empty) => break, |
| 28 | - // without this the sprite atlas grows for the whole video. | 45 | + Err(TryRecvError::Disconnected) => { |
| 29 | - let _ = window.drop_image(old); | 46 | + self.eos = true; |
| 30 | - } | 47 | + break; |
| 48 | + } | ||
| 49 | + }, | ||
| 50 | + }; | ||
| 51 | + if f64::from(frame.index) <= target { | ||
| 52 | + self.dropped += u32::from(newest.is_some()); | ||
| 53 | + newest = Some(frame); | ||
| 54 | + } else { | ||
| 55 | + self.held = Some(frame); | ||
| 56 | + break; | ||
| 57 | + } | ||
| 58 | + } | ||
| 59 | + | ||
| 60 | + if let Some(frame) = newest { | ||
| 61 | + self.displayed += 1; | ||
| 62 | + self.started.get_or_insert_with(|| { | ||
| 63 | + eprintln!("first frame displayed (index {})", frame.index); | ||
| 64 | + Instant::now() | ||
| 65 | + }); | ||
| 66 | + let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra) | ||
| 67 | + .expect("frame buffer sized width*height*4"); | ||
| 68 | + let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)])); | ||
| 69 | + if let Some(old) = self.image.replace(next) { | ||
| 70 | + // Every RenderImage gets a fresh id and its own atlas tile: | ||
| 71 | + // without this the sprite atlas grows for the whole video. | ||
| 72 | + let _ = window.drop_image(old); | ||
| 31 | } | 73 | } |
| 32 | - Err(TryRecvError::Empty) => {} | 74 | + } |
| 33 | - Err(TryRecvError::Disconnected) => self.finished = true, | 75 | + |
| 76 | + if self.eos && self.held.is_none() && !self.done { | ||
| 77 | + self.done = true; | ||
| 78 | + let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64()); | ||
| 79 | + eprintln!( | ||
| 80 | + "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s", | ||
| 81 | + self.displayed, | ||
| 82 | + self.dropped, | ||
| 83 | + self.session.now() | ||
| 84 | + ); | ||
| 34 | } | 85 | } |
| 35 | } | 86 | } |
| 36 | } | 87 | } |
| 37 | 88 | ||
| 38 | impl Render for Player { | 89 | impl Render for Player { |
| 39 | - fn render(&mut self, window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement { | 90 | + fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement { |
| 91 | + // Starts on launch: the session opens paused so the clock begins with | ||
| 92 | + // the first rendered frame rather than with the process (which would | ||
| 93 | + // charge window setup to the timeline and drop the frames it covers). | ||
| 94 | + if !std::mem::replace(&mut self.launched, true) { | ||
| 95 | + self.session.play(); | ||
| 96 | + } | ||
| 97 | + self.session.tick(); | ||
| 40 | self.pump(window); | 98 | self.pump(window); |
| 41 | - if !self.finished { | 99 | + if !self.done { |
| 42 | window.request_animation_frame(); | 100 | window.request_animation_frame(); |
| 43 | } | 101 | } |
| 44 | 102 | ||
| 45 | div() | 103 | div() |
| 104 | + .track_focus(&self.focus) | ||
| 105 | + .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, _| { | ||
| 106 | + // `is_held` filters auto-repeat, which would otherwise toggle | ||
| 107 | + // playback many times a second. | ||
| 108 | + if event.keystroke.key == "space" && !event.is_held { | ||
| 109 | + this.session.toggle(); | ||
| 110 | + } | ||
| 111 | + })) | ||
| 46 | .size_full() | 112 | .size_full() |
| 47 | .bg(rgb(0x101010)) | 113 | .bg(rgb(0x101010)) |
| 48 | .flex() | 114 | .flex() |
| @@ -61,13 +127,14 @@ fn main() { | |||
| 61 | eprintln!("usage: app <video.mp4>"); | 127 | eprintln!("usage: app <video.mp4>"); |
| 62 | std::process::exit(2); | 128 | std::process::exit(2); |
| 63 | }; | 129 | }; |
| 64 | - let (meta, rx) = match DecodeSession::open(&path) { | 130 | + let session = match PlaybackSession::open(&path) { |
| 65 | Ok(v) => v, | 131 | Ok(v) => v, |
| 66 | Err(e) => { | 132 | Err(e) => { |
| 67 | eprintln!("cannot open {path}: {e}"); | 133 | eprintln!("cannot open {path}: {e}"); |
| 68 | std::process::exit(1); | 134 | std::process::exit(1); |
| 69 | } | 135 | } |
| 70 | }; | 136 | }; |
| 137 | + let meta = *session.meta(); | ||
| 71 | println!( | 138 | println!( |
| 72 | "{path}: {}x{} @ {:.2} fps, {} samples", | 139 | "{path}: {}x{} @ {:.2} fps, {} samples", |
| 73 | meta.width, meta.height, meta.frame_rate, meta.frame_count | 140 | meta.width, meta.height, meta.frame_rate, meta.frame_count |
| @@ -88,12 +155,24 @@ fn main() { | |||
| 88 | }), | 155 | }), |
| 89 | ..Default::default() | 156 | ..Default::default() |
| 90 | }, | 157 | }, |
| 91 | - |_, cx| { | 158 | + |window, cx| { |
| 92 | - cx.new(|_| Player { | 159 | + let player = cx.new(|cx| Player { |
| 93 | - rx, | 160 | + session, |
| 161 | + fps: meta.frame_rate, | ||
| 94 | image: None, | 162 | image: None, |
| 95 | - finished: false, | 163 | + held: None, |
| 96 | - }) | 164 | + eos: false, |
| 165 | + done: false, | ||
| 166 | + launched: false, | ||
| 167 | + displayed: 0, | ||
| 168 | + dropped: 0, | ||
| 169 | + started: None, | ||
| 170 | + focus: cx.focus_handle(), | ||
| 171 | + }); | ||
| 172 | + // Nothing else takes focus, and without it the key listener | ||
| 173 | + // above is never reached. | ||
| 174 | + window.focus(&player.read(cx).focus); | ||
| 175 | + player | ||
| 97 | }, | 176 | }, |
| 98 | ) | 177 | ) |
| 99 | .unwrap(); | 178 | .unwrap(); |
crates/engine/src/lib.rsmodified+2 -0
| @@ -7,9 +7,11 @@ pub mod convert; | |||
| 7 | pub mod decode; | 7 | pub mod decode; |
| 8 | pub mod demux; | 8 | pub mod demux; |
| 9 | pub mod hw; | 9 | pub mod hw; |
| 10 | +pub mod playback; | ||
| 10 | 11 | ||
| 11 | pub use audio::{AudioChunk, AudioMeta, AudioSession}; | 12 | pub use audio::{AudioChunk, AudioMeta, AudioSession}; |
| 12 | pub use clock::PlaybackClock; | 13 | pub use clock::PlaybackClock; |
| 14 | +pub use playback::PlaybackSession; | ||
| 13 | pub use decode::{DecodeSession, Frame}; | 15 | pub use decode::{DecodeSession, Frame}; |
| 14 | pub use demux::VideoMeta; | 16 | pub use demux::VideoMeta; |
| 15 | 17 | ||
crates/engine/src/playback.rsadded+217 -0
| @@ -0,0 +1,217 @@ | |||
| 1 | +//! One file, one timeline: the decode workers, the audio output and the master | ||
| 2 | +//! clock wired together so a front-end only has to render and call [`tick`]. | ||
| 3 | +//! | ||
| 4 | +//! [`tick`]: PlaybackSession::tick | ||
| 5 | +//! | ||
| 6 | +//! Everything degrades to silent-but-correct: no audio track, no plugin, no | ||
| 7 | +//! PipeWire daemon and an unusable format all end up in [`ClockSource::Wall`], | ||
| 8 | +//! where the video is paced by real time instead of by the device. | ||
| 9 | +//! | ||
| 10 | +//! Drift policy stays with the caller -- this type answers "what time is it", | ||
| 11 | +//! the renderer decides which frame that means. | ||
| 12 | + | ||
| 13 | +use std::path::Path; | ||
| 14 | +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; | ||
| 15 | +use std::sync::mpsc::Receiver; | ||
| 16 | +use std::sync::{Arc, Mutex}; | ||
| 17 | +use std::thread; | ||
| 18 | +use std::time::Duration; | ||
| 19 | + | ||
| 20 | +use crate::ao::AoSession; | ||
| 21 | +use crate::audio::{AudioChunk, AudioSession}; | ||
| 22 | +use crate::clock::{ClockSource, PlaybackClock}; | ||
| 23 | +use crate::decode::{DecodeSession, Frame}; | ||
| 24 | +use crate::demux::VideoMeta; | ||
| 25 | + | ||
| 26 | +/// How long the feeder waits out a full ring. The ring holds a second, so this | ||
| 27 | +/// only has to be short next to that; it costs one wakeup per 10 ms of audio. | ||
| 28 | +const RING_FULL_WAIT: Duration = Duration::from_millis(10); | ||
| 29 | + | ||
| 30 | +/// The output half of a session: the device, plus what the feeder has handed it. | ||
| 31 | +struct Audio { | ||
| 32 | + /// Shared because `write` runs on the feeder thread while `position` and | ||
| 33 | + /// `set_active` are called from the caller's. The plugin serialises those | ||
| 34 | + /// itself (atomics and a channel), but the lock is what makes it sayable in | ||
| 35 | + /// Rust and it is never held for more than a memcpy. | ||
| 36 | + ao: Arc<Mutex<AoSession>>, | ||
| 37 | + sample_rate: u32, | ||
| 38 | + channels: u64, | ||
| 39 | + /// Interleaved samples accepted by the device so far. | ||
| 40 | + fed: Arc<AtomicU64>, | ||
| 41 | + /// The decoder ran out and `fed` is final. | ||
| 42 | + fed_all: Arc<AtomicBool>, | ||
| 43 | +} | ||
| 44 | + | ||
| 45 | +impl Audio { | ||
| 46 | + /// Whether the device has played everything there will ever be, i.e. the | ||
| 47 | + /// audio clock is about to stop meaning anything. | ||
| 48 | + fn played_out(&self, position: i64) -> bool { | ||
| 49 | + self.fed_all.load(Ordering::Acquire) | ||
| 50 | + && position as u64 * self.channels >= self.fed.load(Ordering::Relaxed) | ||
| 51 | + } | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/// A file opened for playback. Starts paused at t=0; call [`PlaybackSession::play`]. | ||
| 55 | +pub struct PlaybackSession { | ||
| 56 | + meta: VideoMeta, | ||
| 57 | + frames: Receiver<Frame>, | ||
| 58 | + clock: PlaybackClock, | ||
| 59 | + audio: Option<Audio>, | ||
| 60 | +} | ||
| 61 | + | ||
| 62 | +impl PlaybackSession { | ||
| 63 | + /// Opens `path` and starts both decode workers. Only video failure is fatal: | ||
| 64 | + /// a file we cannot hear is still a file we can watch. | ||
| 65 | + pub fn open(path: impl AsRef<Path>) -> crate::Result<Self> { | ||
| 66 | + let path = path.as_ref(); | ||
| 67 | + let (meta, frames) = DecodeSession::open(path)?; | ||
| 68 | + let audio = open_audio(path); | ||
| 69 | + let source = match audio { | ||
| 70 | + Some(_) => ClockSource::Audio, | ||
| 71 | + None => ClockSource::Wall, | ||
| 72 | + }; | ||
| 73 | + Ok(Self { | ||
| 74 | + meta, | ||
| 75 | + frames, | ||
| 76 | + clock: PlaybackClock::new(source), | ||
| 77 | + audio, | ||
| 78 | + }) | ||
| 79 | + } | ||
| 80 | + | ||
| 81 | + pub fn meta(&self) -> &VideoMeta { | ||
| 82 | + &self.meta | ||
| 83 | + } | ||
| 84 | + | ||
| 85 | + /// Decoded frames, in decode order. The channel is bounded, so leaving it | ||
| 86 | + /// alone is what pauses the decoder. | ||
| 87 | + pub fn frames(&self) -> &Receiver<Frame> { | ||
| 88 | + &self.frames | ||
| 89 | + } | ||
| 90 | + | ||
| 91 | + /// Current timeline position in seconds. | ||
| 92 | + pub fn now(&self) -> f64 { | ||
| 93 | + self.clock.now() | ||
| 94 | + } | ||
| 95 | + | ||
| 96 | + pub fn is_playing(&self) -> bool { | ||
| 97 | + self.clock.is_playing() | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + pub fn play(&mut self) { | ||
| 101 | + if self.clock.is_playing() { | ||
| 102 | + return; | ||
| 103 | + } | ||
| 104 | + // Invariant: the clock is positioned *before* audio restarts. Audio | ||
| 105 | + // reports are relative to the first one after that, so a seek would go | ||
| 106 | + // here too -- `clock.seek_to(t)` and then `set_active(true)`. | ||
| 107 | + self.clock.play(); | ||
| 108 | + if let Some(audio) = &self.audio { | ||
| 109 | + audio.ao.lock().unwrap().set_active(true); | ||
| 110 | + } | ||
| 111 | + } | ||
| 112 | + | ||
| 113 | + pub fn pause(&mut self) { | ||
| 114 | + if !self.clock.is_playing() { | ||
| 115 | + return; | ||
| 116 | + } | ||
| 117 | + if let Some(audio) = &self.audio { | ||
| 118 | + audio.ao.lock().unwrap().set_active(false); | ||
| 119 | + } | ||
| 120 | + self.clock.pause(); | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + pub fn toggle(&mut self) { | ||
| 124 | + if self.clock.is_playing() { | ||
| 125 | + self.pause() | ||
| 126 | + } else { | ||
| 127 | + self.play() | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + | ||
| 131 | + /// Moves the clock forward; the caller runs this once per rendered frame. | ||
| 132 | + /// Costs an atomic load, and once per session a mode switch. | ||
| 133 | + pub fn tick(&mut self) { | ||
| 134 | + let Some(audio) = &self.audio else { | ||
| 135 | + return; // wall time from the start, nothing to poll | ||
| 136 | + }; | ||
| 137 | + if self.clock.source() != ClockSource::Audio { | ||
| 138 | + return; | ||
| 139 | + } | ||
| 140 | + // `None` until the device's first callback: the clock holds at its | ||
| 141 | + // anchor rather than guessing, which is why playback starts on time | ||
| 142 | + // instead of a quantum early. | ||
| 143 | + let Some(position) = audio.ao.lock().unwrap().position() else { | ||
| 144 | + return; | ||
| 145 | + }; | ||
| 146 | + if audio.played_out(position) { | ||
| 147 | + // Audio EOF. Wall time carries the same timeline on from here, with | ||
| 148 | + // no jump, and this branch cannot be reached again. | ||
| 149 | + self.clock.switch_to_wall(); | ||
| 150 | + } else { | ||
| 151 | + self.clock.set_audio_position(position as u64, audio.sample_rate); | ||
| 152 | + } | ||
| 153 | + } | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/// `None` for a silent session -- no audio track, no plugin, no daemon, or a | ||
| 157 | +/// track the decoder refuses. Dropping the receiver on the way out stops the | ||
| 158 | +/// audio decode worker, so a failure here leaves nothing running. | ||
| 159 | +fn open_audio(path: &Path) -> Option<Audio> { | ||
| 160 | + let (meta, rx) = match AudioSession::open(path) { | ||
| 161 | + Ok(Some(opened)) => opened, | ||
| 162 | + Ok(None) => return None, | ||
| 163 | + Err(e) => { | ||
| 164 | + eprintln!("audio disabled: {e}"); | ||
| 165 | + return None; | ||
| 166 | + } | ||
| 167 | + }; | ||
| 168 | + let ao = AoSession::open(meta.sample_rate, u32::from(meta.channels))?; | ||
| 169 | + // The stream comes up streaming; a session starts paused, so silence the | ||
| 170 | + // device until `play`. The feeder still fills the ring in the meantime. | ||
| 171 | + ao.set_active(false); | ||
| 172 | + | ||
| 173 | + let audio = Audio { | ||
| 174 | + ao: Arc::new(Mutex::new(ao)), | ||
| 175 | + sample_rate: meta.sample_rate, | ||
| 176 | + channels: u64::from(meta.channels), | ||
| 177 | + fed: Arc::new(AtomicU64::new(0)), | ||
| 178 | + fed_all: Arc::new(AtomicBool::new(false)), | ||
| 179 | + }; | ||
| 180 | + let (ao, fed, fed_all) = ( | ||
| 181 | + audio.ao.clone(), | ||
| 182 | + audio.fed.clone(), | ||
| 183 | + audio.fed_all.clone(), | ||
| 184 | + ); | ||
| 185 | + thread::Builder::new() | ||
| 186 | + .name("audio-feed".into()) | ||
| 187 | + .spawn(move || { | ||
| 188 | + feed(rx, &ao, &fed); | ||
| 189 | + fed_all.store(true, Ordering::Release); | ||
| 190 | + }) | ||
| 191 | + .ok()?; | ||
| 192 | + Some(audio) | ||
| 193 | +} | ||
| 194 | + | ||
| 195 | +/// Pours decoded chunks into the device, keeping whatever the ring would not | ||
| 196 | +/// take. Ends when the decoder is done or the output dies. | ||
| 197 | +fn feed(rx: Receiver<AudioChunk>, ao: &Mutex<AoSession>, fed: &AtomicU64) { | ||
| 198 | + let mut pending: Vec<f32> = Vec::new(); | ||
| 199 | + loop { | ||
| 200 | + if pending.is_empty() { | ||
| 201 | + match rx.recv() { | ||
| 202 | + Ok(chunk) => pending = chunk.samples, | ||
| 203 | + Err(_) => return, // decoder finished or went away | ||
| 204 | + } | ||
| 205 | + } | ||
| 206 | + let accepted = match ao.lock().unwrap().write(&pending) { | ||
| 207 | + Some(n) => n, | ||
| 208 | + None => return, // output died; the clock switches to wall | ||
| 209 | + }; | ||
| 210 | + fed.fetch_add(accepted as u64, Ordering::Relaxed); | ||
| 211 | + pending.drain(..accepted); | ||
| 212 | + if !pending.is_empty() { | ||
| 213 | + // Ring full: nothing to do but let the device drain it. | ||
| 214 | + thread::sleep(RING_FULL_WAIT); | ||
| 215 | + } | ||
| 216 | + } | ||
| 217 | +} | ||
crates/engine/tests/playback.rsadded+108 -0
| @@ -0,0 +1,108 @@ | |||
| 1 | +//! End-to-end playback timing, without a UI. Both files run through the same | ||
| 2 | +//! checks: `test_baseline.mp4` has no audio and is therefore always wall-paced, | ||
| 3 | +//! `test_av.mp4` uses the audio clock when a PipeWire daemon is around and falls | ||
| 4 | +//! back to the same wall path when it is not -- so neither test is `#[ignore]`d. | ||
| 5 | +//! | ||
| 6 | +//! ```text | ||
| 7 | +//! cargo test -p engine --release --test playback -- --nocapture | ||
| 8 | +//! ``` | ||
| 9 | + | ||
| 10 | +use std::path::PathBuf; | ||
| 11 | +use std::sync::mpsc::TryRecvError; | ||
| 12 | +use std::thread::sleep; | ||
| 13 | +use std::time::{Duration, Instant}; | ||
| 14 | + | ||
| 15 | +use engine::PlaybackSession; | ||
| 16 | + | ||
| 17 | +fn asset(name: &str) -> PathBuf { | ||
| 18 | + PathBuf::from(env!("CARGO_MANIFEST_DIR")) | ||
| 19 | + .join("../../assets") | ||
| 20 | + .join(name) | ||
| 21 | +} | ||
| 22 | + | ||
| 23 | +/// One render tick of a front-end: advance the clock, take whatever frames are | ||
| 24 | +/// due. Returns the highest frame index seen so far. | ||
| 25 | +fn pump(session: &mut PlaybackSession, last_index: &mut Option<u32>) { | ||
| 26 | + session.tick(); | ||
| 27 | + let target = session.now() * session.meta().frame_rate; | ||
| 28 | + loop { | ||
| 29 | + match session.frames().try_recv() { | ||
| 30 | + Ok(frame) => { | ||
| 31 | + if let Some(previous) = *last_index { | ||
| 32 | + assert_eq!( | ||
| 33 | + frame.index, | ||
| 34 | + previous + 1, | ||
| 35 | + "frames must arrive in index order" | ||
| 36 | + ); | ||
| 37 | + } | ||
| 38 | + *last_index = Some(frame.index); | ||
| 39 | + // Stop at the first frame past the clock; the real app holds it | ||
| 40 | + // for the next tick, we simply stop draining. | ||
| 41 | + if f64::from(frame.index) > target { | ||
| 42 | + return; | ||
| 43 | + } | ||
| 44 | + } | ||
| 45 | + Err(TryRecvError::Empty) | Err(TryRecvError::Disconnected) => return, | ||
| 46 | + } | ||
| 47 | + } | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// Pumps for `duration` of wall time at roughly a display refresh. | ||
| 51 | +fn run_for(session: &mut PlaybackSession, last_index: &mut Option<u32>, duration: Duration) { | ||
| 52 | + let deadline = Instant::now() + duration; | ||
| 53 | + while Instant::now() < deadline { | ||
| 54 | + pump(session, last_index); | ||
| 55 | + sleep(Duration::from_millis(8)); | ||
| 56 | + } | ||
| 57 | +} | ||
| 58 | + | ||
| 59 | +fn plays_at_real_speed(name: &str) { | ||
| 60 | + let path = asset(name); | ||
| 61 | + let mut session = PlaybackSession::open(&path).expect("open"); | ||
| 62 | + assert_eq!(session.now(), 0.0, "a fresh session starts at zero"); | ||
| 63 | + assert!(!session.is_playing(), "a fresh session starts paused"); | ||
| 64 | + let mut last_index = None; | ||
| 65 | + | ||
| 66 | + session.play(); | ||
| 67 | + let started = Instant::now(); | ||
| 68 | + run_for(&mut session, &mut last_index, Duration::from_secs(2)); | ||
| 69 | + let (played, wall) = (session.now(), started.elapsed().as_secs_f64()); | ||
| 70 | + eprintln!("{name}: clock {played:.3}s over {wall:.3}s wall"); | ||
| 71 | + assert!( | ||
| 72 | + (played - wall).abs() < wall * 0.15, | ||
| 73 | + "clock ran at the wrong speed: {played:.3}s in {wall:.3}s" | ||
| 74 | + ); | ||
| 75 | + assert!(last_index.is_some(), "no frames arrived"); | ||
| 76 | + | ||
| 77 | + session.pause(); | ||
| 78 | + let frozen = session.now(); | ||
| 79 | + run_for(&mut session, &mut last_index, Duration::from_millis(300)); | ||
| 80 | + assert!( | ||
| 81 | + (session.now() - frozen).abs() < 0.025, | ||
| 82 | + "paused clock moved: {frozen:.3}s -> {:.3}s", | ||
| 83 | + session.now() | ||
| 84 | + ); | ||
| 85 | + | ||
| 86 | + session.play(); | ||
| 87 | + run_for(&mut session, &mut last_index, Duration::from_millis(500)); | ||
| 88 | + let resumed = session.now(); | ||
| 89 | + assert!( | ||
| 90 | + resumed > frozen + 0.3, | ||
| 91 | + "clock did not resume: {frozen:.3}s -> {resumed:.3}s" | ||
| 92 | + ); | ||
| 93 | + // No time was invented across the pause: 2.5 s of playing, not 2.8 s. | ||
| 94 | + assert!( | ||
| 95 | + resumed < wall + 0.7, | ||
| 96 | + "the pause leaked into the timeline: {resumed:.3}s" | ||
| 97 | + ); | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +#[test] | ||
| 101 | +fn video_only_plays_at_real_speed() { | ||
| 102 | + plays_at_real_speed("test_baseline.mp4"); | ||
| 103 | +} | ||
| 104 | + | ||
| 105 | +#[test] | ||
| 106 | +fn audio_video_plays_at_real_speed() { | ||
| 107 | + plays_at_real_speed("test_av.mp4"); | ||
| 108 | +} | ||