diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs index 64edb658fe8..9ea8084e919 100644 --- a/apps/desktop-gpui/src/editor_window.rs +++ b/apps/desktop-gpui/src/editor_window.rs @@ -996,6 +996,7 @@ pub struct Desired { pub seek: Option, pub seek_gen: u64, pub resolution: XY, + pub rate: f64, } impl Default for Desired { @@ -1005,10 +1006,17 @@ impl Default for Desired { seek: None, seek_gen: 0, resolution: default_preview_resolution(), + rate: 1.0, } } } +// A running session plays at the rate it started with, so a new rate needs a +// fresh session even when the UI's pause and play collapsed into one write. +fn rate_needs_restart(applied_playing: bool, applied_rate: f64, want: &Desired) -> bool { + applied_playing && want.playing && want.rate.to_bits() != applied_rate.to_bits() +} + /// The UI half. Cheap to clone, safe to call from the main thread: writing it /// takes an uncontended `Mutex` and a `try_send` on a one-slot channel. #[derive(Clone)] @@ -1070,6 +1078,10 @@ impl TransportHandle { self.modify(|desired| desired.resolution = resolution); } + pub fn set_rate(&self, rate: f64) { + self.modify(|desired| desired.rate = rate); + } + pub fn play_from(&self, frame: u32) { self.modify(|desired| { desired.playing = true; @@ -1102,6 +1114,7 @@ pub async fn run_transport(instance: Arc, driver: TransportDrive let fps = EDITOR_PREVIEW_FPS; let mut applied_playing = false; let mut applied_gen = 0u64; + let mut applied_rate = 1.0f64; // The engine's own liveness, epoch-guarded inside `EditorInstance` so a // deliberate stop/start transition can never masquerade as a death. let mut active_rx = instance.playback_watch(); @@ -1148,7 +1161,9 @@ pub async fn run_transport(instance: Arc, driver: TransportDrive // instead of paying stop/warmup/audio-attach per tick -- the round // trip the source pays in `seekPlayheadTo` // (`Timeline/index.tsx:829-853`). - if applied_playing && !want.playing { + if (applied_playing && !want.playing) + || rate_needs_restart(applied_playing, applied_rate, &want) + { applied_playing = false; let handle = { let mut state = instance.state.lock().await; @@ -1197,6 +1212,8 @@ pub async fn run_transport(instance: Arc, driver: TransportDrive } if want.playing && !applied_playing { + instance.set_playback_rate(want.rate); + applied_rate = want.rate; match instance .start_playback_with_handle(fps, want.resolution, None) .await @@ -1370,6 +1387,7 @@ pub struct EditorWindow { /// Kept alive for the window's lifetime: dropping the last `Arc` is what /// tears the decoders down, and `dispose()` on close does it explicitly. pub(crate) instance: Option>, + playback_rate: f64, focus: FocusHandle, // -- Transport ---------------------------------------------------------- @@ -2081,6 +2099,7 @@ impl EditorWindow { timeline_view, frame_layout: None, instance: None, + playback_rate: 1.0, focus: cx.focus_handle(), playing: false, playhead: 0.0, @@ -3253,6 +3272,7 @@ impl EditorWindow { /// `handlePlayPauseClick` (`Player.tsx:212-233`), verbatim: at the end, /// restart from 0; playing, stop; otherwise seek to the playhead and go. pub fn toggle_play(&mut self, _window: &mut Window, cx: &mut Context) { + self.set_playback_rate(1.0); if self.preparing_transport_active() { if self.preparing_controls_ready() { let seek = self.is_at_end().then_some(0.0); @@ -3283,6 +3303,63 @@ impl EditorWindow { } } + fn set_playback_rate(&mut self, rate: f64) { + self.playback_rate = rate; + if let Some(transport) = &self.transport { + transport.set_rate(rate); + } + } + + fn shuttle(&mut self, rate: f64, window: &mut Window, cx: &mut Context) { + if self.is_at_end() || self.preparing_transport_active() { + return; + } + self.set_playback_rate(rate); + let from = self.playhead; + if self.playing { + self.stop_playback(cx); + } + self.start_playback(from, cx); + window.refresh(); + } + + fn shuttle_faster(&mut self, window: &mut Window, cx: &mut Context) { + let current = if self.playing { + self.playback_rate + } else { + 0.0 + }; + let next = SHUTTLE_RATES + .iter() + .copied() + .find(|rate| *rate > current && *rate >= 1.0) + .unwrap_or(SHUTTLE_RATES[SHUTTLE_RATES.len() - 1]); + self.shuttle(next, window, cx); + } + + fn shuttle_slower(&mut self, window: &mut Window, cx: &mut Context) { + let current = if self.playing { + self.playback_rate + } else { + 1.0 + }; + let next = SHUTTLE_RATES + .iter() + .rev() + .copied() + .find(|rate| *rate < current) + .unwrap_or(SHUTTLE_RATES[0]); + self.shuttle(next, window, cx); + } + + fn shuttle_stop(&mut self, window: &mut Window, cx: &mut Context) { + if self.playing { + self.stop_playback(cx); + } + self.set_playback_rate(1.0); + window.refresh(); + } + /// `seekPlayheadTo` (`Timeline/index.tsx:829-853`), minus the source's /// stop/seek/restart round trip: the driver live-seeks the running engine /// (`PlaybackHandle::seek`), so a scrub during playback holds the last @@ -3770,6 +3847,18 @@ impl EditorWindow { cx.stop_propagation(); self.split_at_playhead(window, cx); } + "j" => { + cx.stop_propagation(); + self.shuttle_slower(window, cx); + } + "k" => { + cx.stop_propagation(); + self.shuttle_stop(window, cx); + } + "l" => { + cx.stop_propagation(); + self.shuttle_faster(window, cx); + } "escape" => { cx.stop_propagation(); if self.lane_reorder.is_some() { @@ -10659,6 +10748,19 @@ impl EditorWindow { .flex_none() .text_size(px(13.)) .when(narrow, |clock| clock.text_size(px(12.))) + .children( + (self.playing && (self.playback_rate - 1.0).abs() > 1e-3).then(|| { + div() + .mr(px(6.)) + .px(px(5.)) + .rounded(px(4.)) + .bg(Hsla::from(editor.accent)) + .text_color(Hsla::from(editor.card)) + .text_size(px(11.)) + .font_weight(FontWeight::SEMIBOLD) + .child(SharedString::from(shuttle_rate_label(self.playback_rate))) + }), + ) .child( div() .font_weight(FontWeight::MEDIUM) @@ -10881,6 +10983,7 @@ impl EditorWindow { self.playing, self.playhead_epoch_live, self.last_playhead_redraw.elapsed().as_secs_f64(), + self.playback_rate, ); if ahead > 0.0 { view.playhead = (view.playhead + ahead).min(self.total_duration()); @@ -11794,11 +11897,26 @@ const MAX_PLAYHEAD_EXTRAPOLATION: f64 = 0.25; /// back: the "playhead jumps on play, then goes back" glitch. So: no epoch /// sample yet, no extrapolation -- the line holds still, which is exactly /// what the engine is doing. -fn playhead_extrapolation(playing: bool, epoch_has_sample: bool, since_last_sample: f64) -> f64 { +fn playhead_extrapolation( + playing: bool, + epoch_has_sample: bool, + since_last_sample: f64, + rate: f64, +) -> f64 { if !playing || !epoch_has_sample { return 0.0; } - since_last_sample.clamp(0.0, MAX_PLAYHEAD_EXTRAPOLATION) + let rate = if rate.is_finite() && rate > 0.0 { + rate + } else { + 1.0 + }; + since_last_sample.clamp(0.0, MAX_PLAYHEAD_EXTRAPOLATION) * rate +} + +fn shuttle_rate_label(rate: f64) -> String { + let text = format!("{rate:.2}"); + format!("{}x", text.trim_end_matches('0').trim_end_matches('.')) } fn dismiss_indexed_sidebar_menu(menu: &mut Option) { @@ -11829,6 +11947,8 @@ fn dismiss_indexed_sidebar_menu(menu: &mut Option) } } +const SHUTTLE_RATES: [f64; 6] = [0.5, 1.0, 1.5, 2.0, 3.0, 4.0]; + fn is_playback_shortcut( keystroke: &gpui::Keystroke, text_input_focused: bool, @@ -14489,24 +14609,53 @@ mod tests { #[test] fn playhead_never_extrapolates_before_the_epochs_first_sample() { // Freshly pressed play, stale anchor: hold the line still. - assert_eq!(playhead_extrapolation(true, false, 0.206), 0.0); - assert_eq!(playhead_extrapolation(true, false, 1.081), 0.0); + assert_eq!(playhead_extrapolation(true, false, 0.206, 1.0), 0.0); + assert_eq!(playhead_extrapolation(true, false, 1.081, 1.0), 0.0); // Paused, no matter what the anchor says. - assert_eq!(playhead_extrapolation(false, true, 0.5), 0.0); - assert_eq!(playhead_extrapolation(false, false, 0.5), 0.0); + assert_eq!(playhead_extrapolation(false, true, 0.5, 1.0), 0.0); + assert_eq!(playhead_extrapolation(false, false, 0.5, 1.0), 0.0); + } + + #[test] + fn a_shuttle_speed_change_restarts_even_when_pause_and_play_collapse() { + let (handle, driver, _stopped) = transport(); + handle.play_from(60); + handle.set_rate(2.0); + handle.pause(); + handle.play_from(90); + let want = *driver.desired.lock().unwrap(); + assert!(want.playing); + assert_eq!(want.rate, 2.0); + assert!(rate_needs_restart(true, 1.0, &want)); + assert!(!rate_needs_restart(true, 2.0, &want)); + assert!(!rate_needs_restart(false, 1.0, &want)); + } + + #[test] + fn the_speed_badge_reads_like_the_shuttle_rates() { + assert_eq!(shuttle_rate_label(2.0), "2x"); + assert_eq!(shuttle_rate_label(0.5), "0.5x"); + assert_eq!(shuttle_rate_label(0.25), "0.25x"); + assert_eq!(shuttle_rate_label(4.0), "4x"); } /// Once the epoch is live the line glides by the wall clock between /// samples, capped so a render stall cannot run it far ahead. #[test] fn playhead_extrapolation_tracks_the_wall_clock_and_caps() { - assert_eq!(playhead_extrapolation(true, true, 0.016), 0.016); + assert_eq!(playhead_extrapolation(true, true, 0.016, 1.0), 0.016); assert_eq!( - playhead_extrapolation(true, true, 3.0), + playhead_extrapolation(true, true, 3.0, 1.0), MAX_PLAYHEAD_EXTRAPOLATION ); + assert_eq!(playhead_extrapolation(true, true, 0.016, 2.0), 0.032); + assert_eq!(playhead_extrapolation(true, true, 0.016, 0.5), 0.008); + assert_eq!( + playhead_extrapolation(true, true, 3.0, 4.0), + MAX_PLAYHEAD_EXTRAPOLATION * 4.0 + ); // A clock hiccup must not pull the playhead backwards. - assert_eq!(playhead_extrapolation(true, true, -0.01), 0.0); + assert_eq!(playhead_extrapolation(true, true, -0.01, 1.0), 0.0); } /// A paused seek stores exactly the time its engine echo carries, so the diff --git a/crates/editor/examples/audio-output-idle-benchmark.rs b/crates/editor/examples/audio-output-idle-benchmark.rs index 8240194ddca..948d8f41b80 100644 --- a/crates/editor/examples/audio-output-idle-benchmark.rs +++ b/crates/editor/examples/audio-output-idle-benchmark.rs @@ -68,6 +68,7 @@ fn spec(tone: &Arc) -> PlaySpec { duration_secs: CLIP_SECS, start_playhead_secs: 0.0, playhead_rx, + playback_rate: 1.0, } } diff --git a/crates/editor/examples/editor-playback-benchmark.rs b/crates/editor/examples/editor-playback-benchmark.rs index 0af9f92b602..db1476c9185 100644 --- a/crates/editor/examples/editor-playback-benchmark.rs +++ b/crates/editor/examples/editor-playback-benchmark.rs @@ -643,6 +643,7 @@ async fn main() { music: cap_editor::MusicTracks::new(), audio_output: audio_output.clone(), telemetry: Some(telemetry.clone()), + playback_rate: 1.0, }; let press_instant = Instant::now(); diff --git a/crates/editor/src/audio_output.rs b/crates/editor/src/audio_output.rs index 3de0d2f2be0..82f520fe0a8 100644 --- a/crates/editor/src/audio_output.rs +++ b/crates/editor/src/audio_output.rs @@ -62,6 +62,9 @@ pub struct PlaySpec { pub duration_secs: f64, pub start_playhead_secs: f64, pub playhead_rx: watch::Receiver, + /// Source seconds consumed per output second (J/K/L shuttle). Non-1x + /// rates are time-stretched on f32 devices, keeping the original pitch. + pub playback_rate: f64, } enum ControlMsg { @@ -544,6 +547,11 @@ struct ActiveSource { refresh_revision: u64, buffer: ActiveSourceBuffer, playhead_rx: watch::Receiver, + playback_rate: f64, + channels: usize, + sample_rate: u32, + rate_scratch: Vec, + stretch: Option, ack: Option, preparing_request: Option>, #[cfg(not(target_os = "windows"))] @@ -910,10 +918,43 @@ fn render_source_block>( return; } match &mut source.buffer { - ActiveSourceBuffer::Ordinary(audio) => { + ActiveSourceBuffer::Ordinary(audio) if (source.playback_rate - 1.0).abs() < 1e-3 => { sync_video_playhead(audio, &mut source.playhead_rx, latency_secs); audio.fill(buffer); } + ActiveSourceBuffer::Ordinary(audio) => { + let rate = source.playback_rate; + // Audio the stretcher already pulled from the buffer but has not + // played yet sits between the buffer's read position and the ear. + let pending_secs = source.stretch.as_ref().map_or(0.0, |stretch| { + stretch.pending_source_secs(source.sample_rate) + }); + let source_latency_secs = latency_secs * rate; + if source.playhead_rx.has_changed().unwrap_or(false) { + let video_playhead = *source.playhead_rx.borrow_and_update(); + let audible_playhead = + audio.current_audible_playhead(source_latency_secs + pending_secs); + let drift = (video_playhead - audible_playhead).abs(); + + if drift > 0.04 * rate.max(1.0) { + audio.set_playhead(video_playhead + source_latency_secs); + if let Some(stretch) = &mut source.stretch { + stretch.reset(); + } + } + } + if let Some(stretch) = &mut source.stretch { + fill_stretched(audio, buffer, stretch, &mut source.rate_scratch); + } else { + fill_at_rate( + audio, + buffer, + rate, + source.channels, + &mut source.rate_scratch, + ); + } + } ActiveSourceBuffer::Preparing(audio) => { if audio.fill(buffer, latency_secs) == 0 { if audio.is_terminal() @@ -940,6 +981,66 @@ fn render_source_block>( } } +/// Frames `rate_scratch` is reserved for: a 4096-frame device block read at +/// the fastest shuttle rate (4x), which also covers the stretcher's refills. +const RATE_SCRATCH_FRAMES: usize = 4096 * 4 + 1024; + +/// Pitch-preserving shuttle audio via WSOLA. Only built for f32 streams (what +/// macOS output devices use); other formats fall back to `fill_at_rate`. +fn fill_stretched>( + audio: &mut crate::audio::PrerenderedAudioBuffer, + buffer: &mut [T], + stretch: &mut crate::time_stretch::TimeStretch, + scratch: &mut Vec, +) { + while stretch.ready_samples() < buffer.len() { + let shortfall = stretch.input_shortfall(); + if shortfall > 0 { + scratch.resize((shortfall + 1024) * stretch.channels(), T::EQUILIBRIUM); + audio.fill(scratch); + let Some(samples) = (scratch as &mut dyn std::any::Any).downcast_mut::>() + else { + buffer.fill(T::EQUILIBRIUM); + return; + }; + stretch.push_input(samples); + } + stretch.hop(); + } + for slot in buffer.iter_mut() { + *slot = ::from_sample(stretch.pop_ready().unwrap_or(0.0)); + } +} + +/// Reads `rate` times as many source frames as the block holds and keeps +/// the nearest one per output frame. Crude (no filtering or pitch +/// correction) but cheap enough for the audio callback, and it only runs +/// while shuttling. +fn fill_at_rate>( + audio: &mut crate::audio::PrerenderedAudioBuffer, + buffer: &mut [T], + rate: f64, + channels: usize, + scratch: &mut Vec, +) { + let channels = channels.max(1); + let out_frames = buffer.len() / channels; + if out_frames == 0 { + buffer.fill(T::EQUILIBRIUM); + return; + } + let in_frames = ((out_frames as f64) * rate).round().max(1.0) as usize; + scratch.resize(in_frames * channels, T::EQUILIBRIUM); + audio.fill(scratch); + for frame in 0..out_frames { + let source_frame = ((frame as f64 * rate) as usize).min(in_frames - 1); + let out = frame * channels; + let src = source_frame * channels; + buffer[out..out + channels].copy_from_slice(&scratch[src..src + channels]); + } + buffer[out_frames * channels..].fill(T::EQUILIBRIUM); +} + /// Builds the per-playback source from a play spec and hands it to the /// output via `install_tx`. `use_device_latency_hint` is false for the /// headless sink, which models a zero-latency device. @@ -966,7 +1067,9 @@ fn install_source>( duration_secs, start_playhead_secs, playhead_rx, + playback_rate, } = *spec; + let output_channels = output_info.channels; if !(duration_secs.is_finite() && duration_secs > 0.0) { return Err(format!( @@ -1053,6 +1156,21 @@ fn install_source>( refresh_revision, buffer: ActiveSourceBuffer::Ordinary(buffer), playhead_rx, + playback_rate: if playback_rate.is_finite() && playback_rate > 0.0 { + playback_rate + } else { + 1.0 + }, + channels: output_channels, + sample_rate: output_info.sample_rate, + // Sized for the largest refill either rate path asks for, so the + // callback's `resize` never allocates. + rate_scratch: Vec::with_capacity(RATE_SCRATCH_FRAMES * output_channels), + stretch: (std::any::TypeId::of::() == std::any::TypeId::of::() + && playback_rate.is_finite() + && playback_rate > 0.0 + && (playback_rate - 1.0).abs() >= 1e-3) + .then(|| crate::time_stretch::TimeStretch::new(output_channels, playback_rate)), ack: Some(ack), preparing_request, #[cfg(not(target_os = "windows"))] @@ -1117,6 +1235,11 @@ fn install_progressive_source>( refresh_revision: 0, buffer: ActiveSourceBuffer::Preparing(buffer), playhead_rx, + playback_rate: 1.0, + channels: 1, + sample_rate: 48_000, + rate_scratch: Vec::new(), + stretch: None, ack: Some(SourceAcknowledgement::Preparing(request.clone())), preparing_request: Some(request.clone()), #[cfg(not(target_os = "windows"))] @@ -1648,6 +1771,7 @@ mod tests { duration_secs: 2.0, start_playhead_secs: 0.0, playhead_rx, + playback_rate: 1.0, }), 0, SourceAcknowledgement::Ordinary(ack_tx), diff --git a/crates/editor/src/audio_output/native_tests.rs b/crates/editor/src/audio_output/native_tests.rs index 3f7c2b7fda9..88793aaca39 100644 --- a/crates/editor/src/audio_output/native_tests.rs +++ b/crates/editor/src/audio_output/native_tests.rs @@ -117,6 +117,7 @@ fn audible_spec_with_duration(duration_secs: usize) -> PlaySpec { duration_secs: duration_secs as f64, start_playhead_secs: 0.0, playhead_rx, + playback_rate: 1.0, } } diff --git a/crates/editor/src/editor_instance.rs b/crates/editor/src/editor_instance.rs index c3c44bec553..a4f8e4a16da 100644 --- a/crates/editor/src/editor_instance.rs +++ b/crates/editor/src/editor_instance.rs @@ -236,6 +236,7 @@ pub struct EditorInstance { // true, and without the epoch check that late Stop would flip the watch // to false while the new playback is running. playback_epoch: AtomicU64, + playback_rate_bits: AtomicU64, pub state: Arc>, on_state_change: Box, pub preview_tx: watch::Sender>, @@ -658,6 +659,7 @@ impl EditorInstance { export_active: AtomicBool::new(false), preview_layers: std::sync::Mutex::new(None), playback_epoch: AtomicU64::new(0), + playback_rate_bits: AtomicU64::new(1.0f64.to_bits()), runtime_handle: tokio::runtime::Handle::current(), audio_output, }); @@ -770,6 +772,7 @@ impl EditorInstance { playback_active, playback_active_rx, playback_epoch: AtomicU64::new(0), + playback_rate_bits: AtomicU64::new(1.0f64.to_bits()), state: Arc::new(Mutex::new(EditorState { playhead_position: 0, playback_task: None, @@ -880,6 +883,22 @@ impl EditorInstance { .unwrap_or_default() } + /// Speed for playback sessions started from now on; the caller restarts + /// a running session to apply it. + pub fn set_playback_rate(&self, rate: f64) { + let rate = if rate.is_finite() && rate > 0.0 { + rate.clamp(playback::MIN_PLAYBACK_RATE, playback::MAX_PLAYBACK_RATE) + } else { + 1.0 + }; + self.playback_rate_bits + .store(rate.to_bits(), Ordering::SeqCst); + } + + pub fn playback_rate(&self) -> f64 { + f64::from_bits(self.playback_rate_bits.load(Ordering::SeqCst)) + } + pub async fn start_playback(self: &Arc, fps: u32, resolution_base: XY) { if let Err(error) = self .start_playback_with_handle(fps, resolution_base, None) @@ -944,6 +963,7 @@ impl EditorInstance { project: self.project_config.0.subscribe(), audio_output: self.audio_output.clone(), telemetry: None, + playback_rate: self.playback_rate(), }; let playback_handle = if let Some(adoption) = adoption { playback diff --git a/crates/editor/src/lib.rs b/crates/editor/src/lib.rs index afe97ba7b1f..0718026b709 100644 --- a/crates/editor/src/lib.rs +++ b/crates/editor/src/lib.rs @@ -13,6 +13,7 @@ mod preparing_preview; mod segments; mod telemetry; mod thumbnail; +mod time_stretch; pub use audio::{AudioRenderer, AudioSegment, MusicTracks, release_playback_audio_caches}; #[cfg(feature = "test-hooks")] diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs index 1e4d2efd150..f4313c24c63 100644 --- a/crates/editor/src/playback.rs +++ b/crates/editor/src/playback.rs @@ -236,8 +236,12 @@ pub struct Playback { pub music: crate::audio::MusicTracks, pub audio_output: Arc, pub telemetry: Option, + pub playback_rate: f64, } +pub const MIN_PLAYBACK_RATE: f64 = 0.25; +pub const MAX_PLAYBACK_RATE: f64 = 4.0; + #[derive(Clone, Copy)] pub enum PlaybackEvent { Start, @@ -699,6 +703,13 @@ impl Playback { diagnostic.field(Field::identifier("resource", resource)); } let fps_f64 = fps as f64; + let playback_rate = + if adopted.is_none() && self.playback_rate.is_finite() && self.playback_rate > 0.0 { + self.playback_rate + .clamp(MIN_PLAYBACK_RATE, MAX_PLAYBACK_RATE) + } else { + 1.0 + }; if !(fps_f64.is_finite() && fps_f64 > 0.0) { warn!(fps, "Invalid FPS provided for playback start"); @@ -1032,7 +1043,7 @@ impl Playback { let (audio_playhead_tx, audio_playhead_rx) = watch::channel(self.start_frame_number as f64 / fps as f64); - let frame_duration = Duration::from_secs_f64(1.0 / fps_f64); + let frame_duration = Duration::from_secs_f64(1.0 / (fps_f64 * playback_rate)); let mut frame_number = self.start_frame_number; let mut seek_generation = 0; let mut prefetch_buffer: VecDeque = @@ -1415,6 +1426,7 @@ impl Playback { duration_secs: duration, start_playhead_secs: playback_start_frame as f64 / fps_f64, playhead_rx: audio_playhead_rx.clone(), + playback_rate, }) }; let mut has_audio = audio_generation.is_some(); @@ -1477,6 +1489,7 @@ impl Playback { duration_secs: duration, start_playhead_secs: frame_number as f64 / fps_f64, playhead_rx: audio_playhead_rx.clone(), + playback_rate, }); let started = runtime.block_on(async { tokio::select! { @@ -1560,6 +1573,7 @@ impl Playback { duration_secs: duration, start_playhead_secs: frame_number as f64 / fps_f64, playhead_rx: audio_playhead_rx.clone(), + playback_rate, }, generation, ); @@ -1590,7 +1604,8 @@ impl Playback { Instant::now().saturating_duration_since(next_deadline) }; if adopted.is_none() && overshoot > frame_duration + frame_duration / 2 { - let frames_behind = (overshoot.as_secs_f64() * fps_f64).floor() as u32; + let frames_behind = + (overshoot.as_secs_f64() * fps_f64 * playback_rate).floor() as u32; let skip = frames_behind.max(1); let skipped_from = frame_number; frame_number += skip; @@ -2065,8 +2080,8 @@ impl Playback { break 'playback; } - let expected_frame = - clock_anchor_frame + (start.elapsed().as_secs_f64() * fps_f64).floor() as u32; + let expected_frame = clock_anchor_frame + + (start.elapsed().as_secs_f64() * fps_f64 * playback_rate).floor() as u32; if frame_number < expected_frame { let frames_behind = expected_frame - frame_number; diff --git a/crates/editor/src/time_stretch.rs b/crates/editor/src/time_stretch.rs new file mode 100644 index 00000000000..eefc81aa1ed --- /dev/null +++ b/crates/editor/src/time_stretch.rs @@ -0,0 +1,264 @@ +use std::collections::VecDeque; + +const GRAIN_FRAMES: usize = 1536; +const HOP_FRAMES: usize = GRAIN_FRAMES / 2; +const SEARCH_FRAMES: usize = 384; +const COARSE_STEP: usize = 8; +const FINE_STEP: usize = 2; +/// Source frames the input buffer can hold before it is trimmed (it drops +/// consumed audio once more than four grains are behind), with room for one +/// 4x hop and a refill. Reserved up front so the audio callback never grows it. +const INPUT_CAPACITY_FRAMES: usize = GRAIN_FRAMES * 8 + 1024; +const READY_CAPACITY_FRAMES: usize = 8192 + HOP_FRAMES; + +/// Streaming WSOLA time-stretcher for interleaved f32 audio: consumes source +/// audio `rate` times faster than it produces output while keeping pitch. +/// Each grain is placed where it best matches the natural continuation of +/// the previous one, which avoids the phasiness of plain overlap-add. +pub struct TimeStretch { + channels: usize, + rate: f64, + window: Vec, + input: Vec, + input_offset: usize, + analysis_frame: f64, + previous_frame: Option, + accumulator: Vec, + ready: VecDeque, +} + +impl TimeStretch { + pub fn new(channels: usize, rate: f64) -> Self { + let channels = channels.max(1); + let window = (0..GRAIN_FRAMES) + .map(|i| { + let x = i as f32 / GRAIN_FRAMES as f32; + 0.5 - 0.5 * (std::f32::consts::TAU * x).cos() + }) + .collect(); + Self { + channels, + rate: rate.clamp(0.25, 4.0), + window, + input: Vec::with_capacity(INPUT_CAPACITY_FRAMES * channels), + input_offset: 0, + analysis_frame: SEARCH_FRAMES as f64, + previous_frame: None, + accumulator: vec![0.0; GRAIN_FRAMES * channels], + ready: VecDeque::with_capacity(READY_CAPACITY_FRAMES * channels), + } + } + + pub fn channels(&self) -> usize { + self.channels + } + + /// Back to the state `new` builds, clearing the buffers in place: this + /// runs on the audio callback (on a resync), so it must not allocate. + pub fn reset(&mut self) { + self.input.clear(); + self.input_offset = 0; + self.analysis_frame = SEARCH_FRAMES as f64; + self.previous_frame = None; + self.accumulator.fill(0.0); + self.ready.clear(); + } + + fn input_frames(&self) -> usize { + self.input_offset + self.input.len() / self.channels + } + + pub fn frames_needed(&self) -> usize { + let target = self.analysis_frame as usize + SEARCH_FRAMES; + let natural = self.previous_frame.map_or(0, |frame| frame + HOP_FRAMES); + target.max(natural) + GRAIN_FRAMES + } + + pub fn input_shortfall(&self) -> usize { + self.frames_needed().saturating_sub(self.input_frames()) + } + + pub fn push_input(&mut self, samples: &[f32]) { + self.input.extend_from_slice(samples); + } + + pub fn ready_samples(&self) -> usize { + self.ready.len() + } + + pub fn pop_ready(&mut self) -> Option { + self.ready.pop_front() + } + + pub fn pending_source_secs(&self, sample_rate: u32) -> f64 { + let unconsumed = self.input_frames() as f64 - self.analysis_frame; + let queued = (self.ready.len() / self.channels) as f64 * self.rate; + (unconsumed + queued).max(0.0) / f64::from(sample_rate.max(1)) + } + + fn frame(&self, absolute: usize, channel: usize) -> f32 { + let local = absolute.saturating_sub(self.input_offset); + self.input + .get(local * self.channels + channel) + .copied() + .unwrap_or(0.0) + } + + fn correlation(&self, candidate: usize, natural: usize, step: usize) -> f32 { + let mut score = 0.0; + let mut i = 0; + while i < HOP_FRAMES { + for c in 0..self.channels { + score += self.frame(candidate + i, c) * self.frame(natural + i, c); + } + i += step; + } + score + } + + fn best_in( + &self, + natural: usize, + lowest: usize, + highest: usize, + candidate_step: usize, + compare_step: usize, + ) -> usize { + let mut best = lowest; + let mut best_score = f32::MIN; + let mut candidate = lowest; + while candidate <= highest { + let score = self.correlation(candidate, natural, compare_step); + if score > best_score { + best_score = score; + best = candidate; + } + candidate += candidate_step; + } + best + } + + fn best_frame(&self, target: usize) -> usize { + let Some(previous) = self.previous_frame else { + return target; + }; + let natural = previous + HOP_FRAMES; + let lowest = target.saturating_sub(SEARCH_FRAMES).max(self.input_offset); + let highest = target + SEARCH_FRAMES; + let coarse = self.best_in(natural, lowest, highest, COARSE_STEP, COARSE_STEP); + self.best_in( + natural, + coarse.saturating_sub(COARSE_STEP - 1).max(lowest), + (coarse + COARSE_STEP - 1).min(highest), + 1, + FINE_STEP, + ) + } + + /// Emits one hop of output. Call only when `input_shortfall()` is 0. + pub fn hop(&mut self) { + let target = self.analysis_frame as usize; + let start = self.best_frame(target); + for i in 0..GRAIN_FRAMES { + let weight = self.window[i]; + for c in 0..self.channels { + self.accumulator[i * self.channels + c] += self.frame(start + i, c) * weight; + } + } + let emitted = HOP_FRAMES * self.channels; + self.ready.extend(self.accumulator.drain(..emitted)); + self.accumulator.resize(GRAIN_FRAMES * self.channels, 0.0); + self.previous_frame = Some(start); + self.analysis_frame += HOP_FRAMES as f64 * self.rate; + + let keep_from = start + .min(target) + .saturating_sub(SEARCH_FRAMES) + .max(self.input_offset); + let drop = keep_from - self.input_offset; + if drop > GRAIN_FRAMES * 4 { + self.input.drain(..drop * self.channels); + self.input_offset += drop; + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn zero_crossings(samples: &[f32]) -> usize { + samples + .windows(2) + .filter(|pair| (pair[0] < 0.0) != (pair[1] < 0.0)) + .count() + } + + #[test] + fn reset_clears_in_place_and_matches_a_fresh_stretcher() { + let mut stretch = TimeStretch::new(2, 2.0); + stretch.push_input(&vec![0.25; 8192 * 2]); + stretch.hop(); + let (input, accumulator) = (stretch.input.as_ptr(), stretch.accumulator.as_ptr()); + stretch.reset(); + assert_eq!(stretch.input.as_ptr(), input, "no reallocation"); + assert_eq!(stretch.accumulator.as_ptr(), accumulator, "no reallocation"); + let fresh = TimeStretch::new(2, 2.0); + assert!(stretch.input.is_empty() && stretch.ready.is_empty()); + assert_eq!(stretch.input_offset, fresh.input_offset); + assert_eq!(stretch.analysis_frame, fresh.analysis_frame); + assert_eq!(stretch.previous_frame, fresh.previous_frame); + assert!(stretch.accumulator.iter().all(|sample| *sample == 0.0)); + assert_eq!(stretch.accumulator.len(), fresh.accumulator.len()); + } + + #[test] + fn doubling_speed_keeps_pitch_and_halves_duration() { + let sample_rate = 48_000.0; + let tone = 440.0; + let source: Vec = (0..sample_rate as usize * 4) + .map(|i| (std::f32::consts::TAU * tone * i as f32 / sample_rate).sin()) + .collect(); + let mut stretch = TimeStretch::new(1, 2.0); + let mut output = Vec::new(); + let mut fed = 0; + while output.len() < sample_rate as usize { + let need = stretch.input_shortfall(); + if need > 0 { + let end = (fed + need + 1024).min(source.len()); + stretch.push_input(&source[fed..end]); + fed = end; + } + stretch.hop(); + while let Some(sample) = stretch.pop_ready() { + output.push(sample); + } + } + let steady = &output[GRAIN_FRAMES..sample_rate as usize]; + let seconds = steady.len() as f32 / sample_rate; + let frequency = zero_crossings(steady) as f32 / 2.0 / seconds; + assert!((frequency - tone).abs() < 15.0, "frequency {frequency}"); + assert!(fed as f32 > sample_rate * 1.8, "consumed {fed}"); + } + + #[test] + fn aligns_opposite_phase_stereo() { + let sample_rate = 48_000.0; + let tone = 440.0; + let frames = GRAIN_FRAMES * 4; + let mut source = Vec::with_capacity(frames * 2); + for i in 0..frames { + let sample = (std::f32::consts::TAU * tone * i as f32 / sample_rate).sin(); + source.push(sample); + source.push(-sample); + } + let mut stretch = TimeStretch::new(2, 1.5); + stretch.push_input(&source); + stretch.previous_frame = Some(0); + let natural = HOP_FRAMES; + let best = stretch.best_frame(HOP_FRAMES + 150); + let energy = stretch.correlation(natural, natural, 1); + let score = stretch.correlation(best, natural, 1); + assert!(score > energy * 0.95, "score {score} energy {energy}"); + } +} diff --git a/crates/verify/tests/audio_support/mod.rs b/crates/verify/tests/audio_support/mod.rs index c92fe3db9e2..8eb1aac4941 100644 --- a/crates/verify/tests/audio_support/mod.rs +++ b/crates/verify/tests/audio_support/mod.rs @@ -179,6 +179,7 @@ impl OfflinePlayer { duration_secs: self.duration, start_playhead_secs: start, playhead_rx: rx, + playback_rate: 1.0, }) .expect("offline audio output accepted the play request"); self.playhead = Some(tx); diff --git a/crates/verify/tests/common/mod.rs b/crates/verify/tests/common/mod.rs index 85ca09d7a66..9c4ed9a2a0c 100644 --- a/crates/verify/tests/common/mod.rs +++ b/crates/verify/tests/common/mod.rs @@ -1208,6 +1208,7 @@ pub async fn realtime_playback( music: cap_editor::MusicTracks::new(), audio_output: Arc::new(audio_output), telemetry: Some(telemetry), + playback_rate: 1.0, }; let started = std::time::Instant::now(); let handle = playback