From 7608af5d1e958e182f0181893367714f0399d7d3 Mon Sep 17 00:00:00 2001 From: REVPKD Date: Mon, 23 Nov 2026 20:31:40 +0100 Subject: [PATCH 1/3] Add timeline audio playback controls --- Cargo.lock | 243 ++++++++++++ crates/align-core/src/export/model.rs | 3 + crates/align-core/src/model.rs | 6 + crates/align-gpui/Cargo.toml | 1 + crates/align-gpui/src/main.rs | 1 + crates/align-gpui/src/playback.rs | 450 +++++++++++++++++++++++ crates/align-gpui/src/state.rs | 10 + crates/align-gpui/src/views/mod.rs | 188 ++++++++++ crates/align-gpui/src/views/operation.rs | 5 +- crates/align-gpui/src/views/root.rs | 15 + crates/align-gpui/src/views/timeline.rs | 93 ++++- 11 files changed, 1010 insertions(+), 5 deletions(-) create mode 100644 crates/align-gpui/src/playback.rs diff --git a/Cargo.lock b/Cargo.lock index 5ebad1b..5d4aa14 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -106,6 +106,7 @@ dependencies = [ "align-cli", "align-core", "align-decode", + "cpal", "dirs 6.0.0", "embed-resource", "futures", @@ -144,6 +145,28 @@ dependencies = [ "equator", ] +[[package]] +name = "alsa" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812947049edcd670a82cd5c73c3661d2e58468577ba8489de58e1a73c04cbd5d" +dependencies = [ + "alsa-sys", + "bitflags 2.13.1", + "cfg-if", + "libc", +] + +[[package]] +name = "alsa-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad7569085a265dd3f607ebecce7458eaab2132a84393534c95b18dcbc3f31e04" +dependencies = [ + "libc", + "pkg-config", +] + [[package]] name = "anstream" version = "1.0.0" @@ -1124,6 +1147,16 @@ version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + [[package]] name = "command-fds" version = "0.3.3" @@ -1334,6 +1367,20 @@ dependencies = [ "libm", ] +[[package]] +name = "coreaudio-rs" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d5d7dca3ebcf65a035582c9ad4385371a9d9ee6537474d2a278f4e1e475bb58" +dependencies = [ + "bitflags 2.13.1", + "libc", + "objc2-audio-toolbox", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", +] + [[package]] name = "cosmic-text" version = "0.14.2" @@ -1357,6 +1404,36 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "cpal" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f02e8d0327b42d3e2e4ab2119af397344eb9fc54a34bf0ddeaa1277af8681f1" +dependencies = [ + "alsa", + "block2", + "coreaudio-rs", + "dasp_sample", + "jni", + "js-sys", + "libc", + "mach2", + "ndk", + "ndk-context", + "num-derive", + "num-traits", + "objc2", + "objc2-audio-toolbox", + "objc2-avf-audio", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-foundation", + "web-sys", + "windows 0.62.2", + "windows-core 0.62.2", +] + [[package]] name = "cpufeatures" version = "0.2.17" @@ -1460,6 +1537,12 @@ version = "0.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2931af7e13dc045d8e9d26afccc6fa115d64e115c9c84b1166288b46f6782c2" +[[package]] +name = "dasp_sample" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c87e182de0887fd5361989c677c4e8f5000cd9491d6d563161a8f3a5519fc7f" + [[package]] name = "data-url" version = "0.3.2" @@ -3067,6 +3150,64 @@ version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.20", + "walkdir", + "windows-link 0.2.1", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + [[package]] name = "jobserver" version = "0.1.35" @@ -3314,6 +3455,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" +[[package]] +name = "mach2" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dae608c151f68243f2b000364e1f7b186d9c29845f7d2d85bd31b9ad77ad552b" + [[package]] name = "malloc_buf" version = "0.0.6" @@ -3494,6 +3641,35 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.1", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + [[package]] name = "new_debug_unreachable" version = "1.0.6" @@ -3688,6 +3864,28 @@ dependencies = [ "libc", ] +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "objc" version = "0.2.7" @@ -3731,6 +3929,21 @@ dependencies = [ "objc2-quartz-core", ] +[[package]] +name = "objc2-audio-toolbox" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6948501a91121d6399b79abaa33a8aa4ea7857fe019f341b8c23ad6e81b79b08" +dependencies = [ + "bitflags 2.13.1", + "libc", + "objc2", + "objc2-core-audio", + "objc2-core-audio-types", + "objc2-core-foundation", + "objc2-foundation", +] + [[package]] name = "objc2-av-foundation" version = "0.3.2" @@ -3746,6 +3959,17 @@ dependencies = [ "objc2-foundation", ] +[[package]] +name = "objc2-avf-audio" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13a380031deed8e99db00065c45937da434ca987c034e13b87e4441f9e4090be" +dependencies = [ + "bitflags 2.13.1", + "objc2", + "objc2-foundation", +] + [[package]] name = "objc2-core-audio" version = "0.3.2" @@ -3756,6 +3980,7 @@ dependencies = [ "objc2", "objc2-core-audio-types", "objc2-core-foundation", + "objc2-foundation", ] [[package]] @@ -3836,6 +4061,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" dependencies = [ "bitflags 2.13.1", + "block2", + "libc", "objc2", "objc2-core-foundation", ] @@ -5298,6 +5525,16 @@ version = "0.3.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + [[package]] name = "simd_helpers" version = "0.1.0" @@ -5307,6 +5544,12 @@ dependencies = [ "quote", ] +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + [[package]] name = "simplecss" version = "0.2.2" diff --git a/crates/align-core/src/export/model.rs b/crates/align-core/src/export/model.rs index b9117f8..43e147c 100644 --- a/crates/align-core/src/export/model.rs +++ b/crates/align-core/src/export/model.rs @@ -1588,6 +1588,9 @@ impl ExportTimeline { }), start: item.start, duration: item.timeline_duration, + source_in: item.source_in, + source_out: item.source_out, + mapping_points: item.mapping_points.clone(), confidence: item.confidence, matched: !unmatched.contains(&item.clip.id), }) diff --git a/crates/align-core/src/model.rs b/crates/align-core/src/model.rs index fabc7f4..88b6b5a 100644 --- a/crates/align-core/src/model.rs +++ b/crates/align-core/src/model.rs @@ -551,6 +551,12 @@ pub struct TimelinePreviewItem { pub source_key: String, pub start: f64, pub duration: f64, + /// Source range and source-to-timeline mapping used by export. + /// Timeline monitors use these same values so drift correction remains + /// consistent with the rendered sequence. + pub source_in: f64, + pub source_out: f64, + pub mapping_points: Vec, pub confidence: f64, pub matched: bool, } diff --git a/crates/align-gpui/Cargo.toml b/crates/align-gpui/Cargo.toml index df8bdfe..13a262e 100644 --- a/crates/align-gpui/Cargo.toml +++ b/crates/align-gpui/Cargo.toml @@ -28,6 +28,7 @@ ureq = "3" semver = "1" url = "2" sha2.workspace = true +cpal = "0.18.2" [target.'cfg(unix)'.dependencies] rustix = { version = "1.1", features = ["fs"] } diff --git a/crates/align-gpui/src/main.rs b/crates/align-gpui/src/main.rs index caef6a2..5ad611a 100644 --- a/crates/align-gpui/src/main.rs +++ b/crates/align-gpui/src/main.rs @@ -10,6 +10,7 @@ mod feedback; mod icons; mod lane; mod motion; +mod playback; mod project; mod settings; mod state; diff --git a/crates/align-gpui/src/playback.rs b/crates/align-gpui/src/playback.rs new file mode 100644 index 0000000..5013ed8 --- /dev/null +++ b/crates/align-gpui/src/playback.rs @@ -0,0 +1,450 @@ +use std::collections::HashSet; +use std::path::PathBuf; +use std::sync::{Arc, Mutex}; +use std::time::Instant; + +use align_core::MappingPoint; + +#[derive(Clone, Debug)] +pub struct PlaybackItem { + pub url: PathBuf, + pub lane_id: String, + /// Position in the exported timeline, in seconds. + pub start: f64, + pub duration: f64, + pub source_in: f64, + pub source_out: f64, + /// Piecewise source-time to exported island-time mapping. + pub mapping_points: Vec, +} + +/// Decoded, mono preview PCM. Audio is normalized to 48 kHz by FFmpeg before +/// it reaches the output callback, keeping that callback allocation-free. +#[derive(Clone, Debug)] +pub struct DecodedItem { + pub item: PlaybackItem, + pub samples: Arc<[f32]>, +} + +#[derive(Debug)] +pub struct PlaybackClock { + pub position: f64, + pub playing: bool, + pub updated_at: Instant, +} + +impl PlaybackClock { + pub fn new(position: f64) -> Self { + Self { + position: position.max(0.0), + playing: false, + updated_at: Instant::now(), + } + } + + pub fn position_at(&self, now: Instant) -> f64 { + if self.playing { + self.position + now.saturating_duration_since(self.updated_at).as_secs_f64() + } else { + self.position + } + } +} + +/// Shared state read by the realtime output callback. The callback only uses +/// `try_lock`, so UI operations never make the audio device wait. +pub type SharedPlayback = Arc>; + +pub struct PlaybackState { + pub clock: PlaybackClock, + pub items: Vec, + pub muted: HashSet, + pub soloed: HashSet, + pub end: f64, +} + +impl PlaybackState { + pub fn sample_at(&self, timeline_seconds: f64) -> f32 { + if !timeline_seconds.is_finite() { + return 0.0; + } + let mut active_lane: Option<&str> = None; + let mut multiple_active_lanes = false; + for decoded in &self.items { + let item = &decoded.item; + if item.source_time_at(timeline_seconds).is_none() { + continue; + } + match active_lane { + None => active_lane = Some(&item.lane_id), + Some(lane_id) if lane_id != item.lane_id => { + multiple_active_lanes = true; + break; + } + Some(_) => {} + } + } + let single_active_lane = active_lane.is_some() && !multiple_active_lanes; + let mut mixed = 0.0; + let mut contributors = 0usize; + for decoded in &self.items { + let item = &decoded.item; + if !single_active_lane && !item.is_audible(&self.muted, &self.soloed) { + continue; + } + let Some(source_seconds) = item.source_time_at(timeline_seconds) else { + continue; + }; + let index = ((source_seconds - item.source_in).max(0.0) * 48_000.0).floor() as usize; + if let Some(sample) = decoded.samples.get(index) { + mixed += sample; + contributors += 1; + } + } + if contributors > 1 { + mixed / (contributors as f32).sqrt() + } else { + mixed + } + } + + pub fn position_at(&self, now: Instant) -> f64 { + self.clock.position_at(now).min(self.end) + } +} + +/// Decode the selected timeline sources off the UI/audio threads. Each source +/// is reduced to 48 kHz mono preview PCM; the export itself is untouched. +pub fn decode_items(items: Vec) -> Result, String> { + let expected_bytes = items.iter().try_fold(0u64, |total, item| { + let duration = (item.source_out - item.source_in).max(0.0); + let bytes = (duration * 48_000.0 * 4.0).ceil() as u64; + total.checked_add(bytes) + }); + if expected_bytes.is_none_or(|bytes| bytes > 512 * 1024 * 1024) { + return Err("Timeline preview audio exceeds the 512 MB memory limit.".into()); + } + items + .into_iter() + .filter_map(|item| match decode_item(item) { + Ok(Some(item)) => Some(Ok(item)), + Ok(None) => None, + Err(error) => Some(Err(error)), + }) + .collect() +} + +fn decode_item(item: PlaybackItem) -> Result, String> { + use std::process::Stdio; + + let ffmpeg = align_decode::ff::ffmpeg_bin() + .ok_or_else(|| "FFmpeg is required for timeline audio playback.".to_owned())?; + let duration = item.source_out - item.source_in; + if !duration.is_finite() || duration <= 0.0 { + return Ok(None); + } + let mut command = align_decode::process::command(ffmpeg); + let output = command + .args(["-v", "error", "-hide_banner", "-i"]) + .arg(&item.url) + .args(["-ss"]) + .arg(item.source_in.to_string()) + .args(["-t"]) + .arg(duration.to_string()) + .args([ + "-map", "0:a:0?", "-vn", "-ac", "1", "-ar", "48000", "-f", "f32le", "pipe:1", + ]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .output() + .map_err(|error| format!("Could not decode {}: {error}", item.url.display()))?; + if !output.status.success() { + return Err(format!( + "Could not decode timeline audio from {}.", + item.url.display() + )); + } + if output.stdout.len() % 4 != 0 { + return Err(format!( + "FFmpeg returned incomplete PCM for {}.", + item.url.display() + )); + } + let samples: Vec = output + .stdout + .as_chunks::<4>() + .0 + .iter() + .map(|bytes| f32::from_le_bytes(*bytes)) + .collect(); + if samples.is_empty() { + return Ok(None); + } + Ok(Some(DecodedItem { + item, + samples: samples.into(), + })) +} + +pub fn output_stream(shared: SharedPlayback) -> Result { + use cpal::traits::{DeviceTrait, HostTrait}; + let device = cpal::default_host() + .default_output_device() + .ok_or_else(|| "No audio output device is available.".to_owned())?; + let supported = device + .default_output_config() + .map_err(|error| format!("Could not configure audio output: {error}"))?; + let sample_format = supported.sample_format(); + let config: cpal::StreamConfig = supported.into(); + match sample_format { + cpal::SampleFormat::I8 => build_output::(&device, config, shared), + cpal::SampleFormat::I16 => build_output::(&device, config, shared), + cpal::SampleFormat::I24 => build_output::(&device, config, shared), + cpal::SampleFormat::I32 => build_output::(&device, config, shared), + cpal::SampleFormat::I64 => build_output::(&device, config, shared), + cpal::SampleFormat::U8 => build_output::(&device, config, shared), + cpal::SampleFormat::U16 => build_output::(&device, config, shared), + cpal::SampleFormat::U24 => build_output::(&device, config, shared), + cpal::SampleFormat::U32 => build_output::(&device, config, shared), + cpal::SampleFormat::U64 => build_output::(&device, config, shared), + cpal::SampleFormat::F32 => build_output::(&device, config, shared), + cpal::SampleFormat::F64 => build_output::(&device, config, shared), + format => Err(format!( + "The selected audio device uses unsupported sample format {format:?}." + )), + } +} + +fn build_output( + device: &cpal::Device, + config: cpal::StreamConfig, + shared: SharedPlayback, +) -> Result +where + T: cpal::SizedSample + cpal::FromSample, +{ + use cpal::traits::DeviceTrait; + use cpal::traits::StreamTrait; + let channels = usize::from(config.channels); + let sample_rate = f64::from(config.sample_rate); + let callback_state = shared.clone(); + let stream = device + .build_output_stream( + config, + move |output: &mut [T], _| { + let Ok(mut state) = callback_state.try_lock() else { + output.fill(T::from_sample(0.0)); + return; + }; + if !state.clock.playing { + output.fill(T::from_sample(0.0)); + return; + } + let mut position = state.clock.position; + for frame in output.chunks_mut(channels) { + let sample = state.sample_at(position).clamp(-1.0, 1.0); + frame.fill(T::from_sample(sample)); + if state.clock.playing { + position += 1.0 / sample_rate; + } + } + if state.clock.playing { + state.clock.position = position.min(state.end); + state.clock.updated_at = Instant::now(); + if position >= state.end { + state.clock.playing = false; + } + } + }, + |error| eprintln!("Timeline audio output error: {error}"), + None, + ) + .map_err(|error| format!("Could not start audio output: {error}"))?; + stream + .play() + .map_err(|error| format!("Could not start audio output: {error}"))?; + Ok(stream) +} + +impl PlaybackItem { + fn source_time_at(&self, timeline_seconds: f64) -> Option { + let end = self.start + self.duration; + if !timeline_seconds.is_finite() || timeline_seconds < self.start || timeline_seconds >= end + { + return None; + } + let points = &self.mapping_points; + let mapped = if points.len() >= 2 { + let pair = points.windows(2).find(|pair| { + let left = pair[0].island.as_seconds(); + let right = pair[1].island.as_seconds(); + timeline_seconds >= left.min(right) && timeline_seconds <= left.max(right) + })?; + let island_a = pair[0].island.as_seconds(); + let island_b = pair[1].island.as_seconds(); + let source_a = pair[0].source.as_seconds(); + let source_b = pair[1].source.as_seconds(); + if (island_b - island_a).abs() < f64::EPSILON { + return None; + } + source_a + (timeline_seconds - island_a) * (source_b - source_a) / (island_b - island_a) + } else { + self.source_in + + (timeline_seconds - self.start) / self.duration + * (self.source_out - self.source_in) + }; + (mapped >= self.source_in && mapped < self.source_out).then_some(mapped) + } + + fn is_audible(&self, muted: &HashSet, soloed: &HashSet) -> bool { + !muted.contains(&self.lane_id) && (soloed.is_empty() || soloed.contains(&self.lane_id)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use align_core::{MappingPoint, MediaTime}; + use std::collections::HashSet; + use std::path::PathBuf; + + fn item() -> PlaybackItem { + PlaybackItem { + url: PathBuf::from("clip.wav"), + lane_id: "lane-1".into(), + start: 5.0, + duration: 4.0, + source_in: 10.0, + source_out: 14.0, + mapping_points: vec![ + MappingPoint { + source: MediaTime::seconds(10.0), + island: MediaTime::seconds(5.0), + }, + MappingPoint { + source: MediaTime::seconds(11.25), + island: MediaTime::seconds(6.0), + }, + MappingPoint { + source: MediaTime::seconds(12.5), + island: MediaTime::seconds(7.0), + }, + MappingPoint { + source: MediaTime::seconds(14.0), + island: MediaTime::seconds(9.0), + }, + ], + } + } + + #[test] + fn timeline_position_maps_piecewise_to_source_time() { + let clip = item(); + + assert_eq!(clip.source_time_at(5.0), Some(10.0)); + assert_eq!(clip.source_time_at(6.0), Some(11.25)); + assert_eq!(clip.source_time_at(7.0), Some(12.5)); + assert_eq!(clip.source_time_at(9.0), None); + } + + #[test] + fn camera_video_lane_is_audible_and_obeys_mute_solo() { + let clip = item(); + let muted = HashSet::new(); + let soloed = HashSet::new(); + assert!(clip.is_audible(&muted, &soloed)); + + let muted = HashSet::from(["lane-1".to_owned()]); + assert!(!clip.is_audible(&muted, &soloed)); + + let muted = HashSet::new(); + let soloed = HashSet::from(["other-lane".to_owned()]); + assert!(!clip.is_audible(&muted, &soloed)); + } + + #[test] + fn playback_samples_follow_piecewise_export_drift_mapping() { + let clip = item(); + let mut samples = vec![0.0; 14 * 48_000]; + samples[((11.25 - 10.0) * 48_000.0) as usize] = 0.75; + let state = PlaybackState { + clock: PlaybackClock::new(0.0), + items: vec![DecodedItem { + item: clip, + samples: samples.into(), + }], + muted: HashSet::new(), + soloed: HashSet::new(), + end: 20.0, + }; + + assert_eq!(state.sample_at(5.8), 0.0); + assert_eq!(state.sample_at(6.0), 0.75); + } + + #[test] + fn mute_and_solo_filter_audio_lanes_but_preserve_camera_audio() { + let mut recorder = item(); + recorder.lane_id = "recorder".into(); + let mut camera = item(); + camera.lane_id = "camera".into(); + let state = PlaybackState { + clock: PlaybackClock::new(0.0), + items: vec![ + DecodedItem { + item: recorder, + samples: vec![0.25; 20 * 48_000].into(), + }, + DecodedItem { + item: camera, + samples: vec![0.5; 20 * 48_000].into(), + }, + ], + muted: HashSet::from(["recorder".to_owned()]), + soloed: HashSet::new(), + end: 20.0, + }; + + assert_eq!(state.sample_at(5.0), 0.5); + } + + #[test] + fn only_active_lane_remains_audible_when_muted_or_excluded_by_solo() { + let mut first = item(); + first.lane_id = "only-lane".into(); + let mut second = first.clone(); + second.start = 6.0; + second.duration = 2.0; + second.source_in = 11.0; + second.source_out = 13.0; + second.mapping_points = vec![ + MappingPoint { + source: MediaTime::seconds(11.0), + island: MediaTime::seconds(6.0), + }, + MappingPoint { + source: MediaTime::seconds(13.0), + island: MediaTime::seconds(8.0), + }, + ]; + let state = PlaybackState { + clock: PlaybackClock::new(0.0), + items: vec![ + DecodedItem { + item: first, + samples: vec![0.25; 20 * 48_000].into(), + }, + DecodedItem { + item: second, + samples: vec![0.25; 20 * 48_000].into(), + }, + ], + muted: HashSet::from(["only-lane".to_owned()]), + soloed: HashSet::from(["another-lane".to_owned()]), + end: 20.0, + }; + + assert!(state.sample_at(6.5) > 0.0); + } +} diff --git a/crates/align-gpui/src/state.rs b/crates/align-gpui/src/state.rs index ec10dbd..94a4a41 100644 --- a/crates/align-gpui/src/state.rs +++ b/crates/align-gpui/src/state.rs @@ -422,6 +422,12 @@ pub struct AppData { pub show_about: bool, pub show_agent_setup: bool, pub zoom_level: f64, + /// NLE-style timeline position in seconds. Playback is opt-in and starts paused. + pub playhead_seconds: f64, + pub timeline_playing: bool, + /// Audio lane ids toggled in the timeline mixer. + pub muted_audio_lanes: HashSet, + pub soloed_audio_lanes: HashSet, /// Scroll position of the main content (timeline panning). pub timeline_scroll: ScrollHandle, /// In-flight run coordination: `cancel` stops the worker @@ -495,6 +501,10 @@ impl Default for AppData { show_about: false, show_agent_setup: false, zoom_level: 0.0, + playhead_seconds: 0.0, + timeline_playing: false, + muted_audio_lanes: HashSet::new(), + soloed_audio_lanes: HashSet::new(), timeline_scroll: ScrollHandle::new(), cancel: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)), generation: 0, diff --git a/crates/align-gpui/src/views/mod.rs b/crates/align-gpui/src/views/mod.rs index ea78f64..5b690cd 100644 --- a/crates/align-gpui/src/views/mod.rs +++ b/crates/align-gpui/src/views/mod.rs @@ -44,6 +44,8 @@ mod sources; mod timeline; mod toolbar; +use crate::playback::{PlaybackClock, PlaybackItem, PlaybackState, SharedPlayback}; + use animation::motion_ease; // ------------------------------------------------------------ messages @@ -514,6 +516,10 @@ pub struct AlignApp { /// Error shown when the report opened, offered for copying (SharedString: /// the panel clones it every frame). feedback_error: Option, + playback: Option, + playback_stream: Option, + playback_generation: u64, + playback_loading: bool, /// The update card was closed; the About panel still offers the update. update_notice_dismissed: bool, } @@ -529,6 +535,180 @@ impl AlignApp { self.projects.busy } + pub(crate) fn stop_timeline_playback(&mut self) { + self.playback_generation = self.playback_generation.wrapping_add(1); + self.playback_loading = false; + self.playback_stream = None; + self.playback = None; + self.data.timeline_playing = false; + } + + pub(crate) fn toggle_timeline_playback(&mut self, cx: &mut Context) { + if self.playback_loading { + self.playback_loading = false; + self.playback_generation = self.playback_generation.wrapping_add(1); + self.data.timeline_playing = false; + cx.notify(); + return; + } + if let Some(playback) = &self.playback { + let Ok(mut playback) = playback.lock() else { + return; + }; + if playback.clock.playing { + playback.clock.playing = false; + self.data.timeline_playing = false; + } else { + if playback.clock.position >= playback.end { + playback.clock.position = 0.0; + self.data.playhead_seconds = 0.0; + } + playback.clock.playing = true; + self.data.timeline_playing = true; + } + drop(playback); + self.schedule_playhead_refresh(cx); + cx.notify(); + return; + } + + use align_core::export_model::ExportTimeline; + let Some(result) = self.data.result.as_ref() else { + self.data.error = Some("Synchronize a timeline before starting playback.".into()); + cx.notify(); + return; + }; + let Ok(timeline) = ExportTimeline::from_result(result, true) else { + self.data.error = Some("The current result cannot be played as a timeline.".into()); + cx.notify(); + return; + }; + let unmatched = result.unmatched.iter().cloned().collect(); + let items = timeline + .preview_items(&unmatched) + .into_iter() + .filter_map(|item| { + let lane_id = self + .data + .lanes + .iter() + .find(|lane| lane.clips.iter().any(|clip| clip.id == item.id))? + .id + .clone(); + Some(PlaybackItem { + url: item.url, + lane_id, + start: item.start, + duration: item.duration, + source_in: item.source_in, + source_out: item.source_out, + mapping_points: item.mapping_points, + }) + }) + .collect::>(); + if items.is_empty() { + self.data.error = Some("There are no playable clips in this timeline.".into()); + cx.notify(); + return; + } + + self.playback_generation = self.playback_generation.wrapping_add(1); + let generation = self.playback_generation; + let position = self.data.playhead_seconds; + self.playback_loading = true; + let task = cx + .background_executor() + .spawn(async move { crate::playback::decode_items(items) }); + cx.spawn(async move |view, cx| { + let decoded = task.await; + let _ = view.update(cx, |this, cx| { + if this.playback_generation != generation { + return; + } + this.playback_loading = false; + let decoded = match decoded { + Ok(decoded) if !decoded.is_empty() => decoded, + Ok(_) => { + this.data.error = + Some("No audio streams were found in the timeline.".into()); + this.data.timeline_playing = false; + cx.notify(); + return; + } + Err(error) => { + this.data.error = Some(error); + this.data.timeline_playing = false; + cx.notify(); + return; + } + }; + let end = decoded + .iter() + .map(|item| item.item.start + item.item.duration) + .fold(1.0f64, f64::max); + let shared = std::sync::Arc::new(std::sync::Mutex::new(PlaybackState { + clock: PlaybackClock::new(position.min(end)), + items: decoded, + muted: this.data.muted_audio_lanes.clone(), + soloed: this.data.soloed_audio_lanes.clone(), + end, + })); + match crate::playback::output_stream(shared.clone()) { + Ok(stream) => { + if let Ok(mut state) = shared.lock() { + state.clock.playing = true; + } + this.playback = Some(shared); + this.playback_stream = Some(stream); + this.data.timeline_playing = true; + this.data.error = None; + this.schedule_playhead_refresh(cx); + } + Err(error) => { + this.data.error = Some(error); + this.data.timeline_playing = false; + } + } + cx.notify(); + }); + }) + .detach(); + self.data.timeline_playing = true; + cx.notify(); + } + + fn schedule_playhead_refresh(&self, cx: &mut Context) { + let Some(playback) = self.playback.clone() else { + return; + }; + let generation = self.playback_generation; + cx.spawn(async move |view, cx| { + loop { + cx.background_executor() + .timer(Duration::from_millis(30)) + .await; + let mut keep_running = false; + let _ = view.update(cx, |this, cx| { + if this.playback_generation != generation { + return; + } + if let Ok(mut state) = playback.lock() { + this.data.playhead_seconds = state.position_at(std::time::Instant::now()); + state.muted = this.data.muted_audio_lanes.clone(); + state.soloed = this.data.soloed_audio_lanes.clone(); + keep_running = state.clock.playing; + this.data.timeline_playing = keep_running; + } + cx.notify(); + }); + if !keep_running { + break; + } + } + }) + .detach(); + } + pub fn new( projects: crate::project::Preferences, writer: crate::project::Writer, @@ -565,6 +745,10 @@ impl AlignApp { show_problem_report: false, feedback_notice_pending: crate::feedback::notice_pending(), feedback_error: None, + playback: None, + playback_stream: None, + playback_generation: 0, + playback_loading: false, update_notice_dismissed: false, }; app.export_inputs @@ -844,6 +1028,10 @@ impl AlignApp { if !self.data.begin_sync_run() { return; } + // A new result can change both clip positions and source mappings. Do + // not keep playing decoded audio from the previous timeline while it + // is being replaced. + self.stop_timeline_playback(); if self.data.lanes.is_empty() { self.timeline_transitions.clear(); } diff --git a/crates/align-gpui/src/views/operation.rs b/crates/align-gpui/src/views/operation.rs index 3d6ffd3..63598aa 100644 --- a/crates/align-gpui/src/views/operation.rs +++ b/crates/align-gpui/src/views/operation.rs @@ -335,7 +335,10 @@ pub(super) fn sequence_results_panel( format!("{check}{} · {name}", index + 1), true, move |this, _, _, cx| { - if this.update_timeline_layout(|data| data.select_sequence_result(index)) { + if this.data.active_sequence_result != index + && this.update_timeline_layout(|data| data.select_sequence_result(index)) + { + this.stop_timeline_playback(); this.project_changed(cx); } cx.notify(); diff --git a/crates/align-gpui/src/views/root.rs b/crates/align-gpui/src/views/root.rs index 9c5b292..80159fc 100644 --- a/crates/align-gpui/src/views/root.rs +++ b/crates/align-gpui/src/views/root.rs @@ -144,6 +144,21 @@ impl Render for AlignApp { if this.data.show_path_fixer && this.path_fixer_inputs.any_focused(window, cx) { return; } + if key == "space" { + if this.data.show_export + || this.data.show_path_fixer + || this.data.show_sequence_results + || this.data.show_search_quality + || this.data.show_search_settings + || this.data.show_stage_settings + || this.data.show_agent_setup + { + return; + } + this.toggle_timeline_playback(cx); + cx.stop_propagation(); + return; + } if this.data.lanes.is_empty() { return; } diff --git a/crates/align-gpui/src/views/timeline.rs b/crates/align-gpui/src/views/timeline.rs index ff15c49..bd65b23 100644 --- a/crates/align-gpui/src/views/timeline.rs +++ b/crates/align-gpui/src/views/timeline.rs @@ -132,9 +132,15 @@ pub(super) fn timeline_lanes( .flex() .flex_col() .child(div().h(px(RULER_H)).flex_shrink_0()); - let mut tracks = div().w(px(timeline_w)).flex_shrink_0().flex().flex_col(); + let mut tracks = div() + .relative() + .w(px(timeline_w)) + .flex_shrink_0() + .flex() + .flex_col(); let mut ticks = div() + .id("timeline-ruler") .relative() .h(px(RULER_H)) .flex_shrink_0() @@ -170,6 +176,22 @@ pub(super) fn timeline_lanes( ) }); } + ticks = ticks.cursor_pointer().on_mouse_down( + MouseButton::Left, + cx.listener(move |this, e: &MouseDownEvent, _, cx| { + let bounds = this.data.timeline_scroll.bounds(); + let offset = this.data.timeline_scroll.offset(); + let content_x = f32::from(e.position.x - bounds.origin.x) + f32::from(offset.x); + this.data.playhead_seconds = + (content_x.max(0.) as f64 / px_per_sec).clamp(0.0, duration); + if let Some(playback) = &this.playback + && let Ok(mut playback) = playback.lock() + { + playback.clock.position = this.data.playhead_seconds; + } + cx.notify(); + }), + ); tracks = tracks.child(ticks); // Rows. @@ -180,6 +202,7 @@ pub(super) fn timeline_lanes( }; let kind_color = theme.icon; let lane_id = lane.id.clone(); + let label_lane_id = lane_id.clone(); let first_clip = lane.clips.first().map(|c| c.clip_id.clone()); // The tooltip shows the source and any active stream/channel override. let override_suffix = match data.effective_lane_analysis_source(&lane_id) { @@ -215,6 +238,10 @@ pub(super) fn timeline_lanes( if active { label = label.cursor_pointer(); } + let mute_id = label_lane_id.clone(); + let solo_id = label_lane_id.clone(); + let is_muted = data.muted_audio_lanes.contains(&label_lane_id); + let is_soloed = data.soloed_audio_lanes.contains(&label_lane_id); labels = labels.child( label .tooltip(hover_tip(tip, theme)) @@ -234,9 +261,54 @@ pub(super) fn timeline_lanes( ) .child( div() - .text_xs() - .text_color(rgb(kind_color)) - .child(format!("{kind_glyph}{}", lane.number)), + .flex() + .flex_row() + .items_center() + .gap_1() + .child( + div() + .text_xs() + .text_color(rgb(kind_color)) + .child(format!("{kind_glyph}{}", lane.number)), + ) + .child( + div() + .id(SharedString::from(format!("lane-mute-{mute_id}"))) + .px_1() + .rounded_sm() + .text_xs() + .text_color(rgb(if is_muted { theme.accent } else { theme.dim })) + .cursor_pointer() + .child("M") + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, _, _, cx| { + if !this.data.muted_audio_lanes.remove(&mute_id) { + this.data.muted_audio_lanes.insert(mute_id.clone()); + } + cx.notify(); + }), + ), + ) + .child( + div() + .id(SharedString::from(format!("lane-solo-{solo_id}"))) + .px_1() + .rounded_sm() + .text_xs() + .text_color(rgb(if is_soloed { theme.accent } else { theme.dim })) + .cursor_pointer() + .child("S") + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, _, _, cx| { + if !this.data.soloed_audio_lanes.remove(&solo_id) { + this.data.soloed_audio_lanes.insert(solo_id.clone()); + } + cx.notify(); + }), + ), + ), ), ); // Absolute placement prevents minimum-width bars from shifting @@ -408,6 +480,19 @@ pub(super) fn timeline_lanes( tracks = tracks.child(div().h(px(1.)).flex_shrink_0().bg(rgb(theme.separator))); } + // One continuous NLE playhead overlays the ruler and every lane. + let playhead_height = RULER_H + data.lanes.len() as f32 * (TIMELINE_ROW_H + 1.0); + tracks = tracks.child( + div() + .id("timeline-playhead") + .absolute() + .left(px((data.playhead_seconds.max(0.0) * px_per_sec) as f32)) + .top(px(0.)) + .w(px(2.)) + .h(px(playhead_height)) + .bg(rgb(theme.accent)), + ); + let viewport = div() .id("timeline-viewport") .flex_1() From dda63d31ae528e2327149b70f597f318ad36d11e Mon Sep 17 00:00:00 2001 From: REVPKD Date: Wed, 25 Nov 2026 09:40:04 +0100 Subject: [PATCH 2/3] test: normalize clip paths on Windows Keep the clip-details path assertion portable across separators so the Windows workspace suite exercises the same path semantics as Unix. --- crates/align-gpui/src/views/clip_details.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/align-gpui/src/views/clip_details.rs b/crates/align-gpui/src/views/clip_details.rs index 79a615a..0515abb 100644 --- a/crates/align-gpui/src/views/clip_details.rs +++ b/crates/align-gpui/src/views/clip_details.rs @@ -399,7 +399,7 @@ mod tests { Some("00:01:40 – 00:02:40 · 0:01:00") ); assert_eq!(row(&waveform, "Source TC"), None); - assert_eq!(waveform.path, "/shoot/C1.MP4"); + assert_eq!(waveform.path.replace('\\', "/"), "/shoot/C1.MP4"); data.ruler_timecode = Some(3603.6); assert_eq!( row(&card(&data, "C1"), "Timeline"), From 631d921b68c6ec4d94f76049eb32cf2081ac9d64 Mon Sep 17 00:00:00 2001 From: REVPKD Date: Wed, 25 Nov 2026 10:30:21 +0100 Subject: [PATCH 3/3] Test Windows source revisions after flushing writes Flush rewritten test content before checking the Windows change stamp, then wait for the revision to advance before restoring the original modified time. --- crates/align-decode/src/export.rs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/crates/align-decode/src/export.rs b/crates/align-decode/src/export.rs index fc30b83..7a62157 100644 --- a/crates/align-decode/src/export.rs +++ b/crates/align-decode/src/export.rs @@ -1370,7 +1370,23 @@ mod tests { let before = source_revision_tag(&path, &cancel).unwrap(); assert_eq!(source_revision_tag(&path, &cancel).unwrap(), before); let mtime = std::fs::metadata(&path).unwrap().modified().unwrap(); - std::fs::write(&path, b"replaced").unwrap(); + let mut rewritten = std::fs::File::options().write(true).open(&path).unwrap(); + use std::io::Write as _; + rewritten.write_all(b"replaced").unwrap(); + rewritten.sync_all().unwrap(); + drop(rewritten); + // Some Windows filesystems publish ChangeTime asynchronously or at a + // coarser resolution than the write itself. Wait for the write stamp + // to advance before restoring LastWriteTime, so this test specifically + // verifies that restoring mtime does not hide a completed rewrite. + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(2); + while source_revision_tag(&path, &cancel).unwrap() == before { + assert!( + std::time::Instant::now() < deadline, + "source revision did not advance after replacing file contents" + ); + std::thread::sleep(std::time::Duration::from_millis(10)); + } std::fs::File::options() .write(true) .open(&path)