From 6358b14f5d8978863a2bd777c1a042328f14ec6a Mon Sep 17 00:00:00 2001 From: Yoav Levavi Date: Tue, 20 Oct 2026 22:22:31 +0300 Subject: [PATCH 1/3] feat(gpui): J/K/L playback speed shuttle Playback rate on the editor instance with pitch-preserving audio (WSOLA time stretch; 1x keeps the existing sync path), and J/K/L in the GPUI editor: L speeds up, J slows down, K stops and resets. Co-Authored-By: Claude Opus 5.5 --- apps/desktop-gpui/src/editor_window.rs | 74 ++++++ .../desktop-display-transport-benchmark.rs | 1 + .../examples/audio-output-idle-benchmark.rs | 1 + .../examples/editor-playback-benchmark.rs | 1 + crates/editor/src/audio_output.rs | 120 ++++++++- .../editor/src/audio_output/native_tests.rs | 1 + crates/editor/src/editor_instance.rs | 20 ++ crates/editor/src/lib.rs | 1 + crates/editor/src/playback.rs | 25 +- crates/editor/src/time_stretch.rs | 237 ++++++++++++++++++ crates/verify/tests/audio_support/mod.rs | 1 + crates/verify/tests/common/mod.rs | 1 + 12 files changed, 478 insertions(+), 5 deletions(-) create mode 100644 crates/editor/src/time_stretch.rs diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs index e295f24fab6..2df9ebe1224 100644 --- a/apps/desktop-gpui/src/editor_window.rs +++ b/apps/desktop-gpui/src/editor_window.rs @@ -1393,6 +1393,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 ---------------------------------------------------------- @@ -2076,6 +2077,7 @@ impl EditorWindow { timeline_view, frame_layout: None, instance: None, + playback_rate: 1.0, focus: cx.focus_handle(), playing: false, playhead: 0.0, @@ -3184,7 +3186,65 @@ impl EditorWindow { /// `handlePlayPauseClick` (`Player.tsx:212-233`), verbatim: at the end, /// restart from 0; playing, stop; otherwise seek to the playhead and go. + fn set_playback_rate(&mut self, rate: f64) { + self.playback_rate = rate; + if let Some(instance) = &self.instance { + instance.set_playback_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(); + } + 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); @@ -3617,6 +3677,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() { @@ -11213,6 +11285,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, diff --git a/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs b/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs index f7449e2f940..abe07708d38 100644 --- a/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs +++ b/apps/desktop/src-tauri/examples/desktop-display-transport-benchmark.rs @@ -338,6 +338,7 @@ async fn main() { music: cap_editor::MusicTracks::new(), audio_output, telemetry: Some(telemetry), + playback_rate: 1.0, }; let playback_handle = match playback.start(fps, resolution_base).await { 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 d7d5f7218f5..f79f87b6b98 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,62 @@ fn render_source_block>( } } +/// 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. @@ -965,7 +1062,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!( @@ -1051,6 +1150,19 @@ 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, + rate_scratch: Vec::new(), + 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"))] @@ -1115,6 +1227,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"))] @@ -1630,6 +1747,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 d64b46ebca6..a5d51e294d7 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 71ca1fff17d..ebb32d64985 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>, @@ -656,6 +657,7 @@ impl EditorInstance { export_preview_active: AtomicBool::new(false), export_active: AtomicBool::new(false), playback_epoch: AtomicU64::new(0), + playback_rate_bits: AtomicU64::new(1.0f64.to_bits()), runtime_handle: tokio::runtime::Handle::current(), audio_output, }); @@ -768,6 +770,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, @@ -877,6 +880,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) @@ -941,6 +960,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 16a618e214d..81ec4c639c5 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}; #[cfg(feature = "test-hooks")] diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs index 92cbe23264e..0d9b4d64012 100644 --- a/crates/editor/src/playback.rs +++ b/crates/editor/src/playback.rs @@ -156,8 +156,14 @@ pub struct Playback { pub music: crate::audio::MusicTracks, pub audio_output: Arc, pub telemetry: Option, + /// Wall-clock speed multiplier for editing review (J/K/L shuttle). The + /// audio output consumes source audio at the same rate, keeping pitch. + 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, @@ -619,6 +625,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"); @@ -952,7 +965,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 = @@ -1333,6 +1346,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(); @@ -1395,6 +1409,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! { @@ -1478,6 +1493,7 @@ impl Playback { duration_secs: duration, start_playhead_secs: frame_number as f64 / fps_f64, playhead_rx: audio_playhead_rx.clone(), + playback_rate, }, generation, ); @@ -1508,7 +1524,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; @@ -1983,8 +2000,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..3f53cd395ce --- /dev/null +++ b/crates/editor/src/time_stretch.rs @@ -0,0 +1,237 @@ +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; + +/// 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::new(), + input_offset: 0, + analysis_frame: SEARCH_FRAMES as f64, + previous_frame: None, + accumulator: vec![0.0; GRAIN_FRAMES * channels], + ready: VecDeque::new(), + } + } + + pub fn channels(&self) -> usize { + self.channels + } + + pub fn reset(&mut self) { + let (channels, rate) = (self.channels, self.rate); + *self = Self::new(channels, rate); + } + + fn input_frames(&self) -> usize { + self.input_offset + self.input.len() / self.channels + } + + /// Absolute source frame the next hop needs available. + 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() + } + + /// Source seconds already pulled from the buffer but not yet heard. + 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 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 07e8500e3e3..a238fa4d07e 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 bfbc69c6bd7..6e31f4a3b20 100644 --- a/crates/verify/tests/common/mod.rs +++ b/crates/verify/tests/common/mod.rs @@ -1167,6 +1167,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 From 1500f92385d3ece0aa3e4aa0ef351d1aeb95f701 Mon Sep 17 00:00:00 2001 From: Yoav Levavi Date: Wed, 21 Oct 2026 19:34:29 +0300 Subject: [PATCH 2/3] Shuttle: rate-aware playhead glide, speed badge, allocation-free reset - The drawn playhead glides at the playback rate between samples, so it no longer lags at 2x/4x or overshoots and snaps back at 0.5x. - The transport shows the current speed ("2x") while it isn't 1x. - TimeStretch::reset clears its buffers in place, and the stretcher's buffers and rate_scratch are reserved up front, so the cpal callback no longer allocates on a resync. - The shuttle methods sit below toggle_play again, so handlePlayPauseClick's doc is back on toggle_play. Co-Authored-By: Claude Opus 5.5 --- apps/desktop-gpui/src/editor_window.rs | 129 +++++++++++++++++-------- crates/editor/src/audio_output.rs | 8 +- crates/editor/src/time_stretch.rs | 38 +++++++- 3 files changed, 129 insertions(+), 46 deletions(-) diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs index 2df9ebe1224..97b87acaf3c 100644 --- a/apps/desktop-gpui/src/editor_window.rs +++ b/apps/desktop-gpui/src/editor_window.rs @@ -3186,6 +3186,38 @@ 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); + self.preparing_command(seek, Some(!self.playing)); + } + return; + } + if self.ordinary_handoff_frame.is_some() { + let at_end = self.is_at_end(); + let target = self + .preparing_presentation + .as_mut() + .and_then(|presentation| presentation.toggle_handoff_playback(at_end)); + if let Some(target) = target { + self.seek_to_time(target, cx); + } + cx.notify(); + return; + } + if self.is_at_end() { + self.stop_playback(cx); + self.start_playback(0.0, cx); + } else if self.playing { + self.stop_playback(cx); + } else { + let from = self.playhead; + self.start_playback(from, cx); + } + } + fn set_playback_rate(&mut self, rate: f64) { self.playback_rate = rate; if let Some(instance) = &self.instance { @@ -3243,38 +3275,6 @@ impl EditorWindow { window.refresh(); } - 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); - self.preparing_command(seek, Some(!self.playing)); - } - return; - } - if self.ordinary_handoff_frame.is_some() { - let at_end = self.is_at_end(); - let target = self - .preparing_presentation - .as_mut() - .and_then(|presentation| presentation.toggle_handoff_playback(at_end)); - if let Some(target) = target { - self.seek_to_time(target, cx); - } - cx.notify(); - return; - } - if self.is_at_end() { - self.stop_playback(cx); - self.start_playback(0.0, cx); - } else if self.playing { - self.stop_playback(cx); - } else { - let from = self.playhead; - self.start_playback(from, cx); - } - } - /// `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 @@ -10153,6 +10153,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) @@ -10369,6 +10382,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()); @@ -11250,11 +11264,29 @@ 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 { +/// `rate` is the shuttle speed: the timeline advances `rate` seconds per +/// wall-clock second, so the glide (and its cap) scale with it. +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 +} + +/// The transport's speed badge: "2x", "0.5x". +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) { @@ -12788,24 +12820,39 @@ 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 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 ); + // Shuttling: the line glides at the playback speed. + 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); } /// The perf gate's line. `frames` is what reached the window, `dropped` diff --git a/crates/editor/src/audio_output.rs b/crates/editor/src/audio_output.rs index f79f87b6b98..d86481790f3 100644 --- a/crates/editor/src/audio_output.rs +++ b/crates/editor/src/audio_output.rs @@ -981,6 +981,10 @@ 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>( @@ -1157,7 +1161,9 @@ fn install_source>( }, channels: output_channels, sample_rate: output_info.sample_rate, - rate_scratch: Vec::new(), + // 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 diff --git a/crates/editor/src/time_stretch.rs b/crates/editor/src/time_stretch.rs index 3f53cd395ce..95ef011e86f 100644 --- a/crates/editor/src/time_stretch.rs +++ b/crates/editor/src/time_stretch.rs @@ -5,6 +5,12 @@ 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; +/// Output frames queued at most: one device block plus a hop. +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. @@ -35,12 +41,12 @@ impl TimeStretch { channels, rate: rate.clamp(0.25, 4.0), window, - input: Vec::new(), + 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::new(), + ready: VecDeque::with_capacity(READY_CAPACITY_FRAMES * channels), } } @@ -48,9 +54,15 @@ impl TimeStretch { 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) { - let (channels, rate) = (self.channels, self.rate); - *self = Self::new(channels, rate); + 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 { @@ -185,6 +197,24 @@ mod tests { .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; From 332922b090b795d7e82748ec5c524c82e00367be Mon Sep 17 00:00:00 2001 From: Yoav Levavi Date: Tue, 3 Nov 2026 06:27:27 +0200 Subject: [PATCH 3/3] Shuttle: restart playback when the rate changes; drop narrating comments The shuttle's pause and play could collapse in the transport's latest-wins state into a single seek, so a running session kept its old speed while the badge showed the new one. The rate now travels in the desired transport state, and the driver restarts the session whenever it differs from the rate the running session started with. Co-Authored-By: Claude Opus 5.5 --- apps/desktop-gpui/src/editor_window.rs | 42 +++++++++++++++++++++----- crates/editor/src/playback.rs | 2 -- crates/editor/src/time_stretch.rs | 3 -- 3 files changed, 35 insertions(+), 12 deletions(-) diff --git a/apps/desktop-gpui/src/editor_window.rs b/apps/desktop-gpui/src/editor_window.rs index 2022feaeb73..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 @@ -3288,8 +3305,8 @@ impl EditorWindow { fn set_playback_rate(&mut self, rate: f64) { self.playback_rate = rate; - if let Some(instance) = &self.instance { - instance.set_playback_rate(rate); + if let Some(transport) = &self.transport { + transport.set_rate(rate); } } @@ -11880,8 +11897,6 @@ 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. -/// `rate` is the shuttle speed: the timeline advances `rate` seconds per -/// wall-clock second, so the glide (and its cap) scale with it. fn playhead_extrapolation( playing: bool, epoch_has_sample: bool, @@ -11899,7 +11914,6 @@ fn playhead_extrapolation( since_last_sample.clamp(0.0, MAX_PLAYHEAD_EXTRAPOLATION) * rate } -/// The transport's speed badge: "2x", "0.5x". fn shuttle_rate_label(rate: f64) -> String { let text = format!("{rate:.2}"); format!("{}x", text.trim_end_matches('0').trim_end_matches('.')) @@ -14602,6 +14616,21 @@ mod tests { 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"); @@ -14619,7 +14648,6 @@ mod tests { playhead_extrapolation(true, true, 3.0, 1.0), MAX_PLAYHEAD_EXTRAPOLATION ); - // Shuttling: the line glides at the playback speed. 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!( diff --git a/crates/editor/src/playback.rs b/crates/editor/src/playback.rs index 108f21f461c..f4313c24c63 100644 --- a/crates/editor/src/playback.rs +++ b/crates/editor/src/playback.rs @@ -236,8 +236,6 @@ pub struct Playback { pub music: crate::audio::MusicTracks, pub audio_output: Arc, pub telemetry: Option, - /// Wall-clock speed multiplier for editing review (J/K/L shuttle). The - /// audio output consumes source audio at the same rate, keeping pitch. pub playback_rate: f64, } diff --git a/crates/editor/src/time_stretch.rs b/crates/editor/src/time_stretch.rs index 95ef011e86f..eefc81aa1ed 100644 --- a/crates/editor/src/time_stretch.rs +++ b/crates/editor/src/time_stretch.rs @@ -9,7 +9,6 @@ const FINE_STEP: usize = 2; /// 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; -/// Output frames queued at most: one device block plus a hop. const READY_CAPACITY_FRAMES: usize = 8192 + HOP_FRAMES; /// Streaming WSOLA time-stretcher for interleaved f32 audio: consumes source @@ -69,7 +68,6 @@ impl TimeStretch { self.input_offset + self.input.len() / self.channels } - /// Absolute source frame the next hop needs available. 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); @@ -92,7 +90,6 @@ impl TimeStretch { self.ready.pop_front() } - /// Source seconds already pulled from the buffer but not yet heard. 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;