Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .husky/pre-push
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ if grep -rEn \
'ghp_[A-Za-z0-9]{36}|AKIA[0-9A-Z]{16}|sk-ant-[A-Za-z0-9_\-]{90,}|sk-[A-Za-z0-9]{48}' \
--include='*.ts' --include='*.tsx' --include='*.js' \
--include='*.json' --include='*.py' \
--exclude-dir=node_modules --exclude-dir=.next \
--exclude-dir=node_modules --exclude-dir=.next --exclude-dir=.venv \
.; then
echo "✗ Secret token detected — remove from source before pushing."
exit 1
Expand Down
98 changes: 98 additions & 0 deletions spike/audio-sync/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions spike/audio-sync/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,5 @@ edition = "2021"
[dependencies]
rustfft = "6"
hound = "3"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
19 changes: 17 additions & 2 deletions spike/audio-sync/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,9 +38,24 @@ cargo build

## Run

Against the committed fixture WAVs (from repo root):

```bash
cargo run --manifest-path spike/audio-sync/Cargo.toml -- spike/audio-sync/fixtures/video-audio.wav spike/audio-sync/fixtures/audio-track.wav
# → lag: -6.800000s snr: 9.815
```

Against any two WAV files:

```bash
cargo run --manifest-path spike/audio-sync/Cargo.toml -- <ref.wav> <target.wav>
```

## Test

```bash
cargo run --manifest-path spike/audio-sync/Cargo.toml
# → audio-sync spike — not yet implemented
cargo test --manifest-path spike/audio-sync/Cargo.toml
# 19 tests — includes fixture_roundtrip which asserts lag matches baseline.json to ±1 sample
```

## Dependencies
Expand Down
44 changes: 44 additions & 0 deletions spike/audio-sync/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,20 @@
use rustfft::{num_complex::Complex, FftPlanner};

/// Loads mono PCM samples from a WAV file, normalising to `[-1.0, 1.0]`.
/// Supports 16-bit integer PCM (the fixture format) and 32-bit float WAV.
pub fn load_wav_samples(path: &str) -> Result<(Vec<f32>, u32), Box<dyn std::error::Error>> {
let mut reader = hound::WavReader::open(path)?;
let spec = reader.spec();
let samples: Vec<f32> = match spec.sample_format {
hound::SampleFormat::Int => reader
.samples::<i16>()
.map(|s| s.map(|v| v as f32 / i16::MAX as f32))
.collect::<Result<_, _>>()?,
hound::SampleFormat::Float => reader.samples::<f32>().collect::<Result<_, _>>()?,
};
Ok((samples, spec.sample_rate))
}

// Mirror of AudioSyncer.js constants — must not be changed; baseline.json was computed with these.
const PEAK_NEARNESS_THRESHOLD: f64 = 0.5;
const SYNC_FRAME_RATE: f64 = 30.0;
Expand Down Expand Up @@ -356,4 +371,33 @@ mod tests {
assert_eq!(snr, 0.0, "length-1 array must return snr=0.0, got {snr}");
assert!(!is_reliable, "length-1 array must not be reliable");
}

// --- fixture round-trip test ---

#[test]
fn fixture_roundtrip() {
// Run the full Rust pipeline against the committed fixture WAVs and assert
// the lag matches the JS baseline to within ±1 sample at 8 kHz.
let baseline_json = std::fs::read_to_string("fixtures/baseline.json")
.expect("fixtures/baseline.json not found — run cargo test from spike/audio-sync/");
let baseline: serde_json::Value =
serde_json::from_str(&baseline_json).expect("invalid baseline.json");
let baseline_lag: f64 = baseline["lagSeconds"]
.as_f64()
.expect("baseline.json missing lagSeconds");

let (samples_a, sample_rate) =
load_wav_samples("fixtures/video-audio.wav").expect("failed to load video-audio.wav");
let (samples_b, _) =
load_wav_samples("fixtures/audio-track.wav").expect("failed to load audio-track.wav");

let correlation = compute_cross_correlation(&samples_a, &samples_b);
let lag = find_best_lag(&correlation, sample_rate);

let tolerance = 1.0 / sample_rate as f64; // ±1 sample
assert!(
(lag - baseline_lag).abs() <= tolerance,
"Rust lag {lag:.6}s differs from JS baseline {baseline_lag:.6}s by more than ±1 sample ({tolerance:.9}s)"
);
}
}
26 changes: 25 additions & 1 deletion spike/audio-sync/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,27 @@
use audio_sync::{compute_cross_correlation, find_best_lag, load_wav_samples, validate_peak};

fn main() {
println!("audio-sync spike — not yet implemented");
let args: Vec<String> = std::env::args().collect();
if args.len() != 3 {
eprintln!("Usage: audio-sync <ref.wav> <target.wav>");
std::process::exit(1);
}

let run = || -> Result<(), Box<dyn std::error::Error>> {
let (samples_a, sample_rate) = load_wav_samples(&args[1])?;
let (samples_b, _) = load_wav_samples(&args[2])?;

let correlation = compute_cross_correlation(&samples_a, &samples_b);
let lag = find_best_lag(&correlation, sample_rate);
let (snr, is_reliable) = validate_peak(&correlation, lag, sample_rate);

let confidence = if is_reliable { "" } else { " [LOW CONFIDENCE]" };
println!("lag: {lag:.6}s snr: {snr:.3}{confidence}");
Ok(())
};

if let Err(e) = run() {
eprintln!("error: {e}");
std::process::exit(1);
}
}
Loading