diff --git a/src/player.rs b/src/player.rs index c3547be0..1faa55b6 100644 --- a/src/player.rs +++ b/src/player.rs @@ -48,11 +48,16 @@ impl SeekOrder { (Self { pos, feedback: tx }, rx) } - fn attempt(self, maybe_seekable: &mut S) + /// Performs the seek on `seekable`, the + /// [`TrackPosition`](crate::source::TrackPosition) adapter wrapping the source. + /// + /// `self.pos` is a position in the source's own timeline, so it is passed on + /// unchanged. + fn attempt(self, seekable: &mut S) where S: Source, { - let res = maybe_seekable.try_seek(self.pos); + let res = seekable.try_seek(self.pos); let _ignore_receiver_dropped = self.feedback.send(res); } } @@ -119,11 +124,21 @@ impl Player { let start_played = AtomicBool::new(false); let sound_count_clone = self.sound_count.clone(); + // Adapter order, outermost first (`periodic_access` wraps all of it): + // Done -> Stoppable -> Skippable -> Amplify -> Pausable -> Speed -> TrackPosition -> source + // + // `track_position()` comes before `speed()`: `Speed` only changes the reported + // sample rate, and `TrackPosition` divides its sample count by the rate it sees, so + // placed here it reports the position in the media. It stays inside `pausable()` so + // that silence played while paused is not counted. + // + // Seeks are sent to `TrackPosition`, so the target reaches the source as given. + // + // The `.inner()` / `.inner_mut()` chains in the closure below follow this order. let source = Done::new( source - .speed(1.0) - // Must be placed before pausable but after speed & delay .track_position() + .speed(1.0) .pausable(false) .amplify(1.0) .skippable() @@ -147,20 +162,37 @@ impl Player { *to_clear -= 1; *controls.position.lock().unwrap() = Duration::ZERO; } else { - *controls.position.lock().unwrap() = - src.inner().inner().inner().inner().inner().get_pos(); + // The position comes from `TrackPosition`, the innermost adapter. + *controls.position.lock().unwrap() = src + .inner() // Stoppable + .inner() // Skippable + .inner() // Amplify + .inner() // Pausable + .inner() // Speed + .inner() // TrackPosition + .get_pos(); } } - let amp = src.inner_mut().inner_mut().inner_mut(); + let amp = src + .inner_mut() // Stoppable + .inner_mut() // Skippable + .inner_mut(); // Amplify amp.set_factor(*controls.volume.lock().unwrap()); - amp.inner_mut() + amp.inner_mut() // Pausable .set_paused(controls.pause.load(Ordering::SeqCst)); - amp.inner_mut() - .inner_mut() - .inner_mut() - .set_factor(*controls.speed.lock().unwrap()); + + let speed = *controls.speed.lock().unwrap(); + amp.inner_mut() // Pausable + .inner_mut() // Speed + .set_factor(speed); + if let Some(seek) = controls.seek.lock().unwrap().take() { - seek.attempt(amp) + // Seek the `TrackPosition`; the target reaches the source exactly as given. + seek.attempt( + amp.inner_mut() // Pausable + .inner_mut() // Speed + .inner_mut(), // TrackPosition + ) } start_played.store(true, Ordering::SeqCst); }); @@ -203,11 +235,12 @@ impl Player { /// lowering its pitch. /// - If you set the speed to 2 the frequency will double raising the /// pitch of the sound. - /// 2. **Change in the speed affect the total duration inversely** - /// - If you set the speed to 0.5, the total duration will be twice as long. - /// - If you set the speed to 2 the total duration will be halve of what it - /// was. - /// + /// 2. **A change in the speed affects the playback duration inversely** + /// - If you set the speed to 0.5, playing the sound takes twice as long. + /// - If you set the speed to 2, playing the sound takes half as long. + /// 3. **Positions do not depend on the speed** + /// - [`Player::get_pos`] and [`Player::try_seek`] use positions in the sound + /// itself, so they are not scaled by the speed. #[inline] pub fn set_speed(&self, value: f32) { *self.controls.speed.lock().unwrap() = value; @@ -227,6 +260,13 @@ impl Player { /// Attempts to seek to a given position in the current source. /// + /// `pos` is a position in the source's own timeline and does not depend on the + /// current playback speed: seeking to 30 seconds lands 30 seconds into the media + /// whether the speed is 0.5, 1.0 or 2.0. This is the same timeline as + /// [`Player::get_pos`]. + /// + /// The position is passed to the source exactly as given, at any speed. + /// /// This blocks between 0 and ~5 milliseconds. /// /// As long as the duration of the source is known, seek is guaranteed to saturate @@ -338,13 +378,14 @@ impl Player { self.sound_count.load(Ordering::Relaxed) } - /// Returns the position of the sound that's being played. + /// Returns the playback position within the current source. /// - /// This takes into account any speedup or delay applied. + /// The position is measured in the source's own timeline, so it does not depend + /// on the playback speed. For example, at a speed of `0.5` it advances by half a + /// second for every second of real time, and changing the speed during playback + /// does not make it jump. /// - /// Example: if you apply a speedup of *2* to an mp3 decoder source and - /// [`get_pos()`](Player::get_pos) returns *5s* then the position in the mp3 - /// recording is *10s* from its start. + /// After [`Player::try_seek`] this is the position that was sought to. #[inline] pub fn get_pos(&self) -> Duration { *self.controls.position.lock().unwrap() @@ -365,11 +406,102 @@ impl Drop for Player { #[cfg(test)] mod tests { use std::sync::atomic::Ordering; + use std::sync::{Arc, Mutex}; + use std::time::Duration; use crate::buffer::SamplesBuffer; + use crate::common::{ChannelCount, SampleRate}; use crate::math::nz; + use crate::source::SeekError; use crate::{Player, Source}; + type Sample = ::Item; + + /// A seek target and the sample the source yields next. + type SeekRecord = (Duration, Option); + + /// Wraps a `SamplesBuffer` and records every seek target it receives, together + /// with the sample the buffer yields next. + struct SeekRecorder { + inner: SamplesBuffer, + seeks: Arc>>, + } + + impl Iterator for SeekRecorder { + type Item = Sample; + + fn next(&mut self) -> Option { + self.inner.next() + } + } + + impl Source for SeekRecorder { + fn current_span_len(&self) -> Option { + self.inner.current_span_len() + } + + fn channels(&self) -> ChannelCount { + self.inner.channels() + } + + fn sample_rate(&self) -> SampleRate { + self.inner.sample_rate() + } + + fn total_duration(&self) -> Option { + self.inner.total_duration() + } + + fn try_seek(&mut self, pos: Duration) -> Result<(), SeekError> { + self.inner.try_seek(pos)?; + let next = self.inner.clone().next(); + self.seeks.lock().unwrap().push((pos, next)); + Ok(()) + } + } + + /// Plays a 48 kHz mono buffer whose samples are their own frame index, seeks to + /// 2 ms at the given speed and returns the seeks the source saw. + fn seek_to_2ms_at_speed(speed: f32) -> Vec { + let samples: Vec = (0..48_000).map(|i| i as Sample).collect(); + let seeks = Arc::new(Mutex::new(Vec::new())); + + let (player, mut out) = Player::new(); + player.set_speed(speed); + // Paused, so the source isn't consumed while waiting for the seek to run. + player.pause(); + player.append(SeekRecorder { + inner: SamplesBuffer::new(nz!(1), nz!(48_000), samples), + seeks: seeks.clone(), + }); + + // `try_seek` blocks until the audio thread (here: this thread, pulling `out`) + // has performed the seek. + std::thread::scope(|s| { + let seeker = s.spawn(|| player.try_seek(Duration::from_millis(2))); + while !seeker.is_finished() { + out.next(); + } + seeker.join().unwrap().unwrap(); + }); + + let seeks = seeks.lock().unwrap().clone(); + seeks + } + + #[test] + fn test_seek_target_does_not_depend_on_speed() { + // 2 ms at 48 kHz is exactly frame 96, so the source must receive exactly 2 ms + // and continue from frame 96 at every speed. + for speed in [1.0, 1.5, 2.0, 0.75] { + assert_eq!( + seek_to_2ms_at_speed(speed), + [(Duration::from_millis(2), Some(96 as Sample))], + "speed {speed}" + ); + } + } + #[test] fn test_immediate_length_changes() { let (player, mut source) = Player::new(); diff --git a/src/source/mod.rs b/src/source/mod.rs index e6b9f604..f2a48d98 100644 --- a/src/source/mod.rs +++ b/src/source/mod.rs @@ -505,10 +505,18 @@ pub trait Source: Iterator { /// lowering its pitch. /// - If you set the speed to 2 the frequency will double raising the /// pitch of the sound. - /// 2. **Change in the speed affect the total duration inversely** - /// - If you set the speed to 0.5, the total duration will be twice as long. - /// - If you set the speed to 2 the total duration will be halve of what it - /// was. + /// 2. **A change in the speed affects the playback duration inversely** + /// - If you set the speed to 0.5, playing the source takes twice as long. + /// - If you set the speed to 2, playing the source takes half as long. + /// - [`total_duration`](Source::total_duration) of the returned source reports + /// this playback duration. + /// 3. **Seek targets are scaled by the speed** + /// - [`try_seek`](Source::try_seek) multiplies its target by the speed: at a + /// speed of 2, seeking to 10 seconds seeks to 20 seconds in the original source. + /// - Whether [`track_position`](Source::track_position) reports the position in + /// the original source or the elapsed playback time depends on whether it is + /// applied before or after `speed`, see + /// [`TrackPosition::get_pos`](TrackPosition::get_pos). /// /// See [`Speed`] for details #[inline] @@ -598,15 +606,32 @@ pub trait Source: Iterator { } /// Start tracking the elapsed duration since the start of the underlying - /// source. + /// source. Read it with [`get_pos`](TrackPosition::get_pos). + /// + /// What `get_pos` returns depends on whether you call this before or after + /// [`speed`](Source::speed). With a speed of 2.0: + /// + /// - `source.track_position().speed(2.0)`: `get_pos` is the position in the + /// original source. After 10 seconds of the source have been played it + /// returns 10 seconds. + /// - `source.speed(2.0).track_position()`: `get_pos` is the time spent playing. + /// Those same 10 seconds of the source take 5 seconds to play, so it + /// returns 5 seconds. + /// + /// # Seeking + /// + /// [`try_seek`](Source::try_seek) always uses the timeline of the source you + /// call it on. A source with [`speed`](Source::speed) applied has a shorter + /// timeline: at 2.0 a 20 second source lasts 10 seconds, so seeking it to + /// 10 seconds lands at its end, 20 seconds into the original source. The + /// target is an absolute position, not an offset from the current one. /// - /// If a speedup and or delay is applied after this that will not be reflected - /// in the position returned by [`get_pos`](TrackPosition::get_pos). + /// That means `source.track_position().speed(2.0).try_seek(10s)` sends + /// 20 seconds to the `TrackPosition`, and `get_pos` then returns 20 seconds, + /// not 10. /// - /// This can get confusing when using [`get_pos()`](TrackPosition::get_pos) - /// together with [`Source::try_seek()`] as the latter does take all - /// speedup's and delay's into account. It's recommended therefore to apply - /// track_position after speedup's and delay's. + /// To seek to a position in the original source, call `try_seek` on the + /// `TrackPosition` itself. See [`TrackPosition::get_pos`] for details. fn track_position(self) -> TrackPosition where Self: Sized, diff --git a/src/source/position.rs b/src/source/position.rs index f41848eb..431f3994 100644 --- a/src/source/position.rs +++ b/src/source/position.rs @@ -54,14 +54,36 @@ where { /// Returns the position of the underlying source relative to its start. /// - /// If a speedup and or delay is applied after applying a - /// [`Source::track_position`] it will not be reflected in the position - /// returned by [`get_pos`](TrackPosition::get_pos). + /// The position is the number of samples read from the inner source, divided + /// by the sample rate and channel count that the inner source reports. /// - /// This can get confusing when using [`get_pos()`](TrackPosition::get_pos) - /// together with [`Source::try_seek()`] as the the latter does take all - /// speedup's and delay's into account. Its recommended therefore to apply - /// track_position after speedup's and delay's. + /// [`Source::speed`] (see [`Speed`](super::Speed)) works by changing the reported + /// sample rate, so the result depends on where `track_position()` is placed + /// relative to it: + /// + /// - **Before `speed()`**, as in `source.track_position().speed(x)`: the sample + /// rate is the real one, so this is the position in the original source. It + /// does not depend on the speed, also not when the speed changes during + /// playback. + /// - **After `speed()`**, as in `source.speed(x).track_position()`: the sample + /// rate is the scaled one, so this is the elapsed playback time. At a speed + /// of `2.0` it advances by half a second for every second of source audio + /// read. This is only the position in the original source if the speed never + /// changes, and then only after multiplying it by the speed. + /// + /// # Seeking + /// + /// [`Source::try_seek`] forwards the target to the inner source and then reports + /// the target as the new position. + /// + /// [`Speed`](super::Speed) multiplies the target of its + /// [`try_seek`](Source::try_seek) by its speed factor. With `track_position()` + /// before `speed()`, a seek through the outer source therefore reports the + /// multiplied target: + /// `source.track_position().speed(2.0).try_seek(10s)` seeks to `20s` in the + /// original source and `get_pos()` then returns `20s`. To seek to an exact + /// position in the original source, seek the `TrackPosition` itself (through the + /// speed adapter's `inner_mut()`); it passes the target on unchanged. #[inline] pub fn get_pos(&self) -> Duration { let seconds = self.span.samples_counted as Float @@ -180,4 +202,17 @@ mod tests { assert!(source.try_seek(Duration::new(1, 0)).is_ok()); assert_eq!(source.get_pos().as_secs_f32(), 1.0); } + + #[test] + fn test_position_before_speedup_is_independent_of_speed() { + let inner = SamplesBuffer::new(nz!(1), nz!(1), vec![10.0, -10.0, 10.0, -10.0, 20.0, -20.0]); + let mut source = inner.track_position().speed(2.0); + + assert_eq!(source.inner().get_pos().as_secs_f32(), 0.0); + source.next(); + assert_eq!(source.inner().get_pos().as_secs_f32(), 1.0); + + source.next(); + assert_eq!(source.inner().get_pos().as_secs_f32(), 2.0); + } } diff --git a/src/spatial_player.rs b/src/spatial_player.rs index d1fe3cb2..5c751156 100644 --- a/src/spatial_player.rs +++ b/src/spatial_player.rs @@ -95,20 +95,10 @@ impl SpatialPlayer { self.player.set_volume(value); } - /// Changes the play speed of the sound. Does not adjust the samples, only the playback speed. + /// Gets the speed of the sound. /// - /// # Note: - /// 1. **Increasing the speed will increase the pitch by the same factor** - /// - If you set the speed to 0.5 this will halve the frequency of the sound - /// lowering its pitch. - /// - If you set the speed to 2 the frequency will double raising the - /// pitch of the sound. - /// 2. **Change in the speed affect the total duration inversely** - /// - If you set the speed to 0.5, the total duration will be twice as long. - /// - If you set the speed to 2 the total duration will be halve of what it - /// was. - /// - /// See [`Speed`](crate::source::Speed) for details + /// See [`SpatialPlayer::set_speed`] for what the speed means, and + /// [`Speed`](crate::source::Speed) for details. #[inline] pub fn speed(&self) -> f32 { self.player.speed() @@ -197,10 +187,10 @@ impl SpatialPlayer { /// /// # Errors /// This function will return [`SeekError::NotSupported`] if one of the underlying - /// sources does not support seeking. + /// sources does not support seeking. /// /// It will return an error if an implementation ran - /// into one during the seek. + /// into one during the seek. /// /// When seeking beyond the end of a source this /// function might return an error if the duration of the source is not known. @@ -208,13 +198,9 @@ impl SpatialPlayer { self.player.try_seek(pos) } - /// Returns the position of the sound that's being played. - /// - /// This takes into account any speedup or delay applied. + /// Returns the playback position within the current source. /// - /// Example: if you apply a speedup of *2* to an mp3 decoder source and - /// [`get_pos()`](Player::get_pos) returns *5s* then the position in the mp3 - /// recording is *10s* from its start. + /// See [`Player::get_pos`] for details. #[inline] pub fn get_pos(&self) -> Duration { self.player.get_pos()